Finally revised this fucking algorithm to the point that it works. God
only knows what other problems it may have.