#include <bits/stdc++.h>
using namespace std;
string to_string(string s) { return '"' + s + '"'; }
string to_string(const char* s) { return to_string((string)s); }
string to_string(bool b) { return (b ? "true" : "false"); }
template <typename A, typename B>
string to_string(pair<A, B> p) {
  return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}
template <typename A>
string to_string(A v) {
  bool first = true;
  string res = "{";
  for (const auto& x : v) {
    if (!first) {
      res += ", ";
    }
    first = false;
    res += to_string(x);
  }
  res += "}";
  return res;
}
void debug_out() { cerr << '\n'; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
  cerr << " " << to_string(H);
  debug_out(T...);
}
template <typename A, typename B>
istream& operator>>(istream& input, pair<A, B>& x) {
  input >> x.first >> x.second;
  return input;
}
template <typename A>
istream& operator>>(istream& input, vector<A>& x) {
  for (auto& i : x) input >> i;
  return input;
}
void solve() {
  long long n, d, x, y;
  cin >> n >> x >> y >> d;
  if (x % d == y % d)
    cout << abs(x - y) / d << '\n';
  else if (y % d == 1 % d and y % d != n % d)
    cout << (x - 1 + d - 1) / d + (y - 1) / d << '\n';
  else if (y % d != 1 % d and y % d == n % d)
    cout << (n - x + d - 1) / d + (n - y) / d << '\n';
  else if (y % d == 1 % d and y % d == n % d)
    cout << min((x - 1 + d - 1) / d + (y - 1) / d,
                (n - x + d - 1) / d + (n - y) / d)
         << '\n';
  else
    cout << -1 << '\n';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
