refactored. added lots of DEBUG logging