Refactored and cleaned code for the different states