#include <bits/stdc++.h>
using namespace std;
const long long inf = 20000000000LL;
long long n, x, y, d;
long long f() {
  if (abs((y - x)) % d == 0) return abs((y - x)) / d;
  long long ret = inf;
  if ((y - 1) % d == 0) {
    ret = (y - 1) / d + max((long long)ceil(1.0 * (x - 1) / d), 0LL);
  }
  if ((n - y) % d == 0) {
    ret = min(ret, (n - y) / d + max(0LL, (long long)ceil(1.0 * (n - x) / d)));
  }
  if (ret == inf) ret = -1;
  return ret;
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    cin >> n >> x >> y >> d;
    cout << f() << endl;
  }
}
