Corrected bugs due to incorrect variable scope