adding debugging help
changing function to use and return values from hash references
massive rewrite to correctly pass global variables between subroutines.  UNTESTED.  syntax ok