Refactored code so that the output resembles more the original