Small refactoring and fixed some minor bugs