added some logic for a cursor state machine, some refactoring