*****iest code I've written in ages
Corrected a few random things that stopped working.