I'd move all of the logic in the body of each `if` statement into separate, well-named functions to make it more clear what's actually being done.  Probably the condition of each one, too.  Try and make it read like English!