Update variable scope

Changed variable declaration so that the variables are accessible by the nested functions and are not global.