Remove unused headers and fix file stream closing