Bug fixing and refactoring

- fixed bugs
- refactored code