debugged and appears to be working correctly