
   Integer, Parameter :: N=33
   Integer :: i, k, N_Spell 
   Integer :: X(N)
   Real :: X1(N), M1(N), IMAX1, Spells(N), N_Spell_1, I_Start(N), I_End(N), Miss
   Character (Len=255) :: St

   St="1 0 0 1 1 0 1 1 0 0 0 1 0 1 0 0 1 1 1 1 1 0 1 1 1 0 1 1 0 1 1 0 1"

   read (St,*) (X(i),i=1,N)
   print "(10I3)", (X(i),i=1,N)
   X1(:) = X(:)
   
   Call NSpell_and_Leng (X1, N, M1, Imax1, Spells, N_Spell_1, I_Start, I_End, -99.)

   print "(10I5)", (Int(M1(i)),i=1,Int(Imax1))
   print*
   print "(10I5)", (i,i=1,Int(N_Spell_1))
   print "(10I5)", (Int(Spells(i)),i=1,Int(N_Spell_1))
   print*
   print "(10I5)", (Int(I_Start(i)),i=1,Int(N_Spell_1))
   print "(10I5)", (Int(I_End(i)),i=1,Int(N_Spell_1))

   CONTAINS
   Include "/home/tanpv/Mylibs/Sub_NSpell_and_Leng.f90"

   END

!-----------------------------------------------------------------------
! Calculate percentile
!
      subroutine percentile(x, length, nl, per, oout)
      use COMM
      use functions
      integer :: length,nl    ! elements # of x and per
      real(DP),dimension(length):: x,xtos    ! input array, and its non-MISSING part
      real(DP),dimension(nl)    :: per,oout  ! percentile level and results
      real(DP):: bb,cc ! temporary variable
      integer :: nn,i  ! loop index and count #

! check if percentile level is out of bound.
      if(maxval(per)>1..or.minval(per)<0.) stop 'ERROR in percentile: per out of range [0.,1.] !'

! choose non-MISSING input, but is it necessary? I think x is already chosen ......
      nn=0
      do i=1, length
        if(nomiss(x(i)))then
          nn=nn+1
          xtos(nn)=x(i)
        endif
      enddo

      if(nn.eq.0) then
        oout=MISSING
      else
        call sort(nn,xtos) ! ascending numerical order
        do i=1,nl
          bb=nn*per(i)+per(i)/3.+1./3.
          cc=real(int(bb))
          if(int(cc).ge.nn) then
            oout(i)=xtos(nn)
          else
            oout(i)=xtos(int(cc))+(bb-cc)*       &
               (xtos(int(cc)+1)-xtos(int(cc)))
          endif
        enddo
      endif

      return
      end subroutine percentile
