Use boolean flag to avoid comparison duplication

This makes code a bit clearer (although a bit longer) and eliminates the duplication of the comparison.