use fsm to reorgnize code in a neater way.