General refactoring and several improvements