refactored and cleaned up code