C----------------------------------------------------------
       subroutine graytobin(cg,cb,n)

c      convert word of length n
c      from Gray code Cg[0...n-1] 
c      to binary code Cb[0...n-1]
c      4 bits per time 
c                                 D.Campana - Jan. 2005   
C----------------------------------------------------------
       IMPLICIT NONE
   
       integer n, bit, bi
       integer cg,cb
       integer*1 a,b
       integer*1 i,j,n4
       integer nby4,cgby4(8),cbby4(8)
c
c    devo separare la parola nelle sue componenti da 4 bit
c    ossia (0-3, 4-7, 8-11, 12-15)
c
           
      cb=0
      do i=1,8
        cgby4(i)=0  ! componenti da 4 bit in Gray
        cbby4(i)=0  ! componenti da 4 bit in binario
      enddo
      nby4 = n/4

      do i=1,nby4
        do j=1,4
           n4= (i-1)*4+j
           bi = ibits(cg,n4-1,1)
           if(bi.eq.1)cgby4(i)=ibset(cgby4(i),j-1)
        enddo
      enddo
c
      do i=1,nby4
       bi = ibits(cgby4(i),3,1)
       if(bi.eq.1) cbby4(i) = ibset(cbby4(i),3)     
c
       do bit=2,0,-1
        bi=0 
        a=ibits(cgby4(i),bit,1)
        b=ibits(cbby4(i),bit+1,1)
        if(((a.eq.1).and.(b.eq.0)).or.((a.eq.0).and.(b.eq.1)))bi=1
        if(bi.eq.1)cbby4(i)=ibset(cbby4(i),bit)   
       enddo
       enddo
c
      do i=1,nby4
        do j=1,4
           n4= (i-1)*4+j
           bi=ibits(cbby4(i),j-1,1)
           if(bi.eq.1)cb=ibset(cb,n4-1)
        enddo
      enddo
c
       return
       end
