added lots of error trapping and refactored