program ColSort

! Sort on columns specified by $1 and $2.

! Sort order is ASCII

! Input is stdin, output is stdout.

! Maximum line length is 255

  implicit NONE

  integer :: C1, C2 ! First and last character of key field

  character(255), pointer :: Lines(:)
  character(255), pointer :: Lines_temp(:)
  
  integer :: I, N

  integer, allocatable :: P(:) ! Permutation vector

  interface ! from Math77
    subroutine CSORTP ( C, M, N, K, L, IP )
      character(len=*), intent(in) :: C(*)
      integer, intent(in) :: M, N, K, L
      integer, intent(out) :: IP(*)
    end subroutine CSORTP
  end interface

  allocate ( lines(100) )

  call getarg ( 1, lines(1) )
  read ( lines(1), *, iostat=n ) c1
  if ( n /= 0 ) then
    print *, 'First key position must be an integer'
    stop
  end if
  call getarg ( 2, lines(1) )
  read ( lines(1), *, iostat=n ) c2
  if ( n /= 0 ) then
    print *, 'Second key position must be an integer'
    stop
  end if

  if ( c1 > c2 ) then
    print *, 'First key position must not be greater than second key position'
    stop
  end if

  n = 0
  do
    if ( n > size(lines) ) then
      lines_temp => lines
      nullify ( lines )
      allocate ( lines(2*size(lines_temp)) )
      lines(:n-1) = lines_temp
      deallocate ( lines_temp )
    end if
    n = n + 1
    read ( *, '(a)', end=9 ) lines(n)
  end do

9 allocate ( p(n) )
  call csortp ( lines, 1, n, c1, c2, p )

  write ( *, '(a)' ) ( lines(p(i)), i = 1, n )

end program ColSort
