Clean up perl warnings and reorder code to put global variables first, then subroutines then global code