Fix bugs with -O2 optimisations for the loops