Fixed bug and code refactoring