Made some changes suggested by splint and changed operation of run function to more like a state machine