trim some stray whitespace
some more whitespace changes
set umask() only once
move the setup of output files to separate function