The code below looks exactly the same as the code starting on line 648.  Surely we can break this functionality out?