fixed memory leak, fixed formatting and error checking