Overhauled main state machine

added error returning too