Refactored and fixed bugs