Move variable declarations outside of loop and fix NULL assignment