some reorganising of the code into sub-scripts. improved comments.