Code refactored and working