Is this really the most effective way of doing this? There are *so* many loops, and those if statements inside are brutal for the performance.