program primary
  use image_def
  use gkernel_interfaces
  use gbl_format
  use mapping_primary
  !---------------------------------------------------------------------
  ! Make primary beam division OR multiplication
  !---------------------------------------------------------------------
  ! Local
  character(len=80) :: namex,namey
  type(gildas) :: sky
  type(gildas) :: raw
  real :: bsize,bgood
  real, allocatable :: dprim(:,:)
  real, allocatable :: dtmp(:,:)
  !
  integer :: i,j,nx,ny, ier
  logical :: error, divide
  !
  call gildas_open
  call gildas_char('Y_NAME$',namey)
  call gildas_char('X_NAME$',namex)
  call gildas_real('BEAM$',bsize,1)
  call gildas_real('RADIUS$',bgood,1)
  call gildas_close
  !
  if (bsize.gt.0) then
     divide = .true.
  else
     divide = .false.
  endif
  !
  if (bgood.eq.0) then
     bgood = 0.5*sqrt(log(5.0)/log(2.0))*bsize
  endif
  bgood = exp(-2.0*log(2.0)*(bgood/bsize)**2)
  print *,'Bgood ',bgood
  !
  call gildas_null(raw)
  call gildas_null(sky)
  !
  call sic_parsef(namey,raw%file,' ','.lmv-clean')
  call gdf_read_header(raw,error)
  if (error) then
     call gagout('F-PRIMARY,  Cannot read input file')
     goto 100
  endif
  nx = raw%gil%dim(1)
  ny = raw%gil%dim(2)
  !
  ! Create output image
  call gdf_copy_header(raw,sky,error)
  call sic_parsef(namex,sky%file,' ','.lmv-sky')
  call gdf_create_image(sky,error)
  if (error) then
     call gagout('F-PRIMARY,  Cannot create output image')
     goto 100
  endif
  !
  allocate (dprim(nx,ny),dtmp(nx,ny),stat=ier)
  if (ier.ne.0) goto 100
  call mos_primary (sky,dprim,bsize) 
  if (divide) then
     where (dprim.lt.bgood) 
        dprim = 0
     else where
        dprim = 1.0/dprim
     end where
  else
     where (dprim.lt.bgood) 
        dprim = 0
     end where
  endif
  !
  do j=1,raw%gil%dim(4)
     raw%trc(4) = j
     raw%blc(4) = j
     do i=1,raw%gil%dim(3)
        raw%trc(3) = i
        raw%blc(3) = i
        call gdf_read_data(raw,dtmp,error)
        dtmp(:,:) = dtmp*dprim
        sky%trc = raw%trc
        sky%blc = raw%blc
        call gdf_write_data (sky,dtmp,error)
     enddo
  enddo
  call gdf_close_image (sky,error) 
  call gagout('S-PRIMARY,   Successful completion')
  call sysexi(1)
  !
100 call sysexi(fatale)
end program primary
!

