Not sure who originally created this so I can't credit, sorry. This fixes various problems with logic.