I know that this is a helper, but I think its handling too much. Maybe break up into a few smaller functions which get called from here.