Flush stdout after printing command
Close file on error before exiting
Add tests