Reorganises code, fixes duplication bug.