#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  long long n, x, y, d;
  cin >> t;
  for (int i = 0; i < t; i++) {
    cin >> n >> x >> y >> d;
    if (abs(x - y) % d == 0) {
      cout << abs(x - y) / d << endl;
    } else if ((y - 1) % d != 0 && (n - y) % d != 0) {
      cout << "-1" << endl;
    } else {
      long long b = n;
      if ((y - 1) % d == 0) {
        b = (y - 1) / d + ceil(x * 1.0 / d);
      }
      if ((n - y) % d == 0) {
        long long b1 = ((n - y) / d + ceil((n - x) * 1.0 / d));
        b = min(b, b1);
      }
      cout << b << endl;
    }
  }
}
