Refactoring and optimisaton. This fixes #3.