Refactoring and a little fix

See commits.