Simpler implementation proposed by ekohl