Some refactoring
Bug fixes and optimizations