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