Just for sheets and sheep dip I did a quick pass (sloppy) rewrite that uses some C++ features you probably haven't seen before. A range-based for loop, uniform initialization and the ? ternary operator.
Plus reducing the need for temporary Boolean variables for test comparisons.
I did mention it was a first pass, sloppy bit of code. Which was being revised for a second pass to include the casting. Implicit compiler casting can be notoriously buggy.