Bugfixing (NB: this code still needs refactoring!)