You have a lot of x != 0 checks here as well as the x != 0 check in the while loop.  Is there a way we can just check once?