Fixes and refactoring