Fix for #310
Some refactoring and whitespace fixes