Reorganised some code. Added some comments and cleaned up a bit.