#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int TESTS = 1;
  cin >> TESTS;
  while (TESTS--) {
    long long n, x, y, d;
    cin >> n >> x >> y >> d;
    if (abs(y - x) % d == 0) {
      cout << abs(y - x) / d << "\n";
      continue;
    }
    long long l = 1000000007, r = 1000000007;
    if ((n - y) % d == 0) {
      l = (n - y) / d + (n - x + d - 1) / d;
    }
    if ((y - 1) % d == 0) {
      r = (y - 1) / d + (x - 1 + d - 1) / d;
    }
    long long ans = min(l, r);
    if (ans != 1000000007)
      cout << ans << "\n";
    else
      cout << "-1\n";
  }
  return 0;
}
