#include <bits/stdc++.h>
using namespace std;
long long int t, n, m, k, a, b, c, d;
int main() {
  cin >> t;
  while (t--) {
    cin >> a >> b >> c >> d;
    if (abs(c - b) % d == 0) {
      cout << abs(c - b) / d << endl;
    } else if (abs(c - 1) % d == 0 && abs(a - c) % d == 0) {
      k = (b - 1) / d;
      if ((b - 1) % d != 0) k++;
      k += (c - 1) / d;
      m = (a - b) / d;
      if ((a - b) % d != 0) m++;
      m += (a - c) / d;
      cout << min(k, m) << endl;
    } else if (abs(c - 1) % d == 0) {
      k = (b - 1) / d;
      if ((b - 1) % d != 0) k++;
      k += (c - 1) / d;
      cout << k << endl;
    } else if (abs(a - c) % d == 0) {
      m = (a - b) / d;
      if ((a - b) % d != 0) m++;
      m += (a - c) / d;
      cout << m << endl;
    } else
      cout << -1 << endl;
  }
}
