Changes to logic to finally fully correct the desired functionality. Some code cleanup.