* this subroutine swaps pieces POLD, PNEW in group (GOLD, GNEW)
*****************************************************************************
      SUBROUTINE swap(gold,pold,gnew,pnew)
      IMPLICIT NONE
      INCLUDE 'general.h'
      INCLUDE 'common.h'

* input
      CHARACTER(LEN=lgr) gold,pold,pnew
* output
      CHARACTER(LEN=lgr) gnew
* local
      INTEGER lg,lold,lnew,ibeg,iend,n,i,j
!$    INTEGER         omp_get_thread_num

      IF (wtflag.NE.0) WRITE(*,*) "*swap* "
!$   &    ,omp_get_thread_num()
     &    ,pold,pnew,"in group   ", gold
* initialize
      gnew = ' '

* measure length of group and old and new pieces:
      lg   = INDEX(gold,' ') - 1
      lold = INDEX(pold,' ') - 1
      lnew = INDEX(pnew,' ') - 1

      IF (lg+lnew-lold.GT.lgr) THEN
         WRITE (6,'(a)')'--error-- in swap'
         WRITE (6,'(a)')'new group more than lgr characters'
         STOP
      ENDIF

* locate beginning and ending index of old piece:
      ibeg = INDEX(gold,pold(1:lold))
      IF (ibeg.EQ.0) THEN
         WRITE (6,'(a)') '--error-- in swap'
         WRITE (6,'(a)') pold,' not in ',gold
         STOP
      ENDIF
      iend = ibeg + lold - 1
      
* write to new group:
      n = 0
      DO i=1,lgr
         IF (n.EQ.lgr) GO TO 20
         IF (i.LT.ibeg .OR. i.GT.iend) THEN
            n = n + 1
            gnew(n:n) = gold(i:i)
         ENDIF
         IF (i.EQ.ibeg) THEN
            DO j=1,lnew
               n = n + 1
               gnew(n:n) = pnew(j:j)
            ENDDO
         ENDIF
      ENDDO     
20    CONTINUE

      RETURN
      END

