refactored and debugged