Hopefully fixed logic.  Needs testing