speed up file reading and add finite state machine