bug fixes + a bit of refactoring