Made the proposed main logic somewhat clearer