Proper call to fid.close
More generic rewrite of output code