#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int q, n, x, y, d, s = 0, st = 0, en = 0;
  cin >> q;
  for (int i = 0; i < q; i++) {
    cin >> n >> x >> y >> d;
    if ((y - x) % d != 0 && (y - 1) % d != 0 && (n - y) % d != 0) {
      cout << -1 << endl;
    } else {
      if ((y - x) % d == 0)
        cout << abs((y - x) / d) << endl;
      else if ((y - 1) % d == 0 && (n - y) % d == 0) {
        cout << abs(min((n - y) / d + (n - x + d - 1) / d,
                        (y - 1) / d + (x - 1 + d - 1) / d))
             << endl;
      } else if ((y - n) % d == 0) {
        cout << abs((n - y) / d + (n - x + d - 1) / d) << endl;
        ;
      } else
        cout << abs((y - 1) / d + (x - 1 + d - 1) / d) << endl;
    }
  }
}
