Some fix and refactoring of code