refactor bash scripts into functions

add some comments

Per request from @NanoXD.  There are still shared variables, not everything moves easily into a function.