Little bug fix and some code refactoring