added an out flag to write to files instead of stdout