maybe you should use a library.
For that particular function? For
modinv only?
I use this one for modular multiplicative inverse.
int modInverse(int a, int n)
{
int i = n, v = 0, d = 1;
while (a>0) {
int t = i/a, x = a;
a = i % x;
i = x;
x = d;
d = v - t*x;
v = x;
}
v %= n;
if (v<0) v = (v+n)%n;
return v;
}
On the other hand you would save your time using a library like Bouncy Castle for all your work on ecc calculation

You can find good source code to learn like Casascius one -
https://github.com/casascius/Bitcoin-Address-Utility