fixed errors in scripts, and pulled out common functions