Code refactoring

Bug fixes after changes.