!                                                                     vk/Oct09
!--------------------------------     m f i _     ----------------------------
!
!	GRIB_API Fortran and C interfaces have a major difference in accessing
!	GRIB messages:
!	- C interface uses 'grib_handle' structures
!	- Fortran interface uses 'gribid' integers
!
!	These two methods are not interchangable!
!
!	This file hides the source code for those 'mfi_*' routines that require
!	GRIB_API Fortran libraries (i.e. use 'gribid' integer), so that C/C++
!	programs do not need to know (link) with GRIB_API Fortran libs.
!
!	Subroutines starting with 'mifi_' are "Macro Internal Fortran Interface"
!	routines written in C.

!-------------------------------------------------------- mfi-grib
!

subroutine mfi_load_one_grib( fieldset_id, grib_id )

  use grib_api
  implicit none

  integer   fieldset_id, grib_id
  integer   msg_len, istatus, ista2
  character err_msg*77
  character, allocatable :: grib_msg(:)

  call mifi_get_msg_length( fieldset_id, msg_len )
  allocate( grib_msg( msg_len ) )

  call mifi_load_one_grib_to_memory( fieldset_id, grib_msg )

  call grib_new_from_message( grib_id, grib_msg, istatus )
  if( istatus .ne. 0 ) then
     print*,'GRIB_API error (grib_new_from_message):', istatus
     call grib_get_error_string( istatus, err_msg, ista2 )
     print*,'GRIB_API error msg: ', err_msg
     call mfi_fail( 'mfi_load_one_grib failed!' )
  endif

  return
end


subroutine mfi_save_grib( fieldset_id, grib_id )

  use grib_api
  implicit none

  integer   fieldset_id, grib_id
  integer   (kind=kindOfSize_t) byte_size
  integer   istatus, ista2, byte_size_as_int
  character err_msg*77
  character, allocatable :: grib_msg(:)

  call grib_get_message_size( grib_id, byte_size, istatus )
  if( istatus .ne. 0 ) then
     print*,'GRIB_API error (grib_get_message_size):', istatus
     call grib_get_error_string( istatus, err_msg, ista2 )
     print*,'GRIB_API error msg: ', err_msg
     call mfi_fail( 'mfi_save_grib failed!' )
  endif

  allocate( grib_msg(byte_size) )

  call grib_copy_message( grib_id, grib_msg, istatus ) !-- byte_size ) !, status ) <-- doc error

  byte_size_as_int = byte_size  !-- because it's passed as a pointer to fortint
  call mifi_save_one_grib_to_file( fieldset_id, grib_msg, byte_size_as_int )

  deallocate( grib_msg )

  return
end

