Did some refactoring, solved some bugs