Refactorised code, bug fixes