Did some refactoring and found some bugs