SUBROUTINE KDSAW_INV(ierr)
  !
  use kdsaw_module                  ! used to be TRANSP COMMON
  implicit NONE
  !     
  integer, intent(out) :: ierr      ! error code, 0=OK
  !
  !  ierr=0: OK; ierr=99 -- error which indicates software bug!
  !                         this is note expected to happen.
  !
  !---------------------------------------------------------------

  integer i,inx,ii,j,inm,izpre
  real(fp) :: ztest

  !---------------------------------------------------------------
  !
  !  INVERT MIXING FACTOR ARRAY FOR EACH ZONE IN THE MIXING REGION
  !  (arrays were zeroed in kdsaw_init)
  !
  do J=LCENTR,IMIX
     !  J IS POST-SAWTOOTH ZONE INDEX
     INM=INZMIX(J)
     IF(INM.EQ.0) cycle
     do I=1,INM
        !  PRE-SAWTOOTH ZONE INDEX
        IZPRE=IZMIX(I,J)
        INZMXP(IZPRE)=INZMXP(IZPRE)+1
        IZMIXP(INZMXP(IZPRE),IZPRE)=J
        ZZMIXP(INZMXP(IZPRE),IZPRE)=ZZMIX(I,J)
     enddo
  enddo

  ! combine duplicates (indexing is trimmed but not rearranged...)
  do j=lcentr,imix
     inm=inzmxp(j)
     i=1
     do while (i.lt.inm)
        inx=inm
        do ii=i+1,inm
           if(izmixp(i,j).eq.izmixp(ii,j)) then
              zzmixp(i,j)=zzmixp(i,j)+zzmixp(ii,j)
              zzmixp(ii,j)=ZERO
           else
              inx=ii
              exit
           endif
        enddo
        if(inx.eq.inm) then
           do while (zzmixp(inm,j).eq.ZERO)
              izmixp(inm,j)=0
              inm=inm-1
           enddo
        endif
        i=inx
     enddo
     inzmxp(j)=inm
  enddo

  ! test...

  ierr=0
  do J=LCENTR,IMIX
     INM=INZMXP(J)
     IF(INM.EQ.0) cycle
     ZTEST=zero
     do I=1,INM
        ZTEST=ZTEST+ZZMIXP(I,J)
     enddo
     IF(ABS(ZTEST-1.0).GT.1.0e-4_fp) THEN
        if(ierr.eq.0) then
           WRITE(ABS(NONLIN),9901)
9901       FORMAT(' ? SAWNBI - SAWTOOTH MIXING FACTOR NORMALIZATION ERROR')
           ierr=1
        endif
     endif
  enddo

end SUBROUTINE KDSAW_INV
