rewrite of pbs script, use bash subroutines for clarity and easy maintenance