Bug fixes
Some light refactoring