Fixing issues and refactoring