'x' is only assigned if certain conditions are met, so you will get an error with some combinations of 'a' and 'p'.
However, I see what might be an error in logic beginning at 'while (m == 0)': 'm' is next set to 0, so b^(2*m) == b^0, which is always one. So, the 'while mod...' condition is never satisfied and 'm' is never incremented. It would seem that m would remain zero and therefore the while loop would never exit.
I recommend stepping through this code with the debugger to understand what is happening.