Added many unit tests and tidied up code.