I decided to go with the slightly simpler logic Thorild Selen suggested