refactored the code substantially to fix the regression from 'types' to 'type' in the results.  Added some comments and the code is a little shorter too