//abc183_e.cpp
//Sun Nov 15 21:30:13 2020

#include <bits/stdc++.h>
#define INTINF 2147483647
#define LLINF 9223372036854775807
#define MOD 1000000007
#define rep(i,n) for (int i=0;i<(n);++i)

using namespace std;
using ll=long long;
typedef pair<int,int> P;

int main(){
	int h,w;
	cin >> h >> w;

	string s[h];
	rep(i,h)cin >> s[i];

	ll dptate[h][w];
	ll dpnana[h][w];
	ll dpyoko[h][w];
	rep(i,h)rep(j,w){
		dptate[i][j] = 0;
		dpnana[i][j] = 0;
		dpyoko[i][j] = 0;
	}

	rep(i,h)rep(j,w){
		ll tmp = 0;
		if (s[i][j]=='#')continue;
		if (i==0 && j==0){
			dptate[0][0] = 1;
			dpnana[0][0] = 1;
			dpyoko[0][0] = 1;
		}else {
			if (i-1>=0){
				tmp = (tmp+dptate[i-1][j])%MOD;
			}
			if (j-1>=0){
				tmp = (tmp+dpyoko[i][j-1])%MOD;
			}
			if (i-1>=0 && j-1>=0){
				tmp = (tmp+dpnana[i-1][j-1])%MOD;
			}
			if (i-1>=0){
				dptate[i][j] = (tmp+dptate[i-1][j])%MOD;
			}else {
				dptate[i][j] = tmp;
			}
			if (j-1>=0){
				dpyoko[i][j] = (tmp+dpyoko[i][j-1])%MOD;
			}else {
				dpyoko[i][j] = tmp;
			}
			if (i-1>=0 && j-1>=0){
				dpnana[i][j] = (tmp+dpnana[i-1][j-1])%MOD;
			}else {
				dpnana[i][j] = tmp;
			}
		}
		if (i==h-1 && j==w-1){
			cout << tmp << endl;
			return 0;
		}
	}

//	cout << << endl;
//	printf("%.4f\n",ans);
}
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template<class T,class U> using P = pair<T,U>;
template<class T> using vec = vector<T>;
template<class T> using vvec = vector<vec<T>>;
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
ll gcd(ll a, ll b){
    while (b>0){
        ll tempB = b;
        b = a % b;
        a = tempB;
    }
    return a;
}


ll extgcd(ll a, ll b, ll& x, ll& y){
    ll gcd_ = a * b;
    if (b != 0) {
        gcd_ = extgcd(b, a%b, y, x);
        y -= (a/b) * x;
    } else {
        x = 1; y = 0;
    }
    return gcd_;
}

void solve(ll n, ll s, ll k){
    // n and k is tagaini so
    ll x, y;
    // cout << "k, n = " << k << ", " << n << endl;
    extgcd(k, n, x, y);

    ll ans = ((x * s) % n + n )% n;
    // cout << "ans: " << ans << endl;
    ans = n - ans;
    // cout << x << ", " << y << endl;
    cout << ans << endl;
}

int main(){
    int t; cin >> t;
    vec<int> ni(t), si(t), ki(t);
    rep(i, t) cin >> ni[i] >> si[i] >> ki[i];
    rep(i, t) {
        int n, s, k;
        n = ni[i], s = si[i], k = ki[i];
        int g = gcd(n, k);
        if (g == 1) {
            solve(n, s, k);
        } else {
            if (s % g != 0) cout << -1 << endl;
            else solve(n/g, s/g, k/g);
        }
    }
    return 0;
}