Fix potential crashes
 - some compilers have problems with using locally redeclared loop vars after an internal loop
 - fix ordering of conditional checks
Merge pull request #547 from asmaloney/fix_potential_crashes

Fix potential crashes