#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
using namespace std;
const double E = 1e-7;
const long long INF = 1e17;
int main() {
  int t;
  cin >> t;
  for (int _ = 0; _ < t; ++_) {
    long long n, x, y, d;
    cin >> n >> x >> y >> d;
    if (abs(x - y) % d == 0) {
      cout << abs(x - y) / d << '\n';
      continue;
    }
    long long ans1 = INF, ans2 = INF;
    if (abs(n - y) % d == 0) {
      ans1 =
          abs(n - y) / d + abs(n - x) / d + ((abs(n - x) % d == 0) ? 0ll : 1ll);
    }
    if (abs(1 - y) % d == 0) {
      ans2 =
          abs(1 - y) / d + abs(1 - x) / d + ((abs(1 - x) % d == 0) ? 0ll : 1ll);
    }
    if (ans1 == ans2 && ans1 == INF) {
      cout << -1 << '\n';
      continue;
    }
    cout << min(ans1, ans2) << '\n';
  }
  return 0;
}
