It looks like there's some chunks of duplicated code in these if statements - could these be pulled into a separate method somehow?