Fixed some of the rougher bits in the code - really need to rewrite it from scratch...