!! Pierre-Antoine Bretonnière, Institut Català de Ciènces del Clima <pierre-antoine.bretonniere@ic3.cat>

!! Adapted from nemo2cmor originally created by Alasatair McKinstry, ICHEC

!! Last edited: 2012-07-03

PROGRAM specs2cmor
  USE netcdf
  USE cmor_users_functions
  IMPLICIT NONE

  ! Use params as enumerator not yet supported everywhere
  INTEGER, PARAMETER :: oimon_sic = 1, oimon_sic2 = 3, oimon_sit = 2,  &
       oimon_snd = 128, oimon_tsice = 130, &
       oimon_strairx = 131, oimon_strairy = 132, &
       oimon_usi=146, oimon_vsi=147, oimon_rsdsi=148, &
       da_mrso=21, da_snld=20, da_tauu=19, da_rls=18, da_tauv=17, &
       da_rlds=27, da_uas=26, da_vas=25, da_evlwr=24, da_rss=23, da_rsdt=22,&
       da_psl=32, da_prsn=31, da_hfss=30, da_hfls=29, da_rsds=28, &
       da_sic = 33, da_sit = 34, da_tasmin = 36, &
       da_tasmax = 37, da_pr = 39, da_snd=16, da_tsice=15, &
       da_t20d = 38, da_mlotst= 40, da_tos=41, &
       omon_thetao = 45, omon_so = 46, &
       omon_fsitherm = 50, omon_wfo = 51, &
       omon_vsfsit = 52, omon_mlotst = 53, omon_omlmax = 54, &
       omon_rsntds = 55, omon_uo = 56, omon_vo = 57, &
       omon_masso = 58, omon_pbo = 59, omon_pso = 60, &
       omon_volo = 61, omon_masscello = 62, omon_zostoga = 63, &
       omon_thkcello = 64, omon_zosga = 65, omon_zossga = 66, &
       omon_thetaoga = 66, omon_soga = 67, omon_wmo = 68, &
       omon_wmosq = 69, omon_sfdsi = 70, omon_hfsithermds = 71, &
       omon_umo = 72, omon_vmo = 73, omon_msftmrhoz = 75, &
       omon_msftyyz = 135, & 
       omon_hfx = 77,  omon_hfy = 78, omon_htovgyre = 79, &
       omon_htovovrt = 80, omon_sltovgyre = 81, omon_sltovovrt = 82, &
       omon_pr = 83, omon_prsn = 84, omon_evs = 85, omon_friver = 86, &
       omon_ficeberg = 87, omon_wfonocorr = 89, omon_wfcorr = 90, &
       omon_vsfpr = 91, omon_vsfevap = 92, omon_vsfriver = 93, omon_vsf = 94, &
       omon_vsfcorr = 95, omon_sfriver = 96, omon_hfgeou = 97, omon_hfrainds = 98, &
       omon_hfevapds = 99, omon_hfrunoffds = 100, omon_hfsnthermds = 101, &
       omon_hfibthermds = 102, omon_rlds = 103, omon_hfls = 104, omon_hfss = 105, &
       omon_rsds = 106, omon_hfcorr = 107, omon_hfds = 108, omon_tauuo = 109, &
       omon_tauvo = 110, omon_tauucorr = 111, omon_tauvcorr = 112, &
       omon_tossq = 113, omon_zossq = 114, omon_rhopoto = 115, omon_agessc = 116, &
       omon_cfc11 = 117, omon_msftbarot = 118, omon_mlotstsq = 119, &
       omon_omldamax = 120, omon_tos=136, omon_sos=137, omon_zos=138, omon_t20d=139, &
       omon_thetaot=140, omon_wo=141, &
       omon_msftmyza = 149, omon_msftmyz = 150, omon_msftmyzba = 151, omon_hfnortha = 152, &
       omon_hfnorth = 153, omon_sltnortha = 154, omon_sltnorth = 155, &
       lmon_mrros = 122, &
       fx_deptho = 123, fx_areacello = 124, fx_sftof = 125, fx_basin = 126, &
       fx_basinv = 127, fx_volcello = 128, fx_sftlf=129, fx_goro=130, fx_wmb=144, fx_al=145, &
       fx_fc=133, fx_sftgif=134, fx_sr=142, fx_wp=143, mon_lt=195, da_lt=196 
  
  INTEGER :: sy , sx 
!  INTEGER, PARAMETER :: sy = 362, sx = 292
  CHARACTER (len=80) :: namfile
  
  CHARACTER (len=80) :: time_units, calendar, interval, interval_i
  INTEGER :: status, j,k, ncid_t, ncid_i, ncid_u, ncid_v, ncid_w, ntimes, ntimes_i
  LOGICAL :: initialized = .FALSE., fourmonths = .FALSE., finished = .FALSE.
  INTEGER, PARAMETER :: priority = 0   ! Only output highest priority items for now
  INTEGER, DIMENSION(200) :: varids 
  DOUBLE PRECISION :: bt
  DOUBLE PRECISION, DIMENSION(:), ALLOCATABLE :: oimon_time, omon_time,fx_time,day_time
  DOUBLE PRECISION, DIMENSION(:,:), ALLOCATABLE :: oimon_time_bnds, omon_time_bnds,fx_time_bnds,day_time_bnds
  REAL, DIMENSION(:,:), ALLOCATABLE  :: lat_coords, long_coords
  REAL, DIMENSION(:,:,:), ALLOCATABLE :: lat_vertices, long_vertices
!  REAL, DIMENSION(sy,sx)  :: lat_coords, long_coords
!  REAL, DIMENSION(4,sy, sx) :: lat_vertices, long_vertices
  REAL, DIMENSION(:), ALLOCATABLE :: depths_u, depths_v, depths_t, depths_w
  INTEGER :: numvars, year, month, realization, initialization_method, startyear, endyear, ioe, startmonth, endmonth, physics_version
  INTEGER :: ax_time_oimon, ax_time_omon, monthnum,ax_time_fx,ax_time_day
  CHARACTER (len=4) :: expname
  CHARACTER(LEN=2) :: frequency
  CHARACTER (len=256) :: inpath,outpath, experiment_id, institution, model_id, source, &
   & history, comment, references, forcing, contact, institute_id,  parent_experiment_id, &
   & parent_experiment_rip, project_id, physics_description,associated_model,initialization_description,forecast_reference_time,prefix,associated_experiment!batch
!  character(len=7) :: series
  integer:: i, numyears, nmonths, monthspresent,interv,jj,ecearth
  integer,dimension(4,6)::ind
  integer,dimension(6)::ncid

  ! 'fourmonths'  obsolete but left here so that old namelists still work.
!to be generalized (add model description?)
  NAMELIST /NAMEXP/ inpath, outpath, expname, experiment_id, institution, institute_id, model_id, source, &
   realization, history, comment, references, forcing, contact, institute_id, &
   startyear, endyear, parent_experiment_id, parent_experiment_rip, &
   startmonth, endmonth, initialization_method, initialization_description, physics_version, physics_description,&
   associated_model,forecast_reference_time,prefix,associated_experiment,ecearth!,series!,frequency!,calendar,batch

  write(6,*)"in specs2cmor0"!,ecearth
  call flush(6) 
  project_id="SPECS project"
  bt = 0.0
  ind=0
  ecearth=3
  write(6,*)"in specs2cmor"!,ecearth
  call flush(6) 
  IF (command_argument_count() /= 1) THEN
     WRITE(6,*) "Must be called with a namelist: specs2cmor <namelist>"
  ENDIF
  CALL get_command_argument( 1, namfile, status=status)
  CALL check( status, "Failed to read namelist file", namfile)
  OPEN(10, file=namfile, IOSTAT=ioe)
  READ(10, NAMEXP, IOSTAT=ioe, ERR=100)
  CLOSE(10)
  if (forcing .eq. "" ) then 
   forcing="N/A"
  endif
  if (physics_description .eq. "" ) then 
   physics_description="N/A"
  endif
  if (initialization_description .eq. "" ) then 
   initialization_description="N/A"
  endif
  if (associated_experiment .eq. "" ) then 
   associated_experiment="N/A"
  endif
  if (associated_model .eq. "" ) then 
   associated_model="N/A"
  endif
  
!4juillet  year=startyear
!4juillet  month=startmonth

!  write(6,*)"model_id ",model_id
!  call flush(6)
!  write(6,*)"str model_id ",model_id(9:9)
!  call flush(6)
!  write(ecearth,*) model_id(9:9)
!  read(model_id(9:9),*) ecearth
!  ecearth=2
  write(6,*)"ecearth version:",ecearth
  call flush(6)
   numyears = (endyear - startyear)
  if (startyear == endyear) then
      nmonths = endmonth - startmonth +1
   else
      nmonths = (numyears -1)*12 + (13-startmonth) + endmonth
   endif
  !write(6,*)"nmonths=",nmonths,numyears,startmonth,endmonth
  !call flush(6)
  if(nmonths.lt.1)then
   write(6,*)"nmonths < 1 , check your start/end dates coherency"
   call flush(6)
   stop 
  endif
!  write(6,*)'after =',physics_version,'-',initialization_method,'-',model_id,'-',realization,'-',experiment_id,'startyear,endyear',startyear,endyear,'nmonths=',nmonths
!  call flush(6) 
 
!  monthnum = 1 
!loop_interv: DO interv=1,4 !general loop on intervals
 DO interv=1,4 !general loop on intervals
  monthnum = 1 
  year=startyear
  month=startmonth
  initialized=.false.
!  var_avail=1
  ind=0
  DO while (monthnum <= nmonths)
!to be generalized
!  write(6,*)'before next_nemo file',numyears,endyear,year,month,interv,ecearth
!  call flush(6) 
     CALL next_nemo_files(year, month, ncid, monthspresent,ind(interv,:),interv,ecearth)
!  write(6,*)'after next_nemo file',interv,"ind:",ind(interv,:)
!  call flush(6) 
!loop2:  do jj=1,6
  do jj=1,6
!   if(jj.eq.6) cycle
   if(jj.eq.6) goto 200
   if(ind(interv,jj).eq.1) goto 200
!   write(6,*)'ind(',interv,',',jj,') after next_nemo file=',ind(interv,jj)
!   call flush(6) 
  enddo !loop2 
!  if(jj.eq.6) exit loop_interv
200 if(jj.eq.6) goto 300 
!
  IF (.NOT. initialized) THEN
        varids = -1
!  write(6,*)'before read calendar',ncid_t
!  call flush(6) 

        CALL read_calendar( ncid(1), calendar,ecearth)
!  write(6,*)'after read calendar',calendar
!  call flush(6) 

        j = CMOR_REPLACE_4
        K = CMOR_EXIT_ON_MAJOR
!write(6,*)"before setup"
!call flush(6)
!        CMOR_SPECS=1
        CMOR_PROJECT="SPECS"
        CALL check( cmor_setup( &
             inpath = 'data', &
             netcdf_file_action = j, &
             exit_control = k,&
             arg_cmor_project = CMOR_PROJECT), &
!             specs = CMOR_SPECS), &
             "cmor_setup failed")
  physics_description=trim(physics_description)
  associated_model=trim(associated_model)
  associated_experiment=trim(associated_experiment)

!  write(6,*)'after cmor_setup'!,parent_experiment_rip,'-----','experiment_id:',experiment_id
!  call flush(6) 
!  write(6,*)'before cmor_dataset',realization!,'-----','experiment_id:',experiment_id
!  call flush(6) 
        CALL check( cmor_dataset( &
             outpath=outpath, &
             experiment_id=experiment_id, &
             institution= institution, &
             institute_id= institute_id, &
             source=source, &
             calendar="gregorian", &
!             calendar=calendar, &
             realization=realization, &
             contact=contact, &
             history=history, &
             comment=comment, &
             references = references, &
             model_id=model_id, &
             forcing=forcing, &    
             initialization_method=initialization_method, &
             physics_version=physics_version, &
             parent_experiment_id=parent_experiment_id, &
             project_id=project_id, &
             initialization_description=initialization_description, &
             forecast_reference_time=forecast_reference_time, &
             associated_model=trim(associated_model) , &
             associated_experiment=trim(associated_experiment) , &
             physics_description=trim(physics_description), &
            ! series=series,&
             parent_experiment_rip=parent_experiment_rip), &
             "cmor_dataset() failed")
!  write(6,*)'after cmor_dataset',realization!,'-----','experiment_id:',experiment_id
!  call flush(6) 
!add grid conformity check
      CALL read_grids(ncid, & 
                      lat_vertices, long_vertices, lat_coords, long_coords )
write(6,*)"after read_grids"
call flush(6)
write(6,*)"sx,sy:",sx,sy
call flush(6)
!
!create time variables
     if(interv.eq.4.and.ind(4,5).eq.1)then
      write(6,*)"create axis and variable for OImon"
      call flush(6)
      CALL create_time_axis( ax_time_oimon, ncid(5), 'ice', 'Tables/SPECS_OImon', oimon_time, oimon_time_bnds, &
                             startyear, endyear, startmonth, endmonth,ecearth)
      CALL create_variables_oimon(varids, ncid(5),ncid(1), priority, ax_time_oimon, lat_coords, long_coords)
     endif
!    if(allocated(oimon_time))then
!     write(6,*)"after create time axis oimon, time allocated"
!     call flush(6)
!    else
!     write(6,*)"after create time axis oimon, time NOT allocated"
!     call flush(6)
!    endif


     if(interv.eq.1.and.ind(1,1).eq.1)then
!      write(6,*)"create axis and variable for fx"
!      call flush(6)
      CALL create_time_axis( ax_time_fx, ncid(1), 'oce', 'Tables/SPECS_fx', fx_time, fx_time_bnds, &
                             startyear, endyear, startmonth, endmonth,ecearth)!new pab
      CALL create_variables_fx(varids, ncid(1), priority, lat_coords, long_coords) !new pab
     endif

     if(interv.eq.4.and.ind(4,1).eq.1)then
!      write(6,*)"create axis and variable for Omon"
!      call flush(6)
      CALL create_time_axis( ax_time_omon, ncid(1), 'oce', 'Tables/SPECS_Omon', omon_time, omon_time_bnds, &
                             startyear, endyear, startmonth, endmonth,ecearth)
!  write(6,*)'after create variable omon thetao'!,ax_time_omon,'-----',omon_time,omon_time_bnds
!  call flush(6)
      CALL create_variables_omon(varids, ncid(1), priority, ax_time_omon, lat_coords, long_coords)
     endif
     if(interv.eq.4.and.ind(4,6).eq.1)then
!      write(6,*)"create axis and variable for diaptr",ncid(6)
!      call flush(6)
      CALL create_time_axis( ax_time_omon, ncid(6), 'oce', 'Tables/SPECS_Omon', omon_time, omon_time_bnds, &
                             startyear, endyear, startmonth, endmonth,ecearth)
      CALL create_variables_diaptr(varids, ncid(6), priority, ax_time_omon, lat_coords, long_coords)
     endif
!    if(allocated(omon_time))then
!     write(6,*)"after create time axis omon, time allocated"
!     call flush(6)
!    else
!     write(6,*)"after create time axis omon, time NOT allocated"
!     call flush(6)
!    endif


     if(interv.eq.3.and.ind(3,1).eq.1)then
!      write(6,*)"create axis and variable for day"
!      call flush(6)
      CALL create_time_axis( ax_time_day, ncid(1), 'oce', 'Tables/SPECS_day', day_time, day_time_bnds, &
                             startyear, endyear, startmonth, endmonth,ecearth)!new pab
     
!    if(allocated(day_time))then
!     write(6,*)"after create time axis, time allocated"
!     call flush(6)
!    else
!     write(6,*)"after create time axis, time NOT allocated"
!     call flush(6)
!    endif
      CALL create_variables_day(varids, ncid(1), priority, ax_time_day, lat_coords, long_coords)!new pab
     endif
!      write(6,*)"after create axis and variable for day"!,day_time

      initialized = .TRUE.
     END IF
!write(6,*)"before output simple"
!call flush(6)
     CALL output_simple_vars(varids, ncid,oimon_time, oimon_time_bnds,  omon_time, omon_time_bnds, &
!     CALL output_simple_vars(varids, ncid(1), ncid(5),ncid(2),ncid(3),oimon_time, oimon_time_bnds,  omon_time, omon_time_bnds, &
                             day_time, day_time_bnds,fx_time, fx_time_bnds, monthnum, monthspresent)
!  write(6,*)'after output'!,parent_experiment_rip,'-----','experiment_id:',experiment_id
!  call flush(6) 

     monthnum = monthnum + monthspresent
       
    DO jj=1,6
     if(ind(interv,jj).eq.1)then
      CALL close_file( ncid(jj))
     endif
    ENDDO
!write(6,*)"after close"
!call flush(6)
!     CALL close_file( ncid_u)
!     CALL close_file( ncid_v)
!     CALL close_file( ncid_w)
!     CALL close_file( ncid_i)
     month = month + monthspresent
     do while (month > 12) 
       month = month - 12
       year = year + 1
     end do
  END DO
!write(6,*)"before end loop",interv
!call flush(6)
  CALL check(cmor_close(), "cmor_close() failed!")  
!300 write(6,*)"before end loop2",interv
300 call flush(6)

 ENDDO !loop_interv ! end loop on intervals

  STOP

100 PRINT *,"FAILED TO READ NAMELIST" 

CONTAINS


  !> Open the files given the experiment, time.  Return the netcdf file handes.
  !@param syear,smonth  start year, month.
  !@param ncid_i, ncid_n, ncid_v, nvid_w, ncid_w, ncid_t  -  netcdf file handles.
  SUBROUTINE next_nemo_files(syear, smon, ncid, nmonths,ind_l,interv,ecearth)
    IMPLICIT NONE
    INTEGER, INTENT(IN) :: syear, smon, ecearth
    INTEGER,DIMENSION(6),INTENT(INOUT)::ind_l
    INTEGER, INTENT(OUT) :: nmonths
    INTEGER,DIMENSION(6) :: ncid!, nmonths
    CHARACTER(LEN=200),DIMENSION(6) :: file_name,grid_name
    CHARACTER(LEN=2) :: frequency
    INTEGER :: eday, emon, eyear, numyears, mn, interv
    INTEGER, DIMENSION(12) :: dayspermon = (/ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 /) 
    LOGICAL :: exists = .FALSE.
  write(6,*)'in next nemo files',syear,smon
  call flush(6) 

 if(interv.eq.1)then
  frequency="fx"
 elseif(interv.eq.2)then
  frequency="6h"
 elseif(interv.eq.3)then
  if(ecearth.eq.3)then
   frequency="1d"
  else
  frequency="DD"
  endif
 elseif(interv.eq.4)then
  if(ecearth.eq.3)then
   frequency="1m"
  else
   frequency="MM"
  endif
 endif

grid_name(1)="grid_T"
grid_name(2)="grid_U"
grid_name(3)="grid_V"
grid_name(4)="grid_W"
grid_name(5)="icemod"
grid_name(6)="diaptr"
    ! Iterate until we reach
    ! File formats are of the type: ORCA1_MM_18500101_18501231_grid_U.nc
    ! In principle this runs off the end of 
    mn = smon
outer:    do eyear = syear,endyear
       do emon = mn,endmonth
         eday = dayspermon(emon)
  call flush(6) 
         if (isLeap(eyear) .and. (emon == 2)) eday = 29
!to be generalized
!         WRITE(6,'(A,A,A1,A2,A1,I4,I2.2,A3,I4,I2.2,I2,A10)') trim(inpath),trim(prefix),'_',frequency,'_',syear,smon,'01_',eyear,emon,eday,'_grid_T.nc'
         WRITE(file_name(1),'(A,A,A1,A2,A1,I4,I2.2,A3,I4,I2.2,I2,A10)') trim(inpath),trim(prefix),'_',frequency,'_',syear,smon,'01_',eyear,emon,eday,'_grid_T.nc'
!!
         INQUIRE(FILE=file_name(1), EXIST=exists)
         IF (exists)  then
          ind_l(1)=1
!write(6,*),file_name(1), "found"
!call flush(6)
    IF ( eyear * 100 + emon > endyear * 100 + endmonth)  call check(1, "File found is beyond enddate in namelist")
          exit outer
         ELSE 
!write(6,*),file_name(1), "doesn't exist"
!call flush(6)
         ENDIF
       end do 
       mn = 1
    end do outer

!    if (.not. exists) then
!       write(*,*) 'DEBUG: Failed to find ', file_name(1)
!       call check( 1, "Could not find file")
!    endif
!    IF ( eyear * 100 + emon > endyear * 100 + endmonth)  call check(1, "File found is beyond enddate in namelist")

   numyears  = eyear - syear
   if (syear == eyear) then
      nmonths = emon - smon + 1
   else
      nmonths = (numyears -1)*12 + (13-smon) + emon
   endif
    

    ! File formats are of the type: ORCA1_MM_18500101_18501231_grid_U.nc
!to be generalized
!    WRITE(file_u,'(A,A,A4,A4,I4,I2.2,A3,I4,I2.2,I2,A10)') trim(inpath),trim(prefix),expname,'_MM_',syear,smon,'01_',eyear,emon,eday,'_grid_U.nc'
!    WRITE(file_v,'(A,A,A4,A4,I4,I2.2,A3,I4,I2.2,I2,A10)') trim(inpath),trim(prefix),expname,'_MM_',syear,smon,'01_',eyear,emon,eday,'_grid_V.nc'
!    WRITE(file_t,'(A,A,A4,A4,I4,I2.2,A3,I4,I2.2,I2,A10)') trim(inpath),trim(prefix),expname,'_MM_',syear,smon,'01_',eyear,emon,eday,'_grid_T.nc'
!    WRITE(file_w,'(A,A,A4,A4,I4,I2.2,A3,I4,I2.2,I2,A10)') trim(inpath),trim(prefix),expname,'_MM_',syear,smon,'01_',eyear,emon,eday,'_grid_W.nc'
!    WRITE(file_i,'(A,A,A4,A4,I4,I2.2,A3,I4,I2.2,I2,A10)') trim(inpath),trim(prefix),expname,'_MM_',syear,smon,'01_',eyear,emon,eday,'_icemod.nc'

!    WRITE(file_u,'(A,A,A4,I4,I2.2,A3,I4,I2.2,I2,A10)') trim(inpath),trim(prefix),'_MM_',syear,smon,'01_',eyear,emon,eday,'_grid_U.nc'
!    WRITE(file_v,'(A,A,A4,I4,I2.2,A3,I4,I2.2,I2,A10)') trim(inpath),trim(prefix),'_MM_',syear,smon,'01_',eyear,emon,eday,'_grid_V.nc'
!    WRITE(file_t,'(A,A,A4,I4,I2.2,A3,I4,I2.2,I2,A10)') trim(inpath),trim(prefix),'_MM_',syear,smon,'01_',eyear,emon,eday,'_grid_T.nc'
!    WRITE(file_w,'(A,A,A4,I4,I2.2,A3,I4,I2.2,I2,A10)') trim(inpath),trim(prefix),'_MM_',syear,smon,'01_',eyear,emon,eday,'_grid_W.nc'
!    WRITE(file_i,'(A,A,A4,I4,I2.2,A3,I4,I2.2,I2,A10)') trim(inpath),trim(prefix),'_MM_',syear,smon,'01_',eyear,emon,eday,'_icemod.nc'
!   

   DO jj=1,6
    WRITE(file_name(jj),'(A,A,A1,A2,A1,I4,I2.2,A3,I4,I2.2,I2,A1,A,A3)') trim(inpath),trim(prefix),'_',frequency,'_',syear,smon,'01_',eyear,emon,eday,'_',trim(grid_name(jj)),'.nc'
!    WRITE(file_v,'(A,A,A4,I4,I2.2,A3,I4,I2.2,I2,A10)') trim(inpath),trim(prefix),'_',frequency,'_',syear,smon,'01_',eyear,emon,eday,'_grid_V.nc'
!    WRITE(file_t,'(A,A,A4,I4,I2.2,A3,I4,I2.2,I2,A10)') trim(inpath),trim(prefix),'_',frequency,'_',syear,smon,'01_',eyear,emon,eday,'_grid_T.nc'
!    WRITE(file_w,'(A,A,A4,I4,I2.2,A3,I4,I2.2,I2,A10)') trim(inpath),trim(prefix),'_',frequency,'_',syear,smon,'01_',eyear,emon,eday,'_grid_W.nc'
!    WRITE(file_i,'(A,A,A4,I4,I2.2,A3,I4,I2.2,I2,A10)') trim(inpath),trim(prefix),'_',frequency,'_',syear,smon,'01_',eyear,emon,eday,'_icemod.nc'
!     write(6,*)"in next nemo, inquiring for file",file_name(jj),"interv=",interv
     INQUIRE(FILE=file_name(jj), EXIST=exists)
     
     IF (exists)  then
      ind_l(jj)=1
      CALL open_file(ncid(jj),file_name(jj))
      write(6,*)"opening ",file_name(jj),"jj=",jj,"ncid",ncid
      call flush(6)
     ELSE
      write(6,*)file_name(jj)," (jj=",jj,") doesn't exist"
      call flush(6)
     ENDIF 

ENDDO ! jj, loop on grids

!     write(6,*)"ind_l:",ind_l
!     call flush(6)

!    write(6,*),file_u,'before opened'
!    call flush(6)
!    CALL open_file( ncid_u, file_u)
!    write(6,*),file_u,'opened'
!    call flush(6)
!    CALL open_file( ncid_t, file_t)
!    write(6,*),file_t,'opened'
!    call flush(6)
!    CALL open_file( ncid_v, file_v)
!    write(6,*),file_v,'opened'
!    call flush(6)
!    CALL open_file( ncid_w, file_w)
!    write(6,*),file_w,'opened'
!    call flush(6)
!    CALL open_file( ncid_i, file_i)
!    write(6,*),file_i,'opened'
!    call flush(6)

  END SUBROUTINE next_nemo_files


  !> Open netcdf file; return handle. Abort on failure
  !@param ncid      netcdf handle
  !@param filename  name
  SUBROUTINE open_file(ncid, filename)
    IMPLICIT NONE
    CHARACTER(len=*), INTENT(IN) :: filename
    INTEGER,INTENT(out) :: ncid
    CALL check( nf90_open(filename, nf90_nowrite, ncid), "nf90_open failed", filename)
  END SUBROUTINE OPEN_FILE

  !> Trivial wrapper to close netcdf file
  !@param ncid   file handle
  SUBROUTINE close_file(ncid)
    IMPLICIT NONE
    INTEGER, INTENT(IN) :: ncid
    CALL check (nf90_close( ncid), "Close failed")
  END SUBROUTINE close_file


  !> Read a 1d array from a netCDF file
  !@param ncid     netcdf file handle
  !@param name     name of array. Will be ALLOCATEd; must be freed by CALLer.
  !@param array    data to return    
  SUBROUTINE read_array_1d( ncid, name, array,var_avail)
    IMPLICIT NONE
    INTEGER, INTENT(IN) :: ncid
    INTEGER,INTENT(OUT)::var_avail
    CHARACTER(len=*), INTENT(IN) :: name
    REAL, DIMENSION(:), ALLOCATABLE :: array      
    INTEGER :: varid, len_x
    INTEGER, DIMENSION(nf90_max_var_dims) :: dimIDs


    
    var_avail=nf90_inq_varid( ncid, name, varid)

   if(var_avail.eq.0)then
    CALL check( nf90_inquire_variable(ncid, varid, dimids = dimIDs), "inquire failed", name)
    CALL check( nf90_inquire_DIMENSION(ncid, dimIDs(1), len = len_x), "inquire failed", name)
    IF(.not.allocated(array)) ALLOCATE(array(len_x))
    CALL check( nf90_get_var( ncid, varid, array), "Failed to get var", name)
!   else
!    CALL check( var_avail, "Failed to read varid", name)
!    write(6,*)"pb in create ",name," ncid",ncid
!    call flush(6)
   endif
  END SUBROUTINE read_array_1d



  !> Read a 2d array from a netCDF file
  !@param ncid     netcdf file handle
  !@param name     name of array. Will be ALLOCATEd; must be freed by CALLer.
  !@param array    data to return
  !@param elm      (optional) element to retrieve from array (default = 1)
  SUBROUTINE read_array_2d( ncid, name, array, var_avail,elm)
    IMPLICIT NONE
    INTEGER, OPTIONAL :: elm
    INTEGER, INTENT(IN) :: ncid
    CHARACTER(len=*), INTENT(IN) :: name
    INTEGER,INTENT(OUT)::var_avail
    REAL, DIMENSION(:,:), ALLOCATABLE :: array      
    INTEGER :: varid, len_x, len_y
    INTEGER, DIMENSION(nf90_max_var_dims) :: dimIDs

    
    var_avail=nf90_inq_varid( ncid, name, varid) 
!    CALL check( nf90_inq_varid( ncid, name, varid), "Failed to read varid", name)
    CALL check( var_avail, "Failed to read varid", name)
!    write(6,*)"inq var status:",nf90_inq_varid( ncid, name, varid),nf90_strerror(nf90_inq_varid( ncid, name, varid))
!    call flush(6)
    if(var_avail.eq.0)then
!    if(nf90_inquire_variable( ncid, varid,dimids = dimIDs).eq.0)then
     CALL check( nf90_inquire_variable(ncid, varid, dimids = dimIDs), "inquire failed", name)
     CALL check( nf90_inquire_DIMENSION(ncid, dimIDs(1), len = len_x), "inquire failed", name)
     CALL check( nf90_inquire_DIMENSION(ncid, dimIDs(2), len = len_y), "inquire failed", name)
    if(allocated(array)) deallocate(array)
     ALLOCATE (array(len_x,len_y))
!"write(6,*)"dimensions:",len_x,len_y,"name:",name,"id:",ncid
!call flush(6)
     if (present(elm)) then
      CALL check( nf90_get_var( ncid, varid, array, start= (/ 1 , 1, elm /)), "Failed to get var element", name)
     else 
      CALL check( nf90_get_var( ncid, varid, array), "Failed to get var", name)
     endif
    endif
  END SUBROUTINE read_array_2d

  !> Read a 3D array from netCDF file.
  !@param ncid     netcdf file handle
  !@param name     name of array. Will be ALLOCATEd; must be freed by CALLer.
  !@param array    data to return
  !@param elm      (optional) element ,elmto retrieve from array (default = 1)
  SUBROUTINE read_array_3d( ncid, name, array,var_avail,elm)
    IMPLICIT NONE
    INTEGER, OPTIONAL :: elm
    INTEGER, INTENT(IN) :: ncid
    INTEGER,INTENT(OUT) :: var_avail
    CHARACTER(len=*), INTENT(IN) :: name
    REAL, DIMENSION(:,:,:), ALLOCATABLE :: array      
    INTEGER :: varid, len_x, len_y, len_z,x_id,y_id,z_id,true_lenx,true_leny,true_lenz
    INTEGER, DIMENSION(nf90_max_var_dims) :: dimIDs

!     write(6,*)"before reading varaible",name," in file with id:",ncid
!     call flush(6)
    var_avail=nf90_inq_varid( ncid, name, varid)

    CALL check( var_avail, "Failed to read varid", name)
    if(var_avail.eq.0)then
!    CALL check( nf90_inq_varid( ncid, name, varid), "Failed to read varid", name)
    CALL check( nf90_inquire_variable(ncid, varid, dimids = dimIDs), "inquire failed", name)
    CALL check( nf90_inquire_DIMENSION(ncid, dimIDs(1), len = len_x), "inquire failed", name)
    CALL check( nf90_inquire_DIMENSION(ncid, dimIDs(2), len = len_y), "inquire failed", name)
    CALL check( nf90_inquire_DIMENSION(ncid, dimIDs(3), len = len_z), "inquire failed", name)
!    if(allocated(array)) deallocate(array)
    ALLOCATE (array(len_x,len_y, len_z))
!write(6,*)"dimensions3d:",len_x,len_y,len_z,"name:",name,"id:",ncid
!call flush(6)
!        CALL check(nf90_inq_dimid(ncid,"x",x_id))
!        CALL check(nf90_inq_dimid(ncid,"y",y_id))
!        CALL check(nf90_inq_dimid(ncid,"deptht",z_id))
!        CALL check(nf90_inquire_dimension(ncid,x_id,len=true_lenx))
!        CALL check(nf90_inquire_dimension(ncid,y_id,len=true_leny))
!        CALL check(nf90_inquire_dimension(ncid,z_id,len=true_lenz))
!    write(6,*)"vraies dims:",true_lenx,true_leny,true_lenz
!    call flush(6)
    if (present(elm)) then
!      write(6,*)"le bug0 arrive",elm
!      call flush(6) 
      CALL check( nf90_get_var( ncid, varid, array, start=(/1,1,1,elm /)), "Failed to get var", name)
!      write(6,*)"le bug0 est passé",elm
!      call flush(6) 
    else
!      write(6,*)"le bug arrive"
!      call flush(6) 
      CALL check( nf90_get_var( ncid, varid, array), "Failed to get var", name)
!      write(6,*)"le bug est passé"
!      call flush(6) 
    endif
   endif
  END SUBROUTINE read_array_3d


  !> Check the status of a CALL, aborting with error message IF necessary
  !@param status    Status to check. Fail IF non-zero
  !@param str       String to report
  !@param parm      optional string to SUBROUTINE.

  SUBROUTINE check(status, str, parm)
    IMPLICIT NONE
    INTEGER, INTENT(IN) :: status
    CHARACTER(len=*), OPTIONAL, INTENT(IN) :: str, parm
    IF (status /= 0) THEN
       write(6,*)"error:",nf90_strerror(status)
       IF (present(str)) THEN
          IF (present(parm)) THEN
             WRITE(6,*) str, " : ", parm
          ELSE
             WRITE(6,*) str
          ENDIF
       ENDIF
!       CALL abort
    ENDIF
  END SUBROUTINE check

  !> Generate depth-axis from coordinate in netcdf file
  !@param axis_id   returned handle
  !@param ncid      netcdf file handle
  !@param varname   name of depth coordinate in netcdf file
  !@param table     SPECS table
  SUBROUTINE create_depth_axis(axis_id, ncid, varname, table)
    IMPLICIT NONE
    INTEGER, INTENT(OUT) :: axis_id
    INTEGER, INTENT(IN)  :: ncid
    INTEGER ::var_avail
    CHARACTER(len=*) :: varname, table
    REAL, DIMENSION(:), ALLOCATABLE :: depth, depth_bnds
    INTEGER :: i, sz

    axis_id=1
!    write(6,*)"call read array1d in create depth axis",ncid,varname
!    call flush(6)
    CALL read_array_1d( ncid, varname, depth,var_avail)      
    
    !  boundaries of the depth cells are half-way between depth points.
    ALLOCATE(depth_bnds( size(depth)+1))
    depth_bnds(1) = 0.
    sz = size(depth)
    if(sz.ge.2)then
    do i=1, sz-1
       depth_bnds(i+1) = (depth(i) +depth(i+1) )/2
    END do
    depth_bnds(sz+1) =  5500. ! Max depth
    axis_id = cmor_axis( &
         table=table, & 
         table_entry='depth_coord', &
         units='m', &
         length=sz, &
         coord_vals=depth, &
         cell_bounds=depth_bnds)
    endif 
  END SUBROUTINE create_depth_axis


  !> Read the grids from the files. Calculate cell boundaries
  SUBROUTINE  read_grids(ncid, &
                         lat_vertices, long_vertices, lat_coords, long_coords)
    IMPLICIT NONE
    INTEGER,DIMENSION(5), INTENT(IN) :: ncid
    real, intent(out),  dimension(:,:,:),allocatable :: lat_vertices, long_vertices
    real, intent(out), dimension(:,: ),allocatable :: lat_coords, long_coords
    REAL, DIMENSION(:,:), ALLOCATABLE :: longs_u, longs_v, longs_t, lats_u, lats_v, lats_t 
    INTEGER::var_avail,varid
    INTEGER, DIMENSION(nf90_max_var_dims) :: dimIDs 

call flush(6)
   if(ind(interv,2).eq.1)then
write(6,*)"ind(interv,2)"
call flush(6)
   CALL check( nf90_inq_varid( ncid(2), 'nav_lon', varid), "Failed to read varid for nav_lon in read_grid")
   CALL check( nf90_inquire_variable(ncid(2), varid, dimids = dimIDs), "inquire failed", "nav_lon")
   CALL check( nf90_inquire_DIMENSION(ncid(2), dimIDs(1), len = sy), "inquire failed", "nav_lon")
   CALL check( nf90_inquire_DIMENSION(ncid(2), dimIDs(2), len = sx), "inquire failed", "nav_lon")
write(6,*) "sx,sy2:",sx,sy
call flush(6)
    CALL read_array_2d(ncid(2), 'nav_lon', longs_u,var_avail)
    CALL read_array_2d(ncid(2), 'nav_lat', lats_u,var_avail)
    CALL read_array_1d(ncid(2), 'depthu', depths_u,var_avail)
    ! Don't have negative longitudes. 
    WHERE (longs_u < 0.) longs_u = longs_u + 360.
if(.not.allocated(long_vertices)) allocate(long_vertices(4,sy,sx))
    long_vertices(1,:,:) = longs_u
    long_vertices(4,:,:) = longs_u
    long_vertices(2,1,:) = longs_u(sy,:)
    long_vertices(3,1,:) = longs_u(sy,:)
    long_vertices(2,2:sy,:) = longs_u(1:sy-1,:)
    long_vertices(3,2:sy,:) = longs_u(1:sy-1,:)
    DEALLOCATE(longs_u,lats_u)
   endif
   if(ind(interv,3).eq.1)then
write(6,*)"ind(interv,3)"
call flush(6)
   CALL check( nf90_inq_varid( ncid(2), 'nav_lon', varid), "Failed to read varid for nav_lon in read_grid")
   CALL check( nf90_inquire_variable(ncid(3), varid, dimids = dimIDs), "inquire failed", "nav_lon")
   CALL check( nf90_inquire_DIMENSION(ncid(3), dimIDs(1), len = sy), "inquire failed", "nav_lon")
   CALL check( nf90_inquire_DIMENSION(ncid(3), dimIDs(2), len = sx), "inquire failed", "nav_lon")
write(6,*) "sx,sy3:",sx,sy
call flush(6)
    CALL read_array_2d(ncid(3), 'nav_lon', longs_v,var_avail)
    CALL read_array_2d(ncid(3), 'nav_lat', lats_v,var_avail)
    CALL read_array_1d(ncid(3), 'depthv', depths_v,var_avail)
    ! Don't have negative longitudes. 
    WHERE (longs_v < 0.) longs_v = longs_v + 360.
if(.not.allocated(lat_vertices)) allocate(lat_vertices(4,sy,sx))
    lat_vertices(1,:,:) = lats_v
    lat_vertices(2,:,:) = lats_v
    lat_vertices(3,:,2:sx) = lats_v(:,1:sx-1)
    lat_vertices(4,:,2:sx) = lats_v(:,1:sx-1)
    lat_vertices(3,:,1) = -90.
    lat_vertices(4,:,1) = -90.
    DEALLOCATE(longs_v,lats_v)
   endif
   if(ind(interv,1).eq.1)then
write(6,*)"ind(interv,1)"
call flush(6)
   CALL check( nf90_inq_varid( ncid(1), 'nav_lon', varid), "Failed to read varid for nav_lon in read_grid")
   CALL check( nf90_inquire_variable(ncid(1), varid, dimids = dimIDs), "inquire failed", "nav_lon")
   CALL check( nf90_inquire_DIMENSION(ncid(1), dimIDs(1), len = sy), "inquire failed", "nav_lon")
   CALL check( nf90_inquire_DIMENSION(ncid(1), dimIDs(2), len = sx), "inquire failed", "nav_lon")
write(6,*) "sx,sy1:",sx,sy
call flush(6)
    CALL read_array_2d(ncid(1), 'nav_lon', longs_t,var_avail)
    CALL read_array_2d(ncid(1), 'nav_lat', lats_t,var_avail)
    CALL read_array_1d(ncid(1), 'deptht', depths_t,var_avail)
    ! Don't have negative longitudes. 
    WHERE (longs_t < 0.) longs_t = longs_t + 360.
    !  Now calculate cell boundaries.
write(6,*)"before l752"
call flush(6)
write(6,*)"size(long_coords)"
call flush(6)
if(.not.allocated(long_coords)) allocate(long_coords(sy,sx))
if(.not.allocated(lat_coords)) allocate(lat_coords(sy,sx))
    long_coords = longs_t
    lat_coords = lats_t
    DEALLOCATE(longs_t,lats_t)
   endif
   if(ind(interv,5).eq.1)then
    CALL read_array_1d(ncid(4), 'depthw', depths_w,var_avail)
   endif


!to be checked according to variable cell method chosen
!if(.not.allocated(long_coords)) allocate(long_coords(sy,sx))
!if(.not.allocated(lat_coords)) allocate(lat_coords(sy,sx))
write(6,*)"before lat_vertices"
call flush(6)
    
!     
  if(ALLOCATED(longs_u)) DEALLOCATE(longs_u)
  if(ALLOCATED(longs_v)) DEALLOCATE(longs_v)
  if(ALLOCATED(longs_t)) DEALLOCATE(longs_t)
  if(ALLOCATED(lats_u)) DEALLOCATE(lats_u)
  if(ALLOCATED(lats_v)) DEALLOCATE(lats_v)
  if(ALLOCATED(lats_t)) DEALLOCATE(lats_t)
!    DEALLOCATE(longs_u, longs_v, longs_t, lats_u, lats_v, lats_t)!to be put under "if allocated" test

  END SUBROUTINE   
 
  !> Generate grid.
  !@param axis_id    Id of axis generated
!to be generalized
  SUBROUTINE create_grid(grid, lat_coords, long_coords, lat_id, lon_id)
    IMPLICIT NONE
    INTEGER, INTENT(OUT) :: grid
    REAL, DIMENSION(:,:) :: lat_coords, long_coords
    INTEGER :: lat_id, lon_id
    INTEGER :: i
    INTEGER, DIMENSION(sy) :: i_indices
    INTEGER, DIMENSION(sx) :: j_indices
write(6,*) "sx,sy in create_grid",sx,sy
call flush(6)
    do i=1,sx
     j_indices(i) = i
    end do
    do i=1,sy
     i_indices(i) = i
    end do
    lon_id = cmor_axis( table = 'Tables/SPECS_grids', &
            table_entry='i_index',  units='1', &
            length=sy,  coord_vals = i_indices)
    lat_id = cmor_axis( table = 'Tables/SPECS_grids', &
            table_entry='j_index',  units='1', &
            length=sx, coord_vals = j_indices)
   grid = cmor_grid( (/lon_id, lat_id/), &
           latitude = lat_coords, &
           longitude = long_coords, & 
           latitude_vertices = lat_vertices, &
           longitude_vertices = long_vertices) 
    ! DEALLOCATE(lon, lat)

  END SUBROUTINE create_grid
  SUBROUTINE create_grid_diaptr(grid, lat_coords, long_coords, lat_id, lon_id)
    IMPLICIT NONE
    INTEGER, INTENT(OUT) :: grid
    REAL, DIMENSION(:,:) :: lat_coords, long_coords
    REAL, DIMENSION(:,:),ALLOCATABLE :: lat_coords2, long_coords2
    INTEGER :: lat_id, lon_id
    INTEGER :: i
    INTEGER, DIMENSION(1) :: i_indices
    INTEGER, DIMENSION(sx) :: j_indices

    do i=1,sx
     j_indices(i) = i
    end do
    do i=1,1
     i_indices(i) = i
    end do
    ALLOCATE(long_coords2(size(long_coords(:,1)),1))
    ALLOCATE(lat_coords2(size(lat_coords(:,1)),1))
    long_coords2(:,1)=long_coords(:,1)
    lat_coords2(:,1)=lat_coords(:,1)
    lon_id = cmor_axis( table = 'Tables/SPECS_grids', &
            table_entry='i_index',  units='1', &
            length=1,  coord_vals = i_indices)
    lat_id = cmor_axis( table = 'Tables/SPECS_grids', &
            table_entry='j_index',  units='1', &
            length=sx, coord_vals = j_indices)
   grid = cmor_grid( (/lon_id, lat_id/), &
           latitude = lat_coords2, &
           longitude = long_coords2)!, & 
!           latitude_vertices = lat_vertices, &
!           longitude_vertices = long_vertices) 
    ! DEALLOCATE(lon, lat)

  END SUBROUTINE create_grid_diaptr


  !> Read time axis details. 
  ! There are two time axes: those in the 3d fields (eg t.nc)
  ! and the 2d ice fields. Assumed to have the same time origin, but different 
  ! intervals and number of timesteps.
  !
  !@param ncid   Handle of netcdf file
  !@param calendar Calendar used. Normally gregorian
  SUBROUTINE read_calendar(ncid, calendar,ecearth)
    IMPLICIT NONE
    INTEGER, INTENT(IN) :: ncid,ecearth
    CHARACTER(len=80), INTENT(OUT) :: calendar
    INTEGER :: varid
if(ecearth.eq.2)then
    CALL check( nf90_inq_varid( ncid, 'time', varid), "Failed to read varid for time in read_calendar")   
else
    CALL check( nf90_inq_varid( ncid, 'time_counter', varid), "Failed to read varid for time_counter in read_calendar")   
endif
!    CALL check( nf90_inq_varid( ncid, 'reftime', varid), "Failed to read varid for time")   
    CALL check( nf90_get_att( ncid, varid, 'calendar', calendar), "Failed to get calendar")

  END SUBROUTINE read_calendar

   ! Taken from NEMO source
   LOGICAL FUNCTION isLeap(nyear)
   INTEGER, INTENT(in) :: nyear
   isLeap = ( (Modulo(nyear,4) == 0 .AND. Modulo(nyear,100) /= 0) .OR. Modulo(nyear,400) == 0 )
   RETURN
   END FUNCTION isLeap

  !> Create a time axis.
  !@param type 'ice' or 'oce', depending on ncid 
  SUBROUTINE create_time_axis( ax_time, ncid_scal, typ, table, time, time_bnds, startyear, endyear, startmonth, endmonth,ecearth)
    IMPLICIT NONE
    INTEGER, INTENT(OUT) :: ax_time
    INTEGER, INTENT(IN) :: ncid_scal, startyear, endyear, startmonth, endmonth,ecearth
    REAL, DIMENSION(12) :: dayspermon = (/ 31., 28., 31., 30., 31., 30., 31., 31., 30., 31., 30., 31. /)
    REAL, INTENT(OUT), DIMENSION(:), ALLOCATABLE :: time
    REAL, INTENT(OUT), DIMENSION(:,:), ALLOCATABLE :: time_bnds
    CHARACTER(len=*), INTENT(IN) :: typ, table
    CHARACTER(len=80) :: units    
    DOUBLE PRECISION :: prevt

    INTEGER :: varid, votemp_varid, ice_varid, m, y, d, i, nmonths, numyears,length,nmonths_b,numyears_b
    REAL :: interval_operation, interval_write
if(ecearth.eq.2)then
!    write(6,*) "ecearth eq 2"
!    call flush(6)
    CALL check( nf90_inq_varid( ncid_scal, 'time', varid), "Failed to read varid for time")   
else
!    write(6,*) "ecearth neq 2"
!    call flush(6)
    CALL check( nf90_inq_varid( ncid_scal, 'time_counter', varid), "Failed to read varid for time_counter")   
endif
!    CALL check( nf90_inq_varid( ncid, 'reftime', varid), "Failed to read varid for time create")   
    CALL check( nf90_get_att( ncid_scal, varid, 'units', units), "Failed to read units in read_time")
    CALL check( nf90_inquire_dimension( ncid_scal, varid, len=length), "Failed to read time_length in read_time")
    length=4
    numyears_b = (startyear - 1850)
    numyears = (endyear - startyear)
!    if (startyear == endyear) then
    if (startyear == endyear) then
       nmonths = endmonth - startmonth + 1
    else
       nmonths = (numyears -1)*12 + (13-startmonth) + endmonth 
    endif
    if (startyear == 1850) then
       nmonths_b = startmonth 
    else
       nmonths_b = numyears_b *12 + startmonth - 1 
!       nmonths_b = (numyears_b -1)*12 + (13-startmonth)  
    endif
    ALLOCATE (time(nmonths),  time_bnds(2,nmonths))
    prevt = 0.
    y=1850
    m=1
    do i=1,nmonths_b
     d = dayspermon(m)
     if ((m == 2) .and. isLeap(y)) d=29
!     prevt=prevt + d
     prevt=prevt + d*24.*3600.
     m = m+1
     if (m == 13) then
       y = y+1
       m = 1
     endif
    enddo   
    time=prevt
!    write(6,*)"in create time_axis,nmonths=",nmonths,nmonths_b,startmonth,numyears_b,endyear,startyear,prevt
!    call flush(6)
!    y = startyear
!    m = startmonth
!    do i=1,nmonths 
!         d = dayspermon(m)
!         if ((m == 2) .and. isLeap(y)) d=29
!         time_bnds(1,i) = prevt
!         time_bnds(2,i) = prevt + d*24.*3600.
!         time(i) = ( time_bnds(2,i) - time_bnds(1,i)) / 2. + time_bnds(1,i)
!         prevt = time_bnds(2,i)
!         m = m+1
!         if (m == 13) then
!           y = y+1
!           m = 1
!         endif
!     end do

    ! read the interval from one of the variables    
    IF (typ == 'oce') THEN
!       CALL check( nf90_inq_varid( ncid, 'thetao', votemp_varid))
       CALL check( nf90_inq_varid( ncid_scal, 'votemper', votemp_varid))
       CALL check( nf90_get_att( ncid_scal, votemp_varid, 'interval_operation', interval_operation))
       CALL check( nf90_get_att( ncid_scal, votemp_varid, 'interval_write', interval_write ))    
    ELSE
       ! Ice on a different timescale.
       CALL check( nf90_inq_varid( ncid_scal, 'iicethic',ice_varid))
       CALL check( nf90_get_att( ncid_scal, ice_varid, 'interval_operation', interval_operation))
       CALL check( nf90_get_att( ncid_scal, ice_varid, 'interval_write', interval_write))
    ENDIF
    WRITE(interval,'(F10.2)') abs(interval_write)
    interval=trim(interval)//" "//trim(units)
    ! interval is the sampling period; eg '3600 seconds' for monthly mean data
    ! means the data was sampled every hour, then averaged to monthly
!    write(6,*)'before cmor_axis in create_time_axis ',units
!    call flush(6)
!    write(6,*)"in create time axis, units:",units,time,table
!    call flush(6)   
    ax_time = cmor_axis(table = table, &
         table_entry='time', &
!         units = 'seconds since ?', &
         units = units, &
         length = length, &
!         coord_vals = time , & 
         interval = interval) 
    write(6,*)'after cmor_axis in create_time_axis',units
    call flush(6)

  END SUBROUTINE CREATE_TIME_AXIS

  !> Simple 2d variables 
  !> @param monthnum : current month
  !> @param months   : number of months in file, to process
  SUBROUTINE trans2d( varid, lt, nam, ncid, time, time_bnds, monthnum, months,ecearth,fx)!,var_avail)
    INTEGER, INTENT(IN) :: varid, ncid, monthnum, months,lt,ecearth!,var_avail
    DOUBLE PRECISION, INTENT(IN), DIMENSION(:), ALLOCATABLE :: time
    DOUBLE PRECISION, INTENT(IN), DIMENSION(:,:), ALLOCATABLE :: time_bnds
    DOUBLE PRECISION, DIMENSION(:,:), ALLOCATABLE :: time_bnds2
    CHARACTER(LEN=2), INTENT(IN), OPTIONAL :: fx
    REAL, DIMENSION(:,:), ALLOCATABLE :: dat,dat1,dat2
    CHARACTER(len=*), INTENT(IN) :: nam
    DOUBLE PRECISION, DIMENSION(1) :: t,time2
    DOUBLE PRECISION, DIMENSION(2,1) :: tb
    DOUBLE PRECISION, DIMENSION(:), ALLOCATABLE :: t2
    INTEGER :: i,j,nt,var_avail,var_avail2
    
!    write(6,*)"in trans2d ",nam
!    call flush(6)
    if(present(fx))then
     nt=0
!     write(6,*)"nt=0"
!     call flush(6)
    else
     nt=1
    endif
    j = 1
    !write(6,*)'monthnum, mons = ', monthnum, mons
if(ecearth.eq.2)then
       CALL read_array_1d( ncid, "time", t2,var_avail2)
else
       CALL read_array_1d( ncid, "time_counter", t2,var_avail2)
endif
!       CALL read_array_1d( ncid, "leadtime", t2)
!    if(allocated(time))then
!     write(6,*)"in trans2d, time allocated",size(t2)
!     call flush(6)
!     stop
!    else
!     write(6,*)"in trans2d, time NOT allocated"
!     call flush(6)
!    endif
      CALL read_array_2d( ncid, "time_counter_bnds", time_bnds2,var_avail)
!   DO j=monthnum, monthnum + months -1
     DO i=1,size(t2)
!       CALL read_array_2d( ncid, nam, dat,var_avail)
!       write(6,*)"niveau du bug ",nam,var_avail!,"time:",time 
      if(nam.eq."hfnorth")then
       CALL read_array_2d( ncid, "sohtatl", dat1, var_avail,i)
       CALL read_array_2d( ncid, "sohtipc", dat2, var_avail,i)
       allocate(dat(size(dat1(:,1)),size(dat1(1,:))))
       dat=dat1+dat2
      elseif(nam.eq."sltnorth")then
       CALL read_array_2d( ncid, "sostatl", dat1, var_avail,i)
       CALL read_array_2d( ncid, "sostipc", dat2, var_avail,i)
       allocate(dat(size(dat1(:,1)),size(dat1(1,:))))
       dat=dat1+dat2
      else
       CALL read_array_2d( ncid, nam, dat, var_avail,i)
      endif
     if(var_avail.eq.0)then
       t = time(1)
       time2 = t2(i)
!       if(nam.eq."so20chgt")then 
!        write(6,*)"avant cmorWrite (2d): t= ",t,"--",time2,"nt=",nt
!        call flush(6)
!       endif
       tb(1,1) = time_bnds2(1,i)
       tb(2,1) = time_bnds2(2,i)
       CALL check( cmor_write( var_id = varid, &
!         lt_id = lt, &
!         ncid_in = ncid, &
         data = dat, &
         ntimes_passed = nt, &
!         ntimes_passed = 1, &
         time_vals = t+time2, &
         leadtime_vals = time2, &
!         reftime_vals = t, &
         time_bnds = tb ) )
       DEALLOCATE(dat)
       if(allocated(dat1)) deallocate(dat1)
       if(allocated(dat2)) deallocate(dat2)
       j = j + 1
     endif
    END DO
    var_avail=1
  END SUBROUTINE trans2d

  !> Translate Simple 3d variables
  !> @param monthnum : current month
  !> @param months   : number of months in file, to process
  SUBROUTINE trans3d (varid, lt, nam, ncid, time, time_bnds, monthnum, months,ecearth,fx)
    INTEGER, INTENT(IN) :: varid, ncid, monthnum, months,lt,ecearth
    DOUBLE PRECISION, INTENT(IN), DIMENSION(:), ALLOCATABLE :: time
    DOUBLE PRECISION, INTENT(IN), DIMENSION(:,:), ALLOCATABLE :: time_bnds
    DOUBLE PRECISION, DIMENSION(:,:), ALLOCATABLE :: time_bnds2
    CHARACTER(len=*), INTENT(IN) :: nam
    CHARACTER(LEN=2), INTENT(IN), OPTIONAL :: fx

    DOUBLE PRECISION :: prevt
    REAL, DIMENSION(:,:,:), ALLOCATABLE :: dat
    DOUBLE PRECISION, DIMENSION(1) :: t,time2
    DOUBLE PRECISION, DIMENSION(2,1) :: tb
    INTEGER :: i,j,nt,numAtts,var_avail,var_avail2
    DOUBLE PRECISION, DIMENSION(:), ALLOCATABLE :: t2

!    write(6,*)"in trans3d, ",nam
!    call flush(6)
    if(present(fx))then
!    if(nam=="goro".or.nam=="iicetemp")then
     nt=0
!     write(6,*)"nt=0"
!     call flush(6)
    else
     nt=1
    endif
    j=1
if(ecearth.eq.2)then
       CALL read_array_1d( ncid, "time", t2,var_avail2)
else
       CALL read_array_1d( ncid, "time_counter", t2,var_avail2)
endif
!    DO i=monthnum, monthnum + months -1
      CALL read_array_2d( ncid, "time_counter_bnds", time_bnds2,var_avail)
    DO i=1,size(t2)
       ! Write a single step
      CALL read_array_3d( ncid, nam, dat,var_avail,i)
!      CALL read_array_2d( ncid, time_counter_bnds, tb,var_avail,i)
!      CALL read_array_3d( ncid, nam, dat,j,var_avail)
      if(var_avail.eq.0)then 
       t = time(1)
!       t2 = time(i)
       time2 = t2(i)
!       write(6,*)"avant cmorWrite (3d): ",nam,size(dat(:,1,1)),size(dat(1,:,1)),size(dat(1,1,:))
!       call flush(6) 
       tb(1,1) = time_bnds2(1,i)
       tb(2,1) = time_bnds2(2,i)

       CALL check( cmor_write( var_id = varid, &
!            lt_id = lt, &
!            ncid_in = ncid, &
            data = dat, &
            ntimes_passed = nt, &
!            ntimes_passed = 1, &
            time_vals = t+time2, &
!            time_vals = time2, &
!            reftime_vals = t2, &
            leadtime_vals = time2, &
!            reftime_vals = t+time2, &
!            reftime_vals = t, &
            time_bnds = tb))
!       write(6,*)"apres cmorWrite (3d): ",nam
!       call flush(6) 

       DEALLOCATE(dat)
       j=j+1
     endif
    END DO
  var_avail=1
  END SUBROUTINE trans3d

  !> Create all the necessary variables for SPECS_day table
  !> da: daily mean ocean fields
  !> Not currently used in EC-EARTH/

  SUBROUTINE create_variables_day( varids, ncid_t, priority, ax_time, lat_coords, long_coords)
    IMPLICIT NONE
    INTEGER, INTENT(INOUT),  DIMENSION(:) :: varids
    INTEGER, INTENT(IN) :: ncid_t, priority, ax_time
    INTEGER :: grid, dum1, dum2, ax_depth !add pab 
    ! REAL, INTENT(OUT), DIMENSION(:), ALLOCATABLE :: time
    REAL, DIMENSION(:,:) :: lat_coords, long_coords

    CALL create_grid(grid, lat_coords, long_coords, dum1, dum2)
   if(ind(interv,1).eq.1)then
    CALL create_depth_axis(ax_depth, ncid_t, 'deptht', 'Tables/SPECS_day')
   elseif(ind(interv,2).eq.1)then
    CALL create_depth_axis(ax_depth, ncid_u, 'depthu', 'Tables/SPECS_day')
   elseif(ind(interv,3).eq.1)then
    CALL create_depth_axis(ax_depth, ncid_v, 'depthv', 'Tables/SPECS_day')
   endif
!write(6,*)"in create varibales day-after create depth axis-deptht"
!call flush(6)
!to be checked according to updated tables
    !! Priority '0': Already generated by NEMO
!     varids(da_lt) = cmor_variable( &
!      table='Tables/SPECS_day', &
!      table_entry='leadtime', &             ! sea ice fraction
!      units='days since 1850-1-1', &
!      units='days since ?', &
!      axis_ids = (/ ax_time /))
!write(6,*)"after cmor_var(lt)"
!call flush(6)
    varids(da_sic) = cmor_variable( &
         table='Tables/SPECS_day', & !new pab
         table_entry='sic', &             ! sea ice fraction
         axis_ids = (/ grid, ax_time /), &
         units = '%', &
         original_name='ice_pres')
    varids(da_snd) = cmor_variable( &
         table='Tables/SPECS_day', & !new pab
         table_entry='snld', &             ! sea ice fraction
         axis_ids = (/ grid, ax_time /), &
         units = 'm', &
         original_name='isnowthi')
    varids(da_tsice) = cmor_variable( &
         table='Tables/SPECS_day', & !new pab
         table_entry='tsice', &             ! sea ice fraction
         axis_ids = (/ grid, ax_time /), &
         units = 'K', &
         original_name='iicetemp')
    varids(da_mlotst) = cmor_variable( & ! FIXME  check.
         table='Tables/SPECS_day', & ! sobowlin is "bowl index", 
         table_entry='mlotst', &
         axis_ids = (/ grid, ax_time /), &
         units ='m', &
         original_name = 'somxl010')
    varids(da_t20d) = cmor_variable( &
         table='Tables/SPECS_day', &
         table_entry='t20d', &
         axis_ids = (/ grid, ax_time /), &
         units = 'm ',&
         original_name = 'so20chgt')
!    varids(da_tos) = cmor_variable( &
!         table='Tables/SPECS_day', &
!         table_entry = 'tos', &           ! sea surface temperature
!         axis_ids = (/ grid, ax_time /), &
!         units = 'degC', &
!         original_name='sosstsst', &
!         comment = 'May differ from "surface temp" in regions of ice')
!debug...    varids(da_sit) = cmor_variable( &
!         table='Tables/SPECS_day', &
!         table_entry='sit', &             ! sea ice thickness
!         axis_ids = (/ grid, ax_time /), &
!         units = 'm', &
!...ici         original_name='iicethic')
!
    IF (priority >=1 ) THEN
       !! Priority 1
       !! These are available on the ATM grid. Are they being generated for the ocean grid ?
       !! do we need to do them here, or just the IFS output ?
       !!

!        varids(da_huss) = cmor_variable( &
!            table='Tables/SPECS_day', &
!             table_entry='huss', & ! near surface specific humidity
!             axis_ids = (/ grid, ax_time /), &
!             units = '1', &
!             comment = 'FIXME available on ATM grid')
!pab atmosph!        varids(da_tasmin) = cmor_variable( &
!pab atmosph             table='Tables/SPECS_day', &
!pab atmosph             table_entry='tasmin', & ! daily min near surface air temp
!pab atmosph             axis_ids = (/ grid, ax_time /), &
!pab atmosph             units = 'K', &
!pab atmosph             comment = 'FIXME avail on ATM grid')
!pab atmosph        varids(da_tasmax) = cmor_variable( &
!pab atmosph             table='Tables/SPECS_day', &
!pab atmosph             table_entry='tasmax', & ! daily max near surface air temp
!pab atmosph             axis_ids = (/ grid, ax_time /), &
!pab atmosph             units = 'K', &
!pab atmosph             comment = 'FIXME on atm grid')
!        varids(da_tas) = cmor_variable( &
!             table='Tables/SPECS_day', &
!             table_entry='tas', & ! near surf air temp
!             axis_ids = (/ grid, ax_time /), &
!             units = 'K', &
!             comment = 'FIXME on atm grid')
!        varids(da_pr) = cmor_variable( &
!             table='Tables/SPECS_day', &
!             table='Tables/SPECS_fx', &
!             table_entry='pr', & ! precipitation
!             axis_ids = (/ grid, ax_time /), &
!             units = 'kg m-2 s-1', &
!             comment = 'FIXME generate')
!pab atmosph        varids(da_psl) = cmor_variable( &
!pab atmosph             table='Tables/SPECS_day', &
!pab atmosph             table_entry='psl', & ! sea level pressure
!pab atmosph             axis_ids = (/ grid, ax_time /), &
!pab atmosph             units = 'Pa', &
!pab atmosph             comment = 'FIXME on atm grid')
!pab atmosph    varids(da_prsn) = cmor_variable( &
!pab atmosph         table='Tables/SPECS_day', &
!pab atmosph         table_entry = 'prsn', &          ! snowfall flux, where ice free ocean over sea
!pab atmosph         axis_ids = (/ grid, ax_time /), &
!pab atmosph         units = 'kg m-2 s-1', &
!pab atmosph         comment = 'generated from isnowpre') ! FIXME: Generate from isnowpre snow  precipitation
!pab atmosph    varids(da_hfss) = cmor_variable( &
!pab atmosph         table='Tables/SPECS_day', &
!pab atmosph         table_entry = 'hfss', &          ! surface downward sensible heat flux
!pab atmosph         axis_ids = (/ grid, ax_time /), &
!pab atmosph         positive='down', &
!pab atmosph         units = 'W m-2')
!pab atmosph    varids(da_hfls) = cmor_variable( &
!pab atmosph         table='Tables/SPECS_day', &
!pab atmosph         table_entry = 'hfls', &          ! surface downward latent heat flux
!pab atmosph         axis_ids = (/ grid, ax_time /), &
!pab atmosph         units = 'W m-2', &
!pab atmosph         positive='down')
!pab atmosph    varids(da_rsds) = cmor_variable( &
!pab atmosph         table='Tables/SPECS_day', &
!pab atmosph         table_entry = 'rsds', &          ! downwelling s.w. radiation in sea water
!pab atmosph         axis_ids = (/ grid, ax_depth,  ax_time /), &
!pab atmosph         positive='down', &
!pab atmosph         units = 'W m-2')
!pab atmosph    varids(da_rlds) = cmor_variable( &
!pab atmosph         table='Tables/SPECS_day', &
!pab atmosph         table_entry = 'rlds', &          ! surface new downward longwave radiation
!pab atmosph         axis_ids = (/ grid, ax_time /), &
!pab atmosph         units = 'W m-2', &
!pab atmosph         positive='down')
!pab atmosph    varids(da_uas) = cmor_variable( &
!pab atmosph         table='Tables/SPECS_day', &
!pab atmosph         table_entry = 'uas', &          ! surface new downward longwave radiation
!pab atmosph         axis_ids = (/ grid, ax_time /), &
!pab atmosph         units = 'm s-1')
!pab atmosph    varids(da_vas) = cmor_variable( &
!pab atmosph         table='Tables/SPECS_day', &
!pab atmosph         table_entry = 'vas', &          ! surface new downward longwave radiation
!pab atmosph         axis_ids = (/ grid, ax_time /), &
!pab atmosph         units = 'm s-1')
!pab atmosph    varids(da_evlwr) = cmor_variable( &
!pab atmosph         table='Tables/SPECS_day', &
!pab atmosph         table_entry = 'evlwr', &          ! surface new downward longwave radiation
!pab atmosph         axis_ids = (/ grid, ax_time /), &
!pab atmosph         units = 'm s-1')
!pab atmosph    varids(da_rss) = cmor_variable( &
!pab atmosph         table='Tables/SPECS_day', &
!pab atmosph         table_entry = 'rss', &          ! surface new downward longwave radiation
!pab atmosph         axis_ids = (/ grid, ax_time /), &
!pab atmosph         units = 'W m-2')
!pab atmosph    varids(da_rls) = cmor_variable( &
!pab atmosph         table='Tables/SPECS_day', &
!pab atmosph         table_entry = 'rls', &          ! surface new downward longwave radiation
!pab atmosph         axis_ids = (/ grid, ax_time /), &
!pab atmosph         units = 'W m-2')
!pab atmosph    varids(da_rsdt) = cmor_variable( &
!pab atmosph         table='Tables/SPECS_day', &
!pab atmosph         table_entry = 'rsdt', &          ! surface new downward longwave radiation
!pab atmosph         axis_ids = (/ grid, ax_time /), &
!pab atmosph         units = 'W m-2')
!pab atmosph    varids(da_mrso) = cmor_variable( &
!pab atmosph         table='Tables/SPECS_day', &
!pab atmosph         table_entry = 'mrso', &          ! surface new downward longwave radiation
!pab atmosph         axis_ids = (/ grid, ax_time /), &
!pab atmosph         units = 'm3 m-3')
!pab atmosph    varids(da_snld) = cmor_variable( &
!pab atmosph         table='Tables/SPECS_day', &
!pab atmosph         table_entry = 'snld', &          ! surface new downward longwave radiation
!pab atmosph         axis_ids = (/ grid, ax_time /), &
!pab atmosph         units = 'm')
!pab atmosph    varids(da_tauu) = cmor_variable( &
!pab atmosph         table='Tables/SPECS_day', &
!pab atmosph         table_entry = 'tauu', &          ! surface new downward longwave radiation
!pab atmosph         axis_ids = (/ grid, ax_time /), &
!pab atmosph         units = 'Pa')
!pab atmosph    varids(da_tauv) = cmor_variable( &
!pab atmosph         table='Tables/SPECS_day', &
!pab atmosph         table_entry = 'tauv', &          ! surface new downward longwave radiation
!pab atmosph         axis_ids = (/ grid, ax_time /), &
!pab atmosph         units = 'Pa')

       !! On the OCEAN grid, or none

!       varids(da_tossq) = cmor_variable( &
!            table='Tables/SPECS_day', &
!            table_entry='tossq', & ! square of sea surface temp
!            axis_ids = (/ grid, ax_time /), &
!            units = 'K2')
!       varids(da_omldamax) = cmor_variable( &
!            table='Table/SPECS_day', &
!            table_entry='omldamax', &        ! Daily max ocean mixed layer thickness defined by mixing scheme
!            axis_ids = (/ grid, ax_time /), &
!            units = 'm')
!       varids(da_usi) = cmor_variable( &
!            table='Tables/SPECS_day', &
!            table_entry='usi', &             ! eastward sea ice velocity
!            axis_ids = (/ grid, ax_time /), &
!            units = 'm s-1')
!       varids(da_vsi) = cmor_variable( &
!            table='Tables/SPECS_day', &
!            table_entry='vsi', &             ! northward sea ice velocity
!            axis_ids = (/ grid, ax_time /), &
!            units = 'm s-1')
    ENDIF

  END SUBROUTINE CREATE_VARIABLES_DAY
  
  !> Create all the necessary variables for SPECS_Omon table
  !> Omon: Monthly ocean fields
  !
  ! Skip the biogeochemical fields, Table 2.1
  SUBROUTINE create_variables_diaptr( varids, ncid_t, priority, ax_time, lat_coords, long_coords)
!idem: to be checked according to updated tables
    IMPLICIT NONE
    INTEGER, INTENT(INOUT),  DIMENSION(:) :: varids
    INTEGER, INTENT(IN) :: ncid_t, priority, ax_time
    INTEGER :: grid, ax_depth, ax_lat, ax_lon, ax_lt
    REAL, DIMENSION(:,:) :: lat_coords, long_coords
    REAL, DIMENSION(:), ALLOCATABLE :: lt

    CALL create_grid_diaptr(grid, lat_coords, long_coords, ax_lat, ax_lon)
!    write(6,*)"before create_depth_axis in create_variable_omon"
!    call flush(6)
!    CALL create_depth_axis(ax_depth, ncid_t, 'deptht', 'Tables/SPECS_Omon')
    CALL create_depth_axis(ax_depth, ncid_t, 'depthw', 'Tables/SPECS_Omon')
!    write(6,*)"after create_depth_axis in create_variable_diaptr"
!    call flush(6)

    varids(omon_msftmyza) = cmor_variable( &
         table='Tables/SPECS_Omon', &
         table_entry = 'msftmyza', &        ! sea water potential temperature
!         axis_ids = (/ ax_lat, ax_lon, ax_depth, ax_time /), &
         axis_ids = (/ grid, ax_depth, ax_time /), &
         units = 'm3 s-1', &
         original_name='zomsfatl')

    varids(omon_msftmyz) = cmor_variable( &
         table='Tables/SPECS_Omon', &
         table_entry = 'msftmyz', &        ! sea water potential temperature
         axis_ids = (/ grid, ax_depth, ax_time /), &
         units = 'm3 s-1', &
         original_name='zomsfglo')

    varids(omon_msftmyzba) = cmor_variable( &
         table='Tables/SPECS_Omon', &
         table_entry = 'msftmyzba', &        ! sea water potential temperature
         axis_ids = (/ grid, ax_depth, ax_time /), &
         units = 'm3 s-1', &
         original_name='zomsfeiv')

    varids(omon_hfnortha) = cmor_variable( &
         table='Tables/SPECS_Omon', &
         table_entry = 'hfnortha', &        ! sea water potential temperature
         axis_ids = (/ grid, ax_time /), &
         units = 'W', &
         original_name='sohtatl')

    varids(omon_hfnorth) = cmor_variable( &
         table='Tables/SPECS_Omon', &
         table_entry = 'hfnorth', &        ! sea water potential temperature
         axis_ids = (/ grid, ax_time /), &
         units = 'W', &
         original_name='hfnorth')

    varids(omon_sltnortha) = cmor_variable( &
         table='Tables/SPECS_Omon', &
         table_entry = 'sltnortha', &        ! sea water potential temperature
         axis_ids = (/ grid, ax_time /), &
         units = 'kg s-1', &
         original_name='sostatl')

    varids(omon_sltnorth) = cmor_variable( &
         table='Tables/SPECS_Omon', &
         table_entry = 'sltnorth', &        ! sea water potential temperature
         axis_ids = (/ grid,ax_time /), &
         units = 'kg s-1', &
         original_name='sltnorth')

END SUBROUTINE create_variables_diaptr

  SUBROUTINE create_variables_omon( varids, ncid_t, priority, ax_time, lat_coords, long_coords)
!idem: to be checked according to updated tables
    IMPLICIT NONE
    INTEGER, INTENT(INOUT),  DIMENSION(:) :: varids
    INTEGER, INTENT(IN) :: ncid_t, priority, ax_time
    INTEGER :: grid, ax_depth, ax_basin, ax_rho, ax_lat, ax_lon, ax_lt
    REAL, DIMENSION(:,:) :: lat_coords, long_coords
    REAL, DIMENSION(:), ALLOCATABLE :: lt

    CALL create_grid(grid, lat_coords, long_coords, ax_lat, ax_lon)
!    write(6,*)"before create_depth_axis in create_variable_omon"
!    call flush(6)
!    CALL create_depth_axis(ax_depth, ncid_t, 'deptht', 'Tables/SPECS_Omon')
   if(ind(interv,1).eq.1)then
    CALL create_depth_axis(ax_depth, ncid_t, 'deptht', 'Tables/SPECS_Omon')
   elseif(ind(interv,2).eq.1)then
    CALL create_depth_axis(ax_depth, ncid_u, 'depthu', 'Tables/SPECS_Omon')
   elseif(ind(interv,3).eq.1)then
    CALL create_depth_axis(ax_depth, ncid_v, 'depthv', 'Tables/SPECS_Omon')
   endif
!    write(6,*)"after create_depth_axis in create_variable_omon"
!    call flush(6)

    ax_basin = cmor_axis( table='Tables/SPECS_Omon', &
         table_entry='basin', &
         length=4, &
         coord_vals= (/ "atlantic_arctic_ocean", "indian_pacific_ocean ", "pacific_ocean        ", &
         "global_ocean         " /), &
         units='none')         
!    CALL read_array_1d(ncid_t,"leadtime",lt) 
!    ax_lt = cmor_axis( table='Tables/SPECS_Omon', &
!         table_entry='leadtime', &
!         coord_vals= lt , &
!         units='seconds since')         


    ! TODO: Find values for rho. Need to declare bounds; needed for Priority 2 variables.
    !ax_rho = cmor_axis( table='Tables/SPECS_Omon', &
    !     table_entry='rho', &
    !     length = 1, &
    !     units = 'kg m-3')

    !
    ! "Priority 0" : Variables we already produced by NEMO output.
    !
!    write(6,*)"before cmor_variable in f90"
!    call flush(6)

! varids(mon_lt) = cmor_variable( &
!      table='Tables/SPECS_Omon', &
!      table_entry='leadtime', &             ! sea ice fraction
!!      units='days since 1850-1-1', &
!      units='days since ?', &
!      axis_ids = (/ ax_time /))

    varids(omon_thetao) = cmor_variable( &
         table='Tables/SPECS_Omon', &
         table_entry = 'thetao', &        ! sea water potential temperature
         axis_ids = (/ grid, ax_depth, ax_time /), &
!         axis_ids = (/ grid, ax_depth, ax_time, ax_lt /), &
         units = 'K', &
         original_name='votemper')
    varids(omon_so) = cmor_variable( &
         table='Tables/SPECS_Omon', &
         table_entry = 'so', &            ! salinity
         axis_ids = (/ grid, ax_depth, ax_time /), &
         units = 'psu', &
         original_name='vosaline')
!    write(6,*)"before cmor_variable in f90 (tos)",grid,ax_time
!    call flush(6)
    varids(omon_tos) = cmor_variable( &
         table='Tables/SPECS_Omon', &
         table_entry = 'tos', &           ! sea surface temperature
         axis_ids = (/ grid, ax_time /), &
         units = 'degC', &
         original_name='sosstsst', &
         comment = 'May differ from "surface temp" in regions of ice')
!    write(6,*)"before cmor_variable in f90 (sos)",grid,ax_time
!    call flush(6)
!   varids(omon_sos) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'so', &           ! sea surface salinity
!         axis_ids = (/ grid, ax_depth, ax_time /), &
!         units = 'psu', &
!         original_name='vosaline')
!    write(6,*)"before cmor_variable in f90 (zos)"
!    call flush(6)
    varids(omon_zos) = cmor_variable( &
         table='Tables/SPECS_Omon', &
         table_entry='zos', &             ! sea surface height above geoid
         axis_ids = (/ grid, ax_time /), &
         units = 'm ', &
         original_name ='sossheig')
   ! varids(omon_fsitherm) = cmor_variable( &
   !      table='Tables/SPECS_Omon', &
   !      table_entry = 'fsitherm', &         ! 
   !      axis_ids = (/ grid, ax_time /), &
    !     units = 'kg m-2 s-1', &
     !    original_name='iowaflup') ! Net freshwater flux from sea ice to ocean
    ! This field looks like (T.2) mentioned in emails, not uploaded.
    ! See: http://mailman.cgd.ucar.edu/pipermail/cf-metadata/2008/002296.html
    !varids(omon_wfo) = cmor_variable( &
    !     table='Tables/SPECS_Omon', &
    !     table_entry='wfo', &
    !     axis_ids = (/ grid, ax_time /), &
    !     units = 'kg m-2 s-1')
    ! From  standard_output.pdf, it appears:
    !   wfo = wfonocorr + wforcorr
    !   wfonocorr = pr + prsn + evs + friver + ficeberg + fsitherm
!    write(6,*)"before cmor_variable in f90 (mlotst)"
!    call flush(6)
!    write(6,*)"create var mlotst mon",grid,ax_depth, ax_time
    call flush(6) 
    varids(omon_mlotst) = cmor_variable( & ! FIXME  check.
         table='Tables/SPECS_Omon', & ! sobowlin is "bowl index", 
         table_entry='mlotst', &
         axis_ids = (/ grid, ax_time /), &
         units ='m', &
         original_name = 'somixhgt')
!         original_name = 'somxl010')
    !varids(141) = cmor_variable( &
    !     table='Tables/SPECS_Omon', &
    !     table_entry = 'mlotst', &        ! ocean mixed layer thickness defined by sigma T FIXME 
    !     axis_ids = (/ grid, ax_time /), &
    !     units = 'm', &
    !     original_name='sobolin')
!    varids(omon_wfo) = cmor_variable( & 
!         table='Tables/SPECS_Omon', &
!         table_entry='wfo', &
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1', &
!         original_name = 'sowaflcd') ! concentration/dilution water flux
!    varids(omon_vsfsit) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry='vsfsit', &
!         axis_ids = (/ grid, ax_time /), &
!         units='kg m-2 s-1', &
!         original_name = 'sosalflx') ! surface salt flux
!    varids(omon_hfds) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'hfds', &           ! downward heat flux into seawater surface
!         axis_ids = (/ grid, ax_time /), &
!         units = 'W m-2', &
!         positive='down', & 
!         original_name = 'sohefldo')
!    varids(omon_omlmax) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry='omlmax', &  ! monthly max. ocean mixed layer thickness defined by mixing scheme ax_time 
!         axis_ids = (/ grid, ax_time /), &
!         units = 'm', &
!         original_name='somixhgt')
!    varids(omon_rsntds) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'rsntds', &        ! net downward shortwave radiation at sea water surface
!         positive='down', &
!         axis_ids = (/ grid, ax_time /), &
!         units = 'W m-2', &
!         original_name='soshfldo') 
    varids(omon_uo) = cmor_variable( &
         table='Tables/SPECS_Omon', &
         table_entry='uo', &              ! sea water x velocity
         axis_ids = (/ grid, ax_depth, ax_time /), &
         units = 'm s-1', &
         original_name = 'vozocrtx')
    varids(omon_vo) = cmor_variable( &
         table='Tables/SPECS_Omon', &
         table_entry='vo', &
         axis_ids = (/ grid, ax_depth, ax_time /), &
         units = 'm s-1', &
         original_name='vomecrty')
!    write(6,*)"create var t20d mon",grid,ax_depth, ax_time
!    call flush(6) 
    varids(omon_t20d) = cmor_variable( &
         table='Tables/SPECS_Omon', &
         table_entry='t20d', &
         axis_ids = (/ grid, ax_time /), &
!         axis_ids = (/ grid, ax_depth, ax_time /), &
         units = 'm ',&
         original_name='so20chgt')
!    varids(omon_thetaot) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry='thetaot', &
!         axis_ids = (/ grid, ax_depth, ax_time /), &
!         units = 'K ')
    varids(omon_wo) = cmor_variable( &
         table='Tables/SPECS_Omon', &
         table_entry='wo', &
         axis_ids = (/ grid, ax_depth, ax_time /), &
         units = 'm s-1 ', &
         original_name='vovecrtz')

!    varids(omon_tauuo) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'tauuo', &         ! surface downward X stress
!         axis_ids = (/ grid, ax_time /), &
!         positive='down', & 
!         units = 'N m-2', &
!         original_name='sozotaux' )
!    varids(omon_tauvo) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'tauvo', &         ! surface downward Y stress
!         axis_ids = (/ grid, ax_time /), & 
!         units = 'N m-2', &
!         positive='down', & 
!         original_name = 'sometauy')
         
         
         
!         IF (priority >=1) THEN
    !!
    !! Priority 1
    !!
!    varids(omon_masso) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry='masso', &           ! sea water mass
!         axis_ids = (/ ax_time /), &
!         units = 'kg')
!    varids(omon_pbo) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry='pbo', &             !  sea water pressure at sea floor
!         axis_ids = (/ grid, ax_time /), &
!         units = 'dbar')
!    varids(omon_pso) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry='pso', &             ! sea water pressure at sea surface
!         axis_ids = (/ grid, ax_time /), &
!         units = 'dbar')
!    varids(omon_volo) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry='volo', &            ! sea water volume
!         axis_ids = (/ Ax_time /), &
!         units = 'm3')
!    varids(omon_masscello) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'masscello', &     ! sea water mass per unit area
!         axis_ids = (/ grid, ax_depth, ax_time /), &
!         units = 'kg m-2')
!    varids(omon_zostoga) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'zostoga', &       ! global average thermosteric sea level change
!         axis_ids = (/ ax_time /), &
!         units = 'm')
    !varids(omon_thkcello) = cmor_variable( &
    !     table='Tables/SPECS_Omon', &
    !     table_entry = 'thkcello', &      ! ocean cell model thickness
    !     axis_ids = (/ grid, ax_time /), &
    !     units = 'm', &
    !     comment = 'Not relevant for z-level model') CHECK
!    varids(omon_zosga) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
 !        table_entry = 'zosga', &         ! global average sea level change
!         axis_ids = (/ ax_time /), &
!         units = 'm')
!    varids(omon_zossga) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'zossga', &        ! global average steric sea level change
!         axis_ids = (/ ax_time /), &
!         units = 'm')
!    varids(omon_thetaoga) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'thetaoga', &      ! global average sea water pot. temperature
!         axis_ids = (/ ax_time /), &
!         units = 'K')
!    varids(omon_soga) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'soga', &          ! global mean sea water salinity
!         axis_ids = (/ ax_time /), &
!         units = 'psu')
!    varids(omon_wmo) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'wmo', &           ! upward ocean mass transport
!         axis_ids = (/ grid, ax_depth, ax_time /), &
!         units = 'kg s-1')
!    varids(omon_wmosq) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'wmosq', &         ! square of upward mass transport
!         axis_ids = (/ grid, ax_depth, ax_time /), &
!         units = 'kg2 s-2')
!    varids(omon_sfdsi) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'sfdsi', &          ! Downward sea ice basal salt flux
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1')
!    varids(omon_hfsithermds) = cmor_variable( &
!        ! table='Tables/SPECS_Omon', &
!         table_entry = 'hfsithermds', &    ! heat flux into sea water due to sea ice thermodynamics
!         axis_ids = (/ grid, ax_depth, ax_time /), &
!         units = 'S m-2', &
!         original_name = 'iicenflx', &
!         comment = 'FIXME check this')
! ENDIF
! IF (priority >= 2) THEN
    !!
    !! Priority 2
    !!
!    varids(omon_umo) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'umo', &           ! ocean mass X transport
!         axis_ids = (/ grid, ax_depth, ax_time /), &
!         units = 'kg s-1')
!    varids(omon_vmo) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'vmo', &           ! ocean mass Y transport
!         axis_ids = (/ grid, ax_depth, ax_time /), &
!         units = 'kg s-1')
    !varids(omon_msftmyz) = cmor_variable( &
    !     table='Tables/SPECS_Omon', &
    !     table_entry = 'msftmyz', &       ! ocean merid. overturning mass streamfunction
    !     axis_ids = (/ ax_lat, ax_depth, ax_basin,  ax_time /), &
    !     units = 'kg s-1')
    !!varids(omon_msftmrhoz) = cmor_variable( &
    !     table='Tables/SPECS_Omon', &
    !     table_entry = 'msftmrhoz', &     ! ditto, but fn of Y-rho-basin
    !     axis_ids = (/ ax_lat, ax_rho, ax_basin,  ax_time /), &
    !     units = 'kg s-1')
    !varids(omon_msftyyz) = cmor_variable( &
    !     table='Tables/SPECS_Omon', &
    !     table_entry = 'msftyyz', &       ! Ocean Y overturning mass streamfunction
    !     axis_ids = (/ ax_lat, ax_depth, ax_basin,  ax_time /), &
    !     units = 'kg s-1')
    ! varids(omon_msftyrhoz) = cmor_variable( &
    !      table='Tables/SPECS_Omon', &
    !      table_entry = 'msftyrhoz', &     ! Ocean Y overturning mass streamfunction, Y-rho-basic
    !      axis_ids = (/ ax_lat, ax_rho, ax_basin, ax_time /), &
    !      units = 'kg s-1')
!    varids(omon_hfnorth) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'hfnorth', &       ! Northward ocean heat transport
!         axis_ids = (/ grid, ax_time /), &
!         units = 'W')
!    varids(omon_hfx) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'hfx', &           ! ocean heat X transport
!         axis_ids = (/ grid, ax_time /), &
!         units = 'W')
!    varids(omon_hfy) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'hfy', &           ! ocean heat Y transport
!         axis_ids = (/ grid, ax_time /), &
!         units = 'W')
    !varids(omon_htovgyre) = cmor_variable( &
    !     table='Tables/SPECS_Omon', &
    !     table_entry = 'htovgyre', &      ! Northward ocean heat transport due to gyre
    !     axis_ids = (/ ax_lat, ax_basin, ax_time /), &
    !     units = 'W')
    !varids(omon_htovovrt) = cmor_variable( &
    !     table='Tables/SPECS_Omon', &
    !     table_entry = 'htovovrt', &      ! Northward ocean heat transport due to overturning
    !     axis_ids = (/ ax_lat, ax_basin, ax_time /), &
    !     units = 'W')
    !varids(omon_sltovgyre) = cmor_variable( &
    !     table='Tables/SPECS_Omon', &
    !     table_entry = 'sltovgyre', &     ! Northward ocean salt transport due to gyre
    !     axis_ids = (/ ax_lat, ax_basin, ax_time /), &
    !     units = 'kg s-1')
    !varids(omon_sltovovrt) = cmor_variable( &
    !     table='Tables/SPECS_Omon', &
    !     table_entry = 'sltovovrt', &     ! Northward ocean salt transport due to overturning
    !     axis_ids = (/ ax_lat, ax_basin, ax_time /), &
    !     units = 'kg s-1')
!    varids(omon_pr) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'pr', &            ! rainfall flux, where ice free ocean over sea
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1')
!    varids(omon_prsn) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'prsn', &          ! snowfall flux, where ice free ocean over sea
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1', &
!         comment = 'generated from isnowpre') ! FIXME: Generate from isnowpre snow  precipitation
 !   varids(omon_evs) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'evs', &            ! water evaporation flux
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1')
!    varids(omon_friver) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'friver', &        ! water flux into seawater from rivers
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1')
!    varids(omon_ficeberg) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'ficeberg', &       ! water flux into seawater from icebergs
!         axis_ids = (/ grid, ax_depth, ax_time /), &
!         units = 'kg m-2 s-1')
!    varids(omon_wfo) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'wfo', &           ! water flux into sea water
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1') FIXME: Check against other wfo
!    varids(omon_wfonocorr) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'wfonocorr', &     ! water flux into sea water without flux correction
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1')
!    varids(omon_wfcorr) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'wfcorr', &        ! water flux correction
!         axis_ids = (/ grid, ax_time /), &
!         positive='down', &
!         units = 'kg m-2 s-1')
!    varids(omon_vsfpr) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'vsfpr', &         !  virt. salt flux into sea water due to rainfall
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1')
 !   varids(omon_vsfevap) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'vsfevap', &       ! virt. salt flux into sea water from evaporation
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1')
!    varids(omon_vsfriver) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'vsfriver', &      ! virt. salt flux into seawater from rivers
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1')
!    varids(omon_vsf) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'vsf', &           ! virt. salt flux into sea water
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1')
!    varids(omon_vsfcorr) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'vsfcorr', &       ! virtual salt flux correction
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1')
!    varids(omon_sfriver) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'sfriver', &             ! salt flux into sea waters from rivers
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1')
!    varids(omon_hfgeou) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'hfgeou', &        ! upward geothermal heat flux at sea floor
!         positive='up', &
!         axis_ids = (/ grid, ax_time /), &
!         units = 'W m-2')
!    varids(omon_hfrainds) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'hfrainds', &      ! temp. flux due to rainfall expressed as heat flux into seawater
!         positive='down', &
!         axis_ids = (/ grid, ax_time /), &
!         units = 'W m-2')
!    varids(omon_hfevapds) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'hfevapds', &      ! heat flux due to evaporation expressed as heat flux out of water
!         axis_ids = (/ grid, ax_time /), &
!         positive='down', &
!         units = 'W m-2')
!    varids(omon_hfrunoffds) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'hfrunoffds', &    ! heat flux due to runoff expressed as heat flux into sea water
!         axis_ids = (/ grid, ax_depth, ax_time /), &
!         units = 'W m-2')
!    varids(omon_hfsnthermds) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'hfsnthermds', &   ! heat flux into seawater due to snow thermodynamics
!         axis_ids = (/ grid, ax_depth, ax_time /), &
!         units = 'W m-2')
!    varids(omon_hfibthermds) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'hfibthermds', &   ! heat flux into seawater due to iceberg thermodynamics
!         axis_ids = (/ grid, ax_depth, ax_time /), &
!         units = 'W m-2')
!    varids(omon_rlds) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'rlds', &          ! surface new downward longwave radiation
!         axis_ids = (/ grid, ax_time /), &
!         units = 'W m-2', &
!         positive='down', &
!         comment = "where ice free sea over sea")
!    varids(omon_hfls) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'hfls', &          ! surface downward latent heat flux
!         axis_ids = (/ grid, ax_time /), &
!         units = 'W m-2', &
!         positive='down', &
!         comment = "where ice free sea over sea")
!    varids(omon_hfss) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'hfss', &          ! surface downward sensible heat flux
!         axis_ids = (/ grid, ax_time /), &
!         positive='down', &
!         units = 'W m-2', &
!         comment = "where ice free sea over sea")
!    varids(omon_rsds) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'rsds', &          ! downwelling s.w. radiation in sea water
!         axis_ids = (/ grid, ax_depth,  ax_time /), &
!         positive='down', &
!         units = 'W m-2')
!    varids(omon_hfcorr) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'hfcorr', &        ! heat flux correction
!         axis_ids = (/ grid, ax_time /), &
!         positive='down', &
!         units = 'W m-2')
!    varids(omon_hfds) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'hfds', &          ! downward heat flux at seawater surface
!         axis_ids = (/ grid, ax_time /), &
!         units = 'W m-2', &
!         positive='down', &
!         original_name='sohefldo')
!    varids(omon_tauucorr) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'tauucorr', &      ! Surface downward X stress correlation
!         axis_ids = (/ grid, ax_time /), &
!         units = 'N m-2', &
!         positive='down')
!    varids(omon_tauvcorr) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'tauvcorr', &      ! Surface downward Y stress correlation
!         axis_ids = (/ grid, ax_time /), &
!         units = 'N m-2', &
!         positive = 'down')
! ENDIF

 !!
 !! Priority 3
 !!
! IF (priority >= 3) THEN
!    varids(omon_tossq) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'tossq', &         ! square of sea surf temperature
!         axis_ids = (/ grid, ax_time /), &
!         units = 'K2', &
!         comment = 'FIXME generate')
!    varids(omon_zossq) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry='zossq', &           ! square of sea surface height above geoid
!         axis_ids = (/ grid, ax_time /), &
!         units = 'm2')
!    varids(omon_rhopoto) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'rhopoto', &       ! sea water potential density
!         axis_ids = (/ grid, ax_depth, ax_time /), &
!         units = 'kg m-3')
!    varids(omon_agessc) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'agessc', &        ! sea water age since surface contact
!         axis_ids = (/ grid, ax_depth, ax_time /), &
!         units = 'yr')
!    varids(omon_cfc11) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'cfc11', &         ! moles / mass kg of CFC11 in water 
!         axis_ids = (/ grid, ax_depth, ax_time /), &
!         units = 'mol kg-1')
!    varids(omon_msftbarot) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'msftbarot', &     ! ocean barotropic mass streamfunction
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg s-1')
!    varids(omon_mlotstsq) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'mlotstsq', &      ! square of ocean mixed layer thickness         
!         axis_ids = (/ grid, ax_time /), & 
!         units = 'm2')
!    varids(omon_omldamax) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'omldamax', &      ! mean daily max. ocean mixed layer thickness defined by mixing scheme
!         axis_ids = (/ grid, ax_time /), &
!         units = 'm')
!    varids(omon_omlmax) = cmor_variable( &
!         table='Tables/SPECS_Omon', &
!         table_entry = 'omlmax', &        ! monthly max. ocean mixed layer thickness defined by mixing scheme
!         axis_ids = (/ grid, ax_time /), &
!         units = 'm')
! ENDIF

END SUBROUTINE create_variables_omon

  !> Create all the necessary variables for SPECS_Lmon table
  !> Lmon: Monthly land fields
  !> Not currently used in EC-Earth

  SUBROUTINE create_variables_lmon( varids, ncid_t, priority, ax_time, lat_coords, long_coords)
    IMPLICIT NONE
    INTEGER, INTENT(INOUT),  DIMENSION(:) :: varids
    INTEGER, INTENT(IN) :: ncid_t, priority, ax_time
    INTEGER :: grid, ax_depth, ax_basin, ax_rho
    REAL, DIMENSION(:,:) :: lat_coords, long_coords
    INTEGER :: dum1, dum2
    
    CALL create_grid(grid, lat_coords, long_coords, dum1, dum2)
!   varids(mon_lt) = cmor_variable( &
!      table='Tables/SPECS_Lmon', &
!      table_entry='leadtime', &             ! sea ice fraction
!!      units='days since 1850-1-1', &
!      units='days since ?', &
!      axis_ids = (/ grid, ax_time /))
 
    ! Not doing this from NEMO; designed instead for Land models; we only have
    ! runoff at rivers, not the whole land surface  
    varids(lmon_mrros) = cmor_variable( &
         table='Tables/SPECS_Lmon', &
         table_entry='mrros', &
         axis_ids = (/ grid, ax_time /), &
         units = 'kg m-2 s-1')
  END SUBROUTINE create_variables_lmon


!> Create all the necessary variables for SPECS_fx table
!> fx :  time-invariant fields

SUBROUTINE create_variables_fx(varids, ncid_t, priority, lat_coords, long_coords)
 IMPLICIT NONE
 INTEGER, INTENT(IN) :: ncid_t, priority
 INTEGER, INTENT(INOUT),  DIMENSION(:) :: varids
 REAL, DIMENSION(:,:) :: lat_coords, long_coords
 INTEGER :: grid,  ax_depth, dum1, dum2

 CALL create_grid(grid, lat_coords, long_coords, dum1, dum2)
   if(ind(interv,1).eq.1)then
    CALL create_depth_axis(ax_depth, ncid_t, 'deptht', 'Tables/SPECS_fx')
   elseif(ind(interv,2).eq.1)then
    CALL create_depth_axis(ax_depth, ncid_u, 'depthu', 'Tables/SPECS_fx')
   elseif(ind(interv,3).eq.1)then
    CALL create_depth_axis(ax_depth, ncid_v, 'depthv', 'Tables/SPECS_fx')
   endif
 CALL create_depth_axis(ax_depth, ncid_t, 'deptht', 'Tables/SPECS_fx')

! varids(mon_lt) = cmor_variable( &
!      table='Tables/SPECS_fx', &
!      table_entry='leadtime', &             ! sea ice fraction
!!      units='days since 1850-1-1', &
!      units='days since ?', &
!      axis_ids = (/ grid /))

! varids(fx_sftlf) = cmor_variable( &
!      table='Tables/SPECS_fx', &
!      table_entry='sftlf', &          ! sea floor depth
!      axis_ids = (/ grid /), &
!      units = '%')
 !amck FIXME issue with ax_depth?
 varids(fx_goro) = cmor_variable( &
       table='Tables/SPECS_fx', &
       table_entry='goro', &       ! cell grid volume
       axis_ids = (/ grid /), &
       !axis_ids = (/ grid, ax_depth /), &
       units = 'm2 s-2')
!varids(fx_wmb) = cmor_variable( &
!       table='Tables/SPECS_fx', &
!       table_entry='wmb', &       ! cell grid volume
!       axis_ids = (/ grid /), &
!!       axis_ids = (/ grid, ax_depth /), &
!       units = 'm')

! Warning: variable deptho (7, table: fx) has been defined but never initialized  !
! Warning: variable areacello (8, table: fx) has been defined but never initialized  !
! Warning: variable sftof (9, table: fx) has been defined but never initialized  !
! Warning: variable basin (10, table: fx) has been defined but never initialized  !
! Warning: variable basinv (11, table: fx) has been defined but never initialized  !

! varids(fx_al) = cmor_variable( &
!      table='Tables/SPECS_fx', &
!      table_entry='al', &       ! ocean grid-cell area
!      axis_ids = (/ grid /), &
!      units = '%')
! varids(fx_fc) = cmor_variable( &
!      table='Tables/SPECS_fx', &
!      table_entry='fc', &           ! sea area fraction
!     axis_ids = (/ grid /), &
!      units = 'kg kg-1')
! varids(fx_sftgif) = cmor_variable( &
!      table='Tables/SPECS_fx', &
!      table_entry='sftgif', &          ! region select index
!     axis_ids = (/ grid /), &
!      units='%')
! varids(fx_sr) = cmor_variable( &
!     table='Tables/SPECS_fx', &
!      table_entry='sr', &          ! region select index
!      axis_ids = (/ grid /), &
!      units='m')
!varids(fx_wp) = cmor_variable( &
!       table='Tables/SPECS_fx', &
!       table_entry='wp', &       ! cell grid volume
!       axis_ids = (/ grid /), &
!       units = '%')

END SUBROUTINE create_variables_fx

!> Create all the necessary variables for SPECS_OImon table
!>

SUBROUTINE create_variables_oimon(varids, ncid_i, ncid_t, priority, ax_time, lat_coords, long_coords)
 IMPLICIT NONE
 INTEGER, INTENT(IN) :: ncid_i, ncid_t, priority, ax_time
 INTEGER, INTENT(INOUT),  DIMENSION(:) :: varids
 REAL, DIMENSION(:,:) :: lat_coords, long_coords

 INTEGER :: grid, ax_depth,  i, dum1, dum2

 ! interval is the sampling period; eg '3600 seconds' for monthly mean data
 ! means the data was sampled every hour, then averaged to monthly
 CALL create_grid(grid, lat_coords, long_coords, dum1, dum2)
 CALL create_depth_axis(ax_depth, ncid_t, 'deptht', 'Tables/SPECS_Omon')
!write(6,*)"after create depth axis"
!call flush(6)


 ! FIXME: Iterate over variables, replace ax_time with ax_time_{oce,ice}

 !!
 !! "Priority 0" : Items NEMO already generates
 !!
! varids(mon_lt) = cmor_variable( &
!      table='Tables/SPECS_OImon', &
!      table_entry='leadtime', &             ! sea ice fraction
!!      units='days since 1850-1-1', &
!      units='days since ?', &
!      axis_ids = (/ ax_time /))
!write(6,*)"siiiiiiiiiic var"
!call flush(6)
 varids(oimon_sic) = cmor_variable( &
      table='Tables/SPECS_OImon', &
      table_entry='sic', &             ! sea ice fraction
      units='%', &
      axis_ids = (/ grid, ax_time /), &
      original_name='iiceconc')
 varids(oimon_sic2) = cmor_variable( &
      table='Tables/SPECS_OImon', &
      table_entry='sic', &             ! sea ice fraction
      units='%', &
      axis_ids = (/ grid, ax_time /), &
      original_name='ice_pres')
!      original_name='ileadfra')
 varids(oimon_sit) = cmor_variable( &
      table="Tables/SPECS_OImon", &
      table_entry='sit', &             !sea ice thickness
      units='m', &
      axis_ids = (/ grid, ax_time /), &
      original_name='iicethic')
 varids(oimon_snd)  = cmor_variable( &
      table='Tables/SPECS_OImon', &
      table_entry='snld', &
      axis_ids = (/ grid, ax_time /), &
      units='m', &
      original_name='isnowthi')
! varids(oimon_ialb) = cmor_variable( &
!      table='Tables/SPECS_OImon', &
!      table_entry='ialb', &
!      axis_ids = (/ grid, ax_time /), &
!      units = '1', &
!!      original_name='soicealb', &
!      comment='FIXME: verify')
 varids(oimon_tsice) = cmor_variable( &
      table='Tables/SPECS_OImon', &
      table_entry='tsice', &           ! surface temperature of sea ice         
      axis_ids = (/ grid, ax_time /), &
      units = 'K',  &
      original_name='iicetemp')
 varids(oimon_usi) = cmor_variable( &
      table='Tables/SPECS_OImon', &
      table_entry='usi', &           ! surface temperature of sea ice         
      axis_ids = (/ grid, ax_time /), &
      units = 'm s-1', &
      original_name='iicevelu')
 varids(oimon_vsi) = cmor_variable( &
      table='Tables/SPECS_OImon', &
      table_entry='vsi', &           ! surface temperature of sea ice         
      axis_ids = (/ grid, ax_time /), &
      units = 'm s-1', &
      original_name='iicevelv')
! varids(oimon_strairx) = cmor_variable( &
!      table='Tables/SPECS_OImon', &
!      table_entry='strairx', & ! Eastward atmos stress on sea ice
!      axis_ids = (/ grid, ax_time /), &
!      units = 'N m-2', &
!      positive='up', & ! FIXME 
!      original_name='iocestru' )
! varids(oimon_strairy) = cmor_variable( &
!      table='Tables/SPECS_OImon', &
!      table_entry='strairy', & ! Northward atmos stress on sea ice
!      axis_ids = (/ grid, ax_time /), &
!      units = 'N m-2', &
!      positive='up', & ! FIXME
!      original_name = 'iocestrv' )
 

 ! FIXME: Split ax_time references into ice and ocean ones
 
 IF (priority >= 1) THEN
    
    !!
    !! SPECS_OIMon : Priority 1
    !!
!    varids(oimon_evap) = cmor_variable( &
!         table="Tables/SPECS_OImon", &
!         table_entry='evap', &            ! water evapration flux from sea ice
!         positive='up', & ! FIXME check
!         units='kg m-2 s-1', &
!         axis_ids = (/ grid, ax_time /), &
!         comment='FIXME : no way to generate this ? ')
!    varids(oimon_tsnint) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='tsnint', &          ! temp at interface betweeen bare sea ice and snow
!         axis_ids = (/ grid, ax_time /), &
!         units = 'K')
!    varids(oimon_pr) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='pr', &              ! surf rainfall ratr into sea ice portion of grid cell
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1')
!    varids(oimon_prsn) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='prsn',&
!         axis_ids = (/ grid, ax_time /), &
!         units='kg m-2 s-1')
!    varids(oimon_grfrazil) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='grFrazil', &
!         axis_ids = (/ grid, ax_time /), &
!         units ='kg m-2 s-1', &
!         comment = 'FIXME; only have total growth from IICEPROD')
!    varids(oimon_grCongel) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='grCongel', &
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1')
!    varids(oimon_grlateral) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='grLateral', &
!         units = 'kg m-2 s-1', &
!         axis_ids = (/ grid, ax_time /))
!    varids(oimon_snoToIce) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='snoToIce', &
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1')
!    varids(oimon_snomelt) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='snomelt', &
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1')
!    varids(oimon_tmelt) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='tmelt', &
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1')
!    varids(oimon_bmelt) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='bmelt', & ! rate of melt as sea ice base
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg m-2 s-1')
!pab newly commented...    varids(oimon_rsdsi) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='rsdsi', & ! downward over sea ice
!         axis_ids = (/ grid, ax_time /), &
!         positive='up', & ! FIXME
!         units = 'W m-2', &
!...untill there         comment = 'FIXME only sw total OICESLFX available' )
!    varids(oimon_rsussi) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='rsussi', &
!         units = 'W m-2', &
!         axis_ids = (/ grid, ax_time /), &
!         positive='up')
!    varids(oimon_transix) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='transix', & ! eastward sea ice transport
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg s-1')
!    varids(oimon_transiy) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='transiy', & ! Northward sea ice transport
!         axis_ids = (/ grid, ax_time /), &
!         units = 'kg s-1')
 ENDIF

 !!
 !! SPECS_OImon: Priority 2
 !!
! IF (priority >= 2) THEN 
!    varids(oimon_snc) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='snc', &
!         axis_ids = (/ grid, ax_time /), &
!         units ='%')
!    varids(oimon_hcice) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='hcice', & ! sea ice total heat content
!         axis_ids = (/ grid, ax_time /), &
!         units = 'J')
!    varids(oimon_rldssi) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='rldssi', & ! downward longwave over sea ice
!         axis_ids = (/ grid, ax_time /), &
!         positive='up', &
!         units = 'W m-2')
!    varids(oimon_rlussi) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='rlussi', & ! updward longwave over sea ice
!         axis_ids = (/ grid, ax_time /), &
!         units = 'W m-2', &
!         positive='up')
!    varids(oimon_hfssi) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='hfssi', & ! surf upward sensible heat flux over sea ice
!         axis_ids = (/ grid, ax_time /), &
!         units = 'W m-2', &
!         positive='up', &
!         comment = 'FIXME : only OICETFLX available ' )
!    varids(oimon_hflssi) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='hflssi', &
!         units = 'W m-2', &
!         positive='up', &
!         axis_ids = (/ grid, ax_time /) )
!    varids(oimon_sblsi) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='sblsi', &
!         units = 'kg m-2', &
!         positive='up', &
!         axis_ids = (/ grid, ax_time /) )
!    varids(oimon_transifs) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='transifs', & ! sea ice mass transport through Fram Strait
!         axis_ids = (/ax_time /), &
!         units = 'kg s-1')
!    varids(oimon_strocnx) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='strocnx', & ! Eastward ocean stress on sea ice
!         axis_ids = (/ grid, ax_time /), &
!         units = 'N m-2')
!    varids(oimon_strocny) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='strocny', & ! Northward ocean stress on sea ice
!         axis_ids = (/ grid, ax_time /), &
!         units = 'N m-2')
!    varids(oimon_streng) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='streng', & ! Compressive sea ice strength
!         axis_ids = (/ grid, ax_time /), &
!         units = 'N m-2')
!    varids(oimon_divice) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='divice', & ! Strain rate divergence of sea ice
!         axis_ids = (/ grid, ax_time /), &
!         units = 's-1')
!    varids(oimon_shrice) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='shrice', & ! Strain rate shear of sea ice
!         axis_ids = (/ grid, ax_time /), &
!         units = 's-1')
!    varids(oimon_ridgice) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='ridgice', & ! Sea ice Ridging rate
!         axis_ids = (/ grid, ax_time /), &
!         units = 's-1')
! ENDIF

 !!
 !! SPECS_OImon: Priority 3
 !!
! IF (priority >= 3) THEN
!    varids(oimon_ssi) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='ssi', &              ! sea ice salinity
!         axis_ids = (/ grid, ax_time /), &
!         units = 'psu')
!    varids(oimon_ageice) = cmor_variable( &
!         table='Tables/SPECS_OImon', &
!         table_entry='ageice', &
!         axis_ids = (/ grid, ax_time /), &
!         units = 'years')
! ENDIF

END SUBROUTINE create_variables_OImon

!> Output simple variables
!> @param monthnum current month, simple counter
!> @param month    number of months present in files to read
SUBROUTINE output_simple_vars (varids, ncid,oimon_time, oimon_time_bnds,  omon_time, omon_time_bnds, day_time, day_time_bnds, fx_time, fx_time_bnds, monthnum, months) ! new pab
!SUBROUTINE output_simple_vars (varids, ncid_t, ncid_i, ncid_u,ncid_v,oimon_time, oimon_time_bnds,  omon_time, omon_time_bnds, day_time, day_time_bnds, fx_time, fx_time_bnds, monthnum, months) ! new pab
!SUBROUTINE output_simple_vars (varids, ncid_t, ncid_i, oimon_time, oimon_time_bnds,  omon_time, omon_time_bnds, monthnum, months)
 IMPLICIT NONE
 INTEGER, INTENT(IN), DIMENSION(:) :: varids
 INTEGER, INTENT(IN) :: monthnum, months
 INTEGER, DIMENSION(6), INTENT(IN) :: ncid
! INTEGER, INTENT(IN) :: ncid_t, ncid_i,ncid_u,ncid_v,monthnum, months
 DOUBLE PRECISION, INTENT(IN), DIMENSION(:), ALLOCATABLE :: oimon_time, omon_time, day_time, fx_time
 DOUBLE PRECISION, INTENT(IN), DIMENSION(:,:), ALLOCATABLE :: oimon_time_bnds, omon_time_bnds, day_time_bnds, fx_time_bnds
 INTEGER::jj
!to be checked according to new variables names
do jj=1,4
!write(6,*)"in output simple vars,j=",jj," ind=",ind(jj,:)," -- ",ind(4,2)
!call flush(6)
enddo
if(ind(4,5).eq.1)then
!write(6,*) "siiiiiiic"
!call flush(6)
 CALL trans2d( varids(oimon_sic2), varids(mon_lt),'ice_pres', ncid_i, oimon_time, oimon_time_bnds, monthnum, months,ecearth)!,var_avail(varids(oimon_sic)))
 CALL trans2d( varids(oimon_sic), varids(mon_lt),'iiceconc', ncid(5), oimon_time, oimon_time_bnds, monthnum, months,ecearth)!,var_avail(varids(oimon_sic)))
 CALL trans2d( varids(oimon_sit), varids(mon_lt), 'iicethic', ncid(5), oimon_time,  oimon_time_bnds,monthnum, months,ecearth)!,var_avail(varids(oimon_sit)))
 CALL trans2d( varids(oimon_snd),varids(mon_lt), 'isnowthi', ncid(5), oimon_time,  oimon_time_bnds,monthnum, months,ecearth)!,varids(oimon_snd))
 CALL trans2d( varids(oimon_usi),varids(mon_lt), 'iicevelu', ncid(5), oimon_time,  oimon_time_bnds,monthnum, months,ecearth)!,varids(oimon_usi))
 CALL trans2d( varids(oimon_vsi),varids(mon_lt), 'iicevelv', ncid(5), oimon_time,  oimon_time_bnds,monthnum, months,ecearth)!,varids(oimon_vsi))
 CALL trans2d( varids(oimon_tsice),varids(mon_lt), 'iicetemp', ncid(5), oimon_time,  oimon_time_bnds,monthnum, months,ecearth)!,varids(oimon_tsice))
endif
!write(6,*)"after ice"
!call flush(6)
if(ind(4,1).eq.1)then
 CALL trans3d( varids(omon_thetao), varids(mon_lt), 'votemper', ncid(1), omon_time,  omon_time_bnds,monthnum, months,ecearth)!,varids(omon_thetao))
 CALL trans2d( varids(omon_tos), varids(mon_lt), 'sosstsst', ncid(1), omon_time,  omon_time_bnds,monthnum, months,ecearth)!,varids(omon_tos))
 CALL trans2d( varids(omon_zos), varids(mon_lt), 'sossheig', ncid(1), omon_time,  omon_time_bnds,monthnum, months,ecearth)!,varids(omon_zos))
! CALL trans2d( varids(omon_mlotst), varids(mon_lt), 'somxl010', ncid(1), omon_time,  omon_time_bnds,monthnum, months,ecearth)!,varids(omon_mlotst))
 CALL trans2d( varids(omon_mlotst), varids(mon_lt), 'somixhgt', ncid(1), omon_time,  omon_time_bnds,monthnum, months,ecearth)!,varids(omon_mlotst))
 CALL trans3d( varids(omon_so), varids(mon_lt), 'vosaline', ncid(1), omon_time,  omon_time_bnds,monthnum, months,ecearth)!,varids(omon_sos))
!  write(6,*)"trans2d t20d mon",varids(omon_t20d),ncid(1)
!  call flush(6)
 CALL trans2d( varids(omon_t20d), varids(mon_lt), 'so20chgt', ncid(1), omon_time,  omon_time_bnds,monthnum, months,ecearth)!,varids(omon_t20d))
! write(6,*)"after trans2d t20d mon"
! call flush(6) 
! CALL trans2d( varids(omon_t20d), varids(mon_lt), 't20d', ncid_t, omon_time,  omon_time_bnds,monthnum, months,ecearth)!,varids(omon_t20d))
endif
if(ind(4,6).eq.1)then
 CALL trans3d( varids(omon_msftmyza), varids(mon_lt), 'zomsfatl', ncid(6), omon_time,  omon_time_bnds,monthnum, months,ecearth)
 CALL trans3d( varids(omon_msftmyz), varids(mon_lt), 'zomsfglo', ncid(6), omon_time,  omon_time_bnds,monthnum, months,ecearth)
 CALL trans3d( varids(omon_msftmyzba), varids(mon_lt), 'zomsfeiv', ncid(6), omon_time,  omon_time_bnds,monthnum, months,ecearth)
 CALL trans2d( varids(omon_hfnortha), varids(mon_lt), 'sohtatl', ncid(6), omon_time,  omon_time_bnds,monthnum, months,ecearth)
 CALL trans2d( varids(omon_hfnorth), varids(mon_lt), 'hfnorth', ncid(6), omon_time,  omon_time_bnds,monthnum, months,ecearth)
 CALL trans2d( varids(omon_sltnortha), varids(mon_lt), 'sostatl', ncid(6), omon_time,  omon_time_bnds,monthnum, months,ecearth)
 CALL trans2d( varids(omon_sltnorth), varids(mon_lt), 'sltnorth', ncid(6), omon_time,  omon_time_bnds,monthnum, months,ecearth)
endif
if(ind(4,2).eq.1)then
! write(6,*)"before create uo"
! call flush(6) 
 CALL trans3d( varids(omon_uo), varids(mon_lt), 'vozocrtx', ncid(2), omon_time,  omon_time_bnds,monthnum, months,ecearth)!,varids(omon_uo))
! CALL trans2d( varids(omon_t20d), varids(mon_lt), 't20d', ncid_u, omon_time,  omon_time_bnds,monthnum, months,ecearth)!,varids(omon_t20d))
endif
if(ind(4,3).eq.1)then
! write(6,*)"before create vo"
! call flush(6) 
 CALL trans3d( varids(omon_vo), varids(mon_lt), 'vomecrty', ncid(3), omon_time,  omon_time_bnds,monthnum, months,ecearth)!,varids(omon_vo))
endif
if(ind(4,4).eq.1)then
 CALL trans3d( varids(omon_wo), varids(mon_lt), 'vovecrtz', ncid(4), omon_time,  omon_time_bnds,monthnum, months,ecearth)!,varids(omon_wo))
endif
if(ind(3,4).eq.1)then
! write(6,*)"in write day variable"
! call flush(6)
!    if(allocated(day_time))then
!     write(6,*)"before calling trans2d-day, time allocated"
!     call flush(6)
!    else
!     write(6,*)"before calling trans2d-day, time NOT allocated"
!     call flush(6)
!    endif
 CALL trans2d( varids(da_sic), varids(da_lt), 'ice_pres', ncid(4), day_time, day_time_bnds, monthnum, months,ecearth)!,varids(da_sic)) ! debug
 CALL trans2d( varids(da_snd),varids(da_lt), 'isnowthi', ncid(4), day_time,  day_time_bnds,monthnum, months,ecearth)!,varids(da_snd)) !debug
 CALL trans2d( varids(da_tsice), varids(da_lt),'iicetemp', ncid(4), day_time,  day_time_bnds,monthnum, months,ecearth)!,varids(da_tsice)) !debug
endif
if(ind(3,2).eq.1)then
! CALL trans2d( varids(da_t20d), varids(da_lt), 'so20chgt', ncid_u, day_time,  day_time_bnds,monthnum, months,ecearth)!,varids(da_t20d))
endif
if(ind(3,1).eq.1)then
! write(6,*)"in write day/t variable"!,day_time
! call flush(6)
 CALL trans2d( varids(da_mlotst), varids(da_lt), 'somxl010', ncid(1), day_time,  day_time_bnds,monthnum, months,ecearth)!,varids(da_mlotst))
 CALL trans2d( varids(da_t20d), varids(da_lt), 'so20chgt', ncid(1), day_time,  day_time_bnds,monthnum, months,ecearth)!,varids(da_t20d))
!write(6,*)"after dat20d"
!call flush(6)
! CALL trans2d( varids(da_tos), varids(da_lt), 'sosstsst', ncid_t, day_time,  day_time_bnds,monthnum, months,ecearth)!,varids(omon_tos))
endif
! write(6,*)"before iicetemp"!,ncid_t,ncid_i,oimon_time,varids(oimon_tsice)
! call flush(6)
! CALL trans2d( varids(oimon_rsdsi),varids(mon_lt), 'rsdsi', ncid_i, oimon_time,  oimon_time_bnds,monthnum, months)
! write(6,*)"before votemper",ncid_t,ncid_i
! call flush(6)
! write(6,*)"after votemper"
! call flush(6)
! CALL trans2d( varids(omon_thetaot), varids(mon_lt), 'thetaot', ncid_v, omon_time,  omon_time_bnds,monthnum, months)
! CALL trans2d( varids(omon_tos), varids(mon_lt), 'tos', ncid_t, omon_time,  omon_time_bnds,monthnum, months)
! write(6,*)'before trans3d',varids(omon_thetao),"ncid_t",ncid_t,"omon_time",omon_time,"omon_time_bnds",omon_time_bnds,"monthnum",monthnum,"months",months
! call flush(6)
!
! CALL trans2d( varids(fx_sftlf), varids(fx_lt), 'sftlf', ncid_t, fx_time,  fx_time_bnds,monthnum, months,"fx")
! CALL trans2d( varids(fx_goro), varids(fx_lt), 'goro', ncid_t, fx_time,  fx_time_bnds,monthnum, months,"fx")
! CALL trans2d( varids(fx_wmb), varids(fx_lt), 'wmb', ncid_t, fx_time,  fx_time_bnds,monthnum, months,"fx")
! CALL trans2d( varids(fx_al), varids(fx_lt), 'al', ncid_t, fx_time,  fx_time_bnds,monthnum, months,"fx")
! CALL trans2d( varids(fx_fc), varids(fx_lt), 'fc', ncid_t, fx_time,  fx_time_bnds,monthnum, months,"fx")
! CALL trans2d( varids(fx_sftgif), varids(fx_lt), 'sftgif', ncid_t, fx_time,  fx_time_bnds,monthnum, months,"fx")
! CALL trans2d( varids(fx_sr), varids(fx_lt), 'sr', ncid_t, fx_time,  fx_time_bnds,monthnum, months,"fx")
! CALL trans2d( varids(fx_wp), varids(fx_lt), 'wp', ncid_t, fx_time,  fx_time_bnds,monthnum, months,"fx")
 ! CALL trans3d( varids(omon_hfsithermds), varids(mon_lt), 'iicenflx', ncid_i, omon_time, year) FIXME
 ! CALL trans2d( varids(omon_sltovovrt), varids(mon_lt), 'somlx010',  ncid_t, omon_time, year) FIXME check
 ! CALL trans2d( varids(168), varids(mon_lt), 'sohefldo', ncid_t, ...., year)

 ! Lmon
 ! CALL trans2d( varids(lmon_mrros), varids(mon_lt), 'sorunoff', ncid_t, lmon_time, year )

 ! Fx

! TO BE CHECKED FOR ROUND 2
 !  mlotst, oldamax 
 ! fisitherm

END SUBROUTINE OUTPUT_SIMPLE_VARS

END PROGRAM



!!! Future work
!!! 'sobowlin' == bowl index, == number of levels in the mixed layer.
!!! 'vomeeivv' == Meridional Eddie-Induced-Velocity. cf: northward_sea_water_velocity_due_to_eddies. Not requested ?
!!! ditto with  zonal velocity.
!!! -- 

