Made the script as a whole more automatic, rearranged things
cleanup