MODULE output_field_mod
  USE genmod
  USE xios_mod
  USE profiling_mod
  IMPLICIT NONE
  SAVE
  PRIVATE

  LOGICAL :: xios_output 
!$OMP THREADPRIVATE(xios_output)     
  LOGICAL :: enable_io    
!$OMP THREADPRIVATE(enable_io)     

  INTEGER :: id_output

  PUBLIC enable_io,xios_output,output_field_init,output_field,output_field_finalize, is_active_field

CONTAINS 
  
  SUBROUTINE output_field_init
  USE getin_mod
  IMPLICIT NONE

    CALL register_id('output',id_output)

    enable_io=.TRUE.
    CALL getin('enable_io',enable_io)

    IF (using_xios) THEN
      xios_output=.TRUE.
      CALL getin('xios_output',xios_output)
    ELSE
      xios_output=.FALSE.
    ENDIF
    
    IF (xios_output) THEN
      CALL xios_init_write_field
    ENDIF
  END SUBROUTINE output_field_init

  SUBROUTINE output_field(name_in,field)
    USE field_mod
    USE write_field_mod
    IMPLICIT NONE  
    CHARACTER(LEN=*),INTENT(IN) :: name_in
    TYPE(t_field),POINTER :: field(:)
    
    CALL enter_profile(id_output)
    IF (xios_output) THEN
       CALL xios_write_field(name_in,field)
    ELSE
       CALL writeField(name_in,field)
    ENDIF
    CALL exit_profile(id_output)

  END SUBROUTINE output_field

  SUBROUTINE output_field_finalize
    USE ioipsl
    IMPLICIT NONE
    
    IF (xios_output) THEN
       CALL xios_write_field_finalize
    ENDIF
    
  END SUBROUTINE output_field_finalize
  
  FUNCTION is_active_field(field_id)
  IMPLICIT NONE
    LOGICAL :: is_active_field
    CHARACTER(LEN=*),INTENT(IN) :: field_id
    
    IF (xios_output) THEN
      is_active_field =  xios_is_active_field(field_id)
    ELSE
      is_active_field=.TRUE.
    ENDIF
  END FUNCTION is_active_field
  
END MODULE output_field_mod
  
