Pulled out command handling code into its own function