Is it possible to make this block of code less nested, e.g. move some of it into a separate method, etc.?