Tidied up code.

Split code up into functions. More modular, makes it easier to read and
make any changes.