Changed the structure of the code. Should make the order of the code clearer.