Reorganised and cleaned up the code - still works