Fixed global variable leaks and added better error handling