fixed bugs, did some refactoring