Some bug fixes, refactoring