Bug fixes, refactoring