Implement new state machine

- fix some memory related issues
- implement interactive mode for testing on PC.