Fix potential crashes

 - some compilers have problems with using locally redeclared loop vars after an internal loop
 - fix ordering of conditional checks