Implmented state machine, sorta works maybe?