Moved variable to be defined within the correct scope of function