#include <bits/stdc++.h>
using namespace std;
long long xceil(long long a, long long b) {
  if (a % b == 0)
    return a / b;
  else
    return 1 + a / b;
}
int main() {
  long long t;
  cin >> t;
  while (t--) {
    long long n, x, y, d;
    cin >> n >> x >> y >> d;
    long long ans = 1e18, a = 1e18, b = 1e18;
    if (abs(y - x) % d == 0)
      ans = abs(y - x) / d;
    else {
      if ((y - 1) % d == 0) a = xceil(x - 1, d) + (y - 1) / d;
      if ((n - y) % d == 0) b = xceil(n - x, d) + (n - y) / d;
    }
    ans = min(ans, min(a, b));
    if (ans == 1e18) ans = -1;
    cout << ans << '\n';
  }
}
