Refactor handling code into a mux
Fix mux, tidy up code