Bug fixes + code refactoring