program map_aver
  use gildas_def
  use gkernel_interfaces
  use image_def
  !---------------------------------------------------------------------
  ! GILDAS
  !	Compress an input LMV-like image
  !---------------------------------------------------------------------
  ! Local
  character(len=filename_length) :: mapin,mapout
  integer :: nc(2),n,naver,ier
  logical :: error
  real :: dv
  integer(kind=size_length) :: nd
  type(gildas) :: x,y
  real(kind=8) :: xposi,yposi
  !
  ! Code:
  call gildas_open
  call gildas_char('INPUT_MAP$',mapin)
  call gildas_char('OUTPUT_MAP$',mapout)
  call gildas_inte('NC$',nc,2)
  call gildas_close
  !
  ! Input file
  n = len_trim(mapin)
  call gildas_null(y)
  y%gil%ndim = 3
  call gdf_read_gildas(y,mapin,'.lmv',error)
  if (error) then
    call gagout('F-MAP_COMPRESS,  Cannot read input cube')
    goto 999
  endif
  !
  call gildas_null(x)
  call gdf_copy_header(y,x,error)
  call sic_parsef(mapout,x%file,' ','.lmv')
  !
  ! Define number of channels
  ier = gdf_range(nc,y%gil%dim(3))
  if (ier.ne.0) goto 999
  naver = nc(2)-nc(1)+1
  !
  ! Build a pseudo axis aligned on the input one:
  !  - Number of channels set to 1,
  !  - Increment set to the extracted range,
  !  - Value at reference unchanged (same spectroscopic axis, e.g. regarding
  !    associated Rest Freq),
  !  - Center of averaged range (old axis) is aligned on the center of the
  !    output channel #1 (new axis)
  ! This writes as:
  x%gil%dim(3) = 1
! x%gil%val(3) = unchanged
  yposi = (nc(1)+nc(2))*0.5d0
  xposi = 1.d0
  x%gil%inc(3) = y%gil%inc(3)*naver
  x%gil%ref(3) = xposi - (yposi-y%gil%ref(3))/naver
  ! Do not forget the SPECTRO section
  x%gil%vres = y%gil%vres*naver
  x%gil%fres = y%gil%fres*naver
! x%gil%voff = unchanged
! x%gil%freq = unchanged
! x%gil%fima = unchanged
  !
  x%gil%extr_words = 0
  !
  call gdf_create_image(x,error)
  if (error)  goto 999
  !
  y%blc(3) = nc(1)
  y%trc(3) = nc(2)
  call gdf_read_gildas(y,mapin,'.lmv',error,rank=3)
  allocate (x%r2d(x%gil%dim(1),x%gil%dim(2)),stat=ier)
  !
  dv = 1.0/float(naver)
  nd = x%gil%dim(1)*x%gil%dim(2)
  call compress (y%r3d,nd,x%r2d,naver,dv)
  call gdf_write_data(x,x%r2d,error)
  if (error) goto 999
  call gagout('S-MAP_AVER,  Successful completion')
  call sysexi(1)
999 call sysexi(fatale)
end program map_aver
!
subroutine compress (in,n,out,nc,dv)
  use gildas_def
  integer(kind=size_length) :: n    !
  integer :: nc                     !
  real :: in(n,nc)                  !
  real :: out(n)                    !
  real :: dv                        !
  ! Local
  integer :: ic
  !
  out = in(:,1)
  do ic=2,nc
    out = out+in(:,ic)
  enddo
  out = out*dv
end subroutine compress
