Did some refactoring. Fixed bugs after refactoring