Improved state machine

Created a class to manage state