Split into functions, add __main__
Take input (and output) file from CLI
reduce down to one loop over input
Manual merge of comments from @ralphbean