This is the first working revision (apart from the result is flipped).