#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) {
  if (a == 0) return b;
  return gcd(b % a, a);
}
long long powmod(long long a, long long b, long long p) {
  if (b == 0) return 1;
  if (b == 1) return a;
  long long temp = powmod(a, b / 2, p);
  temp *= temp;
  temp %= p;
  if (b % 2 == 0) return temp;
  temp = temp * a;
  temp %= p;
  return temp;
}
void solve() {
  int n, x, y, d;
  cin >> n >> x >> y >> d;
  if (abs(x - y) % d == 0) {
    cout << abs(x - y) / d << endl;
    ;
    return;
  }
  long long ans = 1e18;
  if (abs(y - 1) % d == 0) {
    ans = (y - 1) / d;
    ans += (x - 1 + d - 1) / d;
  }
  if ((n - y) % d == 0) {
    long long ans2 = (n - y) / d;
    ans2 += (n - x + d - 1) / d;
    ans = min(ans, ans2);
  }
  if (ans > 1e10)
    cout << -1 << endl;
  else
    cout << ans << endl;
  return;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
