Refactored and commented