allow compilation with msvc

MSVC demands predeclaration of all variables. The changes in these commit
move declarations to earlier parts of the code, thus fixing a number of
errors thrown by the MSVC compiler.