#include <bits/stdc++.h>
using namespace std;
const long long int MOD = 1e9 + 7;
bool isPoTwo(long long int x) { return x && (!(x & (x - 1))); }
long long int power(long long int x, unsigned long long int y,
                    long long int p) {
  long long int res = 1;
  x = x % p;
  if (x == 0) return 0;
  while (y > 0) {
    if (y & 1) res = (res * x) % p;
    y = y >> 1;
    x = (x * x) % p;
  }
  return res;
}
void solve() {
  long long int n, x, y, d;
  cin >> n >> x >> y >> d;
  long long int ans = INT_MAX, ans1 = INT_MAX, ans2 = INT_MAX;
  if ((y - x) % d == 0) ans = (abs(y - x) / d);
  if ((y - 1) % d == 0 || (n - y) % d == 0) {
    if ((y - 1) % d == 0) {
      ans1 = (y - 1) / d;
      ans1 += ((x - 1) / d) + 1;
    }
    if ((n - y) % d == 0) {
      ans2 = (n - y) / d;
      ans2 += ((n - x) / d) + 1;
    }
    ans = min(ans, ans2);
    ans = min(ans, ans1);
  }
  if (ans == INT_MAX) ans = -1;
  cout << ans << "\n";
}
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
