rewrote command processing section to be more readable