This function is hard to understand what it is doing.  It should be split up I suspect.