subroutine cubeio_update_cube(cubset,cubdef,head,cub,error)
  use cubeio_messaging
  use cubetools_header_types
  use cubetools_setup_types
  use cubeio_interfaces, except_this=>cubeio_update_cube
  use cubeio_cube_define
  use cubeio_header
  use cubeio_range
  use cubeio_cube
  !---------------------------------------------------------------------
  ! @ private
  ! Update a cube from memory to disk
  !---------------------------------------------------------------------
  type(cube_setup_t),  intent(in)    :: cubset
  type(cube_define_t), intent(in)    :: cubdef
  type(cube_header_t), intent(in)    :: head
  type(cubeio_cube_t), intent(inout) :: cub
  logical,             intent(inout) :: error
  ! Local
  character(len=*), parameter :: rname='UPDATE>CUBE'
  type(cubeio_range_t) :: range
  !
  select case (cub%desc%buffered)
  case (code_buffer_none)
    call cubeio_message(seve%e,rname,'No data available')
    error = .true.
    return
    !
  case (code_buffer_memory)
    ! Update everything (header+data) from memory to disk. The file
    ! should already be opened in cub%file%hgdf
    call cubeio_create_hgdf(head,cub%desc,cub%order(),cub%file%hgdf,error)
    if (error)  return
    call gdf_update_header(cub%file%hgdf,error)
    if (error)  return
    range%blc(:) = 0
    range%trc(:) = 0
    if (cub%desc%iscplx) then
      call cubeio_write_cube_data(rname,cubset,cub,range,cub%memo%c4,error)
    else
      call cubeio_write_cube_data(rname,cubset,cub,range,cub%memo%r4,error)
    endif
    if (error)  return
    ! Do not close the GDF image, as it was opened
    !
    call cubeio_message(seve%i,rname,'Cube updated in file '//cub%file%hgdf%file)
    !
  case (code_buffer_disk)
    ! Already on disk... might need flushing the last buffer.
    call cubeio_flush_block(cubset,head,cub,cub%file%block,error)
    if (error)  return
    !
    call cubeio_message(seve%i,rname,'Cube updated in file '//cub%file%hgdf%file)
    !
  case default
    call cubeio_message(seve%e,rname,'Unexpected buffering kind')
    error = .true.
    return
  end select
  !
end subroutine cubeio_update_cube
