Added state machine and mail func