It looks like there is some code duplication in this function in the various conditionals/switches, no?