#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx")
using namespace std;
const int N = 5 * (1e5);
const int MOD = (1e9) + 7;
const long long INF = (1e17) + 777;
const long double pi = 2 * acos(0.0);
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr), cout.tie(nullptr);
  int t;
  cin >> t;
  for (int i = 1; i <= t; i++) {
    int n, first, second, d;
    long long mx1 = INF, mx2 = INF;
    cin >> n >> first >> second >> d;
    if (abs(first - second) % d == 0) {
      cout << abs(first - second) / d << endl;
      continue;
    }
    if ((second - 1) % d == 0) {
      mx1 = (second / d) + ((first - 1 + (d - 1)) / d);
    }
    if ((n - second) % d == 0) {
      mx2 = (n - second) / d + ((n - first + (d - 1)) / d);
    }
    if (min(mx1, mx2) == INF)
      cout << -1 << endl;
    else
      cout << min(mx1, mx2) << endl;
  }
  return false;
}
