Code cleanup

refactors stuff into functions, moved setup to end