Made some changes to increase the speed of this function. Eliminated redundent if/else statments, and used which %in% instead of a pair of subsets.