reorganised and tidied up code.