Fixed memory leaks and resource (file handle) leaks

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