fixed some bugs + refactoring