Code refactored and commented