Some refactoring and bug fixes
Some fixes