localize $_ in several places for safetey reasons. And a little drive-by...

... use of variables instead of bare filehandles.