!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
define header h 'name'.'type' read
!
if h%ndim.gt.4 then
  message e "PLOTBEAM" "Unsupported number of dimensions"
  return base
endif
!
if h%ndim.eq.4 then
  ! 4D case
  !
  ! --- User inputs here ---
  define integer ifield ibeam
  let ifield 0  ! 0 means plot all mosaic fields
  let ibeam  0  ! 0 means plot all beams
  ! --- End of user inputs ---
  !
  define integer do_ifield do_ibeam nx ny nfields nbeams
  let nx      h%dim[1]
  let ny      h%dim[2]
  let nfields h%dim[3]
  let nbeams  h%dim[4]
  if ifield.eq.0.and.nfields.eq.1 then  ! Degenerate dimension
    let do_ifield 1
  else
    let do_ifield 0
  endif
  if ibeam.eq.0.and.nbeams.eq.1 then  ! Degenerate dimension
    let do_ibeam 1
  else
    let do_ibeam 0
  endif
  !
  ! Sanity check
  if do_ifield.ne.0 then
    if do_ifield.lt.1.or.do_ifield.gt.nfields then
      message e "PLOTBEAM" "Field number must be in range 1-"'nfields'
      return base
    endif
  endif
  if do_ibeam.ne.0 then
    if do_ibeam.lt.1.or.do_ibeam.gt.nbeams then
      message e "PLOTBEAM" "Beam number must be in range 1-"'nbeams'
      return base
    endif
  endif
  if (do_ifield.eq.0.and.nfields.gt.1).and.(do_ibeam.eq.0.and.nbeams.gt.1) then
    message e "PLOTBEAM" "Can not plot all fields and all beams at the same time"
    message e "PLOTBEAM" "Select one field and/or one beam"
    return error
  endif
  !
  ! Now load the relevant data
  define image allbeam 'name'.'type' read  ! Need the whole data
  if exist(mybeam)  delete /var mybeam
  if do_ifield.gt.0.and.do_ibeam.gt.0 then
    ! Single field + single beam => 2D image
    define image mybeam[nx,ny] * real /global
    let mybeam allbeam[,,do_ifield,do_ibeam]
    let mybeam% allbeam%
    ! Only 2 dimensions, nothing to patch
  else if do_ifield.gt.0 then
    ! Single field => 3D cube
    define image mybeam[nx,ny,nbeams] * real /global
    let mybeam allbeam[,,do_ifield,]
    let mybeam% allbeam%
    ! Need to put the 4th dimension (beam dimension) as 3rd one
    let mybeam%convert[,3] allbeam%convert[,4]
    let mybeam%unit3       'allbeam%unit4'
    let mybeam%f_axis      3  ! Beam axis is a spectral axis (see convert array)
  else if do_ibeam.gt.0 then
    define image mybeam[nx,ny,nfields] * real /global
    let mybeam allbeam[,,,do_ibeam]
    let mybeam% allbeam%
    ! 3 first dimensions correctly copied
  endif
  del /var allbeam
  !
  @ p_lmv_map.greg mybeam 1
  !
  delete /var mybeam
  !
else
  ! 2D or 3D case: standard procedure
  @ p_nice
endif
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
