refactored and fixed bugs