Some code refactoring and a quick bugfix (a typo).