This adds a lot of logic to this method; I think that this could be extracted to a private method and called here to make this a bit more simple.