Nice.   the nesting here is starting to make me want helper functions, but the logic looks excellent.