I presume this is plagiarised from the old code. I think this would benefit from some extracting and renaming to make it a bit more readable - I find it quite hard to read as it is.