Minor refactoring and some bug fixes