import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.stream.Stream;

public class TestClass implements Runnable {

	static final double time = 1e9;
	static final int MOD = (int) 1e9 + 7;
	static final long mh = Long.MAX_VALUE;
	static final Reader in = new Reader();
	static final PrintWriter out = new PrintWriter(System.out);
	StringBuilder answer = new StringBuilder();

	public static void main(String[] args) {
		new Thread(null, new TestClass(), "persefone", 1 << 28).start();
	}

	@Override
	public void run() {
		long start = System.nanoTime();
		solve();
		printf();
		long elapsed = System.nanoTime() - start;
//		out.println("stamp : " + elapsed / time);
//		out.println("stamp : " + TimeUnit.SECONDS.convert(elapsed, TimeUnit.NANOSECONDS));
		close();
	}

	void solve() {
		for (int t = in.nextInt(); t > 0; t--) {
			int k = in.nextInt();
			long l = in.nextLong();
			long r = in.nextLong();
			int p = in.nextInt();
			if (k == 1) {
				add(2 % p, '\n');
				continue;
			}

			if (p == 2) {
				add(1 - k % 2, '\n');
				continue;
			}

			if (k % p == 0) {
				add(calc(2, p - 1 - (r - l) % (p - 1), p), '\n');
				continue;
			}

			long y = calc(2, l, p - 1);
			long x = calc(k, y, p);
			if (x == 1) {
				long z = k % 2 == 0 ? 0 : r - l;
				add(calc(2, r - l + 1 - z, p), '\n');
				continue;
			}
			long i = (calc(x, calc(2, r - l + 1, p - 1), p) - 1 + p) % p;
			long j = calc(x - 1, p - 2, p);
//			printf(y, x, i, j);
			if (k % 2 == 0) {

				add(i * j % p, '\n');
			} else {
				long m = calc(2, p - 1 - (r - l) % (p - 1), p);
//				printf(m);
				add(i * j % p * m % p, '\n');
			}
		}
	}

	int pow(int a, int b, int p) {
		long ans = 1, base = a;
		while (b > 0){
			if ((b & 1) > 0) {
				ans *= base %= p;
			}
			base *= base %= p;
			b >>= 1;
		}
		return (int)ans;
	}

	public static int[] enumLowestPrimeFactors(int n) {
		int tot = 0;
		int[] lpf = new int[n + 1];
		int u = n + 32;
		double lu = Math.log(u);
		int[] primes = new int[(int) (u / lu + u / lu / lu * 1.5)];
		for (int i = 2; i <= n; i++)
			lpf[i] = i;
		for (int p = 2; p <= n; p++) {
			if (lpf[p] == p)
				primes[tot++] = p;
			int tmp;
			for (int i = 0; i < tot && primes[i] <= lpf[p] && (tmp = primes[i] * p) <= n; i++) {
				lpf[tmp] = primes[i];
			}
		}
		return lpf;
	}

	public static int[] enumNumDivisorsFast(int n, int[] lpf)
	{
		int[] nd = new int[n+1];
		nd[1] = 1;
		for(int i = 2;i <= n;i++){
			int j = i, e = 0;
			while(j % lpf[i] == 0){
				j /= lpf[i];
				e++;
			}
			nd[i] = nd[j] * (e+1);
		}
		return nd;
	}

	boolean isPrime(long n) {

		for (int i = 2; 1l * i * i <= n; i++)
			if (n % i == 0)
				return false;
		return true;
	}

	void printf() {
		out.print(answer);
	}

	void close() {
		out.close();
	}

	void printf(Stream<?> str) {
		str.forEach(o -> add(o, " "));
		add("\n");
	}

	void printf(Object... obj) {
		printf(false, obj);
	}

	void printfWithDescription(Object... obj) {
		printf(true, obj);
	}

	private void printf(boolean b, Object... obj) {

		if (obj.length > 1) {
			for (int i = 0; i < obj.length; i++) {
				if (b) add(obj[i].getClass().getSimpleName(), " - ");
				if (obj[i] instanceof Collection<?>) {
					printf((Collection<?>) obj[i]);
				} else if (obj[i] instanceof int[][]) {
					printf((int[][])obj[i]);
				} else if (obj[i] instanceof long[][]) {
					printf((long[][])obj[i]);
				} else if (obj[i] instanceof double[][]) {
					printf((double[][])obj[i]);
				} else printf(obj[i]);
			}
			return;
		}

		if (b) add(obj[0].getClass().getSimpleName(), " - ");
		printf(obj[0]);
	}

	void printf(Object o) {
		if (o instanceof int[])
			printf(Arrays.stream((int[]) o).boxed());
		else if (o instanceof char[])
			printf(new String((char[]) o));
		else if (o instanceof long[])
			printf(Arrays.stream((long[]) o).boxed());
		else if (o instanceof double[])
			printf(Arrays.stream((double[]) o).boxed());
		else if (o instanceof boolean[]) {
			for (boolean b : (boolean[]) o) add(b, " ");
			add("\n");
		}
		else
			add(o, "\n");
	}

	void printf(int[]... obj) {
		for (int i = 0; i < obj.length; i++) printf(obj[i]);
	}

	void printf(long[]... obj) {
		for (int i = 0; i < obj.length; i++) printf(obj[i]);
	}

	void printf(double[]... obj) {
		for (int i = 0; i < obj.length; i++) printf(obj[i]);
	}

	void printf(boolean[]... obj) {
		for (int i = 0; i < obj.length; i++) printf(obj[i]);
	}

	void printf(Collection<?> col) {
		printf(col.stream());
	}

	<T, K> void add(T t, K k) {
		if (t instanceof Collection<?>) {
			((Collection<?>) t).forEach(i -> add(i, " "));
		} else if (t instanceof Object[]) {
			Arrays.stream((Object[]) t).forEach(i -> add(i, " "));
		} else
			add(t);
		add(k);
	}

	<T> void add(T t) {
		answer.append(t);
	}

	@SuppressWarnings("unchecked")
	<T extends Comparable<? super T>> T min(T... t) {
		if (t.length == 0)
			return null;
		T m = t[0];
		for (int i = 1; i < t.length; i++)
			if (t[i].compareTo(m) < 0)
				m = t[i];
		return m;
	}

	@SuppressWarnings("unchecked")
	<T extends Comparable<? super T>> T max(T... t) {
		if (t.length == 0)
			return null;
		T m = t[0];
		for (int i = 1; i < t.length; i++)
			if (t[i].compareTo(m) > 0)
				m = t[i];
		return m;
	}

	int gcd(int a, int b) {
		return (b == 0) ? a : gcd(b, a % b);
	}

	long gcd(long a, long b) {
		return (b == 0) ? a : gcd(b, a % b);
	}

	long lcm(int a, int b) {
		return (1l * a * b / gcd(a, b));
	}

	long lcm(long a, long b) {
		if (a > Long.MAX_VALUE / b) throw new RuntimeException();
		return a * b / gcd(a, b);
	}

	// c = gcd(a, b) -> extends gcd method: ax + by = c <----> (b % a)p + q = c;
	int[] ext_gcd(int a, int b) {
		if (b == 0) return new int[] {a, 1, 0 };
		int[] vals = ext_gcd(b, a % b);
		int d = vals[0]; // gcd
	    int p = vals[2]; //
		int q = vals[1] - (a / b) * vals[2];
		return new int[] { d, p, q };
	}

	// find any solution of the equation: ax + by = c using extends gcd
	boolean find_any_solution(int a, int b, int c, int[] root) {
		int[] vals = ext_gcd(Math.abs(a), Math.abs(b));
		if (c % vals[0] != 0) return false;
		printf(vals);
		root[0] = c * vals[1] / vals[0];
		root[1] = c * vals[2] / vals[0];
		if (a < 0) root[0] *= -1;
		if (b < 0) root[1] *= -1;
		return true;
	}

	int mod(int x) { return x % MOD; }

	int mod(int x, int y) { return mod(mod(x) + mod(y)); }

	long mod(long x) { return x % MOD; }

	long mod (long x, long y) { return mod(mod(x) + mod(y)); }

	int lw(long[] f, int l, int r, long k) {
		int R = r, m = 0;
		while (l <= r) {
			m = l + r >> 1;
		    if (m == R) return m;
		    if (f[m] >= k) r = m - 1; else l = m + 1;
		}
		return l;
	}

	int up(long[] f, int l, int r, long k) {
		int R = r, m = 0;
		while (l <= r) {
			m = l + r >> 1;
		    if (m == R) return m;
		    if (f[m] > k) r = m - 1; else l = m + 1;
		}
		return l;
	}

	int lw(int[] f, int l, int r, int k) {
		int R = r, m = 0;
		while (l <= r) {
			m = l + r >> 1;
		    if (m == R) return m;
		    if (f[m] >= k) r = m - 1; else l = m + 1;
		}
		return l;
	}

	int up(int[] f, int l, int r, int k) {
		int R = r, m = 0;
		while (l <= r) {
			m = l + r >> 1;
		    if (m == R) return m;
		    if (f[m] > k) r = m - 1; else l = m + 1;
		}
		return l;
	}

	<K extends Comparable<K>> int lw(List<K> li, int l, int r, K k) {
		int R = r, m = 0;
		while (l <= r) {
			m = l + r >> 1;
		    if (m == R) return m;
		    if (li.get(m).compareTo(k) >= 0)
		    	r = m - 1;
		    else
		    	l = m + 1;
		}
		return l;
	}

	<K extends Comparable<K>> int up(List<K> li, int l, int r, K k) {
		int R = r, m = 0;
		while (l <= r) {
			m = l + r >> 1;
		    if (m == R) return m;
		    if (li.get(m).compareTo(k) > 0)
		    	r = m - 1;
		    else
		    	l = m + 1;
		}
		return l;
	}

	<K extends Comparable<K>> int bs(List<K> li, int l, int r, K k) {
		while (l <= r) {
			int m = l + r >> 1;
		    if (li.get(m) == k) return m;
		    else if (li.get(m).compareTo(k) < 0)
		    	l = m + 1;
		    else
		    	r = m - 1;
		}
		return -1;
	}

	long calc(int base, int exponent, int p) {
		if (exponent == 0) return 1;
		if (exponent == 1) return base % p;
		long m = calc(base, exponent >> 1, p);
		if (exponent % 2 == 0) return (m * m) % p;
		return 1l * base * m  % p * m % p;
	}

	long calc(int base, long exponent, int p) {
		if (exponent == 0) return 1;
		if (exponent == 1) return base % p;
		long m = calc(base, exponent >> 1, p);
		if (exponent % 2 == 0) return (m * m) % p;
		return 1l * base * m  % p * m % p;
	}

	long calc(long base, long exponent, int p) {
		if (exponent == 0) return 1;
		if (exponent == 1) return base % p;
		long m = calc(base, exponent >> 1, p);
		if (exponent % 2 == 0) return (m * m) % p;
		return base * m  % p * m % p;
	}

	long power(int base, int exponent) {
		if (exponent == 0) return 1;
		long m = power(base, exponent / 2);
		if (exponent % 2 == 0) return m * m;
		return base * m * m;
	}

	void swap(int[] a, int i, int j) {
		a[i] ^= a[j];
		a[j] ^= a[i];
		a[i] ^= a[j];
	}

	void swap(long[] a, int i, int j) {
		long tmp = a[i];
		a[i] = a[j];
		a[j] = tmp;
	}

	static class Pair<K extends Comparable<? super K>, V extends Comparable<? super V>>
			implements Comparable<Pair<K, V>> {
		private K k;
		private V v;

		Pair() {}

		Pair(K k, V v) {
			this.k = k;
			this.v = v;
		}

		K getK() { return k; }

		V getV() { return v; }

		void setK(K k) { this.k = k; }

		void setV(V v) { this.v = v; }

		void setKV(K k, V v) {
			this.k = k;
			this.v = v;
		}

		@SuppressWarnings("unchecked")
		@Override
		public boolean equals(Object o) {
			if (this == o) return true;
			if (o == null || !(o instanceof Pair)) return false;
			Pair<K, V> p = (Pair<K, V>) o;
			return k.compareTo(p.k) == 0 && v.compareTo(p.v) == 0;
		}

		@Override
		public int hashCode() {
			int hash = 31;
			hash = hash * 89 + k.hashCode();
			hash = hash * 89 + v.hashCode();
			return hash;
		}

		@Override
		public int compareTo(Pair<K, V> pair) {
			return k.compareTo(pair.k) == 0 ? v.compareTo(pair.v) : k.compareTo(pair.k);
		}

		@Override
		public Pair<K, V> clone() {
			return new Pair<K, V>(this.k, this.v);
		}

		@Override
		public String toString() {
			return String.valueOf(k).concat(" ").concat(String.valueOf(v)).concat("\n");
		}
	}

	static class Reader {
		private BufferedReader br;
		private StringTokenizer st;

		Reader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			try {
				while (st == null || !st.hasMoreTokens()) {
					st = new StringTokenizer(br.readLine());
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		int[] nextIntArray(int n) {
			int[] arr = new int[n];
			for (int i = 0; i < n; i++)
				arr[i] = nextInt();
			return arr;
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		String nextLine() {
			String s = "";
			try {
				s = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return s;
		}
	}
}


#include<stdio.h>

int main()
{
    int t, m;
    scanf("%d",&t);
    m=t-1;
    int arr[t];
    while(t--)
    {
    int n,x,a,b;
    scanf("%d%d%d%d",&n,&x,&a,&b);
    if(a>b)
    {
    if(n-a>=b)
    {
    if(x>=n-a)
    arr[t]=n-b;
    else
    arr[t]=(a+x)-b;
    }
    else
    {
    if(x>=b)
    arr[t]=a-1;
    else
    arr[t]=a-(b-x);
    }
    }
    else
    {
    if(n-b>=a)
    {
    if(x>=n-b)
    arr[t]=n-a;
    else
    arr[t]=(b+x)-a;
    }
    else
    {
    if(x>=a)
    arr[t]=b-1;
    else
    arr[t]=b-(a-x);
    }

    }
    }
    for(int i=m;i>=0;i--)
    printf("%d\n",arr[i]);
    return 0;
}


#include<stdio.h>

int main()
{
    int t, m;
    scanf("%d",&t);
    m=t-1;
    int arr[t];
    while(t--)
    {
    int n,x,a,b;
    scanf("%d%d%d%d",&n,&x,&a,&b);
    if(a>b)
    {
    if(n-a>=b)
    {
    if(x>=n-a)
    {
    a=n;
    x-=(n-a);
    if(x>=b)
    b=1;
    else
    b=b-x;
    arr[t]=a-b;
    }
    else
    arr[t]=(a+x)-b;
    }
    else
    {
    if(x>=b)
    {
    x-=(b-1);
    b=1;
    if(x>=n-a)
    a=n;
    else
    a=a+x;
    arr[t]=a-b;
    }
    else
    arr[t]=a-(b-x);
    }
    }
    //b>a
    else
    {
    if(n-b>=a)
    {
    if(x>=n-b)
    {
    b=n;
    x-=(n-b);
    if(x>=a)
    a=1;
    else
    a=a-x;
    arr[t]=b-a;

    }
    else
    arr[t]=(b+x)-a;
    }
    else
    {
    if(x>=a)
    {
    x-=(a-1);
    a=1;

    if(x>=n-b)
    b=n;
    else
    b=b+x;
    arr[t]=b-a;

    }
    else
    arr[t]=b-(a-x);
    }

    }
    }
    for(int i=m;i>=0;i--)
    printf("%d\n",arr[i]);
    return 0;
}


#include<stdio.h>

int main()
{
    int t, m;
    scanf("%d",&t);
    m=t-1;
    int arr[t];
    while(t--)
    {
    int n,x,a,b;
    scanf("%d%d%d%d",&n,&x,&a,&b);
    if(a>b)
    {
    if(n-a>=b)
    {
    if(x>=n-a)
    {
    a=n;
    x-=(n-a);
    if(x>=b)
    b=1;
    else
    b=b-x;
    arr[t]=a-b;
    }
    else
    arr[t]=(a+x)-b;
    }
    else
    {
    if(x>=b)
    {
    b=1;
    if(x>=n-a)
    a=n;
    else
    a=a+x;
    arr[t]=a-b;
    }
    else
    arr[t]=a-(b-x);
    }
    }
    //b>a
    else
    {
    if(n-b>=a)
    {
    if(x>=n-b)
    {
    b=n;
    x-=(n-b);
    if(x>=a)
    a=1;
    else
    a=a-x;
    arr[t]=b-a;

    }
    else
    arr[t]=(b+x)-a;
    }
    else
    {
    if(x>=a)
    {

    a=1;
    if(x>=n-b)
    b=n;
    else
    b=b+x;
    arr[t]=b-a;

    }
    else
    arr[t]=b-(a-x);
    }

    }
    }
    for(int i=m;i>=0;i--)
    printf("%d\n",arr[i]);
    return 0;
}


#include<stdio.h>
#include<stdlib.h>
int main()
{
    int t,i,n,x,a,b;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d%d%d",&n,&x,&a,&b);
        int m=abs(a-b);
        if(m+x<n)
            printf("%d\n",m+x);
        else
            printf("%d\n",n-1);
    }
    return 0;
}


#include<stdio.h>
#include<stdlib.h>
int main()
{
    int n,x,a,b,t,i,j,temp;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d%d%d",&n,&x,&a,&b);
        if(a-b==1 || b-a==1)
        {
            if(x!=0)
            {
                printf("%d\n",x+1);
            }
            else
            {
                int s=abs(a-b);
                printf("%d\n",s);
            }
        }
        else
            {
                int s=abs(a-b);
                printf("%d\n",s);
            }
    }
}


#include<stdio.h>
#include<stdlib.h>
int main()
{
    int n,x,a,b,t,i,j,temp;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d%d%d",&n,&x,&a,&b);
        if(a-b==1 || b-a==1)
        {
            if(x!=0 && x<=n)
            {
                printf("%d\n",x+1);
            }
            else
            {
                int s=abs(a-b);
                printf("%d\n",s);
            }
        }
        else
            {
                int s=abs(a-b);
                printf("%d\n",s);
            }
    }
}


#include<stdio.h>
main()
{
    int n,i,j,a,b,c,d,e,f;
    scanf("%d",&n);
    for(i=0; i<n; i++)
    {
        scanf("%d%d%d%d",&a,&b,&c,&d);
        e=abs(c-d)+b;
        f=a-1;

      if(e>=f)
      printf("%d\n",f);
      else
        printf("%d\n",e);

    }
}


#include<stdio.h>
main()
{
    int n,i,j,a,b,c,d,e,f;
    scanf("%d",&n);
    for(i=0; i<n; i++)
    {
        scanf("%d%d%d%d",&a,&b,&c,&d);
        e=abs(c-d)+b;
        f=a-1;

      if(e>=f)
      printf("%d",f);
      else
        printf("%d",e);

    }
}


#include<stdio.h>
#include<stdlib.h>

int main()
{
    int t, n, i, a, b, c, d, sum, dif;

    scanf("%d", &t);

    for(i=1; i<=t; i++)
    {

        scanf("%d %d %d %d", &a, &b, &c, &d);

        if( (c==a && d==1) || (d==a && c==1) )
        {

            printf("%d\n", a-1);
        }
        else if(c > d)
        {

            c+=b;

            if(c > a)
            {

                dif = c - a;
                c-=dif;

                if(dif > d)
                {

                    printf("%d\n", a-1);
                }
                else
                {

                    n = d - dif;

                    if(n==0){

                        n = 1;
                    }

                    printf("%d\n", abs(n-c));
                }

            }
            else
            {

                n = c - d;
                printf("%d\n", n);
            }
        }
        else
        {

            d+=b;

            if(d > a)
            {

                dif = d - a;
                d-=dif;

                if(dif > c)
                {

                    printf("%d\n", a-1);
                }
                else
                {

                    n = c - dif;

                    if(n==0){
                        n = 1;
                    }

                    printf("%d\n", abs(n-d));
                }

            }
            else
            {

                n = d - c;
                printf("%d\n", n);
            }
        }
    }

    return 0;
}


#include<stdio.h>
#include<stdlib.h>

int main()
{
    int t, n, i, a, b, c, d, sum, dif;

    scanf("%d", &t);

    for(i=1; i<=t; i++)
    {

        scanf("%d %d %d %d", &a, &b, &c, &d);

        if( (c==a && d==1) || (d==a && c==1) )
        {

            printf("%d\n", a-1);
        }
        else if(c > d)
        {

            c+=b;

            if(c > a)
            {

                dif = c - a;
                c-=dif;

                n = d+dif;

                printf("%d\n", abs(n-c));

            }
            else
            {

                n = c - d;
                printf("%d\n", n);
            }
        }
        else
        {

            d+=b;

            if(d > a)
            {

                dif = d - a;
                d-=dif;

                n = c+dif;

                printf("%d\n", abs(n-d));

            }
            else
            {

                n = d - c;
                printf("%d\n", n);
            }
        }
    }
}


#include<stdio.h>
#include<stdlib.h>

int main()
{
    int t, n, i, a, b, c, d, sum, dif;

    scanf("%d", &t);

    for(i=1; i<=t; i++)
    {

        scanf("%d %d %d %d", &a, &b, &c, &d);

        if( (c==a && d==1) || (d==a && c==1) )
        {

            printf("%d\n", a-1);
        }
        else if(c > d)
        {

            c+=b;

            if(c > a)
            {

                dif = c - a;
                c-=dif;

                if(dif > d)
                {

                    printf("%d\n", a-1);
                }
                else
                {

                    n = d - dif;

                    printf("%d\n", abs(n-c));
                }

            }
            else
            {

                n = c - d;
                printf("%d\n", n);
            }
        }
        else
        {

            d+=b;

            if(d > a)
            {

                dif = d - a;
                d-=dif;

                if(dif > c)
                {

                    printf("%d\n", a-1);
                }
                else
                {

                    n = c - dif;

                    printf("%d\n", abs(n-d));
                }

            }
            else
            {

                n = d - c;
                printf("%d\n", n);
            }
        }
    }
}


#include<stdio.h>
#include<stdlib.h>

int main()
{
    int t, n, i, a, b, c, d, sum, dif;

    scanf("%d", &t);

    for(i=1; i<=t; i++)
    {

        scanf("%d %d %d %d", &a, &b, &c, &d);

        if( (c==a && d==1) || (d==a && c==1) )
        {

            printf("%d\n", a-1);
        }
        else if(c > d)
        {

            c+=b;

            if(c > a)
            {

                dif = c - a;
                c-=dif;

                n = abs(d - dif);

                printf("%d\n", abs(n-c));

            }
            else
            {

                n = c - d;
                printf("%d\n", n);
            }
        }
        else
        {

            d+=b;

            if(d > a)
            {

                dif = d - a;
                d-=dif;

                n = abs(c - dif);

                printf("%d\n", abs(n-d));

            }
            else
            {

                n = d - c;
                printf("%d\n", n);
            }
        }
    }
}


#include<stdio.h>
int main()
{
    int t,n,x,a,b,dis;
    scanf("%d",&t);
    while(n>0)
    {
        scanf("%d%d%d%d",&n,&x,&a,&b);
        dis=a-b;
        if(dis<0)
            dis=dis*(-1);
        if(dis+x>n-1)
            printf("%d\n",n-1);
        else
            printf("%d\n",dis+x);
        t--;
    }
    return 0;
}


#include<stdio.h>
int main()
{
    int t,n,x,a,b,dis;
    scanf("%d",&t);
    while(n>0)
    {
        scanf("%d%d%d%d",&n,&x,&a,&b);
        dis=a-b;
        if(dis<0)
            dis=dis*(-1);
        dis=dis+x;
        if(dis>n-1)
            printf("%d\n",n-1);
        else
            printf("%d\n",dis);
        t--;
    }
    return 0;
}


#include<stdio.h>
#include<math.h>
int main()
{
    int t,n,x,a,b,dis;
    scanf("%d",&t);
    while(t>0)
    {
        scanf("%d%d%d%d",&n,&x,&a,&b);
        dis=abs(a-b);
        if(dis+x>n-1)
            printf("%d\n",n-1);
        else
            printf("%d\n",dis+x);
        t--;
    }
    return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int abs(int );

int main(int argc, char *argv[])
{
	int num,i,n,x,a,b;

	scanf("%d",&num);
	for(i=0;i<num;i++)
	{
		scanf("%d %d %d %d",&n,&x,&a,&b);
		if(abs(a-b)+x<n-1)
			printf("%d",abs(a-b+x));
		else
			printf("%d",abs(n-1));
		if(i!=num-1)
			printf("\n");
	}
}

int abs(int n)
{
	if(n>0)
		return n;
	else
		return -n;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int abs(int );

int main(int argc, char *argv[])
{
	int num,i,n,x,a,b;

	scanf("%d",&num);
	for(i=0;i<num;i++)
	{
		scanf("%d %d %d %d",&n,&x,&a,&b);
		if(a-b+x<n-1)
			printf("%d",abs(a-b+x));
		else
			printf("%d",abs(n-1));
		if(i!=num-1)
			printf("\n");
	}
}

int abs(int n)
{
	if(n>0)
		return n;
	else
		return -n;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int abs(int );

int main(int argc, char *argv[])
{
	int num,i,n,x,a,b;

	scanf("%d",&num);
	for(i=0;i<num;i++)
	{
		scanf("%d %d %d %d",&n,&x,&a,&b);
		if(abs(a-b+x)<n-1)
			printf("%d",abs(a-b+x));
		else
			printf("%d",abs(n-1));
		if(i!=num-1)
			printf("\n");
	}
}

int abs(int n)
{
	if(n>0)
		return n;
	else
		return -n;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int abs(int );

int main(int argc, char *argv[])
{
	int num,i,n,x,a,b;

	scanf("%d",&num);
	for(i=0;i<num;i++)
	{
		scanf("%d %d %d %d",&n,&x,&a,&b);
		if(abs(a-b)+x<n-1)
			printf("%d",abs(a-b)+x);
		else
			printf("%d",abs(n-1));
		if(i!=num-1)
			printf("\n");
	}
}

int abs(int n)
{
	if(n>0)
		return n;
	else
		return -n;
}


#include<stdio.h>
#include<stdlib.h>
int main()
{
    int t;
    scanf("%d",&t);
    for(int i=0;i<t;i++)
    {
        int n,s,a,b;
        scanf("%d%d%d%d",&n,&s,&a,&b);
        int diff=abs(a-b);
        if(a<=b)
        {
        }
        else
        {
            int temp=a;
//		printf("max is %d\n",max);
            a=b;
//		printf("b is %d\n",b);
            b=temp;
//		printf("a is %d\n",a);
        }
//	printf("%d\n",a);
//	printf("%d\n",b);
        int q=abs(n-b);
//	printf("%d\n",q);
//		printf("yes\n");
            if(q>=s)
		{
                diff=diff+s;
		s=0;
		}
            else if(q<n)
		{
                diff=diff+q;
		s=s-q;
		}

            if(a>s)
                diff=diff+s;
            else if(a>1)
                diff=diff+a-1;
        printf("%d\n",diff);

    }
}


#include<stdio.h>
#include<stdlib.h>
int main()
{
    int t;
    scanf("%d",&t);
    for(int i=0;i<t;i++)
    {
        int n,s,a,b;
        scanf("%d%d%d%d",&n,&s,&a,&b);
        int diff=abs(a-b);
//      printf("diff is %d\n",diff);
        if(a<=b)
        {
        }
        else
        {
            int temp=a;
//              printf("max is %d\n",max);
            a=b;
//              printf("b is %d\n",b);
            b=temp;
//              printf("a is %d\n",a);
        }
//      printf("%d\n",a);
//      printf("%d\n",b);
        int q=abs(n-b);
//      printf("%d\n",q);
        if(q>=a)
        {
//              printf("yes\n");
            if(q>=s)
                diff=diff+s;
            else if(q<n)
                diff=diff+q;
        }
        else
        {
            if(a>=s)
                diff=diff+s;
            else if(a>1)
                diff=diff+a;
        }
        printf("%d\n",diff);

    }
}

-- INSERT --


#include<stdio.h>
#include<stdlib.h>
int main()
{
    int t;
    scanf("%d",&t);
    for(int i=0;i<t;i++)
    {
        int n,s,a,b;
        scanf("%d%d%d%d",&n,&s,&a,&b);
        int diff=abs(a-b);
//	printf("diff is %d\n",diff);
        if(a<=b)
        {
        }
        else
        {
            int temp=a;
//		printf("max is %d\n",max);
            a=b;
//		printf("b is %d\n",b);
            b=temp;
//		printf("a is %d\n",a);
        }
//	printf("%d\n",a);
//	printf("%d\n",b);
        int q=abs(n-b);
//	printf("%d\n",q);
        if(q>=a)
        {
//		printf("yes\n");
            if(q>=s)
                diff=diff+s;
            else if(q<n)
                diff=diff+q;

        }
        else
        {
            if(a>=s)
                diff=diff+s;
            else if(a>1)
                diff=diff+a;
        }
        printf("%d\n",diff);

    }
}


#include<stdio.h>
#include<stdlib.h>
int main()
{
    int t;
    scanf("%d",&t);
    for(int i=0;i<t;i++)
    {
        int n,s,a,b;
        scanf("%d%d%d%d",&n,&s,&a,&b);
        int diff=abs(a-b);
        if(a<=b)
        {
        }
        else
        {
            int temp=a;
//		printf("max is %d\n",max);
            a=b;
//		printf("b is %d\n",b);
            b=temp;
//		printf("a is %d\n",a);
        }
//	printf("%d\n",a);
//	printf("%d\n",b);
        int q=abs(n-b);
//	printf("%d\n",q);
//		printf("yes\n");
            if(q>=s)
		{
                diff=diff+s;
		s=0;
		}
            else if(q<n)
		{
                diff=diff+q;
		s=s-q;
		}

            if(a>=s)
                diff=diff+s;
            else if(a>1)
                diff=diff+a-1;
        printf("%d\n",diff);

    }
}


#include<stdio.h>
#include<stdlib.h>
int main()
{
    int t;
    scanf("%d",&t);
    for(int i=0;i<t;i++)
    {
        int n,s,a,b;
        scanf("%d%d%d%d",&n,&s,&a,&b);
        int diff=abs(a-b);
        if(a<=b)
        {
        }
        else
        {
            int temp=a;
//		printf("max is %d\n",max);
            a=b;
//		printf("b is %d\n",b);
            b=temp;
//		printf("a is %d\n",a);
        }
//	printf("%d\n",a);
//	printf("%d\n",b);
        int q=abs(n-b);
//	printf("%d\n",q);
//		printf("yes\n");
            if(q>=s)
		{
                diff=diff+s;
		s=0;
		}
            else if(q<n)
		{
                diff=diff+q;
		s=s-q;
		}

            if(a>=s)
                diff=diff+s;
            else if(a>1)
                diff=diff+a;
        printf("%d\n",diff);

    }
}


#include<stdio.h>
#include<math.h>
int main()
{
    int t,n,x,a,b,c,d,e;
 	scanf("%d",&t);
 	for(int i=0;i<n;i++)
{
  	scanf("%d%d%d%d",&n,&x,&a,&b);
  	c= abs(a-b);
  	d=x+c;
  	if(d>=n)
   		printf("%d\n",n-1);
  	else
   		printf("%d\n",d);
 }
    return 0;
}


#include<stdio.h>
#include<math.h>
int main()
{
    int t,n,x,a,b,c,d,e;
 	scanf("%d",&t);
 	for(int i=0;i<t;i++)
{
  	scanf("%d%d%d%d",&n,&x,&a,&b);
  	c= abs(a-b);
  	d=x+c;
  	if(d>=n)
   		printf("%d\n",n-1);
  	else
   		printf("%d\n",d);
 }
    return 0;
}


// Don't look here. Just some reading API
function onReadable(a,b,c){return()=>{const d=a.read();d&&(b.val=Buffer.concat([b.val,d]));let e=b.val.indexOf("\n");if(d||(e=b.val.length),-1!==e){const a=b.val.slice(0,e);return b.val=b.val.slice(e+1),c(a.toString("utf-8"))}return a.once("readable",onReadable(a,b,c))}}
function IO(a,b){const c={val:Buffer.from([])};return{async rl(){const b=c.val.indexOf("\n");if(-1!==b){const a=c.val.slice(0,b);return c.val=c.val.slice(b+1),a.toString("ascii")}return new Promise(b=>a.once("readable",onReadable(a,c,b)))},wr(a){return b.write(a)},wl(a){return b.write(a+"\n")}}}
(async()=>{const a=IO(process.stdin,process.stdout);return sol(a)})();

async function sol({ rl, wr, wl }) {
  const t = Number(await rl());

  for(let i = 0; i < t; i += 1) {
    let [n, x, a, b] = (await rl()).split(' ').map(Number);

    if (b < a) { [b, a] = [a, b]; }

    wl(Math.min(a + (n - b) + (b - a) - 1, (b - a) + x));
  }
}


process.stdin.resume()
process.stdin.setEncoding('utf-8')

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  const t = parseInt(arr.shift())

  for(let i = 0; i < t; i++) {
    const arrT = arr[i].split(' ').map(a => parseInt(a))
    const n = arrT[0]
    let x = arrT[1]
    let a = arrT[2]
    let b = arrT[3]

    if(x == 0) {
      console.log(Math.abs(a - b))
    }

    else {
      if(a > b) {
        const temp = a
        a = b
        b = temp
      }
      if(a - x < 1){
        a = 1
        x = x - (a - 1)

        if(b + x >= n) b = n
      }
      else {
        a = a - x
        // console.log('sf')
      }
      console.log(Math.abs(a - b))
    }
  }
})


process.stdin.resume()
process.stdin.setEncoding('utf-8')

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  const t = parseInt(arr.shift())

  for(let i = 0; i < t; i++) {
    const arrT = arr[i].split(' ').map(a => parseInt(a))
    const n = arrT[0]
    let x = arrT[1]
    let a = arrT[2]
    let b = arrT[3]

    if(x == 0) {
      console.log(Math.abs(a - b))
    }

    else {
      if(a > b) {
        const temp = a
        a = b
        b = temp
      }
      if((a - x) < 1){
        x = x - a + 1
        a = 1

        if(b + x >= n) b = n
        else b = b + x
        // console.log(a,b)
      }
      else {
        a = a - x
        // console.log('sf')
      }
      console.log(Math.abs(a - b))
    }
  }
})


process.stdin.resume()
process.stdin.setEncoding('utf-8')

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  const t = parseInt(arr.shift())

  for(let i = 0; i < t; i++) {
    const arrT = arr[i].split(' ').map(a => parseInt(a))
    const n = arrT[0]
    let x = arrT[1]
    let a = arrT[2]
    let b = arrT[3]

    if(x == 0) {
      console.log(Math.abs(a - b))
    }

    else {
      if(a > b) {
        const temp = a
        a = b
        b = temp
      }
      if(a - x < 1){
        a = 1
        x = x - (a - 1)

        if(b + x >= n) b = n
        else b = b + x
      }
      else {
        a = a - x
        // console.log('sf')
      }
      console.log(Math.abs(a - b))
    }
  }
})


//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var one = nextIntArray();
    var n = one[0];
    var x = one[1];
    var a = one[2];
    var b = one[3];
    output[i] = Math.min(n - 1, Math.abs(a - b) + x);
  }
  myout(myconv(output, 9));
}


const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  const [n, x, a, b] = d.split(' ').map(Number);
  const min = Math.min(a, b);
  const max = Math.max(a, b);
  const ans = Math.min(n - 1, max - min + x);

  console.log(ans);
  c++;
});


const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  const [n, x, a, b] = d.split(' ').map(Number);
  const min = Math.min(a, b);
  const max = Math.max(a, b);
  const ans = Math.min(99, max - min + x);

  console.log(ans);
  c++;
});


'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

// thats all what you have to write to get input from stdin, using readLine.

// Main code runs in main();

function main() {
    const t = +readline();
    for (let i = 0; i < t; i++) {
        const [n, x, a, b] = readline().split(" ").map(x => parseInt(x));
        console.log(students(n, x, a, b));
    }
}

const students = (n, x, a, b) => {
    let p1 = Math.min(a, b);
    let p2 = Math.max(a, b);
    while (x) {
        if (p1 > 1) {
            --p1;
        } else if (p2 < n) {
            ++p2;
        }
        --x;
    }
    return p2 - p1;
}


let fs = require('fs');
let txt = fs.readFileSync(0, 'utf-8').split("\r\n");
txt.forEach((data) => {
    let info = data.split(" ").filter(data => {
        return data.length > 0
    })
    rival(info[0] * 1, info[1] * 1, info[2] * 1, info[3] * 1);
})

function rival(n, x, a, b) {
    if(b>a){
        let i=a;
        a=b;
        b=i;
    }
    while (x > 0) {
        if (a + 1 <= n) {
            ++a;
        } else if (b - 1 > 0) {
            --b;
        } else {
            break;
        }
        --x;
    }

    console.log(Math.abs(a - b));

}


let fs=require('fs');
let txt=fs.readFileSync(0,'utf-8').split("\r\n");
txt.forEach((data)=>{
     rival(data.split(" ").filter(data=>{return data.length>0}).map(data=>{return data*1}));
})

function rival(arr){
     let smallest=Infinity;
     arr.forEach(data=>{
          arr.forEach(data1=>{
               if(Math.abs(data-data1)>0 && Math.abs(data-data1)<smallest){
                    smallest=Math.abs(data-data1);
               }
          })
     })
     console.log(smallest)
}


let fs = require('fs');
let txt = fs.readFileSync(0, 'utf-8').split("\r\n");
txt.shift()
txt.forEach((data) => {
    let info = data.split(" ").filter(data => {
        return data.length > 0
    })
    rival(info[0] * 1, info[1] * 1, info[2] * 1, info[3] * 1);
})

function rival(n, x, a, b) {
    if(b>a){
        let i=a;
        a=b;
        b=i;
    }
    while (x > 0) {
        if (a + 1 <= n) {
            ++a;
        } else if (b - 1 > 0) {
            --b;
        } else {
            break;
        }
        --x;
    }

    console.log(Math.abs(a - b));

}


let fs = require('fs');
let txt = fs.readFileSync(0, 'utf-8').split("\r\n");
txt.shift()
txt.forEach((data) => {
    let info = data.split(" ")
    rival(info[0] * 1, info[1] * 1, info[2] * 1, info[3] * 1);
})

function rival(n, x, a, b) {
    while (x > 0) {
        if (a + 1 <= n) {
            ++a;
        } else if (b - 1 > 0) {
            --b;
        } else {
            break;
        }
        --x;
    }

    console.log(Math.abs(a - b));

}


let fs=require('fs');
let txt=fs.readFileSync(0,'utf-8').split("\r\n");
txt.forEach((data)=>{
    let info=data.split(" ").filter(data=>{return data.length>0})
     rival(info[0]*1,info[1]*1,info[2]*1,info[3]*1);
})

function rival(n,x,a,b){
    while (x>0) {
        if(a+1<=n){
            ++a;
            --x;
        }else if(b-1>0){
            --b;
            --x;
        }else{
            break;
        }
    }

     console.log(Math.abs(a-b));

}


let fs = require('fs');
let txt = fs.readFileSync(0, 'utf-8').split("\r\n");
txt.shift()
txt.forEach((data) => {
    let info = data.split(" ")
    rival(info[0] * 1, info[1] * 1, info[2] * 1, info[3] * 1);
})

function rival(n, x, a, b) {
     if(b>a){
          let i=a;
          a=b;
          b=i;
     }
    while (x > 0) {
        if (a + 1 <= n) {
            ++a;
        } else if (b - 1 > 0) {
            --b;
        } else {
            break;
        }
        --x;
    }

    console.log(Math.abs(a - b));

}


let fs = require('fs');
let txt = fs.readFileSync(0, 'utf-8').split("\r\n").filter(data=>{return data.length>0});
txt.shift()
txt.forEach((data) => {
    let info = data.split(" ")
    rival(info[0] * 1, info[1] * 1, info[2] * 1, info[3] * 1);
})

function rival(n, x, a, b) {
    if(b>a){
        let i=a;
        a=b;
        b=i;
    }
    while (x > 0) {
        if (a + 1 <= n) {
            ++a;
        } else if (b - 1 > 0) {
            --b;
        } else {
            break;
        }
        --x;
    }

    console.log(Math.abs(a - b));

}


let fs=require('fs');
let txt=fs.readFileSync(0,'utf-8').split("\r\n");
txt.forEach((data)=>{
     rival(data.split(" ").filter(data=>{return data.length>0}).map(data=>{return data*1}));
})

function rival(arr){
     let smallest=-Infinity;
     arr.forEach(data=>{
          arr.forEach(data1=>{
               if(Math.abs(data-data1)>smallest){
                    smallest=Math.abs(data-data1);
               }
          })
     })
     console.log(smallest);

     return smallest;
}


const fs = require('fs');
const stdinBuffer = fs.readFileSync(0);
const inputString = stdinBuffer.toString();

const [_, ...data] = inputString.split('\n');

function find(dataString) {
  const [n, x, a, b] = dataString.split(' ').map(x => { return parseInt(x, 10) });
  const maxLeft = Math.min(a,b) - 1, maxRight = n - Math.max(a,b);
  const max = maxLeft + maxRight;
  console.log(n, x, a, b, maxRight, maxLeft, max);

  return Math.min(max, x) + Math.abs(b - a);
}

process.stdout.write(`${data.map(find).join('\n')}`);


const fs = require('fs');
const stdinBuffer = fs.readFileSync(0);
const inputString = stdinBuffer.toString();

const [count, ...data] = inputString.split('\n');

data.length = parseInt(count, 10);

function find(dataString) {
  const [n, x, a, b] = dataString.split(' ').map(x => { return parseInt(x, 10) });
  const maxLeft = Math.min(a,b) - 1, maxRight = n - Math.max(a,b);
  const max = maxLeft + maxRight;

  return Math.min(max, x) + Math.abs(b - a);
}

process.stdout.write(`${data.map(find).join('\n')}`);


let data = '';
process.stdin.on('data', c => data += c);

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	let t = nl.num();
  let ans = [];
  for(let i = 0; i < t; i++){
    let [n, x, a, b] = nl.nums();
    let ab = Math.abs(a - b);
    ans.push((ab + x > n - 1)?n-1:ab + x);
  }
	console.log(ans.join('\n'));

};

process.stdin.on('end', sol);


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using static System.Console;
using static System.Convert;
using static System.Math;
using static Template;
using SC = Scanner;

public partial class Solver
{
    public void Solve()
    {
        int n, x, a, b;
        sc.Make(out n, out x, out a, out b);a--;b--;
        if (a > b) swap(ref a, ref b);
        if (a < x) { x -= a;a = 0; }
        else { a -= x; x = 0; }

        if ((n - 1 - b) < x) { b = n - 1; }
        else { b += x; }
        Console.WriteLine(b-a);

    }
}

#region Template
public partial class Solver
{
    public SC sc = new SC();
    static void Main(string[] args)
    {
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        var sol = new Solver();
        int testcase = 1;
        testcase = sol.sc.Int;
        //var th = new Thread(sol.Solve, 1 << 26);th.Start();th.Join();
        while (testcase-- > 0)
            sol.Solve();
        Console.Out.Flush();
    }
}
public static class Template
{
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmin<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) > 0) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmax<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) < 0) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(ref T a, ref T b) { var t = b; b = a; a = t; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(this IList<T> A, int i, int j) { var t = A[i]; A[i] = A[j]; A[j] = t; }
    public static T[] Create<T>(int n, Func<T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(); return rt; }
    public static T[] Create<T>(int n, Func<int, T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(i); return rt; }
    public static void Out<T>(this IList<T> A, out T a) => a = A[0];
    public static void Out<T>(this IList<T> A, out T a, out T b) { a = A[0]; b = A[1]; }
    public static void Out<T>(this IList<T> A, out T a, out T b, out T c) { A.Out(out a, out b); c = A[2]; }
    public static void Out<T>(this IList<T> A, out T a, out T b, out T c, out T d) { A.Out(out a, out b, out c); d = A[3]; }
    public static string Concat<T>(this IEnumerable<T> A, string sp) => string.Join(sp, A);
    public static char ToChar(this int s, char begin = '0') => (char)(s + begin);
    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> A) => A.OrderBy(v => Guid.NewGuid());
    public static int CompareTo<T>(this T[] A, T[] B, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; for (var i = 0; i < Min(A.Length, B.Length); i++) { int c = cmp(A[i], B[i]); if (c > 0) return 1; else if (c < 0) return -1; } if (A.Length == B.Length) return 0; if (A.Length > B.Length) return 1; else return -1; }
    public static string ToStr<T>(this T[][] A) => A.Select(a => a.Concat(" ")).Concat("\n");
    public static int ArgMax<T>(this IList<T> A, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; T max = A[0]; int rt = 0; for (int i = 1; i < A.Count; i++) if (cmp(max, A[i]) < 0) { max = A[i]; rt = i; } return rt; }
    public static T PopBack<T>(this List<T> A) { var v = A[A.Count - 1]; A.RemoveAt(A.Count - 1); return v; }
    public static void Fail<T>(T s) { Console.WriteLine(s); Console.Out.Close(); Environment.Exit(0); }
}
public class Scanner
{
    public string Str => Console.ReadLine().Trim();
    public int Int => int.Parse(Str);
    public long Long => long.Parse(Str);
    public double Double => double.Parse(Str);
    public int[] ArrInt => Str.Split(' ').Select(int.Parse).ToArray();
    public long[] ArrLong => Str.Split(' ').Select(long.Parse).ToArray();
    public char[][] Grid(int n) => Create(n, () => Str.ToCharArray());
    public int[] ArrInt1D(int n) => Create(n, () => Int);
    public long[] ArrLong1D(int n) => Create(n, () => Long);
    public int[][] ArrInt2D(int n) => Create(n, () => ArrInt);
    public long[][] ArrLong2D(int n) => Create(n, () => ArrLong);
    private Queue<string> q = new Queue<string>();
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public T Next<T>() { if (q.Count == 0) foreach (var item in Str.Split(' ')) q.Enqueue(item); return (T)Convert.ChangeType(q.Dequeue(), typeof(T)); }
    public void Make<T1>(out T1 v1) => v1 = Next<T1>();
    public void Make<T1, T2>(out T1 v1, out T2 v2) { v1 = Next<T1>(); v2 = Next<T2>(); }
    public void Make<T1, T2, T3>(out T1 v1, out T2 v2, out T3 v3) { Make(out v1, out v2); v3 = Next<T3>(); }
    public void Make<T1, T2, T3, T4>(out T1 v1, out T2 v2, out T3 v3, out T4 v4) { Make(out v1, out v2, out v3); v4 = Next<T4>(); }
    public void Make<T1, T2, T3, T4, T5>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5) { Make(out v1, out v2, out v3, out v4); v5 = Next<T5>(); }
    public void Make<T1, T2, T3, T4, T5, T6>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6) { Make(out v1, out v2, out v3, out v4, out v5); v6 = Next<T6>(); }
    public void Make<T1, T2, T3, T4, T5, T6, T7>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6, out T7 v7) { Make(out v1, out v2, out v3, out v4, out v5, out v6); v7 = Next<T7>(); }
    public (T1, T2) Make<T1, T2>() { Make(out T1 v1, out T2 v2); return (v1, v2); }
    public (T1, T2, T3) Make<T1, T2, T3>() { Make(out T1 v1, out T2 v2, out T3 v3); return (v1, v2, v3); }
    public (T1, T2, T3, T4) Make<T1, T2, T3, T4>() { Make(out T1 v1, out T2 v2, out T3 v3, out T4 v4); return (v1, v2, v3, v4); }
}

#endregion


using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        int n = int.Parse(Console.ReadLine());
        int[][] v = new int[n][];
        for (int i = 0; i < n; i++)
        {
            v[i] = Array.ConvertAll(Console.ReadLine().Split(' '), x => int.Parse(x));
        }
        for (int i = 0; i < n; i++)
        {
            int mxDiff = v[i][0] - 1;
            int curDiff = Math.Abs(v[i][2] - v[i][3]);
            int noSwp = v[i][1];
            if (curDiff == mxDiff)
            {
                Console.WriteLine(curDiff);
            }
            else
            {
                Console.WriteLine(curDiff + noSwp);
            }
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        int n = int.Parse(Console.ReadLine());
        int[][] v = new int[n][];
        for (int i = 0; i < n; i++)
        {
            v[i] = Array.ConvertAll(Console.ReadLine().Split(' '), x => int.Parse(x));
        }
        for (int i = 0; i < n; i++)
        {
            int mxDiff = v[i][0] - 1;
            int curDiff = Math.Abs(v[i][2] - v[i][3]);
            int noSwp = v[i][1];
            if (curDiff == mxDiff)
            {
                Console.WriteLine(curDiff);
            }
            else
            {
                Console.WriteLine(((curDiff + noSwp) > mxDiff) ? mxDiff :curDiff + noSwp);
            }
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CF
{
    class Program
    {
        static void Main(string[] args)
        {
            new Program().run();
        }

        void run()
        {
            int n = ReadInt()[0];
            while(n != 0)
            {
                int[] arr = ReadInt();

                int num = arr[0];
                int c = arr[1];
                int a = arr[2], b = arr[3];

                int l = Math.Min(a, b);
                int r = Math.Max(a, b);

                int ml = l - 1;
                int mr = num - r;

                int add = Math.Min(c, ml + mr);

                Console.WriteLine(add + (r - l));

                n--;
            }
        }

        int[] ReadInt()
        {
            return Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
        }

        long[] ReadLong()
        {
            return Console.ReadLine().Split(' ').Select(long.Parse).ToArray();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace A
{
    class Program
    {
        static void Main(string[] args)
        {
          int t = Convert.ToInt32(Console.ReadLine());
            int n, x, a, b;

            for (int i = 0; i < t; i++)
            {
                string[] s = (Console.ReadLine().Split(' '));
                n = Convert.ToInt32(s[0]);
                x = Convert.ToInt32(s[1]);
                a = Convert.ToInt32(s[2]);
                b = Convert.ToInt32(s[3]);
                for (int g = 0; g < x; g++)
                {
                    if (b > a)
                    {
                        if (b < n)
                            b++;
                        else
                            if (a> 1)
                            a--;
                    }
                    else
                    {
                        if (a < n)
                            a++;
                        else
                            if(b>1)
                            b--;
                    }

                }
                Console.WriteLine(Math.Abs(a - b));

            }

        }
    }
}


<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{CC4D3703-486F-48AC-B808-33D996E21FDA}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <RootNamespace>A</RootNamespace>
    <AssemblyName>A</AssemblyName>
    <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <Deterministic>true</Deterministic>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Data" />
    <Reference Include="System.Net.Http" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Include="App.config" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace codeforces
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.SetIn(new StreamReader("input.txt"));
            int count = int.Parse(Console.ReadLine());
            string rez = "";
            for (int i = 0; i < count; i++)
            {
                int[] numbers = Console.ReadLine().Split().Select(int.Parse).ToArray() ;
                int n = numbers[0], x = numbers[1], a = numbers[2], b = numbers[3];
                int r;
                rez += (r = Math.Abs(a - b) + x) < n - 1 ? r : n - 1;
                rez += Environment.NewLine;

            }

            Console.WriteLine(rez);
            //Console.ReadKey();
        }
    }
}


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace codeforces
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.SetIn(new StreamReader("input.txt"));
            int count = int.Parse(Console.ReadLine());
            string rez = "";
            for (int i = 0; i < count; i++)
            {
                int[] numbers = Console.ReadLine().Split().Select(int.Parse).ToArray() ;
                int n = numbers[0], x = numbers[1], a = numbers[2], b = numbers[3];
                int r;
                rez += (r = Math.Abs(a - b + x)) < n - 1 ? r : n - 1;
                rez += Environment.NewLine;

            }

            Console.WriteLine(rez);
            //Console.ReadKey();
        }
    }
}


using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Numerics;

namespace cfe76
{
    class Program
    {
        static void Main(string[] args)
        {
           //Console.SetIn(new StreamReader("input.txt"));
            solve_cfe76A();
        }

        public static void solve_cfe76B()
        {
        }

        public static void solve_cfe76A()
        {
            int t = Convert.ToInt32(Console.ReadLine());

            for (int i = 0; i < t; i++)
            {
                int[] nxab = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);

                int n = nxab[0];
                int x = nxab[1];
                int a = nxab[2];
                int b = nxab[3];

                if (a > b)
                {
                    int temp = a;
                    a = b;
                    b = temp;
                }

                if (x > a)
                {
                    x = a > 1 ? x - a + 1 : x;
                    a = 1;
                }
                else if (x == a)
                {
                    a = 1;
                    x = 1;
                }
                else
                {
                    a = a - x;
                    x = 0;
                }

                b = b + x <= n ? b + x : n;

                Console.WriteLine(Math.Abs(a - b));
            }
        }
    }
}


using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Numerics;

namespace cfe76
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.SetIn(new StreamReader("input.txt"));
            solve_cfe76A();
        }

        public static void solve_cfe76B()
        {
        }

        public static void solve_cfe76A()
        {
            int t = Convert.ToInt32(Console.ReadLine());

            for (int i = 0; i < t; i++)
            {
                int[] nxab = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);

                int n = nxab[0];
                int x = nxab[1];
                int a = nxab[2];
                int b = nxab[3];

                if (a > b)
                {
                    int temp = a;
                    a = b;
                    b = temp;
                }

                if (x > a)
                {
                    a = 1;
                    x = a > 1 ? x - (x - a) : x;
                }
                else if (x == a)
                {
                    a = 1;
                    x = 1;
                }
                else
                {
                    a = a - x;
                    x = 0;
                }

                b += b + x <= n ? x : n;

                Console.WriteLine(Math.Abs(a - b));
            }
        }
    }
}


using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Numerics;

namespace cfe76
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.SetIn(new StreamReader("input.txt"));
            solve_cfe76A();
        }

        public static void solve_cfe76B()
        {
        }

        public static void solve_cfe76A()
        {
            int t = Convert.ToInt32(Console.ReadLine());

            for (int i = 0; i < t; i++)
            {
                int[] nxab = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);

                int n = nxab[0];
                int x = nxab[1];
                int a = nxab[2];
                int b = nxab[3];

                if (a > b)
                {
                    int temp = a;
                    a = b;
                    b = temp;
                }

                if (x > a)
                {
                    a = 1;
                    x -= a > 1 ? x - a : 0;
                }
                else if (x == a)
                {
                    a = 1;
                    x = 0;
                }
                else
                {
                    a = a - x;
                    x = 0;
                }

                b += b < n ? x : 0;

                Console.WriteLine(Math.Abs(a - b));
            }
        }
    }
}


using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Numerics;

namespace cfe76
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.SetIn(new StreamReader("input.txt"));
            solve_cfe76A();
        }

        public static void solve_cfe76B()
        {
        }

        public static void solve_cfe76A()
        {
            int t = Convert.ToInt32(Console.ReadLine());

            for (int i = 0; i < t; i++)
            {
                int[] nxab = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);

                int n = nxab[0];
                int x = nxab[1];
                int a = nxab[2];
                int b = nxab[3];

                if (a > b)
                {
                    int temp = a;
                    a = b;
                    b = temp;
                }

                if (x > a)
                {
                    x = a > 1 ? x - (x - a) : x;
                    a = 1;
                }
                else if (x == a)
                {
                    a = 1;
                    x = 1;
                }
                else
                {
                    a = a - x;
                    x = 0;
                }

                b = b + x <= n ? b + x : n;

                Console.WriteLine(Math.Abs(a - b));
            }
        }
    }
}


using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Numerics;

namespace cfe76
{
    class Program
    {
        static void Main(string[] args)
        {
            // /Console.SetIn(new StreamReader("input.txt"));
            solve_cfe76A();
        }

        public static void solve_cfe76B()
        {
        }

        public static void solve_cfe76A()
        {
            int t = Convert.ToInt32(Console.ReadLine());

            for (int i = 0; i < t; i++)
            {
                int[] nxab = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);

                int n = nxab[0];
                int x = nxab[1];
                int a = nxab[2];
                int b = nxab[3];

                if (a > b)
                {
                    int temp = a;
                    a = b;
                    b = temp;
                }

                if (x > a)
                {
                    a = 1;
                    x = a > 1 ? x - (x - a) : x;
                }
                else if (x == a)
                {
                    a = 1;
                    x = 1;
                }
                else
                {
                    a = a - x;
                    x = 0;
                }

                b += b < n ? x : 0;

                Console.WriteLine(Math.Abs(a - b));
            }
        }
    }
}


using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Numerics;

namespace cfe3
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.SetIn(new StreamReader("input.txt"));
            solve_cfe3();
        }

        public static void solve_cfe3()
        {
            int[] nm = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
            int n = nm[0];
            int m = nm[1];
            int[] a = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);

            int[] g = new int[m];

            for (int i = 0; i < n; i++)
            {
                g[a[i] - 1]++;
            }

            int cnt = 0;
            for (int i = 0; i < m; i++)
            {
                int p = 0;
                for (int j = i + 1; j < m; j++)
                {
                    p += g[i] * g[j];
                }
                cnt += p;
            }

            Console.WriteLine(cnt);
        }
    }
}


using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Numerics;

namespace cfe76
{
    class Program
    {
        static void Main(string[] args)
        {
            // /Console.SetIn(new StreamReader("input.txt"));
            solve_cfe76A();
        }

        public static void solve_cfe76B()
        {
        }

        public static void solve_cfe76A()
        {
            int t = Convert.ToInt32(Console.ReadLine());

            for (int i = 0; i < t; i++)
            {
                int[] nxab = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);

                int n = nxab[0];
                int x = nxab[1];
                int a = nxab[2];
                int b = nxab[3];

                if (a > b)
                {
                    int temp = a;
                    a = b;
                    b = temp;
                }

                if (x > a)
                {
                    x = a > 1 ? x - (x - a + 1) : x;
                    a = 1;
                }
                else if (x == a)
                {
                    a = 1;
                    x = 1;
                }
                else
                {
                    a = a - x;
                    x = 0;
                }

                b = b + x <= n ? b + x : n;

                Console.WriteLine(Math.Abs(a - b));
            }
        }
    }
}


using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Numerics;

namespace cfe76
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.SetIn(new StreamReader("input.txt"));
            solve_cfe76A();
        }

        public static void solve_cfe76B()
        {
        }

        public static void solve_cfe76A()
        {
            int t = Convert.ToInt32(Console.ReadLine());

            for (int i = 0; i < t; i++)
            {
                int[] nxab = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);

                int n = nxab[0];
                int x = nxab[1];
                int a = nxab[2];
                int b = nxab[3];

                if (a > b)
                {
                    int temp = a;
                    a = b;
                    b = temp;
                }

                if (x > a)
                {
                    a = 1;
                    x = a > 1 ? x - (x - a) : x;
                }
                else if (x == a)
                {
                    a = 1;
                    x = 1;
                }
                else
                {
                    a = a - x;
                    x = 0;
                }

                b += b + x <= n ? x : 0;

                Console.WriteLine(Math.Abs(a - b));
            }
        }
    }
}


using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Numerics;

namespace cfe76
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.SetIn(new StreamReader("input.txt"));
            solve_cfe76A();
        }

        public static void solve_cfe76B()
        {
        }

        public static void solve_cfe76A()
        {
            int t = Convert.ToInt32(Console.ReadLine());

            for (int i = 0; i < t; i++)
            {
                int[] nxab = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);

                int n = nxab[0];
                int x = nxab[1];
                int a = nxab[2];
                int b = nxab[3];

                if (a > b)
                {
                    int temp = a;
                    a = b;
                    b = temp;
                }

                if (x > a)
                {
                    a = 1;
                    x = a > 1 ? x - (x - a) : x;
                }
                else if (x == a)
                {
                    a = 1;
                    x = 1;
                }
                else
                {
                    a = a - x;
                    x = 0;
                }

                b = b + x <= n ? b + x : n;

                Console.WriteLine(Math.Abs(a - b));
            }
        }
    }
}


using System;
using System.Text;

public class Program
{
    public void Solve()
    {
        var sc = new Scanner();
        int T = sc.NextInt();

        var sb = new StringBuilder();
        for (int i = 0; i < T; i++)
        {
            sb.AppendLine(Query(sc.NextInt(), sc.NextInt(), sc.NextInt(), sc.NextInt()).ToString());
        }

        Console.WriteLine(sb.ToString());
    }

    private int Query(int n, int x, int a, int b)
    {
        return Math.Min(n - 1, Math.Abs(a - b) + x);
    }

    public static void Main(string[] args)
    {
        new Program().Solve();
    }
}

class Scanner
{
    public Scanner()
    {
        _pos = 0;
        _line = new string[0];
    }

    const char Separator = ' ';
    private int _pos;
    private string[] _line;

    #region スペース区切りで取得

    public string Next()
    {
        if (_pos >= _line.Length)
        {
            _line = Console.ReadLine().Split(Separator);
            _pos = 0;
        }

        return _line[_pos++];
    }

    public int NextInt()
    {
        return int.Parse(Next());
    }

    public long NextLong()
    {
        return long.Parse(Next());
    }

    public double NextDouble()
    {
        return double.Parse(Next());
    }

    #endregion

    #region 型変換

    private int[] ToIntArray(string[] array)
    {
        var result = new int[array.Length];
        for (int i = 0; i < array.Length; i++)
        {
            result[i] = int.Parse(array[i]);
        }

        return result;
    }

    private long[] ToLongArray(string[] array)
    {
        var result = new long[array.Length];
        for (int i = 0; i < array.Length; i++)
        {
            result[i] = long.Parse(array[i]);
        }

        return result;
    }

    private double[] ToDoubleArray(string[] array)
    {
        var result = new double[array.Length];
        for (int i = 0; i < array.Length; i++)
        {
            result[i] = double.Parse(array[i]);
        }

        return result;
    }

    #endregion

    #region 配列取得

    public string[] Array()
    {
        if (_pos >= _line.Length)
            _line = Console.ReadLine().Split(Separator);

        _pos = _line.Length;
        return _line;
    }

    public int[] IntArray()
    {
        return ToIntArray(Array());
    }

    public long[] LongArray()
    {
        return ToLongArray(Array());
    }

    public double[] DoubleArray()
    {
        return ToDoubleArray(Array());
    }

    #endregion
}


using System;
using System.Collections.Generic;

namespace Problems
{
    class Program
    {
        static void Main(string[] args)
        {
            int t = Convert.ToInt32(Console.ReadLine());

            while (t-- > 0)
            {
                int n, x, a, b;

                string[] input = Console.ReadLine().Split(' ');

                n = Convert.ToInt32(input[0]);
                x = Convert.ToInt32(input[1]);
                a = Convert.ToInt32(input[2]);
                b = Convert.ToInt32(input[3]);

                int answer;

                while (x-- > 0)
                {
                    if(a == 1 && b == n)
                    {
                        break;
                    }
                    else if(b == 1 && a == n)
                    {
                        break;
                    }
                    else if(a > b)
                    {
                        if(a < n)
                        {
                            a++;
                        }
                        else
                        {
                            b--;
                        }
                    }
                    else
                    {
                        if(b < n)
                        {
                            b++;
                        }
                        else
                        {
                            a--;
                        }
                    }
                }

                //Console.WriteLine(a + " " + b);

                answer = Math.Abs(a - b);

                Console.WriteLine(answer);
            }
        }
    }
}


using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using static System.Console;
using static System.Math;

namespace Olymp
{
  public class ProblemSolver
  {
    private readonly Tokenizer input;

    public void Solve()
    {
      var t = input.ReadInt();
      for (int i = 0; i < t; i++)
      {
        var (n, x, a, b) = input.Read4Int();
        WriteLine(Abs(a - b) + Min(x, n - Abs(a - b) - 1));
      }
    }

    public ProblemSolver(TextReader input)
    {
      this.input = new Tokenizer(input);
    }
  }

  #region Service classes

  public class Tokenizer
  {
    private readonly TextReader reader;

    public string ReadToEnd()
    {
      return reader.ReadToEnd();
    }

    public int ReadInt()
    {
      var c = SkipWs();
      if (c == -1)
        throw new EndOfStreamException();
      var isNegative = false;
      if (c == '-' || c == '+')
      {
        isNegative = c == '-';
        c = reader.Read();
        if (c == -1)
          throw new EndOfStreamException("Digit expected, but end of stream occurs");
      }

      if (!char.IsDigit((char)c))
        throw new InvalidOperationException($"Digit expected, but was: '{(char)c}'");

      checked
      {
        var result = (char)c - '0';
        c = reader.Read();
        while (c > 0 && !char.IsWhiteSpace((char)c))
        {
          if (!char.IsDigit((char)c))
            throw new InvalidOperationException($"Digit expected, but was: '{(char)c}'");
          result = result * 10 + (char)c - '0';
          c = reader.Read();
        }

        if (isNegative)
          result = -result;
        return result;
      }
    }

    public string ReadLine()
    {
      return reader.ReadLine();
    }

    public long ReadLong()
    {
      return long.Parse(ReadToken());
    }

    public double ReadDouble()
    {
      return double.Parse(ReadToken(), CultureInfo.InvariantCulture);
    }

    public int[] ReadIntArray(int n)
    {
      var a = new int[n];
      for (var i = 0; i < n; i++)
        a[i] = ReadInt();
      return a;
    }

    public (int, int) Read2Int() =>
      (ReadInt(), ReadInt());

    public (int, int, int) Read3Int() =>
      (ReadInt(), ReadInt(), ReadInt());

    public (int, int, int, int) Read4Int() =>
      (ReadInt(), ReadInt(), ReadInt(), ReadInt());

    public long[] ReadLongArray(int n)
    {
      var a = new long[n];
      for (var i = 0; i < n; i++)
        a[i] = ReadLong();
      return a;
    }

    public double[] ReadDoubleArray(int n)
    {
      var a = new double[n];
      for (var i = 0; i < n; i++)
        a[i] = ReadDouble();
      return a;
    }

    public string ReadToken()
    {
      var c = SkipWs();
      if (c == -1)
        return null;
      var sb = new StringBuilder();
      while (c > 0 && !char.IsWhiteSpace((char)c))
      {
        sb.Append((char)c);
        c = reader.Read();
      }

      return sb.ToString();
    }

    private int SkipWs()
    {
      var c = reader.Read();
      if (c == -1)
        return c;
      while (c > 0 && char.IsWhiteSpace((char)c))
        c = reader.Read();
      return c;
    }

    public Tokenizer(TextReader reader)
    {
      this.reader = reader;
    }
  }

  internal class Program
  {
    public static void Main()
    {
      var solver = new ProblemSolver(In);
      solver.Solve();
    }
  }

  #endregion
}


using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Solution
{
    static void Main(string[] args)
    {
        long n = Convert.ToInt32(Console.ReadLine());
        long[] finalvals = new long[n];
        for (long i = 0; i < n; i++)
        {
            long max = 0, min = 0;
            int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp));
            int basicdistance = Math.Abs(arr[3] - arr[2]);
            if(arr[3]>arr[2])
            {
                max = arr[3];
                min = arr[2];
            }
            else{
                max = arr[2];
                min = arr[3];
            }
            long newdistance = basicdistance + arr[1];
            if (newdistance > arr[0]) finalvals[i] = basicdistance;
            else finalvals[i] = (basicdistance >= newdistance) ? basicdistance : newdistance;
        }
        for (long i = 0; i < finalvals.Length; i++)
            Console.WriteLine(finalvals[i]);
    }
}


using System;
using System.Collections;
using System.Collections.Generic;

class Solution
{
    static void Main(string[] args)
    {
        long n = Convert.ToInt32(Console.ReadLine());
        long[] finalvals = new long[n];
        for (long i = 0; i < n; i++)
        {
            long max = 0, min = 0;
            int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp));
            int basicdistance = Math.Abs(arr[3] - arr[2]);
            if (arr[3] > arr[2])
            {
                max = arr[3];
                min = arr[2];
            }
            else
            {
                max = arr[2];
                min = arr[3];
            }
            long newdistance = basicdistance + arr[1];
            if (newdistance > arr[0]) finalvals[i] = arr[0]-1;
            else finalvals[i] = (basicdistance >= newdistance) ? basicdistance : newdistance;
        }
        for (long i = 0; i < finalvals.Length; i++)
            Console.WriteLine(finalvals[i]);
    }
}


using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Solution
{
    static void Main(string[] args)
    {
        long n = Convert.ToInt32(Console.ReadLine());
        long[] finalvals = new long[n];
        int max=0,min=0;
        for (long i = 0; i < n; i++)
        {
            bool max3=false,max2=false;
            int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp));
            int basicdistance = Math.Abs(arr[3] - arr[2]);
            if(arr[3]>=arr[2])
            {
                max = arr[3];
                max3 = true;
                min = arr[2];
            }
            else{
                max = arr[2];
                max2 = true;
                min = arr[3];
            }
            int newdistance = Math.Abs(max+arr[1]-min);
            if (newdistance >= arr[0]) finalvals[i] = basicdistance;
            else finalvals[i] = (basicdistance >= newdistance) ? basicdistance : newdistance;
            Array.Clear(arr, 0, 4);
        }
        for (long i = 0; i < finalvals.Length; i++)
            Console.WriteLine(finalvals[i]);
    }
}


using System;
using System.Collections;
using System.Collections.Generic;

class Solution
{
    static void Main(string[] args)
    {
        long n = Convert.ToInt32(Console.ReadLine());
        long[] finalvals = new long[n];
        for (long i = 0; i < n; i++)
        {
            long max = 0, min = 0;
            int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp));
            int basicdistance = Math.Abs(arr[3] - arr[2]);
            if (arr[3] > arr[2])
            {
                max = arr[3];
                min = arr[2];
            }
            else
            {
                max = arr[2];
                min = arr[3];
            }
            long newdistance = basicdistance + arr[1];
            if (newdistance >= arr[0]) finalvals[i] = arr[0]-1;
            else finalvals[i] = (basicdistance >= newdistance) ? basicdistance : newdistance;
        }
        for (long i = 0; i < finalvals.Length; i++)
            Console.WriteLine(finalvals[i]);
    }
}


using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Solution
{
    static void Main(string[] args)
    {
        long n = Convert.ToInt32(Console.ReadLine());
        long[] finalvals = new long[n];
        for (long i = 0; i < n; i++)
        {
            long max = 0, min = 0;
            int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp));
            int basicdistance = Math.Abs(arr[3] - arr[2]);
            if(arr[3]>arr[2])
            {
                max = arr[3];
                min = arr[2];
            }
            else{
                max = arr[2];
                min = arr[3];
            }
            long newdistance = Math.Abs(max+arr[1]-min);
            if (newdistance > arr[0]) finalvals[i] = basicdistance;
            else finalvals[i] = (basicdistance >= newdistance) ? basicdistance : newdistance;
        }
        for (long i = 0; i < finalvals.Length; i++)
            Console.WriteLine(finalvals[i]);
    }
}


using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Solution
{
    static void Main(string[] args)
    {
        long n = Convert.ToInt32(Console.ReadLine());
        long[] finalvals = new long[n];
        long max=0,min=0;
        for (long i = 0; i < n; i++)
        {
            int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp));
            int basicdistance = Math.Abs(arr[3] - arr[2]);
            if(arr[3]>arr[2])
            {
                max = arr[3];
                min = arr[2];
            }
            else{
                max = arr[2];
                min = arr[3];
            }
            long newdistance = Math.Abs(max+arr[1]-min);
            if (newdistance > arr[0]) finalvals[i] = basicdistance;
            else finalvals[i] = (basicdistance >= newdistance) ? basicdistance : newdistance;
        }
        for (long i = 0; i < finalvals.Length; i++)
            Console.WriteLine(finalvals[i]);
    }
}


using System;
using System.Collections.Generic;
using System.Text;

namespace CodeForcesProblems
{
    class A1257_TwoRivalStudents
    {
        public static void Main()
        {
            var tc = int.Parse(Console.ReadLine());
            while(tc>0)
            {
                string[] a = Console.ReadLine().Split(' ');
                var n = int.Parse(a[0]);
                var x = int.Parse(a[1]);
                var y = int.Parse(a[2]);
                var z = int.Parse(a[3]);
                var result = Math.Abs(y - z) +x;
                n -= 1;
                if (result > n)
                    result = n;
                Console.WriteLine(result);
                tc--;
            }
        }
    }
}


using System;

namespace codeforces_
{
    class Program
    {

        static void Main(string[] args)
        {
            int t = int.Parse(Console.ReadLine());
            for (int q = 0; q < t; q++)
            {
                string[] arr = Console.ReadLine().Split(' ');
                int n = int.Parse(arr[0]);
                int x = int.Parse(arr[1]);
                int pos1 = int.Parse(arr[2]);
                int pos2 = int.Parse(arr[3]);

                if (pos1 > pos2) (pos1, pos2) = (pos2,pos1);

                int MinPos2 = Math.Min(n-pos2,x);
                pos2 += MinPos2;
                x -= MinPos2;
                pos1 -= Math.Min(pos1-1,x);
                Console.WriteLine(pos2-pos1);

            }

        }
    }
}


Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29411.108
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "codeforces`", "codeforces`\codeforces`.csproj", "{4004846A-F65C-4664-8B97-57D32DD2E508}"
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Release|Any CPU = Release|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{4004846A-F65C-4664-8B97-57D32DD2E508}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{4004846A-F65C-4664-8B97-57D32DD2E508}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{4004846A-F65C-4664-8B97-57D32DD2E508}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{4004846A-F65C-4664-8B97-57D32DD2E508}.Release|Any CPU.Build.0 = Release|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
	GlobalSection(ExtensibilityGlobals) = postSolution
		SolutionGuid = {7ADE0E49-6D46-49DD-956F-B22C9AD8AF2D}
	EndGlobalSection
EndGlobal


using System;

namespace codeforces_
{
    class Program
    {

        static void Main(string[] args)
        {
            int t = int.Parse(Console.ReadLine());
            for (int q = 0; q < t; q++)
            {
                string[] arr = Console.ReadLine().Split(' ');
                int n = int.Parse(arr[0]);
                int x = int.Parse(arr[1]);
                int pos1 = int.Parse(arr[2]);
                int pos2 = int.Parse(arr[3]);

                if (pos1 > pos2)
                {
                    int help = pos1;
                    pos1 = pos2;
                    pos2 = help;
                }
                int MinPos2 = Math.Min(n-pos2,x);
                pos2 += MinPos2;
                x -= MinPos2;
                pos1 -= Math.Min(pos1-1,x);
                Console.WriteLine(pos2-pos1);

            }

        }
    }
}


using System;
class a
{
    static void Main()
    {
        int t = int.Parse(Console.ReadLine());
        for (int i = 0; i < t; i++)
        {
            var p = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
            int a = Math.Min(p[2], p[3]);
            int b = Math.Max(p[2], p[3]);
            int j = 0;
            while ( j < p[1])
            {
                if (a > 1) a--;
                else if (b < p[0]) b++;
                j++;
            }
            Console.WriteLine(b-a);
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        /*
        static double bin(int[] arr, double n, int k)
        {

            double max = arr.Max();
            double min = arr.Min();

            double o = min;
            while (true)
            {
                int sum = 0;
                for (int i = 0; i < n; i++)
                    sum += Convert.ToInt32(Math.Floor(arr[i] / o));
                if (sum > k)
                    o = (o + max) / 2;
                else if (sum < k)
                    o = (o + min) / 2;
                else
                {
                    return o;
                    break;
                }
            }

        }
        */
        static void Main(string[] args)
        {
            long m=int.Parse(Console.ReadLine());
            for(int j=0;j<m;j++)
            {
                 string[]y=Console.ReadLine().Split(' ');
                 long a=long.Parse(y[0]);
                 long b=long.Parse(y[1]);
                 long x1=long.Parse(y[2]);
                 long x2=long.Parse(y[3]);
                 Console.WriteLine(Math.Min(a-1,Math.Abs(x1-x2)+b));

            }
        }

    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int t = Int32.Parse(Console.ReadLine());

            for (int i = 0; i < t; i++)
            {
                string[] str = Console.ReadLine().Split();
                int n = Int32.Parse(str[0]);
                int x = Int32.Parse(str[1]);
                int a = Int32.Parse(str[2]);
                int b = Int32.Parse(str[3]);

                int ans = Math.Abs(b - a) + Math.Min(x, n - Math.Abs( b - a) - 1);
                Console.WriteLine(ans);
            }

        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication8
{
    class Program
    {
        static void Main(string[] args)
        {
            int T = int.Parse(Console.ReadLine());

            for (int t = 0; t < T; t++)
            {
                int[] input = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
                int n = input[0];
                int x = input[1];
                int a = input[2];
                int b = input[3];

                if (a > b)
                {
                    int c = a;
                    a = b;
                    b = c;
                }

                int ans = b - a;

                if (x < a) ans += x;
                else if (x - a < n - b) ans += x;
                else ans = n;

                ans = Math.Min(ans, n - 1);

                Console.WriteLine(ans);
            }

#if DEBUG
            Console.ReadKey();
#endif
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pustoi
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = Convert.ToInt32(Console.ReadLine());
            string[] srt = new string[n];
            for(int i = 0; i < n; i++)
            {
                srt[i] = Console.ReadLine();
            }
            for(int i = 0; i < n; i++)
            {
                string str = srt[i];
                string[] s = str.Split(' ');
                long t = Convert.ToInt64(s[0]);
                long x = Convert.ToInt64(s[1]);
                long a = Convert.ToInt64(s[2]);
                long b = Convert.ToInt64(s[3]);

                long d = Math.Abs(a - b);
                for(long j =d; j <n-1; j++)
                {
                    if (x == 0) break;
                    x--;
                    d++;
                }
                Console.WriteLine(d);

            }

            Console.Read();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pustoi
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = Convert.ToInt32(Console.ReadLine());
            string[] srt = new string[n];
            for(int i = 0; i < n; i++)
            {
                srt[i] = Console.ReadLine();
            }
            for(int i = 0; i < n; i++)
            {
                string str = srt[i];
                string[] s = str.Split(' ');
                long t = Convert.ToInt64(s[0]);
                long x = Convert.ToInt64(s[1]);
                long a = Convert.ToInt64(s[2]);
                long b = Convert.ToInt64(s[3]);

                long d = Math.Abs(a - b);
                for(long j =d; j <t-1; j++)
                {
                    if (x == 0) break;
                    x--;
                    d++;
                }
                Console.WriteLine(d);

            }

            Console.Read();
        }
    }
}


using System;

namespace Two_Rival_Students
{
    class Program
    {
        static void Main(string[] args)
        {
            int t = Convert.ToInt32(Console.ReadLine());
            for (int i = 0; i < t; i++)
            {
                string[] line = Console.ReadLine().Split(' ');
                int n = Convert.ToInt32(line[0]);
                int x = Convert.ToInt32(line[1]);
                int a = Convert.ToInt32(line[2]);
                int b = Convert.ToInt32(line[3]);
                int maxDistance = 0;
                for (int j = 0; j < n; j++)
                {
                    if (x == 0)
                    {
                        maxDistance = a - b;
                        break;
                    }
                    if(a==b||b==n)
                    {
                        maxDistance = n - x + 1;
                    }
                    if (a == 1 || b == 1)
                    {
                        maxDistance = a - b;
                        break;
                    }
                    if (a > b)
                    {
                        a = a + x;
                        maxDistance = a - b;
                        break;
                    }
                    if (b > a)
                    {
                        b = b + x;
                        maxDistance = b - a;
                        break;
                    }
                }
                Console.WriteLine(Math.Abs(maxDistance));
            }
        }
    }
}


using System;

namespace Two_Rival_Students
{
    class Program
    {
        static void Main(string[] args)
        {
            int t = Convert.ToInt32(Console.ReadLine());
            for (int i = 0; i < t; i++)
            {
                string[] line = Console.ReadLine().Split(' ');
                int n = Convert.ToInt32(line[0]);
                int x = Convert.ToInt32(line[1]);
                int a = Convert.ToInt32(line[2]);
                int b = Convert.ToInt32(line[3]);
                int maxDistance = 0;
                for (int j = 0; j < n; j++)
                {
                    if (x == 0)
                    {
                        maxDistance = a - b;
                        break;
                    }
                    if (n == a || n == b)
                    {
                        maxDistance = n - 1;
                        break;
                    }
                    if (a > b)
                    {
                        a = a + x;
                        maxDistance = a - b;
                        break;
                    }
                    if (b > a)
                    {
                        b = b + x;
                        maxDistance = b - a;
                        break;
                    }
                }
                Console.WriteLine(Math.Abs(maxDistance));
            }
        }
    }
}


using System;

namespace Two_Rival_Students
{
    class Program
    {
        static void Main(string[] args)
        {
            int t = Convert.ToInt32(Console.ReadLine());
            for (int i = 0; i < t; i++)
            {
                string[] line = Console.ReadLine().Split(' ');
                int n = Convert.ToInt32(line[0]);
                int x = Convert.ToInt32(line[1]);
                int a = Convert.ToInt32(line[2]);
                int b = Convert.ToInt32(line[3]);
                int maxDistance = 0;
                int initialDistance = Math.Abs(a - b);
                maxDistance = initialDistance + x;
                if(maxDistance > n-1)
                {
                    maxDistance = n - 1;
                }
                Console.WriteLine((maxDistance));
            }
        }
    }
}


using System;
using System.Linq;
using System.Collections.Generic;

public static class Program {
    public static void Main() {
        int q=int.Parse(Console.ReadLine());
        for(int t=0;t<q;t++){
            int[]data=Console.ReadLine().Split().Select(int.Parse).ToArray();
            int n=data[0];
            int x=data[1];
            int dif=data[2]-data[3];
            if(dif<0)dif=-dif;
            dif=Math.Min(dif+x,n-1);
            Console.WriteLine(dif);
        }
    }
}


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

class P
{
    static int InputI() => int.Parse(Console.ReadLine());
    static long InputL() => long.Parse(Console.ReadLine());
    static string InputS() => Console.ReadLine();
    static double InputD() => double.Parse(Console.ReadLine());
    static int[] InputAr() => Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
    static void Print<T>(T a) => Console.WriteLine(a.ToString());

    static void Main()
    {
        var n = InputI();
        for (var i = 0; i < n; i++)
        {
            var a = InputAr();
            Print(Math.Min(Math.Abs(a[2] - a[3]) + a[1], a[0] - 1));
        }
    }
}


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace My
{
    class My
    {
        static void Mainp()
        {

        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace Contest
{
    class Program
    {
        static void Main(string[] args)
        {
            int t = int.Parse(Console.ReadLine());
            int[] answers = new int[t];
            for (int i = 0; i < t; i++)
            {
                int[] nxab = StringToIntArray(Console.ReadLine());
                int n = nxab[0]; int x = nxab[1]; int a = nxab[2]; int b = nxab[3];
                if (a > b)
                {
                    int temp = a;
                    a = b;
                    b = temp;
                }
                while (x > 0 && a > 1)
                {
                    a--;
                    x--;
                }
                while (x > 0 && b < n)
                {
                    b++;
                    x--;
                }
                answers[i] = b - a;
            }

            Console.WriteLine(string.Join("\n", answers));
        }

        static int[] StringToIntArray(string input)
        {
            string[] splitInput = input.Split();
            int length = splitInput.Length;
            int[] result = new int[length];
            for (int i = 0; i < length; i++)
            {
                result[i] = int.Parse(splitInput[i]);
            }
            return result;
        }

        static long[] StringToLongArray(string input)
        {
            string[] splitInput = input.Split();
            int length = splitInput.Length;
            long[] result = new long[length];
            for (int i = 0; i < length; i++)
            {
                result[i] = long.Parse(splitInput[i]);
            }
            return result;
        }
    }
}


using System;
using System.Linq;
class A
{
    public static void Main(string[] args)
    {
        int t = int.Parse(Console.ReadLine());
        while(t > 0)
        {
            var arr = Console.ReadLine().Trim().Split().Select(z => int.Parse(z)).ToArray();
            int n = arr[0];
            int x = arr[1];
            int a = arr[2];
            int b = arr[3];
            int ans = Math.Abs(a - b);
            ans = Math.Min(n - 1, x + ans);
            Console.WriteLine(ans);
            t--;
        }
    }
}