Added comments, tidied up code, put the three main functions in logical order.