main: move flag parsing code into new file and tidy up main