Major refactor into functions
Minor formatting improvements