split into functions, add command-line options, and convert to python3