Refactoring

General refactoring and minor improvements.