!     Fortran 95 program to return
!       all _r_ combinations of _n_
!
!     Written by Jeffrey Ryan
!     jeff _dot_ a _dot_ ryan _at_ gmail _dot_ com
!     Copyright 2007
!     Distributed under the MIT-style license

      subroutine ncr(n,r,b,a,ret)
!     Usage:
! 
!     n   integer number of elements to choose from 
!     r   integer number of elements chosen
!     b   set of integer elements to choose from 
!     a   all.comb flag: 1 - show all, 0 - show next
!     ret return array of integers
!
      integer n,r,b(r),a,ret(*)
      integer cout(r),cl,mx,w,pos
! 
      pos=1
      cout = b
      ret(pos:r)  = b
!     cl   current column
!     mx   column maximum value
      cl=r
      mx=n
      do while(1 .eq. 1)
!
!       if can increase column, do so
        if(cout(cl) .lt. mx) then
          w = cout(cl)
          do i=0,(r-cl)
            cout(cl+i) = w+i+1
          end do
          cl = r
          mx = n
          pos = pos + r
          ret(pos:(pos+r-1)) = cout
          if(a == 0) exit
          cycle
        end if
!       if can't increase column, move left
        cl = cl - 1
!       and decrease maximum by one
        mx = mx - 1
!       if 
        if(cl .eq. 0) exit
      end do
      end

