Simplified code to reduce global variables