Major reshuffle

Rewrote some sections of code, moved some sections into functions