tidied and commented the code a bit. still ugly.