Speed-up code suggested by Olivier