Fixed global variables issues in the functions