#include <bits/stdc++.h>
using namespace std;
const int OO = 0x3f3f3f3f, NegOO = -1 * OO, N = 1e6 + 5, mod = 1e9 + 7;
long long gcd(long long x, long long y) {
  if (y == 0) return x;
  return gcd(y, x % y);
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n, x, y, d;
    cin >> n >> x >> y >> d;
    if (x == y) {
      cout << 0 << "\n";
      continue;
    } else if (x < y) {
      int mx = 1e9 + 5;
      int ans1 = mx, ans2 = mx, ans3 = mx;
      if ((y - x) % d == 0) ans1 = (y - x) / d;
      if ((y - 1) % d == 0)
        ans2 = (x - 1) / d + ((x - 1) % d != 0) + (y - 1) / d;
      if ((n - y) % d == 0)
        ans3 = (n - x) / d + ((n - x) % d != 0) + (n - y) / d;
      int ans = min(min(ans1, ans2), ans3);
      cout << ((ans != mx) ? ans : -1) << "\n";
    } else {
      int mx = 1e9 + 5;
      int ans1 = mx, ans2 = mx, ans3 = mx;
      if ((x - y) % d == 0) ans1 = (x - y) / d;
      if ((y - 1) % d == 0)
        ans2 = (x - 1) / d + ((x - 1) % d != 0) + (y - 1) / d;
      if ((n - y) % d == 0)
        ans3 = (n - x) / d + ((n - x) % d != 0) + (n - y) / d;
      int ans = min(min(ans1, ans2), ans3);
      cout << ((ans != mx) ? ans : -1) << "\n";
    }
  }
  return 0;
}
