Some tidy up and make it run under bash instead of sh.