Fix variable scope/memory location problems