program sortint
  use gildas_def
  use image_def
  use gkernel_interfaces
  !---------------------------------------------------------------------
  ! GILDAS	Stand alone program
  !	Sort a table according to a given column
  !	This version considers the data in the sorting column as I*4
  !---------------------------------------------------------------------
  ! Local
  integer :: i,scol,ier
  logical :: error
  character(len=filename_length) :: name
  type(gildas) :: x
  integer, allocatable :: it(:),iw(:),ix(:)
  integer(kind=4) :: n
  !
  call gildas_open
  call gildas_char('TABLE$',name)
  call gildas_inte('COLUMN$',scol,1)
  call gildas_close
  !
  call gildas_null(x, type = 'TABLE')
  x%gil%form = fmt_i4
  call gdf_read_gildas(x, name, '.tab', error, data=.false.)
  if (error) then 
    write(6,*) 'E-SORT,  Error reading table'
    goto 100
  endif
  if (scol.lt.1 .or. scol.gt.x%gil%dim(2)) then
    write(6,*) 'E-SORT,  Sorting column does not exist'
    goto 100
  endif
  !
  allocate (ix(x%gil%dim(1)),it(x%gil%dim(1)),iw(x%gil%dim(1)), stat=ier)
  if (ier.ne.0) goto 98 
  x%blc(2) = scol
  x%trc(2) = scol
  call gdf_read_data(x, ix, error)
  n = x%gil%dim(1)
  call gi4_trie(ix,it,n,error)
  if (error) then
    call gagout ('F-SORT,  Table not sorted')
    call sysexi (fatale)
  endif
  call gdf_write_data(x, x%r1d, error)
  do i=1,x%gil%dim(2)
    if (i.ne.scol) then
      x%blc(2) = i
      x%trc(2) = i
      call gdf_read_data(x, ix, error)
      call gi4_sort(ix,iw,it,n)
      call gdf_write_data(x, ix, error)
    endif
  enddo
  call gdf_close_image (x,error)
  call gagout ('S-SORT,  Successfull completion')
  call sysexi (1)
  goto 100
98 call gagout ('E-SORT,  Memory allocation failure on work space')
100 call sysexi(fatale)
end program sortint
