Code restructuring. Will refactor tomorrow to remove some of the messier bits of code