fixed global/local variable issue & reordered