#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    long long n, x, y, d;
    cin >> n >> x >> y >> d;
    if (x == y) {
      cout << 0 << endl;
      continue;
    }
    long long op1 = -1, op2 = -1, op3 = -1;
    if ((y - x) % d == 0) {
      op1 = (abs(y - x)) / d;
    }
    if ((y - 1) % d == 0) {
      op2 = ((x - 1) / d + 1) + (y - 1) / d;
    }
    if ((n - y) % d == 0) {
      op3 = ((n - x) / d + 1) + (n - y) / d;
    }
    if (op1 == -1 && op2 == -1 && op3 == -1) {
      cout << -1 << endl;
    } else {
      if (op1 == -1) {
        op1 = INT_MAX;
      }
      if (op2 == -1) {
        op2 = INT_MAX;
      }
      if (op3 == -1) {
        op3 = INT_MAX;
      }
      cout << min(op1, min(op2, op3)) << endl;
    }
  }
  return 0;
}
