      subroutine lltooc(xlon,ylat,i,j,n,k,ks1,ks2)

      implicit none
      include 'param_o.h'

      real::xlon,ylat,xmap,ymap,xmap0,xsi,eta
      integer::i,j,n,k,kmap,ind,il,jl,ks1,ks2
      real,dimension(3)::xe
      real,dimension(2)::xm
      logical::lx1,lx2,lx3,ly1,ly2,ly3
      real,parameter::d1r3=1./3.,d2r3=2./3.,one=1.,tri=3.
      real::x0,y0,z0,x1,y1,z1,x2,y2,z2,csal,snal,csbt,snbt,csgm,sngm

        x2=Cos(ylat)*Cos(xlon)
        y2=Cos(ylat)*Sin(xlon)
        z2=Sin(ylat)
 
      csal=Cos(alfa)
      snal=Sin(alfa)
      csbt=Cos(beta)
      snbt=Sin(beta)
      csgm=cos(gamm)
      sngm=sin(gamm)

        x0 = x2 * csgm - y2 * sngm
        y0 = x2 * sngm + y2 * csgm
        z0 = z2  
        x1=x0
        y1=y0*csbt-z0*snbt
        z1=y0*snbt+z0*csbt
        x0=x1*csal-y1*snal
        y0=x1*snal+y1*csal
        z0=z1
        XE(1)=x0
        XE(2)=y0
        XE(3)=z0

      call ctoo(xe,xm,kmap)
        xmap=(1.+xm(1))*0.5
        ymap=(1.+xm(2))*0.5

	lx1=xmap.lt.d1r3
	lx3=xmap.ge.d2r3
	lx2=.not.(lx1.or.lx3)
	ly1=ymap.lt.d1r3
	ly3=ymap.ge.d2r3
	ly2=.not.(ly1.or.ly3)

      If(kmap.gt.0) Then	
	
	If(ly1) Then
	    If(lx1) Then
	      ind=6
	    Else If(lx2) Then
	      ind=7
	      xmap=xmap-d1r3
            Else
	      ind=8
	      xmap=xmap-d2r3
	    End If
	Else If(ly2) Then
	  ymap=ymap-d1r3
	    If(lx1) Then
	      ind=9
	    Else If(lx2) Then
	      ind=10
	      xmap=xmap-d1r3
	    Else
	       ind=11
	       xmap=xmap-d2r3
            End If
	Else 
	  ymap=ymap-d2r3
	    If(lx1) Then
	      ind=12
	    Else If(lx2) Then
	      ind=13
	      xmap=xmap-d1r3
	    Else
	      ind=14
	      xmap=xmap-d2r3
	    End If
	End If

      Else

	If(ly1) Then
	    If(lx1) Then
	      ind=8
	        xmap0=ymap
              ymap=d1r3-xmap
	      xmap=xmap0
	    Else If(lx2) Then
	      ind=1
	      xmap=xmap-d1r3
	    Else
	      ind=6
		xmap0=d1r3-ymap
	      ymap=xmap-d2r3
	      xmap=xmap0
	    End If
	Else If(ly2) Then
	  ymap=ymap-d1r3
	    If(lx1) Then
	      ind=2
	    Else If(lx2) Then
	      ind=3
	      xmap=xmap-d1r3
	    Else
	      ind=4
	      xmap=xmap-d2r3
	    End If
	Else
	    If(lx1) Then
	      ind=14
		xmap0=one-ymap
              ymap=xmap
	      xmap=xmap0
	    Else If(lx2) Then
	      ind=5
    	      xmap=xmap-d1r3
	      ymap=ymap-d2r3
	    Else
	      ind=12
		xmap0=ymap-d2r3
              ymap=one-xmap
	      xmap=xmap0
	    End If
	End If

      End If

	xmap=tri*xmap
	ymap=tri*ymap
	xsi=xmap*(im-1)
	eta=ymap*(jm-1)
	il=xsi+1
	jl=eta+1
        xsi=xsi-il+1
	eta=eta-jl+1

	n=ind

	if(xsi.lt.0.5.and.eta.lt.0.5)then
	  i=il
	  j=jl
	  k=3
        else if(xsi.lt.0.5.and.eta.ge.0.5)then
	  i=il
	  j=jl+1
	  k=1
        else if(xsi.ge.0.5.and.eta.lt.0.5)then
	  i=il+1
	  j=jl
	  k=2
        else
	  i=il+1
	  j=jl+1
	  k=4
        endif

	ks1=xsi*4.+1
	ks2=eta*4.+1

	end subroutine lltooc


