One thing you should look at is not to use the Keyhit command for exiting the program. You can only use the keyhit command once inside a loop. Use keydown.
This is not true. It's perfectly OK to use Keyhit() but just remember that you can only call the function once per keypress. If you need to check more than once the condition of whether or not a key was pressed then use a variable to retain the value of Keyhit() until the end of your loop (i.e. escapekeypressed = Keyhit(1)). And don't forget to reset the variable to false at the end of the loop.