Refactoring and fixes from adrian17

Refactoring and fixes from adrian17.