changed mainloop to use while loop and stack