Do message handling in separate functions
Factoring out nested functions

Also added comment about a potential bug