fixing some bugs and refactoring more