refactored and fixed some bugs