While I certainly think the code could use dramatic algorithmic improvement, I was attempting to keep the logic as consistent as possible, given the OP's apparent level of familiarity. My actual inclination would be to write it as a single pass, stashing results in a hash, so you could separate the processing and the output. Also reduces duplication of code. But to each their own, premature optimization, and all that jazz.