Fixed variable scoping issue which can lead to out of memory error.