Refactored FSM shutdown code to separate state machine callback

All tests work on Linux. Doesn't tested on Windows. But rework is rather mechanical so should be easy to fix if there are typos in Windows code.

The patch is submitted under MIT License