c----------------------------------------------------------- 
c Chapter 1: Next subset of an n-set(p19) 
c-----------------------------------------------------------
c     Name of Subroutine: NEXSUB
c
c     Algorithm:Generating all of the subsets of the set
c               {1,2,...,n} in an order specified by the  
c               gray code
c
c     input:    n=5
c     compiler: f77 nexsub.f
c-----------------------------------------------------------

c-----The driver program is in nexsub_2.f-------------------

c-----Subroutine begins here--------------------------------
      subroutine nexsub(n,in,mtc,ncard,j)
      logical mtc
      dimension in(n)
      if(mtc)goto 20
      do 11 i=1,n
   11 in(i)=0
      ncard=0
      mtc=.true.
      return
   20 j=1
      if(mod(ncard,2).eq.0)goto 30
   40 j=j+1
      if(in(j-1).eq.0)goto 40
c if(j.gt.n)j=n
   30 in(j)=1-in(j)
      ncard=ncard+2*in(j)-1
      mtc=ncard.ne.in(n)
      return
      end
