fixed few bug, did minor refactoring