Split up code into functions, migrate to subprocess module