After some thought, the original code isn't going to do what is needed. The following image is a re-design of the firmware having re-assessed the requirements.