#141, Refactored code. smaller functions