#include <bits/stdc++.h>
using namespace std;
int mySolve(int n, int x, int y, int d) {
  if (abs(y - x) % d == 0) {
    return (abs(y - x)) / d;
  } else {
    long long temp1 = 2e9 + 123;
    long long temp2 = 2e9 + 123;
    bool one = false;
    bool two = false;
    if ((n - y) % d != 0) {
      one = true;
    } else {
      temp1 = ((n - x) / d) + 1;
      temp1 += (n - y) / d;
    }
    if ((y - 1) % d != 0) {
      two = true;
    } else {
      temp2 = ((x - 1) / d) + 1;
      temp2 += (y - 1) / d;
    }
    if (one && two) {
      return -1;
    }
    return min(temp1, temp2);
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  for (int i = 0; i < t; i++) {
    int n, x, y, d;
    cin >> n >> x >> y >> d;
    cout << mySolve(n, x, y, d) << endl;
  }
  return 0;
}
