program spectrum
  use gildas_def
  use image_def
  use gkernel_interfaces
  use gkernel_types
  ! Local
  character(len=filename_length) :: mapdata,mapsort
  character(len=80) :: abscoord
  logical :: error
  integer(kind=size_length) :: ix, iy, n
  real*8 :: abs1, abs2, user1,user2
  character(len=24) :: ra, dec
  type(gildas) :: x,y
  integer :: ier
  type(projection_t) :: proj
  !
  call gildas_open
  call gildas_char('IN$',mapdata)
  call gildas_char('OUT$',mapsort)
  call gildas_char('COORD$',abscoord)
  call gildas_close
  !
  ! Echo the input values
  write(6,*) 'Input file: ',trim(mapdata)
  write(6,*) 'Output file: ',trim(mapsort)
  write(6,*) 'Coordinates (absolute): ',trim(abscoord)
  !
  ! Input file
  if (len_trim(mapdata).eq.0) goto 999
  call gildas_null(y)
  y%gil%ndim = 3 ! Must be a data cube
  call gdf_read_gildas(y,mapdata,'.lmv',error)
  if (error) then
    call gagout('F-SPECTRUM,  Cannot read input cube')
    goto 999
  endif
  !
  call gwcs_projec(y%gil%a0,y%gil%d0,y%gil%pang,y%gil%ptyp,proj,error)
  if (error)  goto 999
  abscoord = adjustl(abscoord)  ! Remove leading blanks to ease parsing
  n = len_trim(abscoord)
  ra = abscoord(1:index(abscoord, ' '))
  dec = abscoord(index(abscoord, ' ')+1:n)
  call sic_decode(ra,abs1,24,error)
  if (error) then
    call gagout('F-SPECTRUM,  error in SIC_DECODE')
    goto 999
  endif
  call sic_decode(dec,abs2,360,error)
  if (error) then
    call gagout('F-SPECTRUM,  error in SIC_DECODE')
    goto 999
  endif
  call abs_to_rel(proj,abs1, abs2, user1, user2, 1)
  ix = nint((user1 - y%gil%val(1))/y%gil%inc(1) + y%gil%ref(1))
  iy = nint((user2 - y%gil%val(2))/y%gil%inc(2) + y%gil%ref(2))
  write(6,*) 'Coordinates (pixels): ',ix,iy
  if (ix.le.0 .or. ix.gt.y%gil%dim(1) .or.  &
      iy.le.0 .or. iy.gt.y%gil%dim(2)) then
    write(6,*) 'F-SPECTRUM, Coordinates are off the cube'
    goto 999
  endif
  !
  ! Output file is a Table
  call gildas_null(x, type = 'TABLE')
  call sic_parsef(mapsort,x%file,' ','.tab')
  !
  ! Reset axes definitions
  x%gil%ndim = 2
  x%gil%dim(1) = y%gil%dim(3)
  x%gil%dim(2) = 2
  allocate (x%r2d(x%gil%dim(1),x%gil%dim(2)), stat=ier)
  !
  ! Velocity values
  do n=1,x%gil%dim(1) 
    x%r2d(n,1) = (dble(n)-y%gil%ref(3))*y%gil%inc(3)+y%gil%val(3)
  enddo
  !
  ! Intensity values
  do n=1,x%gil%dim(1)
    x%r2d(n,2) = y%r3d(ix,iy,n)
  enddo
  !
  call gdf_write_image(x,x%r2d,error)
  call gagout('S-SPECTRUM,  Successful completion')
  call sysexi(1)  ! Success
  !
999 call sysexi(fatale)  ! Error
end program spectrum
