Refactored and works pretty well