Fixed memory leaks and added error checking