#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int t, n, d, x, y, javab1, javab2, ans[1000];
  cin >> t;
  for (int i = 0; i < t; i++) {
    cin >> n >> x >> y >> d;
    javab1 = javab2 = n;
    if ((y - x) % d == 0) {
      ans[i] = ((abs(y - x)) / d);
    } else if ((y - 1) % d == 0 || (n - y) % d == 0) {
      if ((n - y) % d == 0) {
        javab1 = (n - x + d - 1) / d;
        javab1 += (n - y) / d;
      }
      if ((y - 1) % d == 0) {
        javab2 = (x - 1 + d - 1) / d;
        javab2 += (y - 1) / d;
      }
      ans[i] = (min(javab2, javab1));
    } else {
      ans[i] = -1;
    }
  }
  for (int i = 0; i < t; i++) {
    cout << ans[i] << endl;
  }
  return 0;
}
