Bug fixes + refactoring