Refactored code a bit to make more, smaller functions.  This code scored only 16 out of 100 points when submitted to codility.com (18% correctness, 0% performance).  Sigh.