I fixed a now obvious mistake after adding a good amount of code. On the plus side, the algorithm is slightly more optimized.