Fixed memory leaks and resource (file handle) leaks

This fixes a number of leaks and avoids forcing the content-type to text/plain if its already determined