Perhaps this could be split into another function? We have a lot of indentation going on below.