Factoring out union and relative index calculations into a subroutine