This seems very very similar to the code above. I feel that this could be squashed a bit by sharing some code across the two branches