This is a fixed version of the previously reverted commit. Thanks to Daniel Mustieles García for tracking down the flaw.