refactoring and adding a lot of bug fixes