bug fixing and refactoring