Sorry this code is really really smelly, I will fix it later (been sitting on it fo rtoo long).