Simplified the logic a lot. Should output correct results every time now.