Backport #625

This was probably reverted manually after a wrong fix.

@sergeyz can you return early instead of using `else if`?