!***********************************************************************
! ISPACK FORTRAN SUBROUTINE LIBRARY FOR SCIENTIFIC COMPUTING
! Copyright (C) 1998--2019 Keiichi Ishioka <ishioka@gfd-dennou.org>
!
! This library is free software; you can redistribute it and/or
! modify it under the terms of the GNU Lesser General Public
! License as published by the Free Software Foundation; either
! version 2.1 of the License, or (at your option) any later version.
!
! This library is distributed in the hope that it will be useful,
! but WITHOUT ANY WARRANTY; without even the implied warranty of
! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
! Lesser General Public License for more details.
!
! You should have received a copy of the GNU Lesser General Public
! License along with this library; if not, write to the Free Software
! Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
! 02110-1301 USA.
!***********************************************************************
SUBROUTINE SXLMNM(MM,NN,L,N,M,MI)

  IMPLICIT NONE
  INTEGER(8) :: MM,NN,N,M,L,MI,LS,LM,K
  REAL(8) :: DK

  LM=(MM/MI+1)*(2*(NN+1)-MM/MI*MI)

  IF(L.GT.LM) THEN
     N=-1
     M=0
     RETURN
  END IF

  DK= (NN+1D0)/MI + 0.5D0
  DK=DK-SQRT(DK*DK-(L-0.5D0)/MI)
  K=INT(DK, 8)

  M=K*MI

  IF(M.GT.MM) THEN
     N=-1
     M=0
     RETURN
  END IF

  LS=K*(2*(NN+1)-(K-1)*MI)+1

  IF(M.EQ.0) THEN
     N=L-1
  ELSE
     N=M+(L-LS)/2
     IF(MOD(L-LS,2_8).EQ.1) THEN
        M=-M
     END IF
  END IF

  IF(N.GT.NN) THEN
     N=-1
     M=0
  END IF

END SUBROUTINE SXLMNM
