Greatly harden code: simplify logic, add assertions, squash warnings