#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using uint = unsigned int;
using ldb = long double;
struct init {
  init() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cout << fixed << setprecision(10);
  }
  ~init() {
    cerr << "Time elapsed: " << static_cast<double>(clock()) / CLOCKS_PER_SEC
         << "s.\n";
  }
} init;
const long long N = 100500 * 5, MOD = 1000 * 1000 * 1000 + 7;
const ldb EPS = 5e-12, HALF = 0.5;
signed main() {
  long long t;
  cin >> t;
  while (t--) {
    long long n, x, y, d;
    cin >> n >> x >> y >> d;
    long long ans = 1e18;
    if (abs(x - y) % d == 0) {
      ans = abs(x - y) / d;
    }
    if (abs(n - y) % d == 0) {
      ans = min(ans, abs(n - y) / d + (n - x + d - 1) / d);
    }
    if ((y - 1) % d == 0) {
      ans = min(ans, (x - 1 + d - 1) / d + (y - 1) / d);
    }
    if (ans == 1e18) {
      cout << -1 << '\n';
    } else {
      cout << ans << '\n';
    }
  }
}
