Restructure into functions for easier maintaince, reduced code size and to make more features easier to add.