Speed up by precomputing flag variables.