Major code cleanup. Removed loads of duplicate code.