reorganized code to be more readable, resolved bugs in state transitions