Refactored and fixed logical errors