This function was re-written by Josh, but in a bad way. Either revert to the old version or re-write so that it confines to functional programming paradigm.