Tighten up the coding

General clean up
Break up into functions

Make it more modular