refactored and commented