Appears to be an optimisation bug in gcc 4.8. I have set the optimisation on one line of code to -O0, and this fixes the problem, although I can't figure out why the optimised code is getting it wrong. Should be revisited with a later compiler to see if it is still a problem with later releases.
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
Appears to be an optimisation bug in gcc 4.8. I have set the optimisation on one line of code to -O0, and this fixes the problem, although I can't figure out why the optimised code is getting it wrong. Should be revisited with a later compiler to see if it is still a problem with later releases.