Index: /LMDZ6/branches/Ocean_skin/DefLists/CMIP6_ping_aerosol_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/CMIP6_ping_aerosol_lmdz.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/CMIP6_ping_aerosol_lmdz.xml	(revision 3605)
@@ -88,15 +88,15 @@
    <field id="CMIP6_minpblz"       field_ref="dummy_XY"         /> <!-- P1 (m) atmosphere_boundary_layer_thickness : minimum boundary layer height during the day (add cell_methods attribute: "time: minimum") -->
    <field id="CMIP6_mmraerh2o"     field_ref="dummy_XYA"        /> <!-- P1 (kg kg-1) mass_fraction_of_water_in_ambient_aerosol_particles_in_air : Aerosol water mass mixing ratio -->
-   <field id="CMIP6_mmrbc"         field_ref="dummy_XYA"        /> <!-- P1 (kg kg-1) mass_fraction_of_elemental_carbon_dry_aerosol_particles_in_air : Elemental carbon mass mixing ratio -->
-   <field id="CMIP6_mmrdust"       field_ref="dummy_XYA"        /> <!-- P1 (kg kg-1) mass_fraction_of_dust_dry_aerosol_particles_in_air : Dust aerosol mass mixing ratio -->
+   <field id="CMIP6_mmrbc"         field_ref="concbc"   > concbc/pres*temp*287.05967366659070 </field> <!-- P1 (kg kg-1) mass_fraction_of_elemental_carbon_dry_aerosol_particles_in_air : Elemental carbon mass mixing ratio -->
+   <field id="CMIP6_mmrdust"       field_ref="concdust" > concdust/pres*temp*287.05967366659070 </field> <!-- P1 (kg kg-1) mass_fraction_of_dust_dry_aerosol_particles_in_air : Dust aerosol mass mixing ratio -->
    <field id="CMIP6_mmrnh4"        field_ref="dummy_XYA"        /> <!-- P1 (kg kg-1) mass_fraction_of_ammonium_dry_aerosol_particles_in_air : NH4 mass mixing ratio -->
-   <field id="CMIP6_mmrno3"        field_ref="dummy_XYA"        /> <!-- P1 (kg kg-1) mass_fraction_of_nitrate_dry_aerosol_particles_in_air : NO3 aerosol mass mixing ratio -->
-   <field id="CMIP6_mmroa"         field_ref="dummy_XYA"        /> <!-- P1 (kg kg-1) mass_fraction_of_particulate_organic_matter_dry_aerosol_particles_in_air : We recommend a scale factor of POM=1.4*OC, unless your model has more detailed info available. -->
+   <field id="CMIP6_mmrno3"        field_ref="concno3"  > concno3/pres*temp*287.05967366659070 </field> <!-- P1 (kg kg-1) mass_fraction_of_nitrate_dry_aerosol_particles_in_air : NO3 aerosol mass mixing ratio -->
+   <field id="CMIP6_mmroa"         field_ref="concoa"   > concoa/pres*temp*287.05967366659070 </field> <!-- P1 (kg kg-1) mass_fraction_of_particulate_organic_matter_dry_aerosol_particles_in_air : We recommend a scale factor of POM=1.4*OC, unless your model has more detailed info available. -->
    <field id="CMIP6_mmrpm1"        field_ref="dummy_XYA"        /> <!-- P1 (kg kg-1) mass_fraction_of_pm1_dry_aerosol_particles_in_air : E.g. mass_fraction_of_pm1_aerosol_at_50_percent_relative_humidity_in_air. proposed name:  mass_fraction_of_pm1_dry_aerosol_in_air -->
    <field id="CMIP6_mmrpm10"       field_ref="dummy_XYA"        /> <!-- P1 (kg kg-1) mass_fraction_of_pm10_ambient_aerosol_particles_in_air : E.g. mass_fraction_of_pm10_aerosol_at_50_percent_relative_humidity_in_air, proposed name: mass_fraction_of_pm10_dry_aerosol_in_air -->
    <field id="CMIP6_mmrpm2p5"      field_ref="dummy_XYA"        /> <!-- P1 (kg kg-1) mass_fraction_of_pm2p5_dry_aerosol_particles_in_air : E.g. mass_fraction_of_pm2p5_aerosol_at_50_percent_relative_humidity_in_air, proposed_name: mass_fraction_of_pm2p5_dry_aerosol_in_air -->
-   <field id="CMIP6_mmrso4"        field_ref="dummy_XYA"        /> <!-- P1 (kg kg-1) mass_fraction_of_sulfate_dry_aerosol_particles_in_air : Aerosol sulfate mass mixing ratio -->
+   <field id="CMIP6_mmrso4"        field_ref="concso4"  > concso4/pres*temp*287.05967366659070 </field> <!-- P1 (kg kg-1) mass_fraction_of_sulfate_dry_aerosol_particles_in_air : Aerosol sulfate mass mixing ratio -->
    <field id="CMIP6_mmrsoa"        field_ref="dummy_XYA"        /> <!-- P1 (kg kg-1) mass_fraction_of_secondary_particulate_organic_matter_dry_aerosol_particles_in_air : Secondary organic aerosol mass mixing ratio -->
-   <field id="CMIP6_mmrss"         field_ref="dummy_XYA"        /> <!-- P1 (kg kg-1) mass_fraction_of_seasalt_dry_aerosol_particles_in_air : Sea Salt mass mixing ratio -->
+   <field id="CMIP6_mmrss"         field_ref="concss"   > concss/pres*temp*287.05967366659070 </field> <!-- P1 (kg kg-1) mass_fraction_of_seasalt_dry_aerosol_particles_in_air : Sea Salt mass mixing ratio -->
    <field id="CMIP6_nh50"          field_ref="dummy_XYA"        /> <!-- P1 (mol mol-1) mole_fraction_of_artificial_tracer_with_fixed_lifetime_in_air : Fixed surface layer mixing ratio over 30o-50oN (100ppbv), uniform fixed 50-day exponential decay. -->
    <field id="CMIP6_no"            field_ref="dummy_XYA"        /> <!-- P1 (mol mol-1) mole_fraction_of_nitrogen_monoxide_in_air : NO volume mixing ratio -->
Index: /LMDZ6/branches/Ocean_skin/DefLists/CMIP6_ping_atmos.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/CMIP6_ping_atmos.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/CMIP6_ping_atmos.xml	(revision 3605)
@@ -57,5 +57,5 @@
    <field id="CMIP6_clcalipso2"    field_ref="clcalipso2"                   /> <!-- P1 (%) cloud_area_fraction_in_atmosphere_layer : CALIPSO Cloud Fraction Undetected by CloudSat --> 
    <field id="CMIP6_clcalipsoice"  field_ref="clcalipsoice"                 /> <!-- P1 (%) ice_cloud_area_fraction_in_atmosphere_layer : CALIPSO Ice Cloud Fraction -->
-   <field id="CMIP6_clcalipsoliq"  field_ref="clcalipsoice"                 /> <!-- P1 (%) liquid_cloud_area_fraction_in_atmosphere_layer : CALIPSO Liquid Cloud Fraction -->
+   <field id="CMIP6_clcalipsoliq"  field_ref="clcalipsoliq"                 /> <!-- P1 (%) liquid_cloud_area_fraction_in_atmosphere_layer : CALIPSO Liquid Cloud Fraction -->
    <field id="CMIP6_cldicemxrat"   field_ref="cldicemxrat"                  /> <!-- P2 (1) cloud_ice_mixing_ratio : Cloud Ice Mixing Ratio -->
    <field id="CMIP6_cldnci"        field_ref="dummy_XY"                     /> <!-- P1 (m-3) number_concentration_of_ice_crystals_in_air_at_ice_cloud_top : Ice Crystal Number Concentration of Cloud Tops -->
@@ -76,5 +76,5 @@
    <field id="CMIP6_cls"           field_ref="dummy_XYA"                    /> <!-- P1 (%) stratiform_cloud_area_fraction_in_atmosphere_layer : Stratiform Cloud Area Fraction -->
    <field id="CMIP6_clt"           field_ref="cldt"> cldt*100.        </field> <!-- P1 (%) cloud_area_fraction : for the whole atmospheric column, as seen from the surface or the top of the atmosphere. Includes both large-scale and convective cloud. -->
-   <field id="CMIP6_clt_land"      field_ref="dummy_XY"         /> <!-- P1 (%) cloud_area_fraction : Total cloud fraction -->
+   <field id="CMIP6_clt_land"      field_ref="cldt"> cldt*100.        </field> <!-- P1 (%) cloud_area_fraction : Total cloud fraction -->
    <field id="CMIP6_cltc"          field_ref="dummy_XY"         /> <!-- P1 (%) convective_cloud_area_fraction : For the whole atmospheric column, as seen from the surface or the top of the atmosphere. Includes only convective cloud. -->
    <field id="CMIP6_cltcalipso"    field_ref="pcltcalipso"                  /> <!-- P1 (%) cloud_area_fraction :  CALIPSO Total Cloud Fraction -->
@@ -116,14 +116,14 @@
    <field id="CMIP6_hfdsl"         field_ref="bils"> bils*fract_ter   </field> <!-- P1 (W m-2) surface_downward_heat_flux_in_air : Ground heat flux -->
    <field id="CMIP6_hfdsnb"        field_ref="dummy_not_provided"           /> <!-- P1 (W m-2)  : Downward heat flux at snow botton -->
-   <field id="CMIP6_hfls_ist"      field_ref="dummy_XY"         /> <!-- P1 (W m-2) surface_upward_latent_heat_flux : Surface Upward Latent Heat Flux -->
-   <field id="CMIP6_hfls_land"     field_ref="dummy_XY"         /> <!-- P1 (W m-2) surface_upward_latent_heat_flux : Latent heat flux -->
+   <field id="CMIP6_hfls_ist"      field_ref="lat_lic"                      /> <!-- P1 (W m-2) surface_upward_latent_heat_flux : Surface Upward Latent Heat Flux -->
+   <field id="CMIP6_hfls_land"     field_ref="lat_ter"                      /> <!-- P1 (W m-2) surface_upward_latent_heat_flux : Latent heat flux -->
    <field id="CMIP6_hfls"          field_ref="flat"> flat*(-1.)       </field>  <!-- P1 (W m-2) surface_upward_latent_heat_flux : Surface Upward Latent Heat Flux -->
    <field id="CMIP6_hfmlt"         field_ref="dummy_not_provided"           /> <!-- P1 (W m-2) surface_snow_and_ice_melt_heat_flux : Energy of fusion -->
    <field id="CMIP6_hfrs"          field_ref="dummy_not_provided"           /> <!-- P1 (W m-2) temperature_flux_due_to_rainfall_expressed_as_heat_flux_onto_snow_and_ice : Heat transferred to snowpack by rainfall -->
    <field id="CMIP6_hfsbl"         field_ref="dummy_not_provided"           /> <!-- P1 (W m-2) surface_snow_and_ice_sublimation_heat_flux : Energy of sublimation -->
-   <field id="CMIP6_hfss"          field_ref="sens"> sens*(-1.) </field>       <!-- P1 (W m-2) surface_upward_sensible_heat_flux : Surface Upward Sensible Heat Flux -->
-   <field id="CMIP6_hfss_land"     field_ref="dummy_XY"         /> <!-- P1 (W m-2) surface_upward_sensible_heat_flux : Sensible heat flux -->
-   <field id="CMIP6_hfss_ist"      field_ref="dummy_XY"         /> <!-- P1 (W m-2) surface_upward_sensible_heat_flux : Surface Upward Sensible Heat Flux -->
-   <field id="CMIP6_hur"           field_ref="rhum"> rhum*100. </field> <!-- P1 (%) relative_humidity : This is the relative humidity with respect to liquid water for T> 0 C, and with respect to ice for T<0 C. -->
+   <field id="CMIP6_hfss"          field_ref="sens"> sens*(-1.)       </field> <!-- P1 (W m-2) surface_upward_sensible_heat_flux : Surface Upward Sensible Heat Flux -->
+   <field id="CMIP6_hfss_land"     field_ref="sens_ter"                     /> <!-- P1 (W m-2) surface_upward_sensible_heat_flux : Sensible heat flux -->
+   <field id="CMIP6_hfss_ist"      field_ref="sens_lic"                     /> <!-- P1 (W m-2) surface_upward_sensible_heat_flux : Surface Upward Sensible Heat Flux -->
+   <field id="CMIP6_hur"           field_ref="rhum"> rhum*100.        </field> <!-- P1 (%) relative_humidity : This is the relative humidity with respect to liquid water for T> 0 C, and with respect to ice for T<0 C. -->
    <field id="CMIP6_hurs"          field_ref="rh2m"             /> <!-- P1 (%) relative_humidity : This is the relative humidity with respect to liquid water for T> 0 C, and with respect to ice for T<0 C. -->
    <field id="CMIP6_hursmax"       field_ref="rh2m_max" freq_op="1d" > @rh2m_max </field> <!-- P1 (%) relative_humidity : This is the relative humidity with respect to liquid water for T> 0 C, and with respect to ice for T<0 C. -->   
@@ -142,5 +142,5 @@
    <field id="CMIP6_jpdftaureicemodis" field_ref="crimodis"              /> <!-- P1 (%) cloud_area_fraction_in_atmosphere_layer : MODIS Optical Thickness-Particle Size joint  distribution, ice -->
    <field id="CMIP6_jpdftaureliqmodis" field_ref="crlmodis"              /> <!-- P1 (%) cloud_area_fraction_in_atmosphere_layer : MODIS Optical Thickness-Particle Size joint  distribution, liquid -->
-   <field id="CMIP6_latitude"      field_ref="io_lat"                    /> <!-- P1 (degrees_north) latitude : Latitude -->
+   <field id="CMIP6_latitude"      field_ref="dummy_not_provided"        /> <!-- P1 (degrees_north) latitude : Latitude -->
    <field id="CMIP6_lim"           field_ref="dummy_not_provided"        /> <!-- P2 (kg) land_ice_mass : Greenland -->
    <field id="CMIP6_limnsw"        field_ref="dummy_not_provided"        /> <!-- P2 (kg) land_ice_mass_not_displacing_sea_water : Greenland -->
@@ -154,5 +154,5 @@
    <field id="CMIP6_loadsoa"       field_ref="dummy_not_provided"         /> <!-- P1 (kg m-2) atmosphere_mass_content_of_secondary_particulate_organic_matter_dry_aerosol : Load of Dry Aerosol Secondary Organic Matter -->
    <field id="CMIP6_loadss"        field_ref="loadss"           /> <!-- P1 (kg m-2) atmosphere_mass_content_of_seasalt_dry_aerosol : Load of Seasalt -->
-   <field id="CMIP6_longitude"     field_ref="io_lon"              /> <!-- P1 (degrees_east) longitude : Longitude -->
+   <field id="CMIP6_longitude"     field_ref="dummy_not_provided"         /> <!-- P1 (degrees_east) longitude : Longitude -->
    <field id="CMIP6_lwsffluxaero"  field_ref="dummy_not_provided"         /> <!-- P2 (W m-2) longwave__flux__due_to_volcanic_aerosols_at_the_surface : downwelling longwave  flux  due to volcanic aerosols at the surface to be diagnosed through double radiation call -->
    <field id="CMIP6_lwsrfasdust"   field_ref="dummy_not_provided"         /> <!-- P1 (W m-2) surface_instantaneous_longwave_forcing_due_to_dust : All-sky Surface Longwave radiative flux due to Dust -->
@@ -174,5 +174,6 @@
    <field id="CMIP6_od550so4so"    field_ref="dummy_not_provided"        /> <!-- P1 (1)  : Stratospheric Optical depth at 550 nm (sulphate only) 2D-field (here we limit the computation of OD to the stratosphere only) --> 
    <field id="CMIP6_od865dust"     field_ref="dummy_not_provided"        /> <!-- P1 (1) atmosphere_optical_thickness_due_to_dust_ambient_aerosol_particles : Optical thickness at 865 nm Dust -->
-   <field id="CMIP6_parasolRefl" field_ref="parasol_refl"                /> <!-- P1 (1) toa_bidirectional_reflectance : PARASOL Reflectance -->
+   <field id="CMIP6_orog"          field_ref="phis" > phis / 9.80665 </field> <!-- P1 (m) surface_altitude : Surface Altitude -->
+   <field id="CMIP6_parasolRefl"   field_ref="parasol_refl"              /> <!-- P1 (1) toa_bidirectional_reflectance : PARASOL Reflectance -->
    <field id="CMIP6_pctisccp"      field_ref="ctpisccp"                  /> <!-- P1 (Pa) air_pressure_at_cloud_top : time-means weighted by the ISCCP Total Cloud Fraction - see  http://cfmip.metoffice.com/COSP.html -->
    <field id="CMIP6_pfull"         field_ref="pres"                      /> <!-- P1 (Pa) air_pressure : Pressure on Model Levels -->
@@ -186,15 +187,15 @@
    <field id="CMIP6_prlsns"        field_ref="pr_lsc_i"                  /> <!-- P2 (kg m-2 s-1) large_scale_snowfall_flux : large-scale precipitation of all forms of water in the solid phase. -->
    <field id="CMIP6_prlsprof"      field_ref="pr_lsc_l"                  /> <!-- P2 (kg m-2 s-1) large_scale_rainfall_flux : Stratiform Rainfall Flux -->
-   <field id="CMIP6_prra_land"     field_ref="dummy_XY"         /> <!-- P2 (kg m-2 s-1) rainfall_flux : rainfall_flux -->
-   <field id="CMIP6_prra_ifs"      field_ref="dummy_XY"         /> <!-- P1 (kg m-2 s-1) rainfall_flux : computed as the total mass of liquid water falling as liquid rain  into the ice-free portion of the ocean divided by the area of the ocean portion of the grid cell. -->
-   <field id="CMIP6_prra_ist"      field_ref="dummy_XY"         /> <!-- P1 (kg m-2 s-1) rainfall_flux : over Land Ice//quantity averaged over ice sheet (grounded ice sheet and floating ice shelf) only. Needed to analyse the impact of downscaling methods -->
+   <field id="CMIP6_prra_land"     field_ref="rain_fall"         /> <!-- P2 (kg m-2 s-1) rainfall_flux : rainfall_flux -->
+   <field id="CMIP6_prra_ifs"      field_ref="rain_fall"         /> <!-- P1 (kg m-2 s-1) rainfall_flux : computed as the total mass of liquid water falling as liquid rain  into the ice-free portion of the ocean divided by the area of the ocean portion of the grid cell. -->
+   <field id="CMIP6_prra_ist"      field_ref="rain_fall"         /> <!-- P1 (kg m-2 s-1) rainfall_flux : over Land Ice//quantity averaged over ice sheet (grounded ice sheet and floating ice shelf) only. Needed to analyse the impact of downscaling methods -->
    <field id="CMIP6_prra"          field_ref="rain_fall"                 /> <!-- P1 (kg m-2 s-1) rainfall_flux : Rainfall rate -->
-   <field id="CMIP6_prrc_land"     field_ref="dummy_XY"         /> <!-- P1 (kg m-2 s-1) convective_rainfall_flux : convective_rainfall_flux -->
+   <field id="CMIP6_prrc_land"     field_ref="rain_con"         /> <!-- P1 (kg m-2 s-1) convective_rainfall_flux : convective_rainfall_flux -->
    <field id="CMIP6_prrc"          field_ref="rain_con"                  /> <!-- P1 (kg m-2 s-1) convective_rainfall_flux : Convective Rainfall rate -->
    <field id="CMIP6_prrsn"         field_ref="dummy_not_provided"       /> <!-- P1 (1) mass_fraction_of_rainfall_onto_snow : mass_fraction_of_rainfall_onto_snow -->
    <field id="CMIP6_prsn"          field_ref="snow"                     /> <!-- P1 (kg m-2 s-1) snowfall_flux : at surface; includes precipitation of all forms of water in the solid phase -->
-   <field id="CMIP6_prsn_ifs"      field_ref="dummy_XY"         /> <!-- P1 (kg m-2 s-1) snowfall_flux : computed as the total mass per unit time of solid-phase precipitation falling into the ice-free portion of the ocean divided by the area of the ocean portion of the grid cell.   (Snowfall flux includes all types of solid-phase precipitation.) -->
-   <field id="CMIP6_prsn_ist"      field_ref="dummy_XY"         /> <!-- P1 (kg m-2 s-1) snowfall_flux : quantity averaged over ice sheet (grounded ice sheet and floating ice shelf) only. Needed to analyse the impact of downscaling methods -->
-   <field id="CMIP6_prsnc_land"    field_ref="dummy_XYA"        /> <!-- P2 (kg m-2 s-1) convective_snowfall_flux : convective_snowfall_flux -->
+   <field id="CMIP6_prsn_ifs"      field_ref="snow"                     /> <!-- P1 (kg m-2 s-1) snowfall_flux : computed as the total mass per unit time of solid-phase precipitation falling into the ice-free portion of the ocean divided by the area of the ocean portion of the grid cell.   (Snowfall flux includes all types of solid-phase precipitation.) -->
+   <field id="CMIP6_prsn_ist"      field_ref="snow"                     /> <!-- P1 (kg m-2 s-1) snowfall_flux : quantity averaged over ice sheet (grounded ice sheet and floating ice shelf) only. Needed to analyse the impact of downscaling methods -->
+   <field id="CMIP6_prsnc_land"    field_ref="pr_con_i"        /> <!-- P2 (kg m-2 s-1) convective_snowfall_flux : convective_snowfall_flux -->
    <field id="CMIP6_prsnc"         field_ref="pr_con_i"                 /> <!-- P2 (kg m-2 s-1) convective_snowfall_flux : Convective Snowfall rate -->
    <field id="CMIP6_prsnsn"        field_ref="dummy_not_provided"       /> <!-- P1 (1) mass_fraction_of_snowfall_onto_snow : mass_fraction_of_snowfall_onto_snow -->
@@ -215,14 +216,14 @@
    <field id="CMIP6_reffsnowc"     field_ref="dummy_XYA"        /> <!-- P2 (m) effective_radius_of_convective_cloud_snow_particle : This is defined as the in-cloud ratio of the third moment over the second moment of the particle size distribution (obtained by considering only the cloudy portion of the grid cell). -->
    <field id="CMIP6_reffsnows"     field_ref="dummy_XYA"        /> <!-- P2 (m) effective_radius_of_stratiform_cloud_snow_particle : This is defined as the in-cloud ratio of the third moment over the second moment of the particle size distribution (obtained by considering only the cloudy portion of the grid cell). -->
-   <field id="CMIP6_rld"           field_ref="rld"> rld*(-1.)  </field> <!-- P1 (W m-2) downwelling_longwave_flux_in_air : Downwelling Longwave Radiation -->
+   <field id="CMIP6_rld"           field_ref="rld"> rld*(-1.)   </field> <!-- P1 (W m-2) downwelling_longwave_flux_in_air : Downwelling Longwave Radiation -->
    <field id="CMIP6_rld4co2"       field_ref="rld4co2"          /> <!-- P1 (W m-2) downwelling_longwave_flux_in_air : Downwelling Longwave Radiation 4XCO2 Atmosphere --> 
    <field id="CMIP6_rldcs"         field_ref="rldcs"            /> <!-- P1 (W m-2) downwelling_longwave_flux_in_air_assuming_clear_sky : Downwelling Clear-Sky Longwave Radiation -->
    <field id="CMIP6_rldcs4co2"     field_ref="rldcs4co2"        /> <!-- P1 (W m-2) downwelling_longwave_flux_in_air_assuming_clear_sky : Downwelling Clear-Sky Longwave Radiation 4XCO2 Atmosphere -->
-   <field id="CMIP6_rlds_ist"      field_ref="dummy_XY"         /> <!-- P1 (W m-2) surface_downwelling_longwave_flux_in_air : Surface Downwelling Longwave Radiation -->
+   <field id="CMIP6_rlds_ist"      field_ref="LWdnSFC"          /> <!-- P1 (W m-2) surface_downwelling_longwave_flux_in_air : Surface Downwelling Longwave Radiation -->
    <field id="CMIP6_rlds"          field_ref="LWdnSFC"          /> <!-- P1 (W m-2) surface_downwelling_longwave_flux_in_air : Surface Downwelling Longwave Radiation -->
    <field id="CMIP6_rldscs"        field_ref="LWdnSFCclr"       /> <!-- P1 (W m-2) surface_downwelling_longwave_flux_in_air : Surface Downwelling Longwave Radiation -->
    <field id="CMIP6_rls"           field_ref="soll"             /> <!-- P1 (W m-2) surface_net_downward_longwave_flux : Net Longwave Surface Radiation -->
-   <field id="CMIP6_rls_land"      field_ref="dummy_XY"         /> <!-- P1 (W m-2) surface_net_downward_longwave_flux : Net longwave radiation -->
-   <field id="CMIP6_rlu"           field_ref="rlu"              />  <!-- P1 (W m-2) upwelling_longwave_flux_in_air : Fluxes are requested at all levels -->
+   <field id="CMIP6_rls_land"      field_ref="flw_ter"             /> <!-- P1 (W m-2) surface_net_downward_longwave_flux : Net longwave radiation -->
+   <field id="CMIP6_rlu"           field_ref="rlu"              /> <!-- P1 (W m-2) upwelling_longwave_flux_in_air : Fluxes are requested at all levels -->
    <field id="CMIP6_rlu4co2"       field_ref="rlu4co2"          /> <!-- P1 (W m-2) upwelling_longwave_flux_in_air : Upwelling Longwave Radiation 4XCO2 Atmosphere -->
    <field id="CMIP6_rlucs"         field_ref="rlucs"            /> <!-- P1 (W m-2) upwelling_longwave_flux_in_air_assuming_clear_sky : Includes also the fluxes at the surface and TOA. -->
@@ -246,5 +247,5 @@
    <field id="CMIP6_rsdsdiff"      field_ref="dummy_XY"         /> <!-- P1 (W m-2) surface_diffuse_downwelling_shortwave_flux_in_air : Surface Diffuse Downwelling Shortwave Radiation -->
    <field id="CMIP6_rsdt"          field_ref="SWdnTOA"          /> <!-- P1 (W m-2) toa_incoming_shortwave_flux : TOA Incident Shortwave Radiation -->
-   <field id="CMIP6_rss_land"      field_ref="dummy_XY"         /> <!-- P1 (W m-2) surface_net_downward_shortwave_flux : Net shortwave radiation -->
+   <field id="CMIP6_rss_land"      field_ref="fsw_ter"             /> <!-- P1 (W m-2) surface_net_downward_shortwave_flux : Net shortwave radiation -->
    <field id="CMIP6_rss"           field_ref="sols"             /> <!-- P1 (W m-2) surface_net_downward_shortwave_flux : Net Shortwave Surface Radiation -->
    <field id="CMIP6_rsu"           field_ref="rsu"              /> <!-- P1 (W m-2) upwelling_shortwave_flux_in_air : Fluxes are requested at all levels -->
@@ -290,5 +291,5 @@
    <field id="CMIP6_t2"            field_ref="temp"> temp*temp   </field> <!-- P2 (K2) square_of_air_temperature : square_of_air_temperature -->
    <field id="CMIP6_ta"            field_ref="temp"             /> <!-- P1 (K) air_temperature : Air Temperature -->
-   <field id="CMIP6_tas_ist"       field_ref="dummy_XY"         /> <!-- P1 (K) air_temperature : quantity averaged over ice sheet (grounded ice sheet and floating ice shelf) only. Needed to analyse the impact of downscaling methods -->
+   <field id="CMIP6_tas_ist"       field_ref="t2m_lic"          /> <!-- P1 (K) air_temperature : quantity averaged over ice sheet (grounded ice sheet and floating ice shelf) only. Needed to analyse the impact of downscaling methods -->
    <field id="CMIP6_tas"           field_ref="t2m"              /> <!-- P1 (K) air_temperature : This is sampled synoptically. -->
    <field id="CMIP6_tasmax"        field_ref="tasmax" freq_op="1d"> @tasmax </field> <!-- P1 (K) air_temperature : monthly mean of the daily-maximum near-surface air temperature. -->  
@@ -328,5 +329,5 @@
    <field id="CMIP6_tr"            field_ref="tsol"             /> <!-- P1 (K) surface_temperature : Surface Radiative Temperature -->
    <field id="CMIP6_ts"            field_ref="tsol"             /> <!-- P1 (K) surface_temperature : Surface temperature (skin for open ocean) -->
-   <field id="CMIP6_ts_ist"        field_ref="dummy_XY"         /> <!-- P1 (K) surface_temperature : quantity averaged over ice sheet (grounded ice sheet and floating ice shelf) only. Needed to analyse the impact of downscaling methods -->
+   <field id="CMIP6_ts_ist"        field_ref="tsol_lic"         /> <!-- P1 (K) surface_temperature : quantity averaged over ice sheet (grounded ice sheet and floating ice shelf) only. Needed to analyse the impact of downscaling methods -->
    <field id="CMIP6_tsns"          field_ref="dummy_not_provided"         /> <!-- P1 (K) surface_temperature : Snow Surface Temperature -->
    <field id="CMIP6_twap"          field_ref="vitw">vitw*temp </field> <!-- P2 (K Pa s-1) product_of_omega_and_air_temperature : air_temperature_times_omega -->
@@ -360,5 +361,5 @@
    <field id="CMIP6_ygwdparam"     field_ref="west_gwstress"    /> <!-- P2 (Pa) atmosphere_northward_stress_due_to_gravity_wave_drag : y_gravity_wave_drag_param -->
    <field id="CMIP6_zfull"         field_ref="zfull"            /> <!-- P2 (m) height_above_reference_ellipsoid : This is actual height above mean sea level, not geopotential height -->
-   <field id="CMIP6_zg"            field_ref="geoph"             /> <!-- P1 (m) geopotential_height : Geopotential height on the 1000 hPa surface -->
+   <field id="CMIP6_zg"            field_ref="geoph"            /> <!-- P1 (m) geopotential_height : Geopotential height on the 1000 hPa surface -->
    <field id="CMIP6_zhalf"         field_ref="zhalf"            /> <!-- P2 (m) height_above_reference_ellipsoid : This is actual height above mean sea level, not geopotential height.  This is actual height above mean sea level, not geopotential height.  Includes both the top of the model atmosphere and surface levels. -->
    <field id="CMIP6_zmla"          field_ref="s_pblh"           /> <!-- P1 (m) atmosphere_boundary_layer_thickness : Height of Boundary Layer -->
@@ -366,8 +367,12 @@
    <field id="CMIP6_zmswaero"      field_ref="dummy_not_provided"        /> <!-- P1 (K s-1) shortwave_heating_rate_due_to_volcanic_aerosols : shortwave heating rate due to volcanic aerosols to be diagnosed through double radiation call, zonal average values required -->
    <field id="CMIP6_zmtnt"         field_ref="dtphy"            /> <!-- P1 (K s-1) tendency_of_air_temperature_due_to_diabatic_processes : Zonal Mean Diabatic Heating Rates -->
-   <field id="CMIP6_ap" field_ref="Ahyb" /><!-- One of the hybrid coordinate arrays -->
-   <field id="CMIP6_ap_bnds" field_ref="Ahyb_inter" /><!-- One of the hybrid coordinate arrays -->
-   <field id="CMIP6_b" field_ref="Bhyb" /><!-- One of the hybrid coordinate arrays -->
-   <field id="CMIP6_b_bnds" field_ref="Bhyb_inter" /><!-- One of the hybrid coordinate arrays -->
+   <field id="CMIP6_ap" field_ref="Ahyb" /><!-- Ap hybrid coordinate array for level interfaces -->
+   <field id="CMIP6_ap_bnds" field_ref="Ahyb_bounds" /><!-- Ap hybrid coordinate bounds -->
+   <field id="CMIP6_b" field_ref="Bhyb" /><!-- Bp hybrid coordinate array for level interfaces -->
+   <field id="CMIP6_b_bnds" field_ref="Bhyb_bounds" /><!-- Bp hybrid coordinate bounds -->
+   <field id="CMIP6_ahp" field_ref="Ahyb_mid" /><!-- Aps hybrid coordinate array for mid-levels -->
+   <field id="CMIP6_ahp_bnds" field_ref="Ahyb_mid_bounds" /><!-- Aps hybrid coordinate bounds -->
+   <field id="CMIP6_bh" field_ref="Bhyb_mid" /><!-- Bps hybrid coordinate array for mid-levels -->
+   <field id="CMIP6_bh_bnds" field_ref="Bhyb_mid_bounds" /><!-- Bps hybrid coordinate bounds -->
 </field_definition>
 </context>
Index: /LMDZ6/branches/Ocean_skin/DefLists/CMIP6_ping_landIce.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/CMIP6_ping_landIce.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/CMIP6_ping_landIce.xml	(revision 3605)
@@ -47,5 +47,5 @@
    <field id="CMIP6_mrfso"         field_ref="dummy_XY"         /> <!-- P1 (kg m-2) soil_frozen_water_content : the mass (summed over all all layers) of frozen water. -->
    <field id="CMIP6_mrroIs"        field_ref="dummy_XY"         /> <!-- P1 (kg m-2 s-1) runoff_flux : quantity averaged over ice_sheet (meaning grounded ice sheet and floating ice shelf) only, to avoid contamination from other surfaces (eg: permafrost) -->
-   <field id="CMIP6_orogIs"        field_ref="phis" > phis / 9.81  </field>  <!-- P1 (m) surface_altitude : quantity averaged over ice_sheet (meaning grounded ice sheet and floating ice shelf) only, to avoid contamination from other surfaces (eg: permafrost) -->
+   <field id="CMIP6_orogIs"        field_ref="phis" > phis / 9.80665 </field>  <!-- P1 (m) surface_altitude : quantity averaged over ice_sheet (meaning grounded ice sheet and floating ice shelf) only, to avoid contamination from other surfaces (eg: permafrost) -->
    <field id="CMIP6_pflw"          field_ref="dummy_XY"         /> <!-- P1 (kg m-2) liquid_water_content_of_permafrost_layer : "where land over land", i.e., this is the total mass of liquid water contained within the permafrost layer within the land portion of a grid cell divided by the area of the land portion of the cell. -->
    <field id="CMIP6_prraIs"        field_ref="rain_fall" /> <!-- P1 (kg m-2 s-1) rainfall_flux : quantity averaged over ice_sheet (meaning grounded ice sheet and floating ice shelf) only, to avoid contamination from other surfaces (eg: permafrost) -->
Index: /LMDZ6/branches/Ocean_skin/DefLists/config_AMIP.def
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/config_AMIP.def	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/config_AMIP.def	(revision 3605)
@@ -46,7 +46,7 @@
 #
 ### ok_ade=y/n   flag Aerosol direct effect
-ok_ade= y
+ok_ade= n
 ### ok_aie=y/n   flag Aerosol indirect effect
-ok_aie= y
+ok_aie= n
 ### aer_type =   Aerosol variation type : actuel / preind / scenario / annuel
 aer_type=annuel
@@ -55,7 +55,7 @@
 ###  flag_aerosol = type of coupled aerosol, if aerosol offline 
 ###  0 => no aerosol, 1 => sulfate only, 2 => bc only, 3 => pom only, 4 => seasalt only, 5 => dust only, 6 => all aerosol
-flag_aerosol= 6
+flag_aerosol= 0
 ### ok_cdnc=y/n   Cloud droplet number concentration
-ok_cdnc= y
+ok_cdnc= n
 # ok_alw=y flag pour activer l effet LW des poussieres
 ok_alw=y
@@ -71,5 +71,5 @@
 # 
 # Aerosols stratospheriques utilises par defaut 
-flag_aerosol_strat=2
+flag_aerosol_strat=0
 # COSP
-ok_cosp= y
+ok_cosp= n
Index: /LMDZ6/branches/Ocean_skin/DefLists/context_input_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/context_input_lmdz.xml	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/DefLists/context_input_lmdz.xml	(revision 3605)
@@ -0,0 +1,477 @@
+<!--- $Id$ -->
+<!-- Context LMDZ -->
+<context id="LMDZ">
+
+<!------------------------------------------------------------------------------------->
+                     <!--  create etat0_limit --> 
+<!------------------------------------------------------------------------------------->
+  <field_definition>
+
+    <field_group id="etat0_limit_read" read_access="false" enabled="false" operation="instant">
+       <field id="ts"           field_ref="ts_reg"      domain_ref="from_ecphy"     />
+       <field id="qs"           field_ref="qs_reg"      domain_ref="from_ecphy"     />
+       <field id="landice"      field_ref="landice_reg" domain_ref="from_landiceref"  />
+       <field id="mask"         field_ref="mask_reg"    domain_ref="from_relief" />
+       <field id="sic_limit"    field_ref="sic_reg"     domain_ref="from_limit_amip"  />
+       <field id="sst_limit"    field_ref="sst_reg"     domain_ref="from_limit_amip" />
+       <field id="rugos_limit"  field_ref="rugos_reg"   domain_ref="from_limit" > exp(this) </field>
+       <field id="albedo_limit" field_ref="albedo_reg"  domain_ref="from_limit"  />
+
+       <field id="zmea" field_ref="zmea_reg"  domain_ref="from_orography"  />
+       <field id="zstd" field_ref="zstd_reg"  domain_ref="from_orography"  />
+       <field id="zsig" field_ref="zsig_reg"  domain_ref="from_orography"  />
+       <field id="zgam" field_ref="zgam_reg"  domain_ref="from_orography"  />
+       <field id="zthe" field_ref="zthe_reg"  domain_ref="from_orography"  />
+
+    </field_group>
+   
+
+
+  </field_definition>
+  
+  
+   <file_definition>
+    
+    <file_group id="etat0_limit_read" type="one_file" mode="read" enabled=".FALSE." output_level="10" output_freq="1y" >
+      
+      <file id="frac_ocean" name="ocean_fraction" enabled=".FALSE.">
+        <field id="frac_ocean_read" name="OceFrac" domain_ref="dom_glo" operation="instant" freq_offset="1ts" />
+      </file>
+
+      <file id="land_water" enabled=".FALSE.">
+        <field id="land_water" name="MASK" domain_ref="domain_land_water" operation="instant" freq_offset="1ts" />
+      </file>
+      
+      <file id="ECPHY"  name="ECPHY" >
+        <field id="ts_reg"   name="ST"      domain_ref="domain_ecphy" operation="instant"  freq_offset="1ts"/>
+        <field id="qs_reg"   name="CDSW"    domain_ref="domain_ecphy" operation="instant"  freq_offset="1ts"/>
+      </file>
+
+      <file id="landiceref"  name="landiceref" >
+        <field id="landice_reg"   name="landice"   domain_ref="domain_landiceref" operation="instant" freq_offset="1ts"/>
+      </file>
+
+      <file id="relief" name="Relief" >
+        <field id="mask_reg" name="RELIEF" domain_ref="domain_relief" operation="instant" freq_offset="1ts"> this &gt; 1e-5 </field>
+      </file>
+
+
+<!-- Case with amip files --> 
+      <file id="amipbc_sic_1x1" name="amipbc_sic_1x1" >
+        <field id="sic_reg" name="sicbcs" domain_ref="domain_limit_amip" axis_ref="time_sic" operation="instant" freq_offset="1ts"/>
+      </file>
+ 
+      <file id="amipbc_sst_1x1" name="amipbc_sst_1x1" >
+         <field id="sst_reg" name="tosbcs" domain_ref="domain_limit_amip" axis_ref="time_sst" operation="instant" freq_offset="1ts">this+273.15</field> 
+      </file>
+
+<!-- Case with HadISST files --> 
+<!--  
+      <file id="siconc" name="hadisst_siconc" >
+        <field id="sic_reg" name="sicbcs" domain_ref="domain_limit_amip" axis_ref="time_sic" operation="instant" freq_offset="1ts"/>
+      </file>
+ 
+      <file id="tos" name="hadisst_tos" >
+         <field id="sst_reg" name="tosbcs" domain_ref="domain_limit_amip" axis_ref="time_sst" operation="instant" freq_offset="1ts">this+273.15</field> 
+      </file>
+-->
+
+
+      <file id="rugos" name="Rugos" >
+        <field id="rugos_reg" name="RUGOS" domain_ref="domain_limit" axis_ref="time_month" operation="instant" freq_offset="1ts"> log(this) </field> 
+      </file>
+
+      <file id="albedo" name="Albedo" >
+        <field id="albedo_reg" name="ALBEDO" domain_ref="domain_limit" axis_ref="time_month" operation="instant" freq_offset="1ts"/> 
+      </file>
+     
+      <file id="orography" name="orography" >
+
+         <field_group domain_ref="domain_orography" operation="instant" freq_offset="1ts"> 
+            <field id="zmea_reg" name="phi" />
+            <field id="zstd_reg" name="mu" />
+            <field id="zsig_reg" name="sigma" />
+            <field id="zgam_reg" name="gama" />
+            <field id="zthe_reg" name="theta" />
+         </field_group >
+
+      </file>
+
+
+     <file id="grid_atm" type="one_file" output_freq="1y" mode="write" sync_freq="1ts"  >         
+       <field_group domain_ref="dom_glo_p8"  operation="once" prec="8">
+          <field id="area_ce0l"           name="area" long_name="atm cell area" />
+          <field id="fract_oce_ce0l"      name="fract_oce" long_name="ocean fraction" />
+          <field id="fract_sic_ce0l"      name="fract_sic" long_name="sea ice fraction" />
+
+          <field id="fract_oce_sic_ce0l"  name="fract_oce_plus_sic_p8" long_name="ocean + sea ice fraction" > fract_oce_ce0l + fract_sic_ce0l </field>
+          <field field_ref="fract_oce_sic_ce0l"  name="mask_oce_plus_sic" long_name="ocean + sea ice mask" > this &gt; 0  ? 1 : 0 </field>
+       </field_group>
+     </file>
+
+
+     </file_group>
+     
+
+     <file id="limit_write" name="limit" type="one_file" output_freq="1ts" sync_freq="1ts" enabled="false">         
+       <field_group domain_ref="dom_glo" axis_ref="time_year" operation="once">
+          <field id="foce_limout"  name="FOCE" long_name="Fraction ocean"/>
+          <field id="fsic_limout"  name="FSIC" long_name="Fraction glace de mer"/>
+          <field id="fter_limout"  name="FTER" long_name="Fraction terre"/>
+          <field id="flic_limout"  name="FLIC" long_name="Fraction land ice"/>
+          <field id="sst_limout"   name="SST"  long_name="Temperature superficielle de la mer"/>
+          <field id="bils_limout"  name="BILS" long_name="Reference flux de chaleur au sol"/> 
+          <field id="alb_limout"   name="ALB"  long_name="Albedo a la surface"/>
+          <field id="rug_limout"   name="RUG"  long_name="Rugosite" />
+       </field_group>
+     </file>
+
+     <file id="limit_read" name="limit" time_counter_name="time_year" type="one_file" output_freq="1d" mode="read" cyclic="true" enabled="false">         
+       <field_group domain_ref="dom_glo" freq_offset="1ts" operation="instant">
+          <field id="foce_limin"  name="FOCE" long_name="Fraction ocean"/>
+          <field id="fsic_limin"  name="FSIC" long_name="Fraction glace de mer"/>
+          <field id="fter_limin"  name="FTER" long_name="Fraction terre"/>
+          <field id="flic_limin"  name="FLIC" long_name="Fraction land ice"/>
+          <field id="sst_limin"   name="SST"  long_name="Temperature superficielle de la mer"/>
+          <field id="bils_limin"  name="BILS" long_name="Reference flux de chaleur au sol" enabled="false"/> 
+          <field id="alb_limin"   name="ALB"  long_name="Albedo a la surface"/>
+          <field id="rug_limin"   name="RUG"  long_name="Rugosite" />
+       </field_group>
+     </file>
+
+
+  </file_definition> 
+
+  <axis_definition>
+    <axis id="time_sic"/>
+    <axis id="time_sst"/>
+  </axis_definition>
+
+  <!-- Define domains and groups of domains -->
+  <domain_definition>
+
+      <domain id="from_ecphy" domain_ref="dom_glo">
+        <interpolate_domain write_weight="true" mode="read_or_compute"/>
+      </domain>  
+
+      <domain id="from_landiceref" domain_ref="dom_glo">
+        <interpolate_domain write_weight="true" mode="read_or_compute"/>
+      </domain>
+
+      <domain id="from_relief" domain_ref="dom_glo">
+       <interpolate_domain order="1" write_weight="true" mode="read_or_compute" />
+      </domain>
+
+      <domain id="from_orography" domain_ref="dom_glo">
+        <interpolate_domain order="1" write_weight="true" mode="read_or_compute"/>
+      </domain>
+
+      <domain id="from_limit" domain_ref="dom_glo">
+        <interpolate_domain write_weight="true" mode="read_or_compute"/>
+      </domain>
+
+      <domain id="from_limit_amip"domain_ref="dom_glo" >
+        <interpolate_domain write_weight="true" mode="read_or_compute"/>
+      </domain>
+      
+      <domain id="from_land_water"domain_ref="dom_glo" >
+        <interpolate_domain write_weight="true" mode="read_or_compute"/>
+      </domain>
+
+  
+    <domain id="domain_ecphy"  type="rectilinear" >
+       <generate_rectilinear_domain /> 
+    </domain>
+
+    <domain id="domain_landiceref"  type="rectilinear" >
+       <generate_rectilinear_domain /> 
+    </domain>
+
+    <domain id="domain_relief"  type="rectilinear" >
+       <generate_rectilinear_domain /> 
+    </domain>
+ 
+    <domain id="domain_limit"  type="rectilinear" >
+       <generate_rectilinear_domain /> 
+    </domain>
+
+    <domain id="domain_limit_amip"  type="rectilinear" >
+       <generate_rectilinear_domain /> 
+    </domain>
+
+    <domain id="domain_orography" type="rectilinear" >
+       <generate_rectilinear_domain /> 
+    </domain>  
+
+    <domain id="domain_land_water" type="rectilinear" >
+       <generate_rectilinear_domain /> 
+    </domain>  
+
+    <domain id="dom_glo_p8" domain_ref="dom_glo" prec="8"/>
+
+  </domain_definition>
+
+
+<!------------------------------------------------------------------------------------->
+                     <!--  etat0 ozone --> 
+<!------------------------------------------------------------------------------------->
+
+ <field_definition>
+
+    <field id="tro3_in"   grid_ref="grid_climoz" enabled="false"/>
+    <field id="tro3_out"  read_access="true"   field_ref="tro3_in"  grid_ref="grid_from_climoz" enabled="false"/>
+
+ </field_definition> 
+
+
+ <file_definition> 
+
+    <file id="test_o3" output_freq="1ts" type="one_file" enabled="false">
+      <field id="o3_out" grid_ref="grid_from_climoz" operation="instant" />
+     </file>
+
+  </file_definition> 
+
+
+  <domain_definition>
+
+    <domain id="domain_climoz" type="rectilinear" />
+
+    <domain id="from_climoz" domain_ref="dom_glo">
+      <interpolate_domain order="1" write_weight="true" mode="read_or_compute"/>
+    </domain>
+  
+  </domain_definition>
+
+  <axis_definition>
+    <axis id="axis_climoz"  unit="millibar" axis_type="Z"/>
+    <axis id="tr_climoz"  />
+    <axis id="time_axis_climoz" />
+  </axis_definition>
+
+
+  <grid_definition>
+
+       <grid id="grid_climoz">
+         <domain domain_ref="domain_climoz" />
+         <axis axis_ref="axis_climoz" />
+         <axis axis_ref="time_axis_climoz" />
+         <axis axis_ref="tr_climoz" />
+       </grid >
+       
+       <grid id="grid_from_climoz">
+         <domain domain_ref="from_climoz" />
+         <axis axis_ref="axis_climoz" />
+         <axis axis_ref="time_axis_climoz" />
+         <axis axis_ref="tr_climoz" />
+       </grid>
+
+  </grid_definition>
+
+
+
+<!------------------------------------------------------------------------------------->
+                     <!--  read aerosol --> 
+<!------------------------------------------------------------------------------------->
+
+  <field_definition>
+
+    <field_group id="aerosols" enabled="false">
+    
+       <field_group id="aerosol_in" grid_ref="grid_aerosol" >
+         <field id="AIPOMM_in"/>
+         <field id="ASBCM_in"/>
+         <field id="AIBCM_in"/>
+         <field id="ASPOMM_in"/>
+         <field id="CSSSM_in"/>
+         <field id="ASSSM_in"/>
+         <field id="CIDUSTM_in"/>
+         <field id="SO4_in"/>
+         <field id="CSSO4M_in"/>
+         <field id="SSSSM_in"/>
+         <field id="ASNO3M_in"/>
+         <field id="CSNO3M_in"/>
+         <field id="CINO3M_in"/>
+         <field id="ASSO4M_in"/>
+         <field id="CSSO4M_in"/>
+       </field_group>
+
+       <field_group id="load_aerosol_in" domain_ref="domain_aerosol" axis_ref="time_month" >
+         <field id="load_AIPOMM_in"/>
+         <field id="load_ASBCM_in"/>
+         <field id="load_AIBCM_in"/>
+         <field id="load_ASPOMM_in"/>
+         <field id="load_CSSSM_in"/>
+         <field id="load_ASSSM_in"/>
+         <field id="load_CIDUSTM_in"/>
+         <field id="load_SO4_in"/>
+         <field id="load_CSSO4M_in"/>
+         <field id="load_SSSSM_in"/>
+         <field id="load_ASNO3M_in"/>
+         <field id="load_CSNO3M_in"/>
+         <field id="load_CINO3M_in"/>
+         <field id="load_ASSO4M_in"/>
+         <field id="load_CSSO4M_in"/>
+       </field_group>
+       
+       <field_group id="aerosol_out" grid_ref="grid_from_aerosol" read_access="true" >
+         <field id="AIPOMM_out" field_ref="AIPOMM_in" />
+         <field id="ASBCM_out"  field_ref="ASBCM_in"  />
+         <field id="AIBCM_out"  field_ref="AIBCM_in"  />
+         <field id="ASPOMM_out" field_ref="ASPOMM_in" />
+         <field id="CSSSM_out"  field_ref="CSSSM_in"  />
+         <field id="ASSSM_out"  field_ref="ASSSM_in"  />
+         <field id="CIDUSTM_out"field_ref="CIDUSTM_in"/>
+         <field id="SO4_out"    field_ref="SO4_in"    />
+         <field id="CSSO4M_out" field_ref="CSSO4M_in" />
+         <field id="SSSSM_out"  field_ref="SSSSM_in"  />
+         <field id="ASNO3M_out" field_ref="ASNO3M_in" />
+         <field id="CSNO3M_out" field_ref="CSNO3M_in" />
+         <field id="CINO3M_out" field_ref="CINO3M_in" />
+         <field id="ASSO4M_out" field_ref="ASSO4M_in" />
+         <field id="CSSO4M_out" field_ref="CSSO4M_in" />
+       </field_group>
+
+       <field_group id="load_aerosol_out" domain_ref="from_aerosol" axis_ref="time_month" read_access="true">
+         <field id="load_AIPOMM_out" field_ref="load_AIPOMM_in" />
+         <field id="load_ASBCM_out"  field_ref="load_ASBCM_in"  />
+         <field id="load_AIBCM_out"  field_ref="load_AIBCM_in"  />
+         <field id="load_ASPOMM_out" field_ref="load_ASPOMM_in" />
+         <field id="load_CSSSM_out"  field_ref="load_CSSSM_in"  />
+         <field id="load_ASSSM_out"  field_ref="load_ASSSM_in"  />
+         <field id="load_CIDUSTM_out"field_ref="load_CIDUSTM_in"/>
+         <field id="load_SO4_out"    field_ref="load_SO4_in"    />
+         <field id="load_CSSO4M_out" field_ref="load_CSSO4M_in" />
+         <field id="load_SSSSM_out"  field_ref="load_SSSSM_in"  />
+         <field id="load_ASNO3M_out" field_ref="load_ASNO3M_in" />
+         <field id="load_CSNO3M_out" field_ref="load_CSNO3M_in" />
+         <field id="load_CINO3M_out" field_ref="load_CINO3M_in" />
+         <field id="load_ASSO4M_out" field_ref="load_ASSO4M_in" />
+         <field id="load_CSSO4M_out" field_ref="load_CSSO4M_in" />
+       </field_group>
+
+     
+       <field id="psurf_aerosol_in"   domain_ref="domain_aerosol" axis_ref="time_month" />
+       <field id="psurf_aerosol_out"  read_access="true"   field_ref="psurf_aerosol_in"  domain_ref="from_aerosol" axis_ref="time_month" />
+
+  </field_group>
+
+</field_definition>
+
+ <domain_definition>
+    
+    <domain id="domain_aerosol" type="rectilinear" />
+    
+    <domain id="from_aerosol" domain_ref="dom_glo">
+       <interpolate_domain order="1" write_weight="true" mode="read_or_compute"/>
+    </domain>
+
+ </domain_definition>
+
+  <axis_definition>
+    <axis id="axis_aerosol"  unit="millibar" axis_type="Z"/>
+  </axis_definition>
+
+  <grid_definition>
+
+       <grid id="grid_aerosol">
+         <domain domain_ref="domain_aerosol" />
+         <axis axis_ref="axis_aerosol" />
+         <axis axis_ref="time_month" />
+       </grid >
+       
+
+       <grid id="grid_from_aerosol">
+         <domain domain_ref="from_aerosol" />
+         <axis axis_ref="axis_aerosol" />
+         <axis axis_ref="time_month" />
+       </grid>
+       
+  </grid_definition>
+
+
+
+
+<!------------------------------------------------------------------------------------->
+                     <!--  read aerosol strato  --> 
+<!------------------------------------------------------------------------------------->
+
+<field_definition>
+
+    <field_group id="aerosol_strato2" enabled="false" >
+       <field id="tauaerstrat_in"   grid_ref="grid_tauswstrat" />
+       <field id="tauaerstrat_out"  read_access="true"   field_ref="tauaerstrat_in"  grid_ref="grid_from_tauswstrat" />
+
+       <field id="pizaerstrat_in"   grid_ref="grid_tauswstrat" />
+       <field id="pizaerstrat_out"  read_access="true"   field_ref="pizaerstrat_in"  grid_ref="grid_from_tauswstrat" />
+
+       <field id="cgaerstrat_in"   grid_ref="grid_tauswstrat" />
+       <field id="cgaerstrat_out"  read_access="true"   field_ref="cgaerstrat_in"  grid_ref="grid_from_tauswstrat" />
+
+       <field id="taulwaerstrat_in"   grid_ref="grid_taulwstrat" />
+       <field id="taulwaerstrat_out"  read_access="true"   field_ref="taulwaerstrat_in"  grid_ref="grid_from_taulwstrat" />
+    </field_group>
+    
+    <field_group id="aerosol_strato1" enabled="false" >
+      <field id="taustrat_in"   domain_ref="domain_taustrat" axis_ref="klev" />
+      <field id="taustrat_out"  read_access="true"   field_ref="taustrat_in"  domain_ref="from_taustrat" axis_ref="klev" />
+    </field_group>
+
+</field_definition>
+
+
+ <domain_definition>
+
+    <domain id="domain_tauswstrat" type="rectilinear" />
+    <domain id="domain_taulwstrat" type="rectilinear" />
+    <domain id="domain_taustrat" type="rectilinear" />
+
+
+      <domain id="from_tauswstrat" domain_ref="dom_glo">
+        <interpolate_domain order="1" write_weight="true" mode="read_or_compute"/>
+      </domain>
+
+      <domain id="from_taulwstrat" domain_ref="dom_glo">
+        <interpolate_domain order="1" write_weight="true" mode="read_or_compute"/>
+      </domain>
+
+      <domain id="from_taustrat" domain_ref="dom_glo">
+        <interpolate_domain order="1" write_weight="true" mode="read_or_compute"/>
+      </domain> 
+
+ </domain_definition>
+
+  <axis_definition>
+    <axis id="nsw"  />
+    <axis id="nlw"  />
+  </axis_definition>
+
+  <grid_definition>
+
+       <grid id="grid_tauswstrat">
+         <domain domain_ref="domain_tauswstrat" />
+         <axis axis_ref="klev" />
+         <axis axis_ref="nsw" />
+       </grid >
+
+       <grid id="grid_from_tauswstrat">
+         <domain domain_ref="from_tauswstrat" />
+         <axis axis_ref="klev" />
+         <axis axis_ref="nsw" />
+       </grid >
+
+       <grid id="grid_taulwstrat">
+         <domain domain_ref="domain_taulwstrat" />
+         <axis axis_ref="klev" />
+         <axis axis_ref="nlw" />
+       </grid >
+
+       <grid id="grid_from_taulwstrat">
+         <domain domain_ref="from_taulwstrat" />
+         <axis axis_ref="klev" />
+         <axis axis_ref="nlw" />
+       </grid >
+
+  </grid_definition>
+
+</context>
Index: /LMDZ6/branches/Ocean_skin/DefLists/context_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/context_lmdz.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/context_lmdz.xml	(revision 3605)
@@ -1,2 +1,3 @@
+<!-- $Id$ -->
 <!-- Context LMDZ -->
 <context id="LMDZ">
@@ -12,18 +13,32 @@
   <file_definition src="./file_def_histhf_lmdz.xml"/>
   <file_definition src="./file_def_histins_lmdz.xml"/>
-<!--  <file_definition src="./file_def_histLES_lmdz.xml"/> -->
+  <file_definition src="./file_def_histLES_lmdz.xml"/>
   <file_definition src="./file_def_histmth_lmdz.xml"/>
-<!--  <file_definition src="./file_def_histstn_lmdz.xml"/> -->
+  <file_definition src="./file_def_histstn_lmdz.xml"/>
   <file_definition src="./file_def_histmthNMC_lmdz.xml"/>
   <file_definition src="./file_def_histdayNMC_lmdz.xml"/>
   <file_definition src="./file_def_histhfNMC_lmdz.xml"/>
-<!--  <file_definition src="./file_def_histmthCOSP_lmdz.xml"/> -->
-<!--  <file_definition src="./file_def_histdayCOSP_lmdz.xml"/> -->
-<!--  <file_definition src="./file_def_histhfCOSP_lmdz.xml"/> -->
+  <file_definition src="./file_def_histmthCOSP_lmdz.xml"/>
+  <file_definition src="./file_def_histdayCOSP_lmdz.xml"/> 
+  <file_definition src="./file_def_histhfCOSP_lmdz.xml"/>  
   <file_definition src="./file_def_histstrataer_lmdz.xml"/>
- 
+  <file_definition src="./file_def_histdaystrataer_lmdz.xml"/>
+
   <!-- Define domains and groups of domains -->
   <domain_definition>
-    <domain id="dom_glo" data_dim="2" />
+
+    <domain id="dom_glo"  data_dim="1" />
+
+    <domain id="greordered"  domain_ref="dom_glo">
+      <reorder_domain invert_lat="true" shift_lon_fraction="0.5" min_lon="0" max_lon="360" />
+    </domain> 
+   
+    <domain id="dom_regular" ni_glo="144" nj_glo="143" type="rectilinear"  >
+      <generate_rectilinear_domain lat_start="-90" lat_end="90" lon_start="0"/>
+      <interpolate_domain order="1"/>
+    </domain>
+   
+    <domain id="dom_out" domain_ref="dom_glo"/>
+    
   </domain_definition>
   
@@ -36,5 +51,5 @@
   <grid_definition>
     <grid id="grid_scalar" >
-    <scalar/>
+      <scalar/>
     </grid>
   </grid_definition>
@@ -42,54 +57,40 @@
   <!-- Define groups of vertical axes -->
   <axis_definition>
-    <axis id="presnivs" standard_name="Vertical levels" unit="Pa">
-    </axis>
-    <axis id="Ahyb" standard_name="Ahyb comp of Hyb Cord" unit="Pa">
-    </axis> 
-    <axis id="Bhyb" standard_name="Bhyb comp of Hyb Cord" unit="">
-    </axis>
-    <axis id="Ahyb_inter" standard_name="A comp of Hyb Cord at interface" unit="Pa">
-    </axis> 
-    <axis id="Bhyb_inter" standard_name="B comp of Hyb Cord at interface" unit="">
-    </axis>
-    <axis id="Alt" standard_name="Height approx for scale heigh of 8km at levels" unit="km">
-    </axis>
-    <axis id="plev" standard_name="model_level_number" unit="Pa">
-    </axis>
-    <axis id="klev"  prec="8" long_name = "hybrid sigma pressure coordinate"
-          standard_name ="atmosphere_hybrid_sigma_pressure_coordinate" unit="1">
-    </axis>
-    <axis id="bnds" standard_name="bounds" unit="1" >
+    <axis id="time_month" n_glo="12" value="(0,11) [1 2 3 4 5 6 7 8 9 10 11 12]"/>
+    <axis id="time_year" unit="day" />
+    <axis id="presnivs" standard_name="Vertical levels" unit="Pa"/>
+    <axis id="Ahyb" standard_name="Ahyb comp of Hyb Cord" unit="Pa"/>
+    <axis id="Bhyb" standard_name="Bhyb comp of Hyb Cord" unit=""/>
+    <axis id="Ahyb_inter" standard_name="A comp of Hyb Cord at interface" unit="Pa"/>
+    <axis id="Bhyb_inter" standard_name="B comp of Hyb Cord at interface" unit=""/>
+    <axis id="Alt" standard_name="Height approx for scale heigh of 8km at levels" unit="km"/>
+    <axis id="plev" standard_name="model_level_number" unit="Pa"/>
+    <axis id="klev"  prec="8" long_name="number of layers" standard_name="number of layers" unit="1" />
+    <axis id="klevp1"  prec="8" long_name="number of layer interfaces" standard_name="number of layer interfaces" unit="1" />
+    <axis id="bnds" standard_name="bounds" unit="1" />
+    <axis id="spectband" standard_name="Sensor Band Central Radiation Wavenumber" unit="m-1"/>
+    <axis id="axis_lat" standard_name="Latitude axis">
+        <reduce_domain operation="average" direction="iDir" />
     </axis>
     <axis id="spectband" standard_name="Sensor Band Central Radiation Wavenumber" unit="m-1">
     </axis>
     <axis id="axis_lat" standard_name="Latitude axis">
-           <reduce_domain operation="average" direction="iDir" />
+        <reduce_domain operation="average" direction="iDir" />
     </axis>
 
 <!-- Cosp axis definitions-->
-    <axis id="height" standard_name="Cosp levels" unit="m"> 
-    </axis>
-    <axis id="height_mlev" standard_name="height_mlev" unit="m"> 
-    </axis>
-    <axis id="sza" standard_name="solar_zenith_angle" unit="degrees">
-    </axis>
-    <axis id="pressure2" standard_name="pressure" unit="mb">
-    </axis>
-    <axis id="column" standard_name="column" unit="count"> 
-    </axis> 
-    <axis id="temp" standard_name="temperature" unit="K"> 
-    </axis> 
-    <axis id="cth" standard_name="altitude" unit="m"> 
-    </axis> 
-    <axis id="ReffIce" standard_name="ReffIce" unit="microne" >
-    </axis>
-    <axis id="ReffLiq" standard_name="ReffLiq" unit="microne" >
-    </axis>
-    <axis id="scatratio" standard_name="scatratio" unit="1" >
-    </axis>
-    <axis id="dbze" standard_name="dbze" unit="dBZ" >
-    </axis>
-    <axis id="tau" standard_name="tau" unit="1" >
-    </axis>
+    <axis id="height" standard_name="Cosp levels" unit="m"/> 
+    <axis id="height_mlev" standard_name="height_mlev" unit="m"/> 
+    <axis id="sza" standard_name="solar_zenith_angle" unit="degrees"/>
+    <axis id="pressure2" standard_name="pressure" unit="mb"/>
+    <axis id="column" standard_name="column" unit="count"/> 
+    <axis id="temp" standard_name="temperature" unit="K"/> 
+<!--    <axis id="cth16" standard_name="altitude" unit="m"/>   ym unused now to be in adequation with axis definition from model --> 
+    <axis id="cth" standard_name="altitude" unit="m"/> 
+    <axis id="ReffIce" standard_name="ReffIce" unit="microne" />
+    <axis id="ReffLiq" standard_name="ReffLiq" unit="microne" />
+    <axis id="scatratio" standard_name="scatratio" unit="1" />
+    <axis id="dbze" standard_name="dbze" unit="dBZ" />
+    <axis id="tau" standard_name="tau" unit="1" />
   </axis_definition>
 
@@ -97,107 +98,193 @@
 
     <grid id="klev_bnds"> <axis axis_ref="klev" /> <axis axis_ref="bnds" /> </grid>
+    <grid id="klevp1_bnds"> <axis axis_ref="klevp1" /> <axis axis_ref="bnds" /> </grid>
 
      <grid id="grid_glo">
-        <domain id="dom_glo" />
+        <domain domain_ref="dom_glo" />
+     </grid>
+     <grid id="grid_out">
+        <domain domain_ref="dom_out" />
      </grid>
 
      <grid id="grid_glo_presnivs">
-        <domain id="dom_glo" />
-        <axis id="presnivs" />
-     </grid>
-
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="presnivs" />
+     </grid>
+     <grid id="grid_out_presnivs">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="presnivs" />
+     </grid>
 
      <grid id="grid_glo_plev">
-        <domain id="dom_glo" />
-        <axis id="plev" />
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="plev" />
+     </grid>
+     <grid id="grid_out_plev">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="plev" />
      </grid>
 
      <grid id="grid_glo_spectband">
-        <domain id="dom_glo" />
-        <axis id="spectband" />
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="spectband" />
+     </grid>
+     <grid id="grid_out_spectband">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="spectband" />
      </grid>
 
      <grid id="grid_glo_height">
-        <domain id="dom_glo" />
-        <axis id="height" />
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="height" />
+     </grid>
+     <grid id="grid_out_height">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="height" />
      </grid>
 
      <grid id="grid_glo_heightmlev">
-        <domain id="dom_glo" />
-        <axis id="height_mlev" />
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="height_mlev" />
+     </grid>
+     <grid id="grid_out_heightmlev">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="height_mlev" />
      </grid>
 
      <grid id="grid_glo_temp">
-        <domain id="dom_glo" />
-        <axis id="temp" />
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="temp" />
+     </grid>
+     <grid id="grid_out_temp">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="temp" />
      </grid>
 
      <grid id="grid_glo_sza">
-        <domain id="dom_glo" />
-        <axis id="sza" />
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="sza" />
+     </grid>
+     <grid id="grid_out_sza">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="sza" />
      </grid>
 
      <grid id="grid_glo_column">
-        <domain id="dom_glo" />
-        <axis id="column" />
-     </grid>
-
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="column" />
+     </grid>
+     <grid id="grid_out_column">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="column" />
+     </grid>
 
 <!-- Define 4D grids for Cosp simulator -->
      <grid id="grid4Dcol">
-        <domain id="dom_glo" />
-        <axis id="column" />
-        <axis id="height_mlev" />
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="column" />
+        <axis axis_ref="height_mlev" />
+     </grid>
+     <grid id="grid4Dcol_out">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="column" />
+        <axis axis_ref="height_mlev" />
      </grid>
 
      <grid id="grid4Dsrbin">
-        <domain id="dom_glo" />
-        <axis id="height" />
-        <axis id="scatratio" />
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="height" />
+        <axis axis_ref="scatratio" />
+     </grid>
+     <grid id="grid4Dsrbin_out">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="height" />
+        <axis axis_ref="scatratio" />
      </grid>
 
      <grid id="grid4Ddbze">
-        <domain id="dom_glo" />
-        <axis id="height" />
-        <axis id="dbze" />
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="height" />
+        <axis axis_ref="dbze" />
+     </grid>
+     <grid id="grid4Ddbze_out">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="height" />
+        <axis axis_ref="dbze" />
      </grid>
 
      <grid id="grid4Dtau">
-        <domain id="dom_glo" />
-        <axis id="tau" />
-        <axis id="pressure2" />
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="tau" />
+        <axis axis_ref="pressure2" />
+     </grid>
+     <grid id="grid4Dtau_out">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="tau" />
+        <axis axis_ref="pressure2" />
      </grid>
 
      <grid id="grid4Dmisr">
-        <domain id="dom_glo" />
-        <axis id="cth" />
-        <axis id="tau" />
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="cth" />
+        <axis axis_ref="tau" />
+     </grid>
+     <grid id="grid4Dmisr_out">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="cth" />
+        <axis axis_ref="tau" />
      </grid>
 
      <grid id="grid4Dreffi">
-        <domain id="dom_glo" />
-        <axis id="tau" />
-        <axis id="ReffIce" />
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="tau" />
+        <axis axis_ref="ReffIce" />
+     </grid>
+     <grid id="grid4Dreffi_out">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="tau" />
+        <axis axis_ref="ReffIce" />
      </grid>
 
      <grid id="grid4Dreffl">
-        <domain id="dom_glo" />
-        <axis id="tau" />
-        <axis id="ReffLiq" />
-     </grid>
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="tau" />
+        <axis axis_ref="ReffLiq" />
+     </grid>
+     <grid id="grid4Dreffl_out">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="tau" />
+        <axis axis_ref="ReffLiq" />
+     </grid>
+
      <grid id="grid4Dcol2">
-        <domain id="dom_glo" />
-        <axis id="height" />
-        <axis id="column" />
-     </grid>
-
- <!-- Grid definitions to allow summing of a 3D varaible -->    
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="height" />
+        <axis axis_ref="column" />
+     </grid>
+     <grid id="grid4Dcol2_out">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="height" />
+        <axis axis_ref="column" />
+     </grid>
+
+     <grid id="grid4Dsza">
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="column" />
+        <axis axis_ref="sza" />
+     </grid>
+     <grid id="grid4Dsza_out">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="column" />
+        <axis axis_ref="sza" />
+     </grid>
+
+ <!-- Grid definitions to allow summing of a 3D variable -->    
       <grid id="grid_3D" >
-         <domain id="dom_glo" />
-         <axis id="lev" />
+         <domain domain_ref="dom_glo" />
+         <axis axis_ref="lev" />
        </grid>
 
        <grid id="grid_sum_axis">
-         <domain id="dom_glo" />
+         <domain domain_ref="dom_glo" />
          <scalar>
             <reduce_axis operation="sum" />
@@ -207,9 +294,8 @@
        <grid id="grid_sum">
          <scalar >
-        <reduce_domain operation="sum" local="true" />
-        <reduce_scalar operation="sum" />
+           <reduce_domain operation="sum" local="true" />
+           <reduce_scalar operation="sum" />
          </scalar>
-         <scalar>
-         </scalar>
+         <scalar/>
        </grid>
 
Index: /LMDZ6/branches/Ocean_skin/DefLists/context_lmdz_sans_cosp.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/context_lmdz_sans_cosp.xml	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/DefLists/context_lmdz_sans_cosp.xml	(revision 3605)
@@ -0,0 +1,154 @@
+<!-- Context LMDZ -->
+<context id="LMDZ">
+<!--  <calendar type="D360" start_date="1980-01-01 00:00:00" /> -->
+
+  <!-- Define available variables -->
+  <field_definition src="./field_def_lmdz.xml"/>
+
+  <!-- Define output files
+              Each file contains the list of variables and their output levels -->
+
+  <file_definition src="./file_def_histday_lmdz.xml"/>
+  <file_definition src="./file_def_histhf_lmdz.xml"/>
+  <file_definition src="./file_def_histins_lmdz.xml"/>
+  <file_definition src="./file_def_histLES_lmdz.xml"/>
+  <file_definition src="./file_def_histmth_lmdz.xml"/>
+  <file_definition src="./file_def_histstn_lmdz.xml"/>
+  <file_definition src="./file_def_histmthNMC_lmdz.xml"/>
+  <file_definition src="./file_def_histdayNMC_lmdz.xml"/>
+  <file_definition src="./file_def_histhfNMC_lmdz.xml"/>
+  <file_definition src="./file_def_histstrataer_lmdz.xml"/>
+
+
+
+
+
+  <!-- Define domains and groups of domains -->
+  <domain_definition>
+
+    <domain id="dom_glo"  data_dim="1" />
+
+    <domain id="greordered"  domain_ref="dom_glo">
+      <reorder_domain invert_lat="true" shift_lon_fraction="0.5" min_lon="0" max_lon="360" />
+    </domain> 
+   
+    <domain id="dom_regular" ni_glo="144" nj_glo="142" type="rectilinear"  >
+      <generate_rectilinear_domain/>
+      <interpolate_domain order="1"/>
+    </domain>
+   
+    <domain id="dom_out" domain_ref="dom_glo"/>
+    
+  </domain_definition>
+  
+  <!-- Need to define a grid? Do it here -->
+<!--  <grid_definition>
+    <grid_group id="vertical" axis_ref="presnivs" />
+  </grid_> -->
+
+<!-- Define Scalar grid for GHG, orbital parameters and solar constants -->
+  <grid_definition>
+    <grid id="grid_scalar" >
+      <scalar/>
+    </grid>
+  </grid_definition>
+ 
+  <!-- Define groups of vertical axes -->
+  <axis_definition>
+    <axis id="time_month" n_glo="12" value="(0,11) [1 2 3 4 5 6 7 8 9 10 11 12]"/>
+    <axis id="time_year" unit="day" />
+    <axis id="presnivs" standard_name="Vertical levels" unit="Pa"/>
+    <axis id="Ahyb" standard_name="Ahyb comp of Hyb Cord" unit="Pa"/>
+    <axis id="Bhyb" standard_name="Bhyb comp of Hyb Cord" unit=""/>
+    <axis id="Ahyb_inter" standard_name="A comp of Hyb Cord at interface" unit="Pa"/>
+    <axis id="Bhyb_inter" standard_name="B comp of Hyb Cord at interface" unit=""/>
+    <axis id="Alt" standard_name="Height approx for scale heigh of 8km at levels" unit="km"/>
+    <axis id="plev" standard_name="model_level_number" unit="Pa"/>
+    <axis id="klev"  prec="8" long_name="number of layers" standard_name="number of layers" unit="1" />
+    <axis id="klevp1"  prec="8" long_name="number of layer interfaces" standard_name="number of layer interfaces" unit="1" />
+    <axis id="bnds" standard_name="bounds" unit="1" />
+    <axis id="spectband" standard_name="Sensor Band Central Radiation Wavenumber" unit="m-1"/>
+    <axis id="axis_lat" standard_name="Latitude axis">
+      <reduce_domain operation="average" direction="iDir" />
+    </axis>
+    <axis id="spectband" standard_name="Sensor Band Central Radiation Wavenumber" unit="m-1">
+    </axis>
+    <axis id="axis_lat" standard_name="Latitude axis">
+           <reduce_domain operation="average" direction="iDir" />
+    </axis>
+  </axis_definition>
+
+<!-- Cosp axis definitions-->
+
+  <grid_definition>
+
+    <grid id="klev_bnds"> <axis axis_ref="klev" /> <axis axis_ref="bnds" /> </grid>
+    <grid id="klevp1_bnds"> <axis axis_ref="klevp1" /> <axis axis_ref="bnds" /> </grid>
+
+
+     <grid id="grid_glo">
+        <domain domain_ref="dom_glo" />
+     </grid>
+
+     <grid id="grid_out">
+        <domain domain_ref="dom_out" />
+     </grid>
+
+
+     <grid id="grid_glo_presnivs">
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="presnivs" />
+     </grid>
+
+     <grid id="grid_out_presnivs">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="presnivs" />
+     </grid>
+
+
+     <grid id="grid_glo_plev">
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="plev" />
+     </grid>
+
+     <grid id="grid_out_plev">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="plev" />
+     </grid>
+
+
+     <grid id="grid_glo_spectband">
+        <domain domain_ref="dom_glo" />
+        <axis axis_ref="spectband" />
+     </grid>
+
+     <grid id="grid_out_spectband">
+        <domain domain_ref="dom_out" />
+        <axis axis_ref="spectband" />
+     </grid>
+     
+
+ <!-- Grid definitions to allow summing of a 3D variable -->    
+      <grid id="grid_3D" >
+         <domain domain_ref="dom_glo" />
+         <axis axis_ref="lev" />
+       </grid>
+
+       <grid id="grid_sum_axis">
+         <domain domain_ref="dom_glo" />
+         <scalar>
+            <reduce_axis operation="sum" />
+         </scalar>
+       </grid>
+
+       <grid id="grid_sum">
+         <scalar >
+           <reduce_domain operation="sum" local="true" />
+           <reduce_scalar operation="sum" />
+         </scalar>
+         <scalar/>
+       </grid>
+
+  </grid_definition>
+
+</context>
Index: /LMDZ6/branches/Ocean_skin/DefLists/cospv2_input_nl.txt
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/cospv2_input_nl.txt	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/DefLists/cospv2_input_nl.txt	(revision 3605)
@@ -0,0 +1,99 @@
+! (c) British Crown Copyright 2008, the Met Office.
+! All rights reserved.
+! 
+! Redistribution and use in source and binary forms, with or without modification, are permitted 
+! provided that the following conditions are met:
+! 
+!     * Redistributions of source code must retain the above copyright notice, this list 
+!       of conditions and the following disclaimer.
+!     * Redistributions in binary form must reproduce the above copyright notice, this list
+!       of conditions and the following disclaimer in the documentation and/or other materials 
+!       provided with the distribution.
+!     * Neither the name of the Met Office nor the names of its contributors may be used 
+!       to endorse or promote products derived from this software without specific prior written 
+!       permission.
+! 
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 
+! IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
+! FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
+! CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
+! DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
+! DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
+! IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 
+! OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+! Namelist that sets up the main COSP options
+&COSP_INPUT
+  NPOINTS_IT=10000,! Max number of gridpoints to be processed in one iteration
+  NCOLUMNS=20,  ! Number of subcolumns
+  USE_VGRID=.true., ! Use fixed vertical grid for outputs? (if .true. then you need to define number of levels with Nlr)
+  NLR=40,       ! Number of levels in statistical outputs (only used if USE_VGRID=.true.)
+  CSAT_VGRID=.true., ! CloudSat vertical grid? (if .true. then the CloudSat standard grid is used for the outputs.
+                     !  USE_VGRID needs also be .true.)
+  !----------------------------------------------------------------------------------
+  !--------------- Inputs related to radar simulations
+  !----------------------------------------------------------------------------------
+  RADAR_FREQ=94.0, ! CloudSat radar frequency (GHz)
+  SURFACE_RADAR=0, ! surface=1, spaceborne=0
+  use_mie_tables=0,! use a precomputed lookup table? yes=1,no=0
+  use_gas_abs=1,   ! include gaseous absorption? yes=1,no=0
+  do_ray=0,        ! calculate/output Rayleigh refl=1, not=0
+  melt_lay=0,      ! melting layer model off=0, on=1
+  k2=-1,           ! |K|^2, -1=use frequency dependent default
+  use_reff=.true., ! True if you want effective radius to be used by radar simulator (always used by lidar)
+  use_precipitation_fluxes=.true.,  ! True if precipitation fluxes are input to the algorithm 
+  !----------------------------------------------------------------------------------
+  !---------------- Inputs related to lidar simulations
+  !----------------------------------------------------------------------------------
+  Nprmts_max_hydro=12, ! Max number of parameters for hydrometeor size distributions
+  Naero=1,             ! Number of aerosol species (Not used)
+  Nprmts_max_aero=1,   ! Max number of parameters for aerosol size distributions (Not used)
+  lidar_ice_type=0,    ! Ice particle shape in lidar calculations (0=ice-spheres ; 1=ice-non-spherical)
+  OVERLAP=3,   !  overlap type: 1=max, 2=rand, 3=max/rand
+  !----------------------------------------------------------------------------------
+  !---------------- Inputs related to ISCCP simulator
+  !----------------------------------------------------------------------------------
+  ISCCP_TOPHEIGHT=1,  !  1 = adjust top height using both a computed
+                       !  infrared brightness temperature and the visible
+                       !  optical depth to adjust cloud top pressure. Note
+                       !  that this calculation is most appropriate to compare
+                       !  to ISCCP data during sunlit hours.
+                      !  2 = do not adjust top height, that is cloud top
+                       !  pressure is the actual cloud top pressure
+                       !  in the model
+                      !  3 = adjust top height using only the computed
+                       !  infrared brightness temperature. Note that this
+                       !  calculation is most appropriate to compare to ISCCP
+                       !  IR only algortihm (i.e. you can compare to nighttime
+                       !  ISCCP data with this option)
+  ISCCP_TOPHEIGHT_DIRECTION=2,   ! direction for finding atmosphere pressure level
+                                 ! with interpolated temperature equal to the radiance
+                                 ! determined cloud-top temperature
+                                 ! 1 = find the *lowest* altitude (highest pressure) level
+                                 ! with interpolated temperature equal to the radiance
+                                 ! determined cloud-top temperature
+                                 ! 2 = find the *highest* altitude (lowest pressure) level
+                                 ! with interpolated temperature equal to the radiance 
+                                 ! determined cloud-top temperature
+                                 ! ONLY APPLICABLE IF top_height EQUALS 1 or 3
+                                 ! 1 = default setting, and matches all versions of 
+                                 ! ISCCP simulator with versions numbers 3.5.1 and lower
+                                 ! 2 = experimental setting  
+  !----------------------------------------------------------------------------------
+  !-------------- RTTOV inputs
+  !----------------------------------------------------------------------------------
+  Platform=1,    ! satellite platform
+  Satellite=15,  ! satellite
+  Instrument=0,  ! instrument
+  Nchannels=8,   ! Number of channels to be computed
+  Channels=1,3,5,6,8,10,11,13,        ! Channel numbers (please be sure that you supply Nchannels)
+  Surfem=0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,  ! Surface emissivity (please be sure that you supply Nchannels)
+  ZenAng=50.0, ! Satellite Zenith Angle
+  CO2=5.241e-04, ! Mixing ratios of trace gases
+  CH4=9.139e-07,
+  N2O=4.665e-07,
+  CO=2.098e-07
+/
+
+
Index: /LMDZ6/branches/Ocean_skin/DefLists/cospv2_output_nl.txt
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/cospv2_output_nl.txt	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/DefLists/cospv2_output_nl.txt	(revision 3605)
@@ -0,0 +1,149 @@
+! (c) British Crown Copyright 2008, the Met Office.
+! All rights reserved.
+! 
+! Redistribution and use in source and binary forms, with or without modification, are permitted 
+! provided that the following conditions are met:
+! 
+!     * Redistributions of source code must retain the above copyright notice, this list 
+!       of conditions and the following disclaimer.
+!     * Redistributions in binary form must reproduce the above copyright notice, this list
+!       of conditions and the following disclaimer in the documentation and/or other materials 
+!       provided with the distribution.
+!     * Neither the name of the Met Office nor the names of its contributors may be used 
+!       to endorse or promote products derived from this software without specific prior written 
+!       permission.
+! 
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 
+! IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
+! FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
+! CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
+! DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
+! DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
+! IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 
+! OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+! Namelist that sets up output-related variables. It controls 
+! the instrument simulators to run and the list of variables 
+! to be written to file
+&COSP_OUTPUT
+  !- CloudSat
+  Lcfaddbze94=.true.,
+  Ldbze94=.true.,
+  !- CALIPSO
+  Latb532=.true.,
+  LcfadLidarsr532=.true.,
+  Lclcalipso=.true.,
+  Lclhcalipso=.true.,
+  Lcllcalipso=.true.,
+  Lclmcalipso=.true.,
+  Lcltcalipso=.true.,
+  LparasolRefl=.true.,
+  ! CALIPSO phase diagnostics
+  Lclcalipsoliq=.true.,
+  Lclcalipsoice=.true.,
+  Lclcalipsoun=.true.,
+  Lclcalipsotmp=.true.,
+  Lclcalipsotmpliq=.true.,
+  Lclcalipsotmpice=.true.,
+  Lclcalipsotmpun=.true.,
+  Lclhcalipsoliq=.true.,
+  Lcllcalipsoliq=.true.,
+  Lclmcalipsoliq=.true.,
+  Lcltcalipsoliq=.true.,
+  Lclhcalipsoice=.true.,
+  Lcllcalipsoice=.true.,
+  Lclmcalipsoice=.true.,
+  Lcltcalipsoice=.true.,
+  Lclhcalipsoun=.true.,
+  Lcllcalipsoun=.true.,
+  Lclmcalipsoun=.true.,
+  Lcltcalipsoun=.true.,
+  ! CALIPSO OPAQ diagnostics
+  Lclopaquecalipso=.true.,
+  Lclthincalipso=.true., 
+  Lclzopaquecalipso=.true.,
+  Lclcalipsoopaque=.true., 
+  Lclcalipsothin=.true.,  
+  Lclcalipsozopaque=.true.,
+  Lclcalipsoopacity=.true., 
+  Lclopaquetemp=.true., 
+  Lclthintemp=.true., 
+  Lclzopaquetemp=.true., 
+  Lclopaquemeanz=.true., 
+  Lclthinmeanz=.true., 
+  Lclthinemis=.true., 
+  Lclopaquemeanzse=.true.,
+  Lclthinmeanzse=.true., 
+  Lclzopaquecalipsose=.true.,
+  ! GROUND LIDAR diagnostics  
+  LlidarBetaMol532gr=.true.,  
+  LcfadLidarsr532gr=.true.,  
+  Latb532gr=.true.,  
+  LclgrLidar532=.true.,
+  LclhgrLidar532=.true.,  
+  LcllgrLidar532=.true., 
+  LclmgrLidar532=.true.,
+  LcltgrLidar532=.true.,
+  ! ATLID diagnostics
+  LlidarBetaMol355=.true.,
+  LcfadLidarsr355=.true., 
+  Latb355=.true., 
+  Lclatlid=.true., 
+  Lclhatlid=.true., 
+  Lcllatlid=.true.,
+  Lclmatlid=.true.,
+  Lcltatlid=.true.,
+  !- ISCCP
+  Lalbisccp=.true.,
+  Lboxptopisccp=.true.,
+  Lboxtauisccp=.true.,
+  Lpctisccp=.true.,
+  Lclisccp=.true.,
+  Ltauisccp=.true.,
+  Lcltisccp=.true.,
+  Lmeantbisccp=.true.,
+  Lmeantbclrisccp=.true.,
+  !- MISR
+  LclMISR=.true.,
+  !- Use lidar and radar
+  Lclcalipso2=.true.,
+  Lcltlidarradar=.true.,
+  Lcloudsat_tcc=.true.,
+  Lcloudsat_tcc2=.true.,
+  !- These are provided for debugging or special purposes
+  Lfracout=.false.,
+  LlidarBetaMol532=.true.,  
+  !- MODIS
+  Lcltmodis=.true.,
+  Lclwmodis=.true.,
+  Lclimodis=.true.,
+  Lclhmodis=.true.,
+  Lclmmodis=.true.,
+  Lcllmodis=.true.,
+  Ltautmodis=.true.,
+  Ltauwmodis=.true.,
+  Ltauimodis=.true.,
+  Ltautlogmodis=.true.,
+  Ltauwlogmodis=.true.,
+  Ltauilogmodis=.true.,
+  Lreffclwmodis=.true.,
+  Lreffclimodis=.true.,
+  Lpctmodis=.true.,
+  Llwpmodis=.true.,
+  Liwpmodis=.true.,
+  Lclmodis=.true.,
+  !- RTTOV
+  Ltbrttov=.false.,
+  ! -CLOUDSAT precipitation frequency/occurence diagnostics
+  Lptradarflag0=.true.,
+  Lptradarflag1=.true.,
+  Lptradarflag2=.true.,
+  Lptradarflag3=.true.,
+  Lptradarflag4=.true.,
+  Lptradarflag5=.true.,
+  Lptradarflag6=.true.,
+  Lptradarflag7=.true.,
+  Lptradarflag8=.true.,
+  Lptradarflag9=.true.,
+  Lradarpia=.true.
+/
Index: /LMDZ6/branches/Ocean_skin/DefLists/field_def_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/field_def_lmdz.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/field_def_lmdz.xml	(revision 3605)
@@ -1,2 +1,3 @@
+<!-- $Id$ -->
 <field_definition level="1" prec="4" operation="average" freq_op="1ts" enabled=".true." default_value="9.96921e+36">
     
@@ -7,4 +8,15 @@
 <!--    </field_group>  -->
 
+    <field_group id="remap_expr" level="_reset_" prec="_reset_" operation="_reset_" freq_op="_reset_" enabled="_reset_" default_value="_reset_">
+      <field_group id="remap_1ts" />
+      <field_group id="remap_1800s" />
+      <field_group id="remap_1h" />
+      <field_group id="remap_3h" />
+      <field_group id="remap_6h" />
+      <field_group id="remap_1d" />
+      <field_group id="remap_1mo" />
+    </field_group>
+    
+    
     <field_group id="coordinates" grid_ref="grid_glo">
         <field id="io_lon"  />
@@ -13,14 +25,18 @@
 
     <field_group id="coord_hyb">
-        <field id="Ahyb"      axis_ref="klev" />
-        <field id="Ahyb_inter" grid_ref="klev_bnds" />
-        <field id="Bhyb"       axis_ref="klev"  />
-        <field id="Bhyb_inter"  grid_ref="klev_bnds" />
+        <field id="Ahyb" long_name="Ahyb at level interface"     axis_ref="klevp1" />
+        <field id="Ahyb_bounds" long_name="" grid_ref="klevp1_bnds" />
+        <field id="Bhyb" long_name="Bhyb at level interface"       axis_ref="klevp1"  />
+        <field id="Bhyb_bounds" long_name=""  grid_ref="klevp1_bnds" />
+        <field id="Ahyb_mid" long_name="Ahyb at the middle of the level"      axis_ref="klev" />
+        <field id="Ahyb_mid_bounds" long_name="" grid_ref="klev_bnds" />
+        <field id="Bhyb_mid" long_name="Bhyb at the middle of the level"       axis_ref="klev"  />
+        <field id="Bhyb_mid_bounds" long_name=""  grid_ref="klev_bnds" />
     </field_group>
     
     <field_group id="fields_2D" grid_ref="grid_glo">
         <field id="phis"    long_name="Surface geop.height"     unit="m2/s2" />
-        <field id="aire"    long_name="Grid area"               unit="-"    />
-        <field id="contfracATM"     long_name="% sfce ter+lic"  unit="-"    />
+        <field id="aire"    long_name="Grid area"               unit="m2"    />
+        <field id="contfracATM"     long_name="% sfce ter+lic"  unit="-"   /> 
         <field id="contfracOR"      long_name="% sfce terre OR" unit="-" />
         <field id="sza"     long_name="Solar zenithal angle "   unit="deg" />
@@ -43,6 +59,6 @@
         <field id="gusts"    long_name="surface gustiness"    unit="m2/s2" />
         <field id="wind10m"    long_name="10-m wind speed"      unit="m/s" />
-        <field id="wind10max"  long_name="10m wind speed max"   unit="m/s" />
-	<field id="sfcWindmax" field_ref="wind10m" operation="maximum" />
+        <field id="wind10max"  long_name="10m wind speed max"   unit="m/s" operation="maximum"/>
+        <field id="sfcWindmax" field_ref="wind10m" operation="maximum" />
         <field id="sicf"    long_name="Sea-ice fraction"        unit="-" />
         <field id="q2m"     long_name="Specific humidity 2m"    unit="kg/kg" />
@@ -76,9 +92,9 @@
         <field id="cldtjn"      long_name="Total cloudiness Day"         unit="-" />
         <field id="rnebjn"      long_name="Cloud fraction in day"         unit="-" />
-        <field id="ndayrain"    long_name="Number of dayrain(liq+sol)"  unit="-" />
+        <field id="ndayrain"    long_name="Number of dayrain(liq+sol)"  unit="-" operation="instant"/>
         <field id="precip"      long_name="Precip Totale liq+sol"       unit="kg/(s*m2)" />
         <field id="prhmax"      field_ref="precip" operation="maximum"           />
         <field id="rain_fall"   long_name="Precip Totale liq"   unit="kg/(s*m2)" />
-        <field id="rain_con"   long_name="Precip convective liq"   unit="kg/(s*m2)" />
+        <field id="rain_con"    long_name="Precip convective liq"   unit="kg/(s*m2)" />
         <field id="plul"    long_name="Large-scale Precip."     unit="kg/(s*m2)" />
         <field id="plun"    long_name="Numerical Precip."       unit="kg/(s*m2)" />
@@ -146,5 +162,5 @@
         <field id="flat_x"    long_name="flat off-wake"    unit="W/m2" />
         <field id="flat_w"    long_name="flat within-wake"    unit="W/m2" />
-        <field id="delta_tsurf"    long_name="Temperature difference (w-x)"    unit="K" />
+        <field id="delta_tsurf"    long_name="Temperature difference (w-x)"    unit="K" enabled="false" /> <!-- ym --field disabled-- delta_tsurf is not conform to the associated grid (the is an arry containing all sub_surface) --> 
         <field id="cdragh_x"    long_name="cdragh off-wake"    unit="-" />
         <field id="cdragh_w"    long_name="cdragh within-wake"    unit="-" />
@@ -327,6 +343,6 @@
         <field id="v10_sic"    long_name="-"    unit="-" />
         <field id="rh2m"    long_name="Relative humidity at 2m"    unit="%" />
-        <field id="rh2m_max"    field_ref="rh2m" operation="maximum" />
-        <field id="rh2m_min"    field_ref="rh2m" operation="minimum" />
+        <field id="rh2m_max"    field_ref="rh2m" operation="maximum" enabled="false"/> <!-- ym Problem : field is disabled check rh2m_min has a reference (field_ref) to rh2 but is also sent by model which is not compatible-->
+        <field id="rh2m_min"    field_ref="rh2m" operation="minimum" enabled="false"/> <!-- ym Problem : field is disabled check rh2m_max has a reference (field_ref) to rh2 but is also sent by model which is not compatible-->
 <!--        <field id="rh2m_min"    long_name="Min Relative humidity at 2m"    unit="%" /> -->
 <!--        <field id="rh2m_max"    long_name="Max Relative humidity at 2m"    unit="%" /> -->
@@ -335,7 +351,8 @@
         <field id="tpote"    long_name="Surface air equivalent potential temperature"    unit="K" />
         <field id="SWnetOR"    long_name="Sfce net SW radiation OR"    unit="W/m2" />
+        <field id="SWdownOR"    long_name="Sfce incident SW radiation OR"    unit="W/m2" />
         <field id="LWdownOR"    long_name="Sfce incident LW radiation OR"    unit="W/m2" />
         <field id="snowl"    long_name="Solid Large-scale Precip."    unit="kg/(m2*s)" />
-        <field id="cape_max"    long_name="CAPE max."    unit="J/kg" />
+        <field id="cape_max"    long_name="CAPE max."    unit="J/kg" operation="maximum"/>
         <field id="solldown"    long_name="Down. IR rad. at surface"    unit="W/m2" />
         <field id="dtsvdfo"    long_name="Boundary-layer dTs(o)"    unit="K/s" />
@@ -371,5 +388,5 @@
         <field id="od550_CSNO3M"   long_name="Aerosol Optical depth at 550 nm "    unit="1" />
         <field id="od550_CINO3M"   long_name="Aerosol Optical depth at 550 nm "    unit="1" />
-        <field id="od550_STRAT"    long_name="Aerosol Optical depth at 550 nm "    unit="1" enabled="TRUE" />
+        <field id="od550_STRAT"    long_name="Aerosol Optical depth at 550 nm "    unit="1"  />
         <field id="dryod550_ASBCM"    long_name="Aerosol Optical depth at 550 nm "    unit="1" />
         <field id="dryod550_ASPOMM"   long_name="Aerosol Optical depth at 550 nm "    unit="1" />
@@ -457,5 +474,5 @@
         <field id="alb1"    long_name="Surface VIS albedo"    unit="-" />
         <field id="alb2"    long_name="Surface Near IR albedo"    unit="-" />
-        <field id="ftime_con"    long_name="Fraction of time convection Occurs"    unit="-" />
+        <field id="ftime_con"    long_name="Fraction of time convection Occurs"    unit="-" operation="instant" />
         <field id="ftime_deepcv"    long_name="Fraction of time deep convection Occurs"    unit="-" />
         <field id="wake_h"    long_name="wake height"    unit="m" />
@@ -494,4 +511,8 @@
         <field id="colO3_strat"    long_name="Ozone stratospheric column"     unit="DU" />             <!-- Added ThL -->
         <field id="colO3_trop"     long_name="Ozone tropospheric column"      unit="DU" />             <!-- Added ThL -->
+        <field id="flx_co2_land"   long_name="CO2 flux from land"             unit="kg CO2/m2/s" />    <!-- Added OB -->
+        <field id="flx_co2_ocean"  long_name="CO2 flux from ocean"            unit="kg CO2/m2/s" />    <!-- Added OB -->
+        <field id="flx_co2_ff"     long_name="CO2 flux from ff"               unit="kg CO2/m2/s" />    <!-- Added OB -->
+        <field id="flx_co2_bb"     long_name="CO2 flux from bb"               unit="kg CO2/m2/s" />    <!-- Added OB -->
     </field_group>
 
@@ -502,8 +523,8 @@
         <field id="tke_oce"    long_name="Max Turb. Kinetic Energy oce"    unit="m2/s2" />
         <field id="tke_sic"    long_name="Max Turb. Kinetic Energy sic"    unit="m2/s2" />
-        <field id="tke_max_ter"    long_name="Max Turb. Kinetic Energy ter"    unit="m2/s2" />
-        <field id="tke_max_lic"    long_name="Max Turb. Kinetic Energy lic"    unit="m2/s2" />
-        <field id="tke_max_oce"    long_name="Max Turb. Kinetic Energy oce"    unit="m2/s2" />
-        <field id="tke_max_sic"    long_name="Max Turb. Kinetic Energy sic"    unit="m2/s2" />
+        <field id="tke_max_ter"    long_name="Max Turb. Kinetic Energy ter"    unit="m2/s2" operation="maximum"/>
+        <field id="tke_max_lic"    long_name="Max Turb. Kinetic Energy lic"    unit="m2/s2" operation="maximum"/>
+        <field id="tke_max_oce"    long_name="Max Turb. Kinetic Energy oce"    unit="m2/s2" operation="maximum"/>
+        <field id="tke_max_sic"    long_name="Max Turb. Kinetic Energy sic"    unit="m2/s2" operation="maximum"/>
         <field id="l_mix_ter"    long_name="PBL mixing length ter"    unit="m" />
         <field id="l_mix_lic"    long_name="PBL mixing length lic"    unit="m" />
@@ -524,7 +545,7 @@
         <field id="cldtau"    long_name="Cloud optical thickness"    unit="1" />
         <field id="cldemi"    long_name="Cloud optical emissivity"    unit="1" />
-        <field id="tke_max"    long_name="TKE max"    unit="m2/s2" />
+        <field id="tke_max"    long_name="TKE max"    unit="m2/s2" operation="maximum"/>
         <field id="kz"    long_name="Kz melange"    unit="m2/s" enabled="FALSE" />
-        <field id="kz_max"    long_name="Kz melange max"    unit="m2/s" enabled="FALSE" />
+        <field id="kz_max"    long_name="Kz melange max"    unit="m2/s" enabled="FALSE" operation="maximum" />
         <field id="concso4"    long_name="Concentration of Sulfate "    unit="kg/m3" />
         <field id="concno3"    long_name="Concentration of Nitrate "    unit="kg/m3" /> 
@@ -543,5 +564,5 @@
         <field id="ocond"    long_name="Condensed water"    unit="kg/kg" />
         <field id="geop"    long_name="Geopotential height"    unit="m2/s2" />
-        <field id="geoph"    field_ref="geop" long_name="Geopotential height" unit="m" > geop/9.80665 </field>
+        <field id="geoph" field_ref="geop" long_name="Geopotential height" unit="m" > geop/9.80665 </field>
         <field id="vitu"    long_name="Zonal wind"    unit="m/s" />
         <field id="vitv"    long_name="Meridional wind"    unit="m/s" />
@@ -583,4 +604,5 @@
         <field id="cldicemxrat"    long_name="Cloud Ice Mixing Ratio"    unit="1" />
         <field id="clwcon"    long_name="Convective Cloud Liquid water content"    unit="kg/kg" />
+        <field id="Mipsh"    long_name="mass flux shed from adiab. ascents"    unit="kg/m2/s" />
         <field id="Ma"    long_name="undilute adiab updraft"    unit="kg/m2/s" />
         <field id="dnwd"    long_name="saturated downdraft"    unit="kg/m2/s" />
@@ -603,6 +625,9 @@
         <field id="wake_omg"    long_name="wake_omg"    unit="-" />
         <field id="wdtrainA"    long_name="precipitation from AA"    unit="-" />
+        <field id="wdtrainS"    long_name="precipitation from shedding of AA"    unit="-" />
         <field id="wdtrainM"    long_name="precipitation from mixture"    unit="-" />
         <field id="Vprecip"    long_name="precipitation vertical profile"    unit="-" />
+        <field id="qtaa"    long_name="specific total water in adiabatic ascents"    unit="kg/kg" /> 
+        <field id="Clwaa"   long_name="specific condensed water in adiabatic ascents"    unit="kg/kg" />
         <field id="ftd"    long_name="tend temp due aux descentes precip"    unit="-" />
         <field id="fqd"    long_name="tend vap eau due aux descentes precip"    unit="-" />
@@ -698,11 +723,13 @@
         <field id="rldcs4co2"    long_name="Downwelling CS LW 4xCO2 atmosphere"    unit="W/m2" />
         <field id="stratomask"    long_name="Stratospheric fraction"    unit="-" />
+        <field id="heat_volc"    long_name="SW heating rate from volcano"    unit="K/s" />
+        <field id="cool_volc"    long_name="LW cooling rate from volcano"    unit="K/s" />
         <field id="pvap"    long_name="pvap intermediary variable" unit="-">pres*ovap*461.5 / (287.04*(1.+ (10.9491/18.0153)*ovap)) </field>
     </field_group>
 
-    <field_group id="fields_strataer_trac_3D" grid_ref="grid_glo_presnivs"/>
-    <field_group id="fields_strataer_trac_2D" grid_ref="grid_glo"/>
-
-    <field_group id="fields_strataer_3D" grid_ref="grid_glo_presnivs" >
+    <field_group id="fields_strataer_trac_3D" grid_ref="grid_glo_presnivs" operation="average"/>
+    <field_group id="fields_strataer_trac_2D" grid_ref="grid_glo" operation="average"/>
+
+    <field_group id="fields_strataer_3D" grid_ref="grid_glo_presnivs" operation="average" >
         <field id="ext_strat_550"        long_name="Strat. aerosol extinction coefficient at 550 nm"       unit="1/m" />
         <field id="ext_strat_1020"       long_name="Strat. aerosol extinction coefficient at 1020 nm"      unit="1/m" />
@@ -720,5 +747,5 @@
     </field_group>
 
-    <field_group id="fields_strataer_2D" grid_ref="grid_glo" >
+    <field_group id="fields_strataer_2D" grid_ref="grid_glo" operation="average">
         <field id="OD550_strat_only"   long_name="Stratospheric Aerosol Optical depth at 550 nm "        unit="1" />
         <field id="OD1020_strat_only"  long_name="Stratospheric Aerosol Optical depth at 1020 nm "       unit="1" />
@@ -765,5 +792,5 @@
     </field_group>
 
-    <field_group id="fields_trac_2D" grid_ref="grid_glo_plev" >
+    <field_group id="fields_trac_2D" grid_ref="grid_glo" >
           <field id="cumRN"    long_name="Cumulated tracer  RNVL1"    unit="-" />
           <field id="cumPB"    long_name="Cumulated tracer  PBVL1"    unit="-" />
@@ -826,6 +853,8 @@
 
     <field_group id="fields_solbnd_3D" grid_ref="grid_glo_spectband" >
-      <field id="solbnd"    long_name="Top-of-Atmosphere Solar Insolation for each band"    unit="W m-2" />
-    </field_group>
+      <field id="solbnd"    long_name="Top-of-Atmosphere Solar Insolation for each band"    unit="W m-2"  enabled="false" /> <!-- this field is not sent by LMDZ, vertical axis "spectband" is not properly defined -->
+    </field_group>
+
+    <field_group operation="average" freq_offset="0ts" freq_op="3h">  <!-- ----------------------------COSP------------------------ -->
 
     <field_group id="fields_COSP_CALIPSO_2D" grid_ref="grid_glo" freq_offset="0ts" freq_op="3h">
@@ -931,7 +960,10 @@
       <field id="iwpmodis" long_name="Modis Ice_Water_Path_Mean" unit="kg m-2" detect_missing_value=".true." />
     </field_group>
-      <field id="clmodis" long_name="MODIS Cloud Area Fraction" unit="1" freq_offset="0ts" freq_op="3h" grid_ref="grid4Dtau"  detect_missing_value=".true." />
-      <field id="crimodis" long_name="MODIS Optical_Thickness_vs_ReffIce" unit="1" freq_offset="0ts" freq_op="3h" grid_ref="grid4Dreffi"  detect_missing_value=".true." />
-      <field id="crlmodis" long_name="MODIS Optical_Thickness_vs_ReffLiq" unit="1" freq_offset="0ts" freq_op="3h" grid_ref="grid4Dreffl"  detect_missing_value=".true." />
+      <field id="clmodis" long_name="MODIS Cloud Area Fraction" unit="1"  grid_ref="grid4Dtau"  detect_missing_value=".true." />
+      <field id="crimodis" long_name="MODIS Optical_Thickness_vs_ReffIce" unit="1" grid_ref="grid4Dreffi"  detect_missing_value=".true." />
+      <field id="crlmodis" long_name="MODIS Optical_Thickness_vs_ReffLiq" unit="1" grid_ref="grid4Dreffl"  detect_missing_value=".true." />
+
+
+    </field_group>  <!-- ----------------------------COSP------------------------ -->
 
     <field_group id="fields_AIRS" grid_ref="grid_glo" operation="instant" freq_op="3h">
@@ -982,5 +1014,6 @@
       <field id="CFC12_ppt" long_name="CFC12_ppt" unit="ppt" />
 <!-- reducing mass 3D variable to atmosphere total mass scalar -->
-      <field id="mass_sum" field_ref="mass" grid_ref="grid_sum" grid_path="grid_sum_axis" freq_op="1mo" > @mass  </field>
+      <field id="mass_sum_axis"    field_ref="mass" grid_ref="grid_sum_axis" freq_op="1mo" > @mass  </field>
+      <field id="mass_sum" field_ref="mass_sum_axis" grid_ref="grid_sum" freq_op="1mo" > @mass_sum_axis*aire  </field>
    </field_group>
 
Index: /LMDZ6/branches/Ocean_skin/DefLists/field_def_lmdz_cospv2.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/field_def_lmdz_cospv2.xml	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/DefLists/field_def_lmdz_cospv2.xml	(revision 3605)
@@ -0,0 +1,1069 @@
+<!-- $Id: field_def_lmdz.xml 3515 2019-05-21 10:41:38Z emillour $ -->
+<field_definition level="1" prec="4" operation="average" freq_op="1ts" enabled=".true." default_value="9.96921e+36">
+    
+<!--    <field_group id="fields_1D" grid_ref="vertical">  -->
+<!--        <field id="Ap"   long_name="Hybrid coordinate: pressure part"    unit="Pa" />  -->
+<!--        <field id="Bp"   long_name="Hybrid coordinate: sigma part"    unit="-" />  -->
+<!--        <field id="Alt"  long_name="Pseudo-altitude (for an 8km scale height)"    unit="km" />  -->
+<!--    </field_group>  -->
+
+    <field_group id="remap_expr" level="_reset_" prec="_reset_" operation="_reset_" freq_op="_reset_" enabled="_reset_" default_value="_reset_">
+      <field_group id="remap_1ts" />
+      <field_group id="remap_1800s" />
+      <field_group id="remap_1h" />
+      <field_group id="remap_3h" />
+      <field_group id="remap_6h" />
+      <field_group id="remap_1d" />
+      <field_group id="remap_1mo" />
+    </field_group>
+    
+    
+    <field_group id="coordinates" grid_ref="grid_glo">
+        <field id="io_lon"  />
+        <field id="io_lat"  />
+    </field_group>
+
+    <field_group id="coord_hyb">
+        <field id="Ahyb" long_name="Ahyb at level interface"     axis_ref="klevp1" />
+        <field id="Ahyb_bounds" long_name="" grid_ref="klevp1_bnds" />
+        <field id="Bhyb" long_name="Bhyb at level interface"       axis_ref="klevp1"  />
+        <field id="Bhyb_bounds" long_name=""  grid_ref="klevp1_bnds" />
+        <field id="Ahyb_mid" long_name="Ahyb at the middle of the level"      axis_ref="klev" />
+        <field id="Ahyb_mid_bounds" long_name="" grid_ref="klev_bnds" />
+        <field id="Bhyb_mid" long_name="Bhyb at the middle of the level"       axis_ref="klev"  />
+        <field id="Bhyb_mid_bounds" long_name=""  grid_ref="klev_bnds" />
+    </field_group>
+    
+    <field_group id="fields_2D" grid_ref="grid_glo">
+        <field id="phis"    long_name="Surface geop.height"     unit="m2/s2" />
+        <field id="aire"    long_name="Grid area"               unit="m2"    />
+        <field id="contfracATM"     long_name="% sfce ter+lic"  unit="-"   /> 
+        <field id="contfracOR"      long_name="% sfce terre OR" unit="-" />
+        <field id="sza"     long_name="Solar zenithal angle "   unit="deg" />
+        <field id="flat"    long_name="Latent heat flux"        unit="W/m2" />
+        <field id="slp"     long_name="Sea Level Pressure"      unit="Pa" />
+        <field id="ptstar"  long_name="Air Surface Temperature" unit="K" />
+        <field id="pt0"     long_name="Standard Air Surface Temperature"      unit="K" />
+        <field id="tsol"    long_name="Surface Temperature"     unit="K" />
+        <field id="t2m"        long_name="Temperature 2m" unit="K" />
+        <field id="tasmax"  field_ref="t2m"  operation="maximum" />
+        <field id="tasmin"  field_ref="t2m"  operation="minimum" />
+        <field id="t2m_min"    long_name="Temp 2m min"    unit="K" operation="minimum" />
+        <field id="t2m_max"    long_name="Temp 2m max"    unit="K" operation="maximum" />
+        <field id="t2m_ter"    long_name="Temp 2m ter"    unit="K" />
+        <field id="t2m_max_mon"   long_name="Monthly average max 2m temperature" unit="K" />
+        <field id="t2m_min_mon"   long_name="Monthly average min 2m temperature" unit="K" />
+        <field id="t2m_lic"    long_name="Temp 2m lic"    unit="K" />
+        <field id="t2m_oce"    long_name="Temp 2m oce"    unit="K" />
+        <field id="t2m_sic"    long_name="Temp 2m sic"    unit="K" />
+        <field id="gusts"    long_name="surface gustiness"    unit="m2/s2" />
+        <field id="wind10m"    long_name="10-m wind speed"      unit="m/s" />
+        <field id="wind10max"  long_name="10m wind speed max"   unit="m/s" operation="maximum"/>
+	<field id="sfcWindmax" field_ref="wind10m" operation="maximum" />
+        <field id="sicf"    long_name="Sea-ice fraction"        unit="-" />
+        <field id="q2m"     long_name="Specific humidity 2m"    unit="kg/kg" />
+        <field id="ustar"   long_name="Friction velocity"       unit="m/s" />
+        <field id="u10m"    long_name="Vent zonal 10m"          unit="m/s" />
+        <field id="v10m"    long_name="Vent meridien 10m"       unit="m/s" />
+        <field id="psol"    long_name="Surface Pressure"        unit="Pa" />
+        <field id="qsurf"   long_name="Surface Air humidity"    unit="kg/kg" />
+        <field id="ustar_ter"    long_name="Friction velocity ter"    unit="m/s" />
+        <field id="ustar_lic"    long_name="Friction velocity lic"    unit="m/s" />
+        <field id="ustar_oce"    long_name="Friction velocity oce"    unit="m/s" />
+        <field id="ustar_sic"    long_name="Friction velocity sic"    unit="m/s" />
+        <field id="wstar_ter"    long_name="Friction velocity ter"    unit="m/s" />
+        <field id="wstar_lic"    long_name="Friction velocity lic"    unit="m/s" />
+        <field id="wstar_oce"    long_name="Friction velocity oce"    unit="m/s" />
+        <field id="wstar_sic"    long_name="Friction velocity sic"    unit="m/s" />
+        <field id="wstar"       long_name="w* convective velocity "    unit="m/s" />
+        <field id="u10m_ter"    long_name="Vent Zonal 10m ter"    unit="m/s" />
+        <field id="u10m_lic"    long_name="Vent Zonal 10m lic"    unit="m/s" />
+        <field id="u10m_oce"    long_name="Vent Zonal 10m oce"    unit="m/s" />
+        <field id="u10m_sic"    long_name="Vent Zonal 10m sic"    unit="m/s" />
+        <field id="v10m_ter"    long_name="Vent meredien 10m ter"    unit="m/s" />
+        <field id="v10m_lic"    long_name="Vent meredien 10m lic"    unit="m/s" />
+        <field id="v10m_oce"    long_name="Vent meredien 10m oce"    unit="m/s" />
+        <field id="v10m_sic"    long_name="Vent meredien 10m sic"    unit="m/s" />
+        <field id="qsol"        long_name="Soil watter content"         unit="mm" />
+        <field id="JrNt"        long_name="1 if Day 0 if Night"         unit="-" />
+        <field id="cldhjn"      long_name="High-level cloudiness Day"         unit="-" />
+        <field id="cldmjn"      long_name="Mid-level cloudiness Day"         unit="-" />
+        <field id="cldljn"      long_name="Low-level cloudiness Day"         unit="-" />
+        <field id="cldtjn"      long_name="Total cloudiness Day"         unit="-" />
+        <field id="rnebjn"      long_name="Cloud fraction in day"         unit="-" />
+        <field id="ndayrain"    long_name="Number of dayrain(liq+sol)"  unit="-" operation="instant"/>
+        <field id="precip"      long_name="Precip Totale liq+sol"       unit="kg/(s*m2)" />
+        <field id="prhmax"      field_ref="precip" operation="maximum"           />
+        <field id="rain_fall"   long_name="Precip Totale liq"   unit="kg/(s*m2)" />
+        <field id="rain_con"    long_name="Precip convective liq"   unit="kg/(s*m2)" />
+        <field id="plul"    long_name="Large-scale Precip."     unit="kg/(s*m2)" />
+        <field id="plun"    long_name="Numerical Precip."       unit="kg/(s*m2)" />
+        <field id="pluc"    long_name="Convective Precip."      unit="kg/(s*m2)" />
+        <field id="snow"    long_name="Snow fall"               unit="kg/(s*m2)" />
+        <field id="evap"    long_name="Evaporat"                unit="kg/(s*m2)" />
+        <field id="evap_ter"    long_name="evaporation at surface ter"    unit="kg/(s*m2)" />
+        <field id="evap_lic"    long_name="evaporation at surface lic"    unit="kg/(s*m2)" />
+        <field id="evap_oce"    long_name="evaporation at surface oce"    unit="kg/(s*m2)" />
+        <field id="evap_sic"    long_name="evaporation at surface sic"    unit="kg/(s*m2)" />
+        <field id="msnow"    long_name="Surface snow amount"    unit="kg/m2" />
+        <field id="fsnow"    long_name="Surface snow area fraction"    unit="-" />
+        <field id="tops"    long_name="Solar rad. at TOA"    unit="W/m2" />
+        <field id="tops0"    long_name="CS Solar rad. at TOA"    unit="W/m2" />
+        <field id="topl"    long_name="IR rad. at TOA"    unit="W/m2" />
+        <field id="topl0"    long_name="IR rad. at TOA"    unit="W/m2" />
+        <field id="SWupTOA"    long_name="SWup at TOA"    unit="W/m2" />
+        <field id="SWupTOAclr"    long_name="SWup clear sky at TOA"    unit="W/m2" />
+        <field id="SWupTOAcleanclr"    long_name="SWup clean (no aerosol) clear sky at TOA"    unit="W/m2" />
+        <field id="SWdnTOA"    long_name="SWdn at TOA"    unit="W/m2" />
+        <field id="SWdnTOAclr"    long_name="SWdn clear sky at TOA"    unit="W/m2" />
+        <field id="nettop"    long_name="Net dn radiatif flux at TOA"    unit="W/m2" />
+        <field id="SWup200"    long_name="SWup at 200mb"    unit="W/m2" />
+        <field id="SWup200clr"    long_name="SWup clear sky at 200mb"    unit="W/m2" />
+        <field id="SWdn200"    long_name="SWdn at 200mb"    unit="W/m2" />
+        <field id="SWdn200clr"    long_name="SWdn clear sky at 200mb"    unit="W/m2" />
+        <field id="LWup200"    long_name="LWup at 200mb"    unit="W/m2" />
+        <field id="LWup200clr"    long_name="LWup clear sky at 200mb"    unit="W/m2" />
+        <field id="LWdn200"    long_name="LWdn at 200mb"    unit="W/m2" />
+        <field id="LWdn200clr"    long_name="LWdn clear sky at 200mb"    unit="W/m2" />
+        <field id="sols"    long_name="Solar rad. at surf."    unit="W/m2" />
+        <field id="sols0"    long_name="Solar rad. at surf."    unit="W/m2" />
+        <field id="soll"    long_name="IR rad. at surface"    unit="W/m2" />
+        <field id="soll0"    long_name="IR rad. at surface"    unit="W/m2" />
+        <field id="radsol"    long_name="Rayonnement au sol"    unit="W/m2" />
+        <field id="SWupSFC"    long_name="SWup at surface"    unit="W/m2" />
+        <field id="SWupSFCclr"    long_name="SWup clear sky at surface"    unit="W/m2" />
+        <field id="SWupSFCcleanclr"    long_name="SWup clean (no aerosol) clear sky at surface"    unit="W/m2" />
+        <field id="SWdnSFC"    long_name="SWdn at surface"    unit="W/m2" />
+        <field id="SWdnSFCclr"    long_name="SWdn clear sky at surface"    unit="W/m2" />
+        <field id="SWdnSFCcleanclr"    long_name="SWdn clean (no aerosol) clear sky at surface"    unit="W/m2" />
+        <field id="LWupSFC"    long_name="Upwd. IR rad. at surface"    unit="W/m2" />
+        <field id="LWupSFCclr"    long_name="CS Upwd. IR rad. at surface"    unit="W/m2" />
+        <field id="LWupTOAcleanclr"    long_name="CS clean (no aerosol) Upwd. IR rad. at TOA"    unit="W/m2" />
+        <field id="LWdnSFC"    long_name="Down. IR rad. at surface"    unit="W/m2" />
+        <field id="LWdnSFCclr"    long_name="Down. CS IR rad. at surface"    unit="W/m2" />
+        <field id="LWdnSFCcleanclr"    long_name="Down. CS clean (no aerosol) IR rad. at surface"    unit="W/m2" />
+        <field id="bils"    long_name="Surf. total heat flux"    unit="W/m2" />
+        <field id="bils_tke"    long_name="Surf. total heat flux"    unit="W/m2" />
+        <field id="bils_diss"    long_name="Surf. total heat flux"    unit="W/m2" />
+        <field id="bils_ec"    long_name="Surf. total heat flux"    unit="W/m2" />
+        <field id="bils_kinetic"    long_name="Surf. total heat flux"    unit="W/m2" />
+        <field id="bils_enthalp"    long_name="Surf. total heat flux"    unit="W/m2" />
+        <field id="bils_latent"    long_name="Surf. total heat flux"    unit="W/m2" />
+        <field id="bils_ech"    long_name="peu importe"    unit="W/m2" />
+        <field id="ustr_gwd_hines"    long_name="zonal wind stress Hines gravity waves"    unit="Pa" />
+        <field id="vstr_gwd_hines"    long_name="meridional wind stress Hines gravity waves"    unit="Pa" />
+        <field id="ustr_gwd_front"    long_name="zonal wind stress fronts gravity waves"    unit="Pa" />
+        <field id="vstr_gwd_front"    long_name="meridional wind stress fronts gravity waves"    unit="Pa" />
+        <field id="ustr_gwd_rando"    long_name="zonal wind stress random gravity waves"    unit="Pa" />
+        <field id="vstr_gwd_rando"    long_name="meridinal wind stress random gravity waves"    unit="Pa" />
+        <field id="sens"    long_name="Sensible heat flux"    unit="W/m2" />
+        <field id="sens_x"    long_name="sens off-wake"    unit="W/m2" />
+        <field id="sens_w"    long_name="sens within-wake"    unit="W/m2" />
+        <field id="flat_x"    long_name="flat off-wake"    unit="W/m2" />
+        <field id="flat_w"    long_name="flat within-wake"    unit="W/m2" />
+        <field id="delta_tsurf"    long_name="Temperature difference (w-x)"    unit="K" enabled="false" /> <!-- ym --field disabled-- delta_tsurf is not conform to the associated grid (the is an arry containing all sub_surface) --> 
+        <field id="cdragh_x"    long_name="cdragh off-wake"    unit="-" />
+        <field id="cdragh_w"    long_name="cdragh within-wake"    unit="-" />
+        <field id="cdragm_x"    long_name="cdragm off-wake"    unit="-" />
+        <field id="cdragm_w"    long_name="cdragm within-wake"    unit="-" />
+        <field id="kh"    long_name="Kh"    unit="kg/s/m2" />
+        <field id="kh_x"    long_name="cdragm off-wake"    unit="kg/s/m2" />
+        <field id="kh_w"    long_name="cdragm within-wake"    unit="kg/s/m2" />
+        <field id="fder"    long_name="Heat flux derivation"    unit="W/m2" />
+        <field id="ffonte"    long_name="Thermal flux for snow melting"    unit="W/m2" />
+        <field id="fqcalving"    long_name="Ice Calving"    unit="kg/m2/s" />
+        <field id="fqfonte"    long_name="Land ice melt"    unit="kg/m2/s" />
+        <field id="runofflic"  long_name="Land ice melt to ocean" unit="kg/m2/s" />
+        <field id="mrroli"  long_name="Runoff flux over land ice" unit="kg/m2/s" />
+        <field id="taux"    long_name="Zonal wind stress"    unit="Pa" />
+        <field id="tauy"    long_name="Meridional wind stress"    unit="Pa" />
+        <field id="taux_ter"    long_name="Zonal wind stress ter"    unit="Pa" />
+        <field id="taux_lic"    long_name="Zonal wind stress lic"    unit="Pa" />
+        <field id="taux_oce"    long_name="Zonal wind stress oce"    unit="Pa" />
+        <field id="taux_sic"    long_name="Zonal wind stress sic"    unit="Pa" />
+        <field id="tauy_ter"    long_name="Meridional wind stress ter"    unit="Pa" />
+        <field id="tauy_lic"    long_name="Meridional wind stress lic"    unit="Pa" />
+        <field id="tauy_oce"    long_name="Meridional wind stress oce"    unit="Pa" />
+        <field id="tauy_sic"    long_name="Meridional wind stress sic"    unit="Pa" />
+        <field id="pourc_ter"    long_name="% ter"    unit="%" />
+        <field id="pourc_lic"    long_name="% lic"    unit="%" />
+        <field id="pourc_oce"    long_name="% oce"    unit="%" />
+        <field id="pourc_sic"    long_name="% sic"    unit="%" />
+        <field id="fract_ter"    long_name="Fraction ter"    unit="1" />
+        <field id="fract_lic"    long_name="Fraction lic"    unit="1" />
+        <field id="fract_oce"    long_name="Fraction oce"    unit="1" />
+        <field id="fract_sic"    long_name="Fraction sic"    unit="1" />
+        <field id="tsol_ter"    long_name="Temperature ter"    unit="K" />
+        <field id="tsol_lic"    long_name="Temperature lic"    unit="K" />
+        <field id="tsol_oce"    long_name="Temperature oce"    unit="K" />
+        <field id="tsol_sic"    long_name="Temperature sic"    unit="K" />
+        <field id="evappot_ter"    long_name="Temperature ter"    unit="K" />
+        <field id="evappot_lic"    long_name="Temperature lic"    unit="K" />
+        <field id="evappot_oce"    long_name="Temperature oce"    unit="K" />
+        <field id="evappot_sic"    long_name="Temperature sic"    unit="K" />
+        <field id="sens_ter"    long_name="Sensible heat flux ter"    unit="W/m2" />
+        <field id="sens_lic"    long_name="Sensible heat flux lic"    unit="W/m2" />
+        <field id="sens_oce"    long_name="Sensible heat flux oce"    unit="W/m2" />
+        <field id="sens_sic"    long_name="Sensible heat flux sic"    unit="W/m2" />
+        <field id="lat_ter"    long_name="Latent heat flux ter"    unit="W/m2" />
+        <field id="lat_lic"    long_name="Latent heat flux lic"    unit="W/m2" />
+        <field id="lat_oce"    long_name="Latent heat flux oce"    unit="W/m2" />
+        <field id="lat_sic"    long_name="Latent heat flux sic"    unit="W/m2" />
+        <field id="flw_ter"    long_name="LW ter"    unit="W/m2" />
+        <field id="flw_lic"    long_name="LW lic"    unit="W/m2" />
+        <field id="flw_oce"    long_name="LW oce"    unit="W/m2" />
+        <field id="flw_sic"    long_name="LW sic"    unit="W/m2" />
+        <field id="fsw_ter"    long_name="SW ter"    unit="W/m2" />
+        <field id="fsw_lic"    long_name="SW lic"    unit="W/m2" />
+        <field id="fsw_oce"    long_name="SW oce"    unit="W/m2" />
+        <field id="fsw_sic"    long_name="SW sic"    unit="W/m2" />
+        <field id="wbils_ter"    long_name="Bilan sol ter"    unit="W/m2" />
+        <field id="wbils_lic"    long_name="Bilan sol lic"    unit="W/m2" />
+        <field id="wbils_oce"    long_name="Bilan sol oce"    unit="W/m2" />
+        <field id="wbils_sic"    long_name="Bilan sol sic"    unit="W/m2" />
+        <field id="wbilo_ter"    long_name="Bilan eau ter"    unit="kg/(m2*s)" />
+        <field id="wbilo_lic"    long_name="Bilan eau lic"    unit="kg/(m2*s)" />
+        <field id="wbilo_oce"    long_name="Bilan eau oce"    unit="kg/(m2*s)" />
+        <field id="wbilo_sic"    long_name="Bilan eau sic"    unit="kg/(m2*s)" />
+        <field id="wevap_ter"    long_name="Evap eau ter"    unit="kg/(m2*s)" />
+        <field id="wevap_lic"    long_name="Evap eau lic"    unit="kg/(m2*s)" />
+        <field id="wevap_oce"    long_name="Evap eau oce"    unit="kg/(m2*s)" />
+        <field id="wevap_sic"    long_name="Evap eau sic"    unit="kg/(m2*s)" />
+        <field id="wrain_ter"    long_name="Pluie eau ter"    unit="kg/(m2*s)" />
+        <field id="wrain_lic"    long_name="Pluie eau lic"    unit="kg/(m2*s)" />
+        <field id="wrain_oce"    long_name="Pluie eau oce"    unit="kg/(m2*s)" />
+        <field id="wrain_sic"    long_name="Pluie eau sic"    unit="kg/(m2*s)" />
+        <field id="wsnow_ter"    long_name="Neige eau ter"    unit="kg/(m2*s)" />
+        <field id="wsnow_lic"    long_name="Neige eau lic"    unit="kg/(m2*s)" />
+        <field id="wsnow_oce"    long_name="Neige eau oce"    unit="kg/(m2*s)" />
+        <field id="wsnow_sic"    long_name="Neige eau sic"    unit="kg/(m2*s)" />
+        <field id="cdrm"    long_name="Momentum drag coef."    unit="-" />
+        <field id="cdrh"    long_name="Heat drag coef."    unit="-" />
+        <field id="cldl"    long_name="Low-level cloudiness"    unit="-" />
+        <field id="cldm"    long_name="Mid-level cloudiness"    unit="-" />
+        <field id="cldh"    long_name="High-level cloudiness"    unit="-" />
+        <field id="cldt"    long_name="Total cloudiness"    unit="-" />
+        <field id="cldq"    long_name="Cloud liquid water path"    unit="kg/m2" />
+        <field id="lwp"    long_name="Cloud water path"    unit="kg/m2" />
+        <field id="iwp"    long_name="Cloud ice water path"    unit="kg/m2" />
+        <field id="ue"    long_name="Zonal energy transport"    unit="-" />
+        <field id="ve"    long_name="Merid energy transport"    unit="-" />
+        <field id="uq"    long_name="Zonal humidity transport"    unit="-" />
+        <field id="vq"    long_name="Merid humidity transport"    unit="-" />
+        <field id="uwat"    long_name="Zonal total water transport"    unit="-" />
+        <field id="vwat"    long_name="Merid total water transport"    unit="-" />
+        <field id="cape"    long_name="Conv avlbl pot ener"    unit="J/kg" />
+        <field id="pbase"    long_name="Cld base pressure"    unit="Pa" />
+        <field id="ptop"    long_name="Cld top pressure"    unit="Pa" />
+        <field id="fbase"    long_name="Cld base mass flux"    unit="kg/m2/s" />
+        <field id="plcl"    long_name="Lifting Condensation Level"    unit="hPa" enabled=".false." />
+        <field id="plfc"    long_name="Level of Free Convection"    unit="hPa" />
+        <field id="wbeff"    long_name="Conv. updraft velocity at LFC (inf100)"    unit="m/s" />
+        <field id="convoccur"    long_name="Convective occurence"    unit="-" />
+        <field id="prw"    long_name="Precipitable water"    unit="kg/m2" />
+        <field id="prlw"   long_name="Precipitable liquid water"  unit="kg/m2" />
+        <field id="prsw"   long_name="Precipitable solid water"  unit="kg/m2" />
+        <field id="s_pblh"    long_name="Boundary Layer Height"    unit="m" />
+        <field id="s_pblt"    long_name="t at Boundary Layer Height"    unit="K" />
+        <field id="s_lcl"    long_name="Condensation level"    unit="m" />
+        <field id="s_therm"    long_name="Exces du thermique"    unit="K" />
+        <field id="slab_bils_oce"    long_name="Bilan au sol sur ocean slab"    unit="W/m2" />
+        <field id="ale_bl"    long_name="ALE BL"    unit="m2/s2" />
+        <field id="alp_bl"    long_name="ALP BL"    unit="m2/s2" />
+        <field id="ale_wk"    long_name="ALE WK"    unit="m2/s2" />
+        <field id="alp_wk"    long_name="ALP WK"    unit="m2/s2" />
+        <field id="ale"    long_name="ALE"    unit="m2/s2" />
+        <field id="alp"    long_name="ALP"    unit="W/m2" />
+        <field id="cin"    long_name="Convective INhibition"    unit="m2/s2" />
+        <field id="wape"    long_name="-"    unit="-" />
+        <field id="n2"    long_name="Nombre de panaches de type 2"    unit="-" />
+        <field id="s2"    long_name="Surface moyenne des panaches de type 2"    unit="m2" />
+        <field id="proba_notrig"    long_name="Probabilite de non-declenchement"    unit="-" />
+        <field id="random_notrig"    long_name="Tirage aleatoire de non-declenchement"    unit="-" />
+        <field id="cv_gen"    long_name="Cumulonimbus genesis"    unit="1/(m2 s)" />
+        <field id="ale_bl_stat"    long_name="ALE_BL_STAT"    unit="m2/s2" />
+        <field id="ale_bl_trig"    long_name="ALE_BL_STAT + Condition P>Pseuil"    unit="m2/s2" />
+        <field id="alp_bl_det"    long_name="ALP_BL_DET"    unit="W/m2" />
+        <field id="alp_bl_fluct_m"    long_name="ALP_BL_FLUCT_M"    unit="W/m2" />
+        <field id="alp_bl_fluct_tke"    long_name="ALP_BL_FLUCT_TKE"    unit="W/m2" />
+        <field id="alp_bl_conv"    long_name="ALP_BL_CONV"    unit="W/m2" />
+        <field id="alp_bl_stat"    long_name="ALP_BL_STAT"    unit="W/m2" />
+        <field id="u850"    long_name="Zonal wind 850hPa"    unit="m/s" detect_missing_value=".true." />
+        <field id="u700"    long_name="Zonal wind 700hPa"    unit="m/s" detect_missing_value=".true." />
+        <field id="u500"    long_name="Zonal wind 500hPa"    unit="m/s" detect_missing_value=".true." />
+        <field id="u200"    long_name="Zonal wind 200hPa"    unit="m/s" detect_missing_value=".true." />
+        <field id="u100"    long_name="Zonal wind 100hPa"    unit="m/s" detect_missing_value=".true." />
+        <field id="u50"     long_name="Zonal wind 50hPa"    unit="m/s" detect_missing_value=".true." />
+        <field id="u10"     long_name="Zonal wind 10hPa"    unit="m/s" detect_missing_value=".true." />
+        <field id="v850"    long_name="Meridional wind 850hPa"    unit="m/s" detect_missing_value=".true." />
+        <field id="v700"    long_name="Meridional wind 700hPa"    unit="m/s" detect_missing_value=".true." />
+        <field id="v500"    long_name="Meridional wind 500hPa"    unit="m/s" detect_missing_value=".true." />
+        <field id="v200"    long_name="Meridional wind 200hPa"    unit="m/s" detect_missing_value=".true." />
+        <field id="v100"    long_name="Meridional wind 100hPa"    unit="m/s" detect_missing_value=".true." />
+        <field id="v50"     long_name="Meridional wind 50hPa"    unit="m/s" detect_missing_value=".true." />
+        <field id="v10"    long_name="Meridional wind 10hPa"    unit="m/s" detect_missing_value=".true." />
+        <field id="w850"    long_name="Vertical wind 850hPa"    unit="Pa/s" detect_missing_value=".true." />
+        <field id="w700"    long_name="Vertical wind 700hPa"    unit="Pa/s" detect_missing_value=".true." />
+        <field id="w500"    long_name="Vertical wind 500hPa"    unit="Pa/s" detect_missing_value=".true." />
+        <field id="w200"    long_name="Vertical wind 200hPa"    unit="Pa/s" detect_missing_value=".true." />
+        <field id="w100"    long_name="Vertical wind 100hPa"    unit="Pa/s" detect_missing_value=".true." />
+        <field id="w50"    long_name="Vertical wind 50hPa"    unit="Pa/s" detect_missing_value=".true." />
+        <field id="w10"    long_name="Vertical wind 10hPa"    unit="Pa/s" detect_missing_value=".true." />
+        <field id="t850"    long_name="Temperature 850hPa"    unit="K" detect_missing_value=".true." />
+        <field id="t700"    long_name="Temperature 700hPa"    unit="K" detect_missing_value=".true." />
+        <field id="t500"    long_name="Temperature 500hPa"    unit="K" detect_missing_value=".true." />
+        <field id="t200"    long_name="Temperature 200hPa"    unit="K" detect_missing_value=".true." />
+        <field id="t100"    long_name="Temperature 100hPa"    unit="K" detect_missing_value=".true." />
+        <field id="t50"    long_name="Temperature 50hPa"    unit="K" detect_missing_value=".true." />
+        <field id="t10"    long_name="Temperature 10hPa"    unit="K" detect_missing_value=".true." />
+        <field id="q850"    long_name="Specific humidity 850hPa"    unit="kg/kg" detect_missing_value=".true." />
+        <field id="q700"    long_name="Specific humidity 700hPa"    unit="kg/kg" detect_missing_value=".true." />
+        <field id="q500"    long_name="Specific humidity 500hPa"    unit="kg/kg" detect_missing_value=".true." />
+        <field id="q200"    long_name="Specific humidity 200hPa"    unit="kg/kg" detect_missing_value=".true." />
+        <field id="q100"    long_name="Specific humidity 100hPa"    unit="kg/kg" detect_missing_value=".true." />
+        <field id="q50"    long_name="Specific humidity 50hPa"    unit="kg/kg" detect_missing_value=".true." />
+        <field id="q10"    long_name="Specific humidity 10hPa"    unit="kg/kg" detect_missing_value=".true." />
+        <field id="z850"    long_name="Geopotential height 850hPa"    unit="m" detect_missing_value=".true." />
+        <field id="z700"    long_name="Geopotential height 700hPa"    unit="m" detect_missing_value=".true." />
+        <field id="z500"    long_name="Geopotential height 500hPa"    unit="m" detect_missing_value=".true." />
+        <field id="z200"    long_name="Geopotential height 200hPa"    unit="m" detect_missing_value=".true." />
+        <field id="z100"    long_name="Geopotential height 100hPa"    unit="m" detect_missing_value=".true." />
+        <field id="z50"    long_name="Geopotential height 50hPa"    unit="m" detect_missing_value=".true." />
+        <field id="z10"    long_name="Geopotential height 10hPa"    unit="m" detect_missing_value=".true." />
+        <field id="t_oce_sic"    long_name="Temp mixte oce-sic"    unit="K" />
+        <field id="weakinv"    long_name="Weak inversion"    unit="-" />
+        <field id="dthmin"    long_name="dTheta mini"    unit="K/m" />
+        <field id="u10_ter"    long_name="-"    unit="-" />
+        <field id="u10_lic"    long_name="-"    unit="-" />
+        <field id="u10_oce"    long_name="-"    unit="-" />
+        <field id="u10_sic"    long_name="-"    unit="-" />
+        <field id="v10_ter"    long_name="-"    unit="-" />
+        <field id="v10_lic"    long_name="-"    unit="-" />
+        <field id="v10_oce"    long_name="-"    unit="-" />
+        <field id="v10_sic"    long_name="-"    unit="-" />
+        <field id="rh2m"    long_name="Relative humidity at 2m"    unit="%" />
+        <field id="rh2m_max"    field_ref="rh2m" operation="maximum" enabled="false"/> <!-- ym Problem : field is disabled check rh2m_min has a reference (field_ref) to rh2 but is also sent by model which is not compatible-->
+        <field id="rh2m_min"    field_ref="rh2m" operation="minimum" enabled="false"/> <!-- ym Problem : field is disabled check rh2m_max has a reference (field_ref) to rh2 but is also sent by model which is not compatible-->
+<!--        <field id="rh2m_min"    long_name="Min Relative humidity at 2m"    unit="%" /> -->
+<!--        <field id="rh2m_max"    long_name="Max Relative humidity at 2m"    unit="%" /> -->
+        <field id="qsat2m"    long_name="Saturant humidity at 2m"    unit="%" />
+        <field id="tpot"    long_name="Surface air potential temperature"    unit="K" />
+        <field id="tpote"    long_name="Surface air equivalent potential temperature"    unit="K" />
+        <field id="SWnetOR"    long_name="Sfce net SW radiation OR"    unit="W/m2" />
+        <field id="SWdownOR"    long_name="Sfce incident SW radiation OR"    unit="W/m2" />
+        <field id="LWdownOR"    long_name="Sfce incident LW radiation OR"    unit="W/m2" />
+        <field id="snowl"    long_name="Solid Large-scale Precip."    unit="kg/(m2*s)" />
+        <field id="cape_max"    long_name="CAPE max."    unit="J/kg" operation="maximum"/>
+        <field id="solldown"    long_name="Down. IR rad. at surface"    unit="W/m2" />
+        <field id="dtsvdfo"    long_name="Boundary-layer dTs(o)"    unit="K/s" />
+        <field id="dtsvdft"    long_name="Boundary-layer dTs(t)"    unit="K/s" />
+        <field id="dtsvdfg"    long_name="Boundary-layer dTs(g)"    unit="K/s" />
+        <field id="dtsvdfi"    long_name="Boundary-layer dTs(g)"    unit="K/s" />
+        <field id="rugs"    long_name="rugosity"    unit="-" />
+        <field id="z0m"    long_name="roughness length, momentum"    unit="-" />
+        <field id="z0h"    long_name="roughness length, enthalpy"    unit="-" />
+        <field id="topswad"    long_name="ADE at TOA"    unit="W/m2" />
+        <field id="topswad0"    long_name="ADE clear-sky at TOA"    unit="W/m2" />
+        <field id="topswai"    long_name="AIE at TOA"    unit="W/m2" />
+        <field id="solswad"    long_name="ADE at SRF"    unit="W/m2" />
+        <field id="solswad0"    long_name="ADE clear-sky at SRF"    unit="W/m2" />
+        <field id="solswai"    long_name="AIE at SFR"    unit="W/m2" />
+        <field id="toplwad"    long_name="LW-ADE at TOA" unit="W/m2" />
+        <field id="toplwad0"    long_name="LW-ADE clear-sky at TOA"    unit="W/m2" />
+        <field id="toplwai"    long_name="LW-AIE clear-sky at TOA"    unit="W/m2" />
+        <field id="sollwad"    long_name="LW-ADE at SRF" unit="W/m2" />
+        <field id="sollwad0"    long_name="LW-ADE clear-sky at SRF"    unit="W/m2" />
+        <field id="sollwai"    long_name="LW-AIE at SRF" unit="W/m2" />
+        <field id="od550_ASBCM"    long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="od550_ASPOMM"   long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="od550_ASSO4M"   long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="od550_CSSO4M"   long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="od550_SSSSM"    long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="od550_ASSSM"    long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="od550_CSSSM"    long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="od550_CIDUSTM"  long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="od550_AIBCM"    long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="od550_AIPOMM"   long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="od550_ASNO3M"   long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="od550_CSNO3M"   long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="od550_CINO3M"   long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="od550_STRAT"    long_name="Aerosol Optical depth at 550 nm "    unit="1"  />
+        <field id="dryod550_ASBCM"    long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="dryod550_ASPOMM"   long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="dryod550_ASSO4M"   long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="dryod550_CSSO4M"   long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="dryod550_SSSSM"    long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="dryod550_ASSSM"    long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="dryod550_CSSSM"    long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="dryod550_CIDUSTM"  long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="dryod550_AIBCM"    long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="dryod550_AIPOMM"   long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="dryod550_ASNO3M"   long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="dryod550_CSNO3M"   long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="dryod550_CINO3M"   long_name="Aerosol Optical depth at 550 nm "    unit="1" />
+        <field id="od_10um_STRAT"  long_name="Stratospheric Aerosol Optical depth at 10 um" unit="-" />
+        <field id="od443aer"    long_name="Total aerosol optical depth at 440nm" unit="-" />
+        <field id="od550aer"    long_name="Total aerosol optical depth at 550nm" unit="-" />
+        <field id="dryod550aer" long_name="Total dry aerosol optical depth at 550nm"    unit="-" />
+        <field id="od865aer"    long_name="Total aerosol optical depth at 870nm"    unit="-" />
+        <field id="abs550aer"   long_name="Absorption aerosol optical depth at 550nm"    unit="-" />
+        <field id="od550lt1aer" long_name="Fine mode optical depth"    unit="-" />
+        <field id="sconcso4"    long_name="Surface Concentration of Sulfate "    unit="kg/m3" />
+        <field id="sconcno3"    long_name="Surface Concentration of Nitrate "    unit="kg/m3" />
+        <field id="sconcoa"     long_name="Surface Concentration of Organic Aerosol "    unit="kg/m3" />
+        <field id="sconcbc"     long_name="Surface Concentration of Black Carbon "    unit="kg/m3" />
+        <field id="sconcss"     long_name="Surface Concentration of Sea Salt "    unit="kg/m3" />
+        <field id="sconcdust"   long_name="Surface Concentration of Dust "    unit="kg/m3" />
+        <field id="loadso4"   long_name="Column Load of Sulfate "    unit="kg/m2" />
+        <field id="loadoa"    long_name="Column Load of Organic Aerosol "    unit="kg/m2" />
+        <field id="loadbc"    long_name="Column Load of Black Carbon "    unit="kg/m2" />
+        <field id="loadss"    long_name="Column Load of Sea Salt "    unit="kg/m2" />
+        <field id="loaddust"  long_name="Column Load of Dust "    unit="kg/m2" />
+        <field id="loadno3"   long_name="Column Load of Nitrate " unit="kg/m2" />
+        <field id="swtoaas_nat"    long_name="Natural aerosol radiative forcing all-sky at TOA"    unit="W/m2" />
+        <field id="swsrfas_nat"    long_name="Natural aerosol radiative forcing all-sky at SRF"    unit="W/m2" />
+        <field id="swtoacs_nat"    long_name="Natural aerosol radiative forcing clear-sky at TOA"    unit="W/m2" />
+        <field id="swsrfcs_nat"    long_name="Natural aerosol radiative forcing clear-sky at SRF"    unit="W/m2" />
+        <field id="swtoaas_ant"    long_name="Anthropogenic aerosol radiative forcing all-sky at TOA"    unit="W/m2" />
+        <field id="swsrfas_ant"    long_name="Anthropogenic aerosol radiative forcing all-sky at SRF"    unit="W/m2" />
+        <field id="swtoacs_ant"    long_name="Anthropogenic aerosol radiative forcing clear-sky at TOA"    unit="W/m2" />
+        <field id="swsrfcs_ant"    long_name="Anthropogenic aerosol radiative forcing clear-sky at SRF"    unit="W/m2" />
+        <field id="swtoacf_nat"    long_name="Natural aerosol impact on cloud radiative forcing at TOA"    unit="W/m2" />
+        <field id="swsrfcf_nat"    long_name="Natural aerosol impact on cloud radiative forcing  at SRF"    unit="W/m2" />
+        <field id="swtoacf_ant"    long_name="Anthropogenic aerosol impact on cloud radiative forcing at TOA"    unit="W/m2" />
+        <field id="swsrfcf_ant"    long_name="Anthropogenic aerosol impact on cloud radiative forcing at SRF"    unit="W/m2" />
+        <field id="swtoacf_zero"    long_name="Cloud radiative forcing (allsky-clearsky fluxes) at TOA"    unit="W/m2" />
+        <field id="swsrfcf_zero"    long_name="Cloud radiative forcing (allsky-clearsky fluxes) at SRF"    unit="W/m2" />
+        <field id="cldncl"    long_name="CDNC at top of liquid water cloud"    unit="m-3" />
+        <field id="reffclwtop"    long_name="Droplet effective radius at top of liquid water cloud"    unit="m" />
+        <field id="cldnvi"    long_name="Column Integrated Cloud Droplet Number"    unit="m-2" />
+        <field id="lcc"    long_name="Cloud liquid fraction at top of cloud"    unit="1" />
+        <field id="wvapp"    long_name="-"    unit="-" />
+        <field id="albe_ter"    long_name="Albedo VIS surf. ter"    unit="-" />
+        <field id="albe_lic"    long_name="Albedo VIS surf. lic"    unit="-" />
+        <field id="albe_oce"    long_name="Albedo VIS surf. oce"    unit="-" />
+        <field id="albe_sic"    long_name="Albedo VIS surf. sic"    unit="-" />
+        <field id="ages_ter"    long_name="Snow age ter"    unit="day" />
+        <field id="ages_lic"    long_name="Snow age lic"    unit="day" />
+        <field id="ages_oce"    long_name="Snow age oce"    unit="day" />
+        <field id="ages_sic"    long_name="Snow age sic"    unit="day" />
+        <field id="snow_ter"    long_name="Snow"    unit="kg/m2" />
+        <field id="snow_lic"    long_name="Snow"    unit="kg/m2" />
+        <field id="snow_oce"    long_name="Snow"    unit="kg/m2" />
+        <field id="snow_sic"    long_name="Snow"    unit="kg/m2" />
+        <field id="rugs_ter"    long_name="Surface roughness ter"    unit="m" />
+        <field id="rugs_lic"    long_name="Surface roughness lic"    unit="m" />
+        <field id="rugs_oce"    long_name="Surface roughness oce"    unit="m" />
+        <field id="rugs_sic"    long_name="Surface roughness sic"    unit="m" />
+        <field id="z0m_ter"    long_name="roughness length, momentum ter"    unit="m" />
+        <field id="z0m_lic"    long_name="roughness length, momentum lic"    unit="m" />
+        <field id="z0m_oce"    long_name="roughness length, momentum oce"    unit="m" />
+        <field id="z0m_sic"    long_name="roughness length, momentum sic"    unit="m" />
+        <field id="z0h_ter"    long_name="roughness length, enthalpy ter"    unit="m" />
+        <field id="z0h_lic"    long_name="roughness length, enthalpy lic"    unit="m" />
+        <field id="z0h_oce"    long_name="roughness length, enthalpy oce"    unit="m" />
+        <field id="z0h_sic"    long_name="roughness length, enthalpy sic"    unit="m" />
+        <field id="sens_rain_oce"  long_name="Sensible heat flux associated withliquid prec. over ocean"    unit="W/m2" />
+        <field id="sens_rain_sic"  long_name="Sensible heat flux associated with liquid prec. over seaice"    unit="W/m2" />
+        <field id="sens_snow_oce"  long_name="Sensible heat flux associated with solid prec. over ocean"    unit="W/m2" />
+        <field id="sens_snow_sic"  long_name="Sensible heat flux associated with solid prec. over seaice"    unit="W/m2" />
+        <field id="lat_rain_oce"  long_name="Latent heat flux associated with liquid prec. over ocean"    unit="W/m2" />
+        <field id="lat_rain_sic"  long_name="Latent heat flux associated with liquid prec. over seaice"    unit="W/m2" />
+        <field id="lat_snow_oce"  long_name="Latent heat flux associated with solid prec. over ocean"    unit="W/m2" />
+        <field id="lat_snow_sic"  long_name="Latent heat flux associated with solid prec. over seaice"    unit="W/m2" />
+        <field id="alb1"    long_name="Surface VIS albedo"    unit="-" />
+        <field id="alb2"    long_name="Surface Near IR albedo"    unit="-" />
+        <field id="ftime_con"    long_name="Fraction of time convection Occurs"    unit="-" operation="instant" />
+        <field id="ftime_deepcv"    long_name="Fraction of time deep convection Occurs"    unit="-" />
+        <field id="wake_h"    long_name="wake height"    unit="m" />
+        <field id="wake_dens"    long_name="number of wakes per m2"    unit="1/m2" />
+        <field id="wake_s"    long_name="wake_s"    unit="-" />
+        <field id="epmax"    long_name="epmax en fn cape"    unit="su" />
+        <field id="plulth"    long_name="Rainfall therm."    unit="K/s" />
+        <field id="plulst"    long_name="Rainfall strat."    unit="K/s" />
+        <field id="lmaxth"    long_name="Upper level thermals"    unit="-" />
+        <field id="ftime_th"    long_name="Fraction of time Shallow convection occurs"    unit="-" />
+        <field id="f0_th"    long_name="Thermal closure mass flux"    unit="K/s" />
+        <field id="zmax_th"    long_name="Thermal plume height"    unit="K/s" />
+        <field id="rsut4co2"    long_name="TOA Out SW in 4xCO2 atmosphere"    unit="W/m2" />
+        <field id="rlut4co2"    long_name="TOA Out LW in 4xCO2 atmosphere"    unit="W/m2" />
+        <field id="rsutcs4co2"    long_name="TOA Out CS SW in 4xCO2 atmosphere"    unit="W/m2" />
+        <field id="rlutcs4co2"    long_name="TOA Out CS LW in 4xCO2 atmosphere"    unit="W/m2" />
+        <field id="dqphy2d"    long_name="Physics dQ"    unit="(kg/m2)/s" />
+        <field id="dqlphy2d"    long_name="Physics dQL"    unit="(kg/m2)/s" />
+        <field id="dqsphy2d"    long_name="Physics dQS"    unit="(kg/m2)/s" />
+        <field id="dqdyn2d"    long_name="Dynamics dQ"    unit="(kg/m2)/s" />
+        <field id="dqldyn2d"   long_name="Dynamics dQL"    unit="(kg/m2)/s" />
+        <field id="dqsdyn2d"   long_name="Dynamics dQS"    unit="(kg/m2)/s" />
+        <field id="dqcon2d"    long_name="Convection dQ"    unit="(kg/m2)/s" />
+        <field id="dqwak2d"    long_name="Wake dQ"    unit="(kg/m2)/s" />
+        <field id="dqlsc2d"    long_name="Condensation dQ"    unit="(kg/m2)/s" />
+        <field id="dqvdf2d"    long_name="Boundary-layer dQ"    unit="(kg/m2)/s" />
+        <field id="dqeva2d"    long_name="Reevaporation dQ"    unit="(kg/m2)/s" />
+        <field id="dqlscth2d"    long_name="dQ therm."    unit="(kg/m2)/s" />
+        <field id="dqlscst2d"    long_name="dQ strat."    unit="(kg/m2)/s" />
+        <field id="dqthe2d"    long_name="Thermal dQ"    unit="(kg/m2)/s" />
+        <field id="dqajs2d"    long_name="Dry ajdust dQ"    unit="(kg/m2)/s" />
+        <field id="tatp"    long_name="Dry ajdust dQ"    unit="(kg/m2)/s" />
+        <field id="p_tropopause"  long_name="Tropopause pressure" unit="Pa"   detect_missing_value=".true."  />
+        <field id="z_tropopause"  long_name="Tropopause height" unit="m"      detect_missing_value=".true."  />
+        <field id="t_tropopause"  long_name="Tropopause temperature" unit="K" detect_missing_value=".true."  />
+        <field id="colO3_strat"    long_name="Ozone stratospheric column"     unit="DU" />             <!-- Added ThL -->
+        <field id="colO3_trop"     long_name="Ozone tropospheric column"      unit="DU" />             <!-- Added ThL -->
+    </field_group>
+
+    <field_group id="fields_3D" grid_ref="grid_glo_presnivs" >
+        <field id="tke"    long_name="TKE"    unit="m2/s2" />
+        <field id="tke_ter"    long_name="Max Turb. Kinetic Energy ter"    unit="m2/s2" />
+        <field id="tke_lic"    long_name="Max Turb. Kinetic Energy lic"    unit="m2/s2" />
+        <field id="tke_oce"    long_name="Max Turb. Kinetic Energy oce"    unit="m2/s2" />
+        <field id="tke_sic"    long_name="Max Turb. Kinetic Energy sic"    unit="m2/s2" />
+        <field id="tke_max_ter"    long_name="Max Turb. Kinetic Energy ter"    unit="m2/s2" operation="maximum"/>
+        <field id="tke_max_lic"    long_name="Max Turb. Kinetic Energy lic"    unit="m2/s2" operation="maximum"/>
+        <field id="tke_max_oce"    long_name="Max Turb. Kinetic Energy oce"    unit="m2/s2" operation="maximum"/>
+        <field id="tke_max_sic"    long_name="Max Turb. Kinetic Energy sic"    unit="m2/s2" operation="maximum"/>
+        <field id="l_mix_ter"    long_name="PBL mixing length ter"    unit="m" />
+        <field id="l_mix_lic"    long_name="PBL mixing length lic"    unit="m" />
+        <field id="l_mix_oce"    long_name="PBL mixing length oce"    unit="m" />
+        <field id="l_mix_sic"    long_name="PBL mixing length sic"    unit="m" />
+        <field id="treedrg_ter"    long_name="tree drag profile ter "    unit="-" />
+        <field id="treedrg_lic"    long_name="tree drag profile ter "    unit="-" />
+        <field id="treedrg_oce"    long_name="tree drag profile ter "    unit="-" />
+        <field id="treedrg_sic"    long_name="tree drag profile ter "    unit="-" />
+        <field id="l_mixmin_ter"    long_name="min PBL mixing length ter"    unit="m" />
+        <field id="l_mixmin_lic"    long_name="min PBL mixing length lic"    unit="m" />
+        <field id="l_mixmin_oce"    long_name="min PBL mixing length oce"    unit="m" />
+        <field id="l_mixmin_sic"    long_name="min PBL mixing length sic"    unit="m" />
+        <field id="dltpbltke_ter"    long_name="TKE difference (w - x)"    unit="m2/s2" />
+        <field id="dltpbltke_lic"    long_name="TKE difference (w - x)"    unit="m2/s2" />
+        <field id="dltpbltke_oce"    long_name="TKE difference (w - x)"    unit="m2/s2" />
+        <field id="dltpbltke_sic"    long_name="TKE difference (w - x)"    unit="m2/s2" />
+        <field id="cldtau"    long_name="Cloud optical thickness"    unit="1" />
+        <field id="cldemi"    long_name="Cloud optical emissivity"    unit="1" />
+        <field id="tke_max"    long_name="TKE max"    unit="m2/s2" operation="maximum"/>
+        <field id="kz"    long_name="Kz melange"    unit="m2/s" enabled="FALSE" />
+        <field id="kz_max"    long_name="Kz melange max"    unit="m2/s" enabled="FALSE" operation="maximum" />
+        <field id="concso4"    long_name="Concentration of Sulfate "    unit="kg/m3" />
+        <field id="concno3"    long_name="Concentration of Nitrate "    unit="kg/m3" /> 
+        <field id="concoa"    long_name="Concentration of Organic Aerosol "    unit="kg/m3" />
+        <field id="concbc"    long_name="Concentration of Black Carbon "    unit="kg/m3" />
+        <field id="concss"    long_name="Concentration of Sea Salt "    unit="kg/m3" />
+        <field id="concdust"    long_name="Concentration of Dust "    unit="kg/m3" />
+        <field id="ec550aer"    long_name="Extinction at 550nm"    unit="m^-1" />
+        <field id="lwcon"    long_name="Cloud liquid water content"    unit="kg/kg" />
+        <field id="iwcon"    long_name="Cloud ice water content"    unit="kg/kg" />
+        <field id="temp"    long_name="Air temperature"    unit="K" />
+        <field id="theta"    long_name="Potential air temperature"    unit="K" />
+        <field id="ovap"    long_name="Specific humidity"    unit="kg/kg" />
+        <field id="ovapinit"    long_name="Specific humidity (begin of timestep)"    unit="kg/kg" />
+        <field id="oliq"    long_name="Liquid water"    unit="kg/kg" />
+        <field id="ocond"    long_name="Condensed water"    unit="kg/kg" />
+        <field id="geop"    long_name="Geopotential height"    unit="m2/s2" />
+        <field id="geoph" field_ref="geop" long_name="Geopotential height" unit="m" > geop/9.80665 </field>
+        <field id="vitu"    long_name="Zonal wind"    unit="m/s" />
+        <field id="vitv"    long_name="Meridional wind"    unit="m/s" />
+        <field id="vitw"    long_name="Vertical wind"    unit="Pa/s" />
+        <field id="pres"    long_name="Air pressure"    unit="Pa" />
+        <field id="paprs"    long_name="Air pressure Inter-Couches"    unit="Pa" />
+        <field id="mass"    long_name="Masse Couches"    unit="kg/m2" />
+        <field id="zfull"    long_name="Altitude of full pressure levels"    unit="m" />
+        <field id="zhalf"    long_name="Altitude of half pressure levels"    unit="m" />
+        <field id="rneb"    long_name="Cloud fraction"    unit="-" />
+        <field id="rnebcon"    long_name="Convective Cloud Fraction"    unit="-" />
+        <field id="rnebls"    long_name="LS Cloud fraction"    unit="-" />
+        <field id="rneblsvol" long_name="LS Cloud fraction by volume"    unit="-" />
+        <field id="rhum"    long_name="Relative humidity"    unit="-" />
+        <field id="ozone"    long_name="Ozone mole fraction"    unit="-" />
+        <field id="ozone_daylight"    long_name="Daylight ozone mole fraction"    unit="-" />
+        <field id="upwd"    long_name="saturated updraft"    unit="kg/m2/s" />
+        <field id="ep"    long_name="ep"    unit="su" />
+        <field id="duphy"    long_name="Physics du"    unit="K/s" />
+        <field id="dtphy"    long_name="Physics dT"    unit="K/s" />
+        <field id="dqphy"    long_name="Physics dQ"    unit="(kg/kg)/s" />
+        <field id="dqlphy"   long_name="Physics dQL"    unit="(kg/kg)/s" />
+        <field id="dqsphy"   long_name="Physics dQS"    unit="(kg/kg)/s" />
+        <field id="pr_con_l"    long_name="Convective precipitation lic"    unit="-" />
+        <field id="pr_con_i"    long_name="Convective precipitation ice"    unit="-" />
+        <field id="pr_lsc_l"    long_name="Large scale precipitation lic"    unit="-" />
+        <field id="pr_lsc_i"    long_name="Large scale precipitation ice"    unit="-" />
+        <field id="re"    long_name="Cloud droplet effective radius"    unit="um" />
+        <field id="fl"    long_name="Denominator of Cloud droplet effective radius"    unit="-" />
+        <field id="scdnc"    long_name="Cloud droplet number concentration"    unit="m-3" />
+        <field id="reffclws"    long_name="Stratiform Cloud Droplet Effective Radius (aerosol diags.)"    unit="m" />
+        <field id="reffclwc"    long_name="Convective Cloud Droplet Effective Radius (aerosol diags.)"    unit="m" />
+        <field id="lcc3d"    long_name="Cloud liquid fraction"    unit="1" />
+        <field id="lcc3dcon"    long_name="Convective cloud liquid fraction"    unit="1" />
+        <field id="lcc3dstra"    long_name="Stratiform cloud liquid fraction"    unit="1" />
+        <field id="cldwatmxrat"    long_name="Cloud Water Mixing Ratio"    unit="1" />
+        <field id="icc3dcon"    long_name="Mass Fraction of Convective Cloud Ice"    unit="kg/kg" />
+        <field id="icc3dstra"    long_name="Mass Fraction of Stratiform Cloud Ice "    unit="kg/kg" />
+        <field id="cldicemxrat"    long_name="Cloud Ice Mixing Ratio"    unit="1" />
+        <field id="clwcon"    long_name="Convective Cloud Liquid water content"    unit="kg/kg" />
+        <field id="Mipsh"    long_name="mass flux shed from adiab. ascents"    unit="kg/m2/s" />
+        <field id="Ma"    long_name="undilute adiab updraft"    unit="kg/m2/s" />
+        <field id="dnwd"    long_name="saturated downdraft"    unit="kg/m2/s" />
+        <field id="dnwd0"    long_name="unsat. downdraft"    unit="kg/m2/s" />
+        <field id="mc"    long_name="Convective mass flux"    unit="kg/m2/s" />
+        <field id="dtdyn"    long_name="Dynamics dT"    unit="K/s" />
+        <field id="dqdyn"    long_name="Dynamics dQ"    unit="(kg/kg)/s" />
+        <field id="dqldyn"    long_name="Dynamics dQL"    unit="(kg/kg)/s" />
+        <field id="dqsdyn"    long_name="Dynamics dQS"    unit="(kg/kg)/s" />
+        <field id="dudyn"    long_name="Dynamics dU"    unit="m/s2" />
+        <field id="dvdyn"    long_name="Dynamics dV"    unit="m/s2" />
+        <field id="dtcon"    long_name="Convection dT"    unit="K/s" />
+        <field id="ducon"    long_name="Convection du"    unit="m/s2" />
+        <field id="dvcon"    long_name="Convection dv"    unit="m/s2" />
+        <field id="dqcon"    long_name="Convection dQ"    unit="(kg/kg)/s" />
+        <field id="dtwak"    long_name="Wake dT"    unit="K/s" />
+        <field id="dqwak"    long_name="Wake dQ"    unit="(kg/kg)/s" />
+        <field id="wake_deltat"    long_name="wake_deltat"    unit="-" />
+        <field id="wake_deltaq"    long_name="wake_deltaq"    unit="-" />
+        <field id="wake_omg"    long_name="wake_omg"    unit="-" />
+        <field id="wdtrainA"    long_name="precipitation from AA"    unit="-" />
+        <field id="wdtrainS"    long_name="precipitation from shedding of AA"    unit="-" />
+        <field id="wdtrainM"    long_name="precipitation from mixture"    unit="-" />
+        <field id="Vprecip"    long_name="precipitation vertical profile"    unit="-" />
+        <field id="qtaa"    long_name="specific total water in adiabatic ascents"    unit="kg/kg" /> 
+        <field id="Clwaa"   long_name="specific condensed water in adiabatic ascents"    unit="kg/kg" />
+        <field id="ftd"    long_name="tend temp due aux descentes precip"    unit="-" />
+        <field id="fqd"    long_name="tend vap eau due aux descentes precip"    unit="-" />
+        <field id="dtlsc"    long_name="Condensation dT"    unit="K/s" />
+        <field id="dtlschr"    long_name="Large-scale condensational heating rate"    unit="K/s" />
+        <field id="dqlsc"    long_name="Condensation dQ"    unit="(kg/kg)/s" />
+        <field id="beta_prec"    long_name="LS Conversion rate to prec"    unit="(kg/kg)/s" />
+        <field id="dtvdf"    long_name="Boundary-layer dT"    unit="K/s" />
+        <field id="dtvdf_x"  long_name="dtvdf off_wake"    unit="K/s" />
+        <field id="dtvdf_w"  long_name="dtvdf within_wake"    unit="K/s" />
+        <field id="dtdis"    long_name="TKE dissipation dT"    unit="K/s" />
+        <field id="dqvdf"    long_name="Boundary-layer dQ"    unit="(kg/kg)/s" />
+        <field id="dqvdf_x" long_name="dqvdf off_wake" unit="(kg/kg)/s" />
+        <field id="dqvdf_w" long_name="dqvdf within_wake" unit="(kg/kg)/s" />
+        <field id="dteva"    long_name="Reevaporation dT"    unit="K/s" />
+        <field id="dqeva"    long_name="Reevaporation dQ"    unit="(kg/kg)/s" />
+        <field id="dqlscth"    long_name="dQ therm."    unit="(kg/kg)/s" />
+        <field id="dqlscst"    long_name="dQ strat."    unit="(kg/kg)/s" />
+        <field id="dtlscth"    long_name="dQ therm."    unit="K/s" />
+        <field id="dtlscst"    long_name="dQ strat."    unit="K/s" />
+        <field id="ptconvth"    long_name="POINTS CONVECTIFS therm."    unit="-" />
+        <field id="ptconv"    long_name="POINTS CONVECTIFS"    unit="-" />
+        <field id="ratqs"    long_name="RATQS"    unit="-" />
+        <field id="dtthe"    long_name="Thermal dT"    unit="K/s" />
+        <field id="duthe"    long_name="Thermal du"    unit="m/s2" />
+        <field id="dvthe"    long_name="Thermal dv"    unit="m/s2" />
+        <field id="f_th"    long_name="Thermal plume mass flux"    unit="kg/(m2*s)" />
+        <field id="e_th"    long_name="Thermal plume entrainment"    unit="K/s" />
+        <field id="w_th"    long_name="Thermal plume vertical velocity"    unit="m/s" />
+        <field id="lambda_th"    long_name="Thermal plume vertical velocity"    unit="m/s" />
+        <field id="q_th"    long_name="Thermal plume total humidity"    unit="kg/kg" />
+        <field id="a_th"    long_name="Thermal plume fraction"    unit="-" />
+        <field id="s_th"    long_name="Thermal plume saturation deficit"    unit="kg/kg" />
+        <field id="s_env"    long_name="Environment saturation deficit"    unit="kg/kg" />
+        <field id="sigma_th"    long_name="Thermal plume gauss variance"    unit="kg/kg" />
+        <field id="sigma_env"    long_name="Environment gauss variance"    unit="kg/kg" />
+        <field id="d_th"    long_name="Thermal plume detrainment"    unit="K/s" />
+        <field id="dqthe"    long_name="Thermal dQ"    unit="(kg/kg)/s" />
+        <field id="dtajs"    long_name="Dry adjust. dT"    unit="K/s" />
+        <field id="dqajs"    long_name="Dry adjust. dQ"    unit="(kg/kg)/s" />
+        <field id="dtswr"    long_name="SW radiation dT"    unit="K/s" />
+        <field id="dtsw0"    long_name="CS SW radiation dT"    unit="K/s" />
+        <field id="dtlwr"    long_name="LW radiation dT"    unit="K/s" />
+        <field id="dtlw0"    long_name="CS LW radiation dT"    unit="K/s" />
+        <field id="dtec"    long_name="Cinetic dissip dT"    unit="K/s" />
+        <field id="duvdf"    long_name="Boundary-layer dU"    unit="m/s2" />
+        <field id="dvvdf"    long_name="Boundary-layer dV"    unit="m/s2" />
+        <field id="duoro"    long_name="Orography dU"    unit="m/s2" />
+        <field id="dvoro"    long_name="Orography dV"    unit="m/s2" />
+        <field id="dulif"    long_name="Orography dU"    unit="m/s2" />
+        <field id="dvlif"    long_name="Orography dV"    unit="m/s2" />
+        <field id="du_gwd_rando"    long_name="peu importe"    unit="W/m2" />
+        <field id="dv_gwd_rando"    long_name="peu importe"    unit="W/m2" />
+        <field id="du_gwd_hines" long_name="Hines GWD dU" unit="m/s2" />
+        <field id="dv_gwd_hines" long_name="Hines GWD dV" unit="m/s2" />
+        <field id="du_gwd_front" long_name="Fronts GWD dU" unit="m/s2" />
+        <field id="dv_gwd_front" long_name="Fronts GWD dV" unit="m/s2" />
+        <field id="east_gwstress" long_name="Eastward GW Stress" unit="Pa" />
+        <field id="west_gwstress" long_name="Westward GW Stress" unit="Pa" />
+        <field id="dtoro"    long_name="Orography dT"    unit="K/s" />
+        <field id="dtlif"    long_name="Orography dT"    unit="K/s" />
+        <field id="dthin"    long_name="Hines GWD dT"    unit="K/s" />
+        <field id="rsu"    long_name="SW upward radiation"    unit="W m-2" />
+        <field id="rsd"    long_name="SW downward radiation"    unit="W m-2" />
+        <field id="rlu"    long_name="LW upward radiation"    unit="W m-2" />
+        <field id="rld"    long_name="LW downward radiation"    unit="W m-2" />
+        <field id="rsucsaf"  long_name="SW clean (no aerosol) CS upward radiation"    unit="W m-2" />
+        <field id="rsdcsaf"  long_name="SW clean (no aerosol) CS downward radiation"    unit="W m-2" />
+        <field id="rsucs"    long_name="SW CS upward radiation"    unit="W m-2" />
+        <field id="rsdcs"    long_name="SW CS downward radiation"    unit="W m-2" />
+        <field id="rlucs"    long_name="LW CS upward radiation"    unit="W m-2" />
+        <field id="rldcs"    long_name="LW CS downward radiation"    unit="W m-2" />
+        <field id="tnt"    long_name="Tendency of air temperature"    unit="K s-1" />
+        <field id="tntc"    long_name="Tendency of air temperature due to Moist Convection"    unit="K s-1" />
+        <field id="tntr"    long_name="Air temperature tendency due to Radiative heating"    unit="K s-1" />
+        <field id="tntscpbl"    long_name="Air temperature tendency due to St cloud and precipitation and BL mixing"    unit="K s-1" />
+        <field id="tnhus"    long_name="Tendency of specific humidity"    unit="s-1" />
+        <field id="tnhusc"    long_name="Tendency of specific humidity due to convection"    unit="s-1" />
+        <field id="tnhusscpbl"    long_name="Tendency of Specific humidity due to ST cl, precip and BL mixing"    unit="s-1" />
+        <field id="evu"    long_name="Eddy viscosity coefficient for Momentum Variables"    unit="m2 s-1" />
+        <field id="h2o"    long_name="Mass Fraction of Water"    unit="1" />
+        <field id="mcd"    long_name="Downdraft COnvective Mass Flux"    unit="kg/(m2*s)" />
+        <field id="dmc"    long_name="Deep COnvective Mass Flux"    unit="kg/(m2*s)" />
+        <field id="ref_liq"    long_name="Effective radius of convective cloud liquid water particle"    unit="m" />
+        <field id="ref_ice"    long_name="Effective radius of startiform cloud ice particle"    unit="m" />
+        <field id="rsu4co2"    long_name="Upwelling SW 4xCO2 atmosphere"    unit="W/m2" />
+        <field id="rlu4co2"    long_name="Upwelling LW 4xCO2 atmosphere"    unit="W/m2" />
+        <field id="rsucs4co2"    long_name="Upwelling CS SW 4xCO2 atmosphere"    unit="W/m2" />
+        <field id="rlucs4co2"    long_name="Upwelling CS LW 4xCO2 atmosphere"    unit="W/m2" />
+        <field id="rsd4co2"    long_name="Downwelling SW 4xCO2 atmosphere"    unit="W/m2" />
+        <field id="rld4co2"    long_name="Downwelling LW 4xCO2 atmosphere"    unit="W/m2" />
+        <field id="rsdcs4co2"    long_name="Downwelling CS SW 4xCO2 atmosphere"    unit="W/m2" />
+        <field id="rldcs4co2"    long_name="Downwelling CS LW 4xCO2 atmosphere"    unit="W/m2" />
+        <field id="stratomask"    long_name="Stratospheric fraction"    unit="-" />
+        <field id="heat_volc"    long_name="SW heating rate from volcano"    unit="K/s" />
+        <field id="cool_volc"    long_name="LW cooling rate from volcano"    unit="K/s" />
+        <field id="pvap"    long_name="pvap intermediary variable" unit="-">pres*ovap*461.5 / (287.04*(1.+ (10.9491/18.0153)*ovap)) </field>
+    </field_group>
+
+    <field_group id="fields_strataer_trac_3D" grid_ref="grid_glo_presnivs" operation="average"/>
+    <field_group id="fields_strataer_trac_2D" grid_ref="grid_glo" operation="average"/>
+
+    <field_group id="fields_strataer_3D" grid_ref="grid_glo_presnivs" operation="average" >
+        <field id="ext_strat_550"        long_name="Strat. aerosol extinction coefficient at 550 nm"       unit="1/m" />
+        <field id="ext_strat_1020"       long_name="Strat. aerosol extinction coefficient at 1020 nm"      unit="1/m" />
+        <field id="budg_3D_nucl"         long_name="H2SO4 nucleation mass flux"                            unit="kg(S)/m2/layer/s" />
+        <field id="budg_3D_cond_evap"    long_name="H2SO4 net condensation/evaporation mass flux"          unit="kg(S)/m2/layer/s" />
+        <field id="budg_3D_ocs_to_so2"   long_name="OCS mass flux converted to SO2"                        unit="kg(S)/m2/layer/s" />
+        <field id="budg_3D_so2_to_h2so4" long_name="SO2 mass flux converted to H2SO4"                      unit="kg(S)/m2/layer/s" />
+        <field id="budg_3D_backgr_ocs"   long_name="OCS background tendency"                               unit="kg(S)/m2/layer/s" />
+        <field id="budg_3D_backgr_so2"   long_name="SO2 background tendency"                               unit="kg(S)/m2/layer/s" />
+        <field id="R2SO4"                long_name="H2SO4 mass fraction in aerosol"                        unit="%" />
+        <field id="OCS_lifetime"         long_name="OCS lifetime"                                          unit="s" />
+        <field id="SO2_lifetime"         long_name="SO2 lifetime"                                          unit="s" />
+        <field id="vsed_aer"             long_name="Strat. aerosol sedimentation velocity (mass-weighted)" unit="m/s" />
+        <field id="f_r_wet"              long_name="Conversion factor dry to wet aerosol radius"           unit="-" />
+    </field_group>
+
+    <field_group id="fields_strataer_2D" grid_ref="grid_glo" operation="average">
+        <field id="OD550_strat_only"   long_name="Stratospheric Aerosol Optical depth at 550 nm "        unit="1" />
+        <field id="OD1020_strat_only"  long_name="Stratospheric Aerosol Optical depth at 1020 nm "       unit="1" />
+        <field id="surf_PM25_sulf"     long_name="Sulfate PM2.5 concentration at the surface"            unit="ug/m3" />
+        <field id="budg_dep_dry_ocs"   long_name="OCS dry deposition flux"                               unit="kg(S)/m2/s" />
+        <field id="budg_dep_wet_ocs"   long_name="OCS wet deposition flux"                               unit="kg(S)/m2/s" />
+        <field id="budg_dep_dry_so2"   long_name="SO2 dry deposition flux"                               unit="kg(S)/m2/s" />
+        <field id="budg_dep_wet_so2"   long_name="SO2 wet deposition flux"                               unit="kg(S)/m2/s" />
+        <field id="budg_dep_dry_h2so4" long_name="H2SO4 dry deposition flux"                             unit="kg(S)/m2/s" />
+        <field id="budg_dep_wet_h2so4" long_name="H2SO4 wet deposition flux"                             unit="kg(S)/m2/s" />
+        <field id="budg_dep_dry_part"  long_name="Particle S dry deposition flux"                        unit="kg(S)/m2/s" />
+        <field id="budg_dep_wet_part"  long_name="Particle S wet deposition flux"                        unit="kg(S)/m2/s" />
+        <field id="budg_emi_ocs"       long_name="OCS emission flux"                                     unit="kg(S)/m2/s" />
+        <field id="budg_emi_so2"       long_name="SO2 emission flux"                                     unit="kg(S)/m2/s" />
+        <field id="budg_emi_h2so4"     long_name="H2SO4 emission flux"                                   unit="kg(S)/m2/s" />
+        <field id="budg_emi_part"      long_name="Particle S emission flux"                              unit="kg(S)/m2/s" />
+        <field id="budg_ocs_to_so2"    long_name="OCS to SO2 conversion flux"                            unit="kg(S)/m2/s" />
+        <field id="budg_so2_to_h2so4"  long_name="SO2 to H2SO4 conversion flux"                          unit="kg(S)/m2/s" />
+        <field id="budg_h2so4_to_part" long_name="H2SO4 to particle conversion flux"                     unit="kg(S)/m2/s" />
+        <field id="budg_sed_part"      long_name="Ground sedimentation flux of strat. particles"         unit="kg(S)/m2/s" />
+    </field_group>
+    
+    <field_group  id="fields_NMC" grid_ref="grid_glo_plev" >
+<!--  <field id="tnondef" long_name="Undefined value of T" unit="K" detect_missing_value=".true." /> -->
+      <field id="ta" long_name="Air temperature" unit="K" detect_missing_value=".true." />
+      <field id="zg" long_name="Geopotential height" unit="m" detect_missing_value=".true." />
+      <field id="hus" long_name="Specific humidity" unit="1" detect_missing_value=".true." />
+      <field id="hur" long_name="Relative humidity" unit="%" detect_missing_value=".true." />
+      <field id="ua" long_name="Eastward wind" unit="m s-1" detect_missing_value=".true." />
+      <field id="va" long_name="Northward wind" unit="m s-1" detect_missing_value=".true." />
+      <field id="wap" long_name="Lagrangian tendency of air pressure" unit="Pa s-1" detect_missing_value=".true." />
+<!--  <field id="psbg" long_name="Pressure sfce below ground" unit="%" detect_missing_value=".true." /> -->
+      <field id="tro3" long_name="Ozone mole fraction" unit="1e-9" detect_missing_value=".true." />
+      <field id="tro3_daylight" long_name="Daylight ozone mole fraction" unit="1e-9" detect_missing_value=".true." />
+      <field id="uv" long_name="uv" unit="m2/s2" detect_missing_value=".true." />
+      <field id="vxq" long_name="vxq" unit="m/s * (kg/kg)" detect_missing_value=".true." />
+      <field id="vT" long_name="vT" unit="mK/s" detect_missing_value=".true." />
+      <field id="wq" long_name="wq" unit="(Pa/s)*(kg/kg)" detect_missing_value=".true." />
+      <field id="vphi" long_name="vphi" unit="m2/s" detect_missing_value=".true." />
+      <field id="wT" long_name="wT" unit="K*Pa/s" detect_missing_value=".true." />
+      <field id="u2" long_name="u2" unit="m2/s2" detect_missing_value=".true." />
+      <field id="v2" long_name="v2" unit="m2/s2" detect_missing_value=".true." />
+      <field id="T2" long_name="T2" unit="K2" detect_missing_value=".true." />
+    </field_group>
+
+    <field_group id="fields_trac_2D" grid_ref="grid_glo" >
+          <field id="cumRN"    long_name="Cumulated tracer  RNVL1"    unit="-" />
+          <field id="cumPB"    long_name="Cumulated tracer  PBVL1"    unit="-" />
+          <field id="cumAga"   long_name="Cumulated tracer  Aga"    unit="-" />
+          <field id="cumCO2"   long_name="Cumulated tracer  CO2"    unit="-" />
+          <field id="cumdRN_dry"  long_name="Surface dry deposition tracer  RNVL1"  unit="- s-1" />
+          <field id="cumdPB_dry"  long_name="Surface dry deposition tracer  PBVL1"  unit="- s-1" />
+          <field id="cumdAga_dry" long_name="Surface dry deposition tracer  Aga"    unit="- s-1" />
+          <field id="cumdCO2_dry" long_name="Surface dry deposition tracer  CO2"    unit="- s-1" />
+    </field_group>
+
+    <field_group id="fields_trac_3D" grid_ref="grid_glo_presnivs" >
+      <field id="RN"    long_name="Tracer RNVL1"    unit="-" />
+      <field id="dRN_vdf"    long_name="Tendance tracer RNVL1"    unit="-" />
+      <field id="dRN_the"    long_name="Tendance tracer  RNVL1"    unit="-" />
+      <field id="dRN_con"    long_name="Tendance tracer  RNVL1"    unit="-" />
+      <field id="dRN_lessi_impa"    long_name="Tendance tracer  RNVL1"    unit="-" />
+      <field id="dRN_lessi_nucl"    long_name="Tendance tracer  RNVL1"    unit="-" />
+      <field id="dRN_insc"    long_name="Tendance tracer  RNVL1"    unit="-" />
+      <field id="dRN_bcscav"    long_name="Tendance tracer  RNVL1"    unit="-" />
+      <field id="dRN_evapls"    long_name="Tendance tracer  RNVL1"    unit="-" />
+      <field id="dRN_ls"    long_name="Tendance tracer  RNVL1"    unit="-" />
+      <field id="dRN_trsp"    long_name="Tendance tracer  RNVL1"    unit="-" />
+      <field id="dRN_sscav"    long_name="Tendance tracer  RNVL1"    unit="-" />
+      <field id="dRN_sat"    long_name="Tendance tracer  RNVL1"    unit="-" />
+      <field id="dRN_uscav"    long_name="Tendance tracer  RNVL1"    unit="-" />
+      <field id="PB"    long_name="Tracer PBVL1"    unit="-" />
+      <field id="dPB_vdf"    long_name="Tendance tracer PBVL1"    unit="-" />
+      <field id="dPB_the"    long_name="Tendance tracer  PBVL1"    unit="-" />
+      <field id="dPB_con"    long_name="Tendance tracer  PBVL1"    unit="-" />
+      <field id="dPB_lessi_impa"    long_name="Tendance tracer  PBVL1"    unit="-" />
+      <field id="dPB_lessi_nucl"    long_name="Tendance tracer  PBVL1"    unit="-" />
+      <field id="dPB_insc"    long_name="Tendance tracer  PBVL1"    unit="-" />
+      <field id="dPB_bcscav"    long_name="Tendance tracer  PBVL1"    unit="-" />
+      <field id="dPB_evapls"    long_name="Tendance tracer  PBVL1"    unit="-" />
+      <field id="dPB_ls"    long_name="Tendance tracer  PBVL1"    unit="-" />
+      <field id="dPB_trsp"    long_name="Tendance tracer  PBVL1"    unit="-" />
+      <field id="dPB_sscav"    long_name="Tendance tracer  PBVL1"    unit="-" />
+      <field id="dPB_sat"    long_name="Tendance tracer  PBVL1"    unit="-" />
+      <field id="dPB_uscav"    long_name="Tendance tracer  PBVL1"    unit="-" />
+      <field id="Aga"    long_name="Tracer AgaVL1"    unit="-" />
+      <field id="dAga_vdf"    long_name="Tendance tracer Aga"    unit="-" />
+      <field id="dAga_the"    long_name="Tendance tracer  Aga"    unit="-" />
+      <field id="dAga_con"    long_name="Tendance tracer  Aga"    unit="-" />
+      <field id="dAga_lessi_impa"    long_name="Tendance tracer  Aga"    unit="-" />
+      <field id="dAga_lessi_nucl"    long_name="Tendance tracer  Aga"    unit="-" />
+      <field id="dAga_insc"    long_name="Tendance tracer  Aga"    unit="-" />
+      <field id="dAga_bcscav"    long_name="Tendance tracer  Aga"    unit="-" />
+      <field id="dAga_evapls"    long_name="Tendance tracer  Aga"    unit="-" />
+      <field id="dAga_ls"    long_name="Tendance tracer  Aga"    unit="-" />
+      <field id="dAga_trsp"    long_name="Tendance tracer  Aga"    unit="-" />
+      <field id="dAga_sscav"    long_name="Tendance tracer  Aga"    unit="-" />
+      <field id="dAga_sat"    long_name="Tendance tracer  Aga"    unit="-" />
+      <field id="dAga_uscav"    long_name="Tendance tracer  Aga"    unit="-" />
+      <field id="CO2"    long_name="Tracer CO2VL1"    unit="-" />
+      <field id="dCO2_vdf"    long_name="Tendance tracer CO2"    unit="-" />
+      <field id="dCO2_the"    long_name="Tendance tracer  CO2"    unit="-" />
+      <field id="dCO2_con"    long_name="Tendance tracer  CO2"    unit="-" />
+    </field_group>
+
+    <field_group id="fields_solbnd_3D" grid_ref="grid_glo_spectband" >
+      <field id="solbnd"    long_name="Top-of-Atmosphere Solar Insolation for each band"    unit="W m-2"  enabled="false" /> <!-- this field is not sent by LMDZ, vertical axis "spectband" is not properly defined -->
+    </field_group>
+
+<!-- LIDAR DIAGNOSTICS -->
+    <field_group id="fields_COSP_LIDAR_2D" grid_ref="grid_glo" freq_offset="0ts" freq_op="3h">
+<!-- CALIPSO 2D -->
+      <field id="cllcalipso"    long_name="CALIPSO Low-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="clhcalipso"    long_name="CALIPSO Hight-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="clmcalipso"    long_name="CALIPSO Mid-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="cltcalipso"    long_name="CALIPSO Total Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="pcllcalipso"   long_name="CALIPSO Low-level Cloud Fraction"   unit="%"  detect_missing_value=".true." > cllcalipso*100 </field>
+      <field id="pclhcalipso"   long_name="CALIPSO High-level Cloud Fraction"   unit="%"  detect_missing_value=".true." > clhcalipso*100 </field>
+      <field id="pclmcalipso"   long_name="CALIPSO Mid-level Cloud Fraction"   unit="%"  detect_missing_value=".true." > clmcalipso*100 </field>
+      <field id="pcltcalipso"   long_name="CALIPSO Total Cloud Fraction"   unit="%" detect_missing_value=".true." > cltcalipso*100 </field>
+      <field id="cllcalipsoice"   long_name="CALIPSO Ice-Phase Low-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="clhcalipsoice"   long_name="CALIPSO Ice-Phase Hight-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="clmcalipsoice"   long_name="CALIPSO Ice-Phase Mid-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="cltcalipsoice"   long_name="CALIPSO Ice-Phase Total Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="cllcalipsoliq"   long_name="CALIPSO Liq-Phase Low-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="clhcalipsoliq"   long_name="CALIPSO Liq-Phase Hight-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="clmcalipsoliq"   long_name="CALIPSO Liq-Phase Mid-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="cltcalipsoliq"   long_name="CALIPSO Liq-Phase Total Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="cllcalipsoun"    long_name="CALIPSO Undefined-Phase Low-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="clhcalipsoun"    long_name="CALIPSO Undefined-Phase Hight-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="clmcalipsoun"    long_name="CALIPSO Undefined-Phase Mid-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="cltcalipsoun"    long_name="CALIPSO Undefined-Phase Total Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="clopaquecalipso"  long_name="CALIPSO Opaque Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="clthincalipso"    long_name="CALIPSO Thin Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="clzopaquecalipso" long_name="CALIPSO Altitude of opacity"   unit="m"  detect_missing_value=".true." />
+      <field id="clopaquetemp" long_name="CALIPSO Opaque Cloud Temperature"   unit="K"  detect_missing_value=".true." />
+      <field id="clthintemp" long_name="CALIPSO Thin Cloud Temperature"   unit="K"  detect_missing_value=".true." />
+      <field id="clzopaquetemp" long_name="CALIPSO Altitude of opacity Temperature"   unit="K"  detect_missing_value=".true." />
+      <field id="clopaquemeanz" long_name="CALIPSO Opaque Cloud Altitude"   unit="m"  detect_missing_value=".true." />
+      <field id="clthinmeanz" long_name="CALIPSO Thin Cloud Altitude"   unit="m"  detect_missing_value=".true." />
+      <field id="clthinemis" long_name="CALIPSO Thin Cloud Emissivity"   unit="1"  detect_missing_value=".true." />
+      <field id="clopaquemeanzse"  long_name="CALIPSO Opaque Cloud Altitude with respect to Surface Elevation"   unit="m"  detect_missing_value=".true." />
+      <field id="clthinmeanzse"    long_name="CALIPSO Thin Cloud Altitude with respect to Surface Elevation"   unit="m"  detect_missing_value=".true." />
+      <field id="clzopaquecalipsose" long_name="CALIPSO Altitude of opacity with respect to Surface Elevation"   unit="m"  detect_missing_value=".true." />
+<!-- GROUND LIDAR 532 nm 2D -->
+      <field id="cllgrLidar532"    long_name="GROUND LIDAR (532 nm) Low-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="clhgrLidar532"    long_name="GROUND LIDAR (532 nm) High-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="clmgrLidar532"    long_name="GROUND LIDAR (532 nm) Mid-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="cltgrLidar532"    long_name="GROUND LIDAR (532 nm) Total Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+<!-- ATLID 2D -->
+      <field id="cllatlid"    long_name="ATLID Low-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="clhatlid"    long_name="ATLID High-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="clmatlid"    long_name="ATLID Mid-level Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+      <field id="cltatlid"    long_name="ATLID Total Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+    </field_group>
+
+    <field_group id="fields_COSP_LIDAR_3D_height" grid_ref="grid_glo_height" freq_offset="0ts" freq_op="3h">
+<!-- CALIPSO 3D -->
+      <field id="clcalipso"  long_name="CALIPSO Cloud Fraction (532 nm)" unit="1" detect_missing_value=".true." />
+      <field id="pclcalipso" long_name="CALIPSO Cloud Fraction (532 nm)" unit="%" detect_missing_value=".true." > clcalipso*100 </field>
+      <field id="clcalipsoice"    long_name="CALIPSO Ice-Phase Cloud Fraction (532 nm)" unit="1" detect_missing_value=".true." />
+      <field id="clcalipsoliq"    long_name="CALIPSO Liq-Phase Cloud Fraction (532 nm)" unit="1" detect_missing_value=".true." />
+      <field id="clcalipsoun"    long_name="CALIPSO Undefined-Phase Cloud Fraction (532 nm)" unit="1" detect_missing_value=".true." />
+      <field id="clcalipsoopaque"  long_name="CALIPSO Opaque Cloud profile Fraction" unit="1" detect_missing_value=".true." />
+      <field id="clcalipsothin"    long_name="CALIPSO Thin Cloud profile Fraction" unit="1" detect_missing_value=".true." />
+      <field id="clcalipsozopaque" long_name="CALIPSO z_opaque Fraction" unit="1"  detect_missing_value=".true." />
+      <field id="clcalipsoopacity" long_name="CALIPSO opacity Fraction" unit="1" detect_missing_value=".true." />
+<!-- GROUND LIDAR 532 nm 3D -->
+      <field id="clgrLidar532"  long_name="GROUND LIDAR (532 nm) Cloud Fraction" unit="1" detect_missing_value=".true." />
+<!-- ATLID 3D -->
+      <field id="clatlid"  long_name="ATLID Cloud Fraction" unit="1" detect_missing_value=".true." />
+    </field_group>
+
+<!-- CALIPSO 3D TEMP -->
+    <field_group id="fields_COSP_CALIPSO_3D_temp" grid_ref="grid_glo_temp" freq_offset="0ts" freq_op="3h">
+      <field id="clcalipsotmp"    long_name="CALIPSO Cloud Fraction (532 nm)" unit="%"  detect_missing_value=".true." />
+      <field id="clcalipsotmpliq" long_name="CALIPSO Liq-Phase Cloud Fraction (532 nm)" unit="1" detect_missing_value=".true." />
+      <field id="clcalipsotmpice" long_name="CALIPSO Ice-Phase Cloud Fraction (532 nm)" unit="1" detect_missing_value=".true." />
+      <field id="clcalipsotmpun"  long_name="CALIPSO Undefined-Phase Total Cloud Fraction"   unit="1"  detect_missing_value=".true." />
+    </field_group>
+
+<!-- CALIPSO 4D -->
+      <field id="lidarBetaMol532" long_name="CALIPSO Molecular Backscatter (532 nm)" unit="m-1 sr-1" freq_offset="0ts" freq_op="3h" grid_ref="grid_glo_heightmlev" detect_missing_value=".true." />
+      <field id="cfadLidarsr532" long_name="CALIPSO Scattering Ratio CFAD (532 nm)" unit="1" freq_offset="0ts" freq_op="3h" grid_ref="grid4Dsrbin"  detect_missing_value=".true." />
+      <field id="atb532" long_name="CALIPSO Attenuated Total Backscatter (532 nm)" unit="1" freq_offset="0ts" freq_op="3h" grid_ref="grid4Dcol"  detect_missing_value=".true." />
+<!-- GROUND LIDAR 532 nm 4D -->
+      <field id="lidarBetaMol532gr" long_name="GROUND LIDAR Molecular Backscatter (532 nm)" unit="m-1 sr-1" freq_offset="0ts" freq_op="3h" grid_ref="grid_glo_heightmlev" detect_missing_value=".true." />
+      <field id="cfadLidarsr532gr" long_name="GROUND LIDAR Scattering Ratio CFAD (532 nm)" unit="1" freq_offset="0ts" freq_op="3h" grid_ref="grid4Dsrbin"  detect_missing_value=".true." />
+      <field id="atb532gr" long_name="GROUND LIDAR Attenuated Total Backscatter (532 nm)" unit="1" freq_offset="0ts" freq_op="3h" grid_ref="grid4Dcol"  detect_missing_value=".true." />
+<!-- ATLID 4D -->
+      <field id="lidarBetaMol355" long_name="ATLID Molecular Backscatter (355 nm)" unit="m-1 sr-1" freq_offset="0ts" freq_op="3h" grid_ref="grid_glo_heightmlev" detect_missing_value=".true." />
+      <field id="cfadLidarsr355" long_name="ATLID Scattering Ratio CFAD (355 nm)" unit="1" freq_offset="0ts" freq_op="3h" grid_ref="grid4Dsrbin"  detect_missing_value=".true." />
+      <field id="atb355" long_name="ATLID Attenuated Total Backscatter (355 nm)" unit="1" freq_offset="0ts" freq_op="3h" grid_ref="grid4Dcol"  detect_missing_value=".true." />
+
+<!-- PARASOL -->
+<!--    <field_group id="fields_COSP_PARASOL_3D_sza" grid_ref="grid_glo_sza" freq_offset="0ts" freq_op="3h"> -->
+     <field id="parasolGrid_refl" long_name="PARASOL Reflectance" unit="1" freq_offset="0ts" freq_op="3h" grid_ref="grid_glo_sza" detect_missing_value=".true." />
+      <field id="parasolPix_refl" long_name="PARASOL Subcolumn Reflectance" unit="1" freq_offset="0ts" freq_op="3h" grid_ref="grid4Dsza" detect_missing_value=".true." />
+<!--       <field id="Ncrefl"  long_name="Nb for PARASOL-like mono-directional reflectance" unit="1" detect_missing_value=".true." /> -->
+<!--     </field_group> -->
+
+    <field_group id="fields_COSP_CLOUDSAT_2D" grid_ref="grid_glo" freq_offset="0ts" freq_op="3h">
+<!-- CLOUDSAT ONLY -->
+      <field id="cloudsat_tcc" long_name="CLOUDSAT Total Cloud Fraction" unit="1"  detect_missing_value=".true." />
+      <field id="cloudsat_tcc2" long_name="CLOUDSAT Total Cloud Fraction (no 1km)" unit="1"  detect_missing_value=".true." />
+
+      <field id="ptradarflag0" long_name="CLOUDSAT precipitation occurence fraction flag 0 (No precipitation)" unit="1"  detect_missing_value=".true." />
+      <field id="ptradarflag1" long_name="CLOUDSAT precipitation occurence fraction flag 1 (Rain possible)" unit="1"  detect_missing_value=".true." />
+      <field id="ptradarflag2" long_name="CLOUDSAT precipitation occurence fraction flag 2 (Rain probable)" unit="1"  detect_missing_value=".true." />
+      <field id="ptradarflag3" long_name="CLOUDSAT precipitation occurence fraction flag 3 (Rain certain)" unit="1"  detect_missing_value=".true." />
+      <field id="ptradarflag4" long_name="CLOUDSAT precipitation occurence fraction flag 4 (Snow possible)" unit="1"  detect_missing_value=".true." />
+      <field id="ptradarflag5" long_name="CLOUDSAT precipitation occurence fraction flag 5 (Snow certain)" unit="1"  detect_missing_value=".true." />
+      <field id="ptradarflag6" long_name="CLOUDSAT precipitation occurence fraction flag 6 (Mixed-precipitation possible)" unit="1"  detect_missing_value=".true." />
+      <field id="ptradarflag7" long_name="CLOUDSAT precipitation occurence fraction flag 7 (Mixed-precipitation certain)" unit="1"  detect_missing_value=".true." />
+      <field id="ptradarflag8" long_name="CLOUDSAT precipitation occurence fraction flag 8 (Heavy rain)" unit="1"  detect_missing_value=".true." />
+      <field id="ptradarflag9" long_name="CLOUDSAT precipitation occurence fraction flag 9 (Default)" unit="1"  detect_missing_value=".true." />
+      <field id="radarpia" long_name="CLOUDSAT PIA" unit="1"  detect_missing_value=".true." />
+<!-- CLOUDSAT + CALIPSO -->
+      <field id="cltlidarradar" long_name="CALIPSO and CLOUDSAT Total Cloud Fraction" unit="1"  detect_missing_value=".true." />
+    </field_group>
+
+    <field_group id="fields_COSP_CLOUDSAT_3D" grid_ref="grid_glo_height" freq_offset="0ts" freq_op="3h">
+      <field id="clcalipso2"  long_name="CALIPSO Cloud Fraction Undetected by CloudSat" unit="1" detect_missing_value=".true." />
+    </field_group>
+
+      <field id="dbze94" long_name="CloudSat Radar Reflectivity" unit="1" freq_offset="0ts" freq_op="3h" grid_ref="grid4Dcol"  detect_missing_value=".true." />
+      <field id="cfadDbze94" long_name="CloudSat Radar Reflectivity CFAD" unit="1" freq_offset="0ts" freq_op="3h" grid_ref="grid4Ddbze"  detect_missing_value=".true." />
+<!-- ISCCP -->
+    <field_group id="fields_COSP_ISCCP_2D" grid_ref="grid_glo" freq_offset="0ts" freq_op="3h">
+<!--      <field id="sunlit" long_name="1 for day points, 0 for nightime" unit="1"  detect_missing_value=".true." /> -->
+      <field id="cltisccp" long_name="Total Cloud Fraction as Calculated by the ISCCP Simulator" unit="1"  detect_missing_value=".true." />
+      <field id="pctisccp" long_name="Mean Cloud Top Pressure as Calculated by the ISCCP Simulator" unit="Pa"  detect_missing_value=".true." />
+      <field id="tauisccp" long_name="Optical Depth as Calculated by the ISCCP Simulator" unit="1"  detect_missing_value=".true." />
+      <field id="albisccp" long_name="Mean Cloud Albedo as Calculated by the ISCCP Simulator" unit="1"  detect_missing_value=".true." />
+      <field id="meantbisccp" long_name="Mean all-sky 10.5 micron brightness temperature as calculated by the ISCCP Simulator" unit="K"  detect_missing_value=".true." />
+      <field id="meantbclrisccp" long_name="Mean clear-sky 10.5 micron brightness temperature as calculated by the ISCCP Simulator" unit="K"  detect_missing_value=".true." />
+    </field_group>
+    <field_group id="fields_COSP_ISCCP_3D" grid_ref="grid_glo_column" freq_offset="0ts" freq_op="3h">
+      <field id="boxtauisccp" long_name="Optical Depth in Each Column as Calculated by the ISCCP Simulator" unit="1" detect_missing_value=".true." />
+      <field id="boxptopisccp" long_name="Cloud Top Pressure in Each Column as Calculated by the ISCCP Simulator" unit="Pa" detect_missing_value=".true." />
+    </field_group>
+      <field id="clisccp" long_name="ISCCP joint-PDF of cloud top pressure and optical depth" unit="1" freq_offset="0ts" freq_op="3h" grid_ref="grid4Dtau"  detect_missing_value=".true." />
+<!-- MISR -->
+    <field_group id="fields_COSP_MISR" freq_offset="0ts" freq_op="3h">
+      <field id="misr_fq" long_name="MISR joint-PDF of cloud top pressure and optical depth" unit="1" grid_ref="grid4Dmisr"  detect_missing_value=".true." />
+      <field id="misr_meanztop" long_name="MISR Mean Cloud Top Height" unit="1" grid_ref="grid_glo"  detect_missing_value=".true." />
+      <field id="misr_cldarea" long_name="MISR cloud cover" unit="1" grid_ref="grid_glo"  detect_missing_value=".true." />
+    </field_group>
+<!-- MODIS -->
+    <field_group id="fields_COSP_MODIS" grid_ref="grid_glo" freq_offset="0ts"  freq_op="3h">
+      <field id="cllmodis" long_name="MODIS Low-level Cloud Fraction" unit="1"  detect_missing_value=".true." />
+      <field id="clmmodis" long_name="MODIS Mid-level Cloud Fraction" unit="1"  detect_missing_value=".true." />
+      <field id="clhmodis" long_name="MODIS High-level Cloud Fraction" unit="1"  detect_missing_value=".true." />
+      <field id="cltmodis" long_name="MODIS Total Cloud Fraction" unit="1"  detect_missing_value=".true." />
+      <field id="clwmodis" long_name="MODIS Cloud Fraction water mean" unit="1"  detect_missing_value=".true." />
+      <field id="climodis" long_name="MODIS Cloud Fraction ice mean" unit="1"  detect_missing_value=".true." />
+      <field id="tautmodis" long_name="MODIS Optical_Thickness_Total_Mean" unit="1"  detect_missing_value=".true." />
+      <field id="tauwmodis" long_name="MODIS Optical_Thickness_Water_Mean" unit="1"  detect_missing_value=".true." /> 
+      <field id="tauimodis" long_name="MODIS Optical_Thickness_Ice_Mean" unit="1"  detect_missing_value=".true." />
+      <field id="tautlogmodis" long_name="MODIS Optical_Thickness_Total_logMean" unit="1"  detect_missing_value=".true." />
+      <field id="tauwlogmodis" long_name="MODIS Optical_Thickness_Water_logMean" unit="1"  detect_missing_value=".true." />
+      <field id="tauilogmodis" long_name="MODIS Optical_Thickness_Ice_logMean" unit="1"  detect_missing_value=".true." />
+      <field id="reffclwmodis"  long_name="Modis Cloud_Particle_Size_Water_Mean" unit="m"  detect_missing_value=".true." />
+      <field id="reffclimodis"  long_name="Modis Cloud_Particle_Size_Ice_Mean" unit="m"  detect_missing_value=".true." />
+      <field id="pctmodis"  long_name="Modis Cloud_Top_Pressure_Total_Mean" unit="Pa"  detect_missing_value=".true." /> 
+      <field id="lwpmodis" long_name="Modis Liquid_Water_Path_Mean" unit="kg m-2"  detect_missing_value=".true." />
+      <field id="iwpmodis" long_name="Modis Ice_Water_Path_Mean" unit="kg m-2" detect_missing_value=".true." />
+    </field_group>
+      <field id="modis_ot_vs_ctp" long_name="MODIS joint-PDF of cloud top pressure and optical depth" unit="1" freq_offset="0ts" freq_op="3h" grid_ref="grid4Dtau"  detect_missing_value=".true." />
+      <field id="modis_ot_vs_reffice" long_name="MODIS Joint-PDF of optical-depth and ice particle size" unit="1" freq_offset="0ts" freq_op="3h" grid_ref="grid4Dreffi"  detect_missing_value=".true." />
+      <field id="modis_ot_vs_reffliq" long_name="MODIS Joint-PDF of optical-depth and liquid particle size" unit="1" freq_offset="0ts" freq_op="3h" grid_ref="grid4Dreffl"  detect_missing_value=".true." />
+
+    
+    <field_group id="fields_AIRS" grid_ref="grid_glo" operation="instant" freq_op="3h">
+      <field id="alt_tropo" long_name="Tropopause pressure" unit="hPa" />
+      <field id="map_prop_hc" long_name="Proportion of high clouds" unit=" "/>
+      <field id="map_prop_hist" long_name="Proportion of high ice semi-transp clouds" unit=" "/>
+      <field id="map_emis_hc" long_name="Emissivity of high clouds" unit=" "/>
+      <field id="map_iwp_hc" long_name="Ice water path of high clouds" unit="g/m2"/>
+      <field id="map_deltaz_hc" long_name="geom thickness of high clouds" unit="m"/>
+      <field id="map_pcld_hc" long_name="cloud pressure of high clouds" unit="hPa"/>
+      <field id="map_tcld_hc" long_name="cloud temperature of high clouds" unit="K"/>
+      <field id="map_emis_hist" long_name="Emissivity of high ice st clouds" unit=" "/>
+      <field id="map_iwp_hist" long_name="Ice water path of high ice st clouds" unit="g/m2"/>
+      <field id="map_deltaz_hist" long_name="geom thickness of high ice st clouds" unit="m"/>
+      <field id="map_rad_hist" long_name="ice crystals radius in high ice st clouds" unit="m"/>
+      <field id="map_emis_Cb" long_name="Emissivity of high Cb clouds" unit=" "/>
+      <field id="map_pcld_Cb" long_name="cloud pressure of high Cb clouds" unit="hPa"/>
+      <field id="map_tcld_Cb" long_name="cloud temperature of high Cb clouds" unit="K"/>
+      <field id="map_emis_Anv" long_name="Emissivity of high Anv clouds" unit=" "/>
+      <field id="map_pcld_Anv" long_name="cloud pressure of high Anv clouds" unit="hPa"/>
+      <field id="map_tcld_Anv" long_name="cloud temperature of high Anv clouds" unit="K"/>
+      <field id="map_emis_ThCi" long_name="Emissivity of high ThCi clouds" unit=" "/>
+      <field id="map_pcld_ThCi" long_name="cloud pressure of high ThCi clouds" unit="hPa"/>
+      <field id="map_tcld_ThCi" long_name="cloud temperature of high ThCi clouds" unit="K"/>
+      <field id="map_ntot" long_name="total AIRS cloud fraction" unit=" "/>
+      <field id="map_hc" long_name="high clouds AIRS cloud fraction" unit=" "/>
+      <field id="map_hist" long_name="high clouds ice st AIRS cloud fraction" unit=" "/>
+      <field id="map_Cb" long_name="high clouds Cb AIRS cloud fraction" unit=" "/>
+      <field id="map_ThCi" long_name="high clouds ThCi AIRS cloud fraction" unit=" "/>
+      <field id="map_Anv" long_name="high clouds Anv AIRS cloud fraction" unit=" "/>
+    </field_group>
+
+   <field_group id="field_scalar" operation="instant" grid_ref="grid_scalar">
+      <field id="R_ecc" long_name="R_ecc" unit="-" />
+      <field id="R_peri" long_name="R_peri" unit="-" />
+      <field id="R_incl" long_name="R_incl" unit="deg" />
+      <field id="solaire" long_name="solaire" unit="W/m2" />
+      <field id="rsun1" long_name="Fraction constante solaire bande 1" unit="W/m2" />
+      <field id="rsun2" long_name="Fraction constante solaire bande 2" unit="W/m2" />
+      <field id="rsun3" long_name="Fraction constante solaire bande 3" unit="W/m2" />
+      <field id="rsun4" long_name="Fraction constante solaire bande 4" unit="W/m2" />
+      <field id="rsun5" long_name="Fraction constante solaire bande 5" unit="W/m2" />
+      <field id="rsun6" long_name="Fraction constante solaire bande 6" unit="W/m2" />
+      <field id="co2_ppm" long_name="co2_ppm" unit="ppm" />
+      <field id="CH4_ppb" long_name="CH4_ppb" unit="ppb" />
+      <field id="N2O_ppb" long_name="N2O_ppb" unit="ppb" />
+      <field id="CFC11_ppt" long_name="CFC11_ppt" unit="ppt" />
+      <field id="CFC12_ppt" long_name="CFC12_ppt" unit="ppt" />
+<!-- reducing mass 3D variable to atmosphere total mass scalar -->
+      <field id="mass_sum_axis"    field_ref="mass" grid_ref="grid_sum_axis" freq_op="1mo" > @mass  </field>
+      <field id="mass_sum" field_ref="mass_sum_axis" grid_ref="grid_sum" freq_op="1mo" > @mass_sum_axis  </field>
+   </field_group>
+
+</field_definition>
Index: /LMDZ6/branches/Ocean_skin/DefLists/file_def_histLES_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/file_def_histLES_lmdz.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/file_def_histLES_lmdz.xml	(revision 3605)
@@ -1,5 +1,6 @@
+<!-- $Id$ -->
 <file_definition>
     <file_group id="defile">
-        <file id="histLES" name="XhistLES" output_freq="1h" output_level="5" enabled=".FALSE.">
+        <file id="histLES" name="XhistLES" output_freq="1h" output_level="11" enabled="false" compression_level="0">
             
             <!-- VARS 1D -->
@@ -11,5 +12,7 @@
         
             <!-- VARS 2D -->
-            <field_group operation="average" freq_op="1ts">
+         <field_group group_ref="remap_1h">
+
+            <field_group operation="average" grid_ref="grid_out">
                 <field field_ref="phis" level="1" />
                 <field field_ref="aire" level="1" operation="once" />
@@ -81,12 +84,12 @@
                 <field field_ref="SWdnTOAclr" level="10" />
                 <field field_ref="nettop" level="10" />
-                <field field_ref="SWup200" level="10" />
-                <field field_ref="SWup200clr" level="10" />
-                <field field_ref="SWdn200" level="10" />
-                <field field_ref="SWdn200clr" level="10" />
-                <field field_ref="LWup200" level="10" />
-                <field field_ref="LWup200clr" level="10" />
-                <field field_ref="LWdn200" level="10" />
-                <field field_ref="LWdn200clr" level="10" />
+                <field field_ref="SWup200" level="15" />
+                <field field_ref="SWup200clr" level="15" />
+                <field field_ref="SWdn200" level="15" />
+                <field field_ref="SWdn200clr" level="15" />
+                <field field_ref="LWup200" level="15" />
+                <field field_ref="LWup200clr" level="15" />
+                <field field_ref="LWdn200" level="15" />
+                <field field_ref="LWdn200clr" level="15" />
                 <field field_ref="sols" level="10" />
                 <field field_ref="sols0" level="10" />
@@ -239,5 +242,5 @@
                 <field field_ref="alp_bl_stat" level="10" />
 
-                <field_group operation="average" freq_op="1ts" detect_missing_value=".true.">
+                <field_group operation="average" detect_missing_value=".true.">
                     <field field_ref="u850" level="10" />
                     <field field_ref="u700" level="10" />
@@ -301,22 +304,6 @@
                 <field field_ref="tpot" level="10" />
                 <field field_ref="tpote" level="10" />
-                <field field_ref="tke" level="10" />
-                <field field_ref="tke_ter" level="10" />
-                <field field_ref="tke_lic" level="10" />
-                <field field_ref="tke_oce" level="10" />
-                <field field_ref="tke_sic" level="10" />
-                <field field_ref="tke_max_ter" level="10" operation="maximum" />
-                <field field_ref="tke_max_lic" level="10" operation="maximum" />
-                <field field_ref="tke_max_oce" level="10" operation="maximum" />
-                <field field_ref="tke_max_sic" level="10" operation="maximum" />
-                <field field_ref="l_mix_ter" level="10" />
-                <field field_ref="l_mix_lic" level="10" />
-                <field field_ref="l_mix_oce" level="10" />
-                <field field_ref="l_mix_sic" level="10" />
-                <field field_ref="l_mixmin_ter" level="10" />
-                <field field_ref="l_mixmin_lic" level="10" />
-                <field field_ref="l_mixmin_oce" level="10" />
-                <field field_ref="l_mixmin_sic" level="10" />
                 <field field_ref="SWnetOR" level="10" />
+                <field field_ref="SWdownOR" level="10" />
                 <field field_ref="LWdownOR" level="10" />
                 <field field_ref="snowl" level="10" />
@@ -385,5 +372,4 @@
                 <field field_ref="lcc" level="10" />
                 <field field_ref="wvapp" level="10" />
-                <field field_ref="ozone_daylight" level="10" />
                 <field field_ref="albe_ter" level="10" />
                 <field field_ref="albe_lic" level="10" />
@@ -414,5 +400,4 @@
                 <field field_ref="ftime_con" level="10" operation="instant" />
                 <field field_ref="wake_h" level="10" />
-                <field field_ref="wake_dens" level="10" />
                 <field field_ref="wake_s" level="10" />
                 <field field_ref="epmax" level="10" />
@@ -446,5 +431,24 @@
 
             <!-- VARS 3D -->
-            <field_group operation="average" freq_op="1ts" grid_ref="grid_glo_presnivs">
+            <field_group operation="average" grid_ref="grid_out_presnivs" >
+                <field field_ref="tke" level="10" />
+                <field field_ref="tke_ter" level="10" />
+                <field field_ref="tke_lic" level="10" />
+                <field field_ref="tke_oce" level="10" />
+                <field field_ref="tke_sic" level="10" />
+                <field field_ref="tke_max_ter" level="10" operation="maximum" />
+                <field field_ref="tke_max_lic" level="10" operation="maximum" />
+                <field field_ref="tke_max_oce" level="10" operation="maximum" />
+                <field field_ref="tke_max_sic" level="10" operation="maximum" />
+                <field field_ref="l_mix_ter" level="10" />
+                <field field_ref="l_mix_lic" level="10" />
+                <field field_ref="l_mix_oce" level="10" />
+                <field field_ref="l_mix_sic" level="10" />
+                <field field_ref="l_mixmin_ter" level="10" />
+                <field field_ref="l_mixmin_lic" level="10" />
+                <field field_ref="l_mixmin_oce" level="10" />
+                <field field_ref="l_mixmin_sic" level="10" />
+
+
                 <field field_ref="cldtau" level="10" />
                 <field field_ref="cldemi" level="10" />
@@ -483,4 +487,5 @@
                 <field field_ref="rhum" level="10" />
                 <field field_ref="ozone" level="10" />
+                <field field_ref="ozone_daylight" level="10" />
                 <field field_ref="upwd" level="10" />
                 <field field_ref="ep" level="10" />
@@ -616,4 +621,6 @@
                 <field field_ref="rldcs4co2" level="10" />
             </field_group>
+          </field_group>
+          
         </file>
     </file_group>
Index: /LMDZ6/branches/Ocean_skin/DefLists/file_def_histdayCOSP_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/file_def_histdayCOSP_lmdz.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/file_def_histdayCOSP_lmdz.xml	(revision 3605)
@@ -1,98 +1,99 @@
 <file_definition>
       <file_group id="defile">
-        <file id="histdayCOSP" name="histdayCOSP" output_freq="1d" output_level="1"  enabled=".TRUE.">
-            <!-- VARS Calipso and PARASOL -->
-            <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
-                <field field_ref="cllcalipso"         level="1" />
-                <field field_ref="clmcalipso"         level="1" />
-                <field field_ref="clhcalipso"         level="1" />
-                <field field_ref="cltcalipso"         level="1" />
-                <field field_ref="pcllcalipso"         level="1" />
-                <field field_ref="pclmcalipso"         level="1" />
-                <field field_ref="pclhcalipso"         level="1" />
-                <field field_ref="pcltcalipso"         level="1" />
-                <field field_ref="cllcalipsoice"         level="1" />
-                <field field_ref="clmcalipsoice"         level="1" />
-                <field field_ref="clhcalipsoice"         level="1" />
-                <field field_ref="cltcalipsoice"         level="1" />
-                <field field_ref="cllcalipsoliq"         level="1" />
-                <field field_ref="clmcalipsoliq"         level="1" />
-                <field field_ref="clhcalipsoliq"         level="1" />
-                <field field_ref="cltcalipsoliq"         level="1" />
-                <field field_ref="cllcalipsoun"         level="1" />
-                <field field_ref="clmcalipsoun"         level="1" />
-                <field field_ref="clhcalipsoun"         level="1" />
-                <field field_ref="cltcalipsoun"         level="1" />
-                <field field_ref="clcalipso"  level="1" />
-                <field field_ref="clcalipsoice"  level="1" />
-                <field field_ref="clcalipsoliq"  level="1" />
-                <field field_ref="clcalipsoun"  level="1" />
-                <field field_ref="clcalipsotmp"  level="1" />
-                <field field_ref="clcalipsotmpice"  level="1" />
-                <field field_ref="clcalipsotmpliq"  level="1" />
-                <field field_ref="clcalipsotmpun"  level="1" />
-                <field field_ref="parasol_refl"  level="1" />
-                <field field_ref="parasol_crefl"  level="1" />
-                <field field_ref="Ncrefl"  level="1" />
-       		    <field field_ref="cfad_lidarsr532"  level="10" />
-                <field field_ref="atb532" level="10" />
-                <field field_ref="beta_mol532" level="10" />
-                <field field_ref="clopaquecalipso"         level="1" />
-                <field field_ref="clthincalipso"           level="1" />
-                <field field_ref="clzopaquecalipso"        level="1" />
-                <field field_ref="clcalipsoopaque"   level="1" />
-                <field field_ref="clcalipsothin"     level="1" />
-                <field field_ref="clcalipsozopaque"  level="1" />
-                <field field_ref="clcalipsoopacity"  level="1" />
-                <field field_ref="proftemp"  level="1" />
-                <field field_ref="profSR"  level="1" />
+        <file id="histdayCOSP" name="histdayCOSP" output_freq="1d" output_level="_AUTO_"  enabled="_AUTO_" compression_level="0">
+          
+            <field_group group_ref="remap_1d">
+              <!-- VARS Calipso and PARASOL -->
+              <field_group operation="average" freq_op="3h" detect_missing_value=".true." >
+                <field field_ref="cllcalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clmcalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clhcalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="cltcalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="pcllcalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="pclmcalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="pclhcalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="pcltcalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="cllcalipsoice"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clmcalipsoice"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clhcalipsoice"         level="5" grid_ref="grid_out"/>
+                <field field_ref="cltcalipsoice"         level="5" grid_ref="grid_out"/>
+                <field field_ref="cllcalipsoliq"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clmcalipsoliq"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clhcalipsoliq"         level="5" grid_ref="grid_out"/>
+                <field field_ref="cltcalipsoliq"         level="5"grid_ref="grid_out" />
+                <field field_ref="cllcalipsoun"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clmcalipsoun"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clhcalipsoun"         level="5" grid_ref="grid_out"/>
+                <field field_ref="cltcalipsoun"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clcalipso"  level="5" grid_ref="grid_out_height"/>
+                <field field_ref="clcalipsoice"  level="5" grid_ref="grid_out_height"/>
+                <field field_ref="clcalipsoliq"  level="5" grid_ref="grid_out_height"/>
+                <field field_ref="clcalipsoun"  level="5" grid_ref="grid_out_height"/>
+                <field field_ref="clcalipsotmp"  level="5" grid_ref="grid_out_temp"/>
+                <field field_ref="clcalipsotmpice"  level="5" grid_ref="grid_out_temp"/>
+                <field field_ref="clcalipsotmpliq"  level="5" grid_ref="grid_out_temp"/>
+                <field field_ref="clcalipsotmpun"  level="5" grid_ref="grid_out_temp"/>
+                <field field_ref="parasol_refl"  level="5" grid_ref="grid_out_sza"/>
+                <field field_ref="parasol_crefl"  level="5" grid_ref="grid_out_sza"/>
+                <field field_ref="Ncrefl"  level="5" grid_ref="grid_out_sza"/>
+       		<field field_ref="cfad_lidarsr532"  level="10" grid_ref="grid4Dsrbin_out"/>
+                <field field_ref="atb532" level="10"grid_ref="grid4Dcol_out" />
+                <field field_ref="beta_mol532" level="10" grid_ref="grid_out_heightmlev"/>
+                <field field_ref="clopaquecalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clthincalipso"           level="5" grid_ref="grid_out"/>
+                <field field_ref="clzopaquecalipso"        level="5" grid_ref="grid_out"/>
+                <field field_ref="clcalipsoopaque"   level="5" grid_ref="grid_out_height"/>
+                <field field_ref="clcalipsothin"     level="5" grid_ref="grid_out_height"/>
+                <field field_ref="clcalipsozopaque"  level="5" grid_ref="grid_out_height"/>
+                <field field_ref="clcalipsoopacity"  level="5" grid_ref="grid_out_height"/>
+                <field field_ref="proftemp"  level="5" grid_ref="grid_out_height" />
+                <field field_ref="profSR"  level="5" grid_ref="grid4Dcol2_out"/>
               </field_group>
-             <!-- VARS CLOUDSAT et/ou Calipso -->
-            <field_group operation="average" freq_op="3h" detect_missing_value=".true."> 
-               <field field_ref="cltlidarradar"  level="1"/>
-               <field field_ref="clcalipso2"  level="1" />
-               <field field_ref="cfadDbze94"  level="10" />
-               <field field_ref="dbze94" level="10" />
+            <!-- VARS CLOUDSAT et/ou Calipso -->
+             <field_group operation="average" freq_op="3h" detect_missing_value=".true.">                       <field field_ref="cltlidarradar"  level="5" grid_ref="grid_out"/>
+               <field field_ref="clcalipso2"  level="5" grid_ref="grid_out_height"/>
+               <field field_ref="cfadDbze94"  level="10" grid_ref="grid4Ddbze_out"/>
+               <field field_ref="dbze94" level="10" grid_ref="grid4Dcol_out" />
               </field_group>
              <!-- VARS ISCCP -->
-            <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
-                <field field_ref="sunlit" level="1" />
-                <field field_ref="clisccp2" level="1" />
-                <field field_ref="boxtauisccp" level="1" />
-                <field field_ref="boxptopisccp" level="1" />
-                <field field_ref="tclisccp" level="1" />
-                <field field_ref="ctpisccp" level="1" />
-                <field field_ref="tauisccp" level="1" /> 
-                <field field_ref="albisccp" level="1" />
-                <field field_ref="meantbisccp" level="10" />
-                <field field_ref="meantbclrisccp" level="10" />
+             <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
+                <field field_ref="sunlit" level="5" grid_ref="grid_out"/>
+                <field field_ref="clisccp2" level="5"grid_ref="grid4Dtau_out" />
+                <field field_ref="boxtauisccp" level="5" grid_ref="grid_out_column"/>
+                <field field_ref="boxptopisccp" level="5" grid_ref="grid_out_column"/>
+                <field field_ref="tclisccp" level="5" grid_ref="grid_out"/>
+                <field field_ref="ctpisccp" level="5" grid_ref="grid_out"/>
+                <field field_ref="tauisccp" level="5"grid_ref="grid_out" /> 
+                <field field_ref="albisccp" level="5" grid_ref="grid_out"/>
+                <field field_ref="meantbisccp" level="10" grid_ref="grid_out"/>
+                <field field_ref="meantbclrisccp" level="10"grid_ref="grid_out" />
              </field_group>
              <!-- VARS MISR -->
             <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
-                <field field_ref="clMISR" level="1" />
+                <field field_ref="clMISR" level="5" grid_ref="grid4Dmisr_out"/>
             </field_group>
             <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
-                <field field_ref="cllmodis" level="1" />
-                <field field_ref="clmmodis" level="1" />
-                <field field_ref="clhmodis" level="1" />
-                <field field_ref="cltmodis" level="1" />
-                <field field_ref="clwmodis" level="1" />
-                <field field_ref="climodis" level="1" />
-                <field field_ref="tautmodis" level="1" />
-                <field field_ref="tauwmodis" level="1" />
-                <field field_ref="tauimodis" level="1" />
-                <field field_ref="tautlogmodis" level="1" />
-                <field field_ref="tauilogmodis" level="1" />
-                <field field_ref="tauwlogmodis" level="1" />
-                <field field_ref="reffclwmodis" level="1" />
-                <field field_ref="reffclimodis" level="1" />
-                <field field_ref="pctmodis"  level="1" />
-                <field field_ref="lwpmodis" level="1" />
-                <field field_ref="iwpmodis" level="1" />
-                <field field_ref="clmodis" level="1" />
-                <field field_ref="crimodis" level="10" />
-                <field field_ref="crlmodis" level="10" />
+                <field field_ref="cllmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="clmmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="clhmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="cltmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="clwmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="climodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="tautmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="tauwmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="tauimodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="tautlogmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="tauilogmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="tauwlogmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="reffclwmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="reffclimodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="pctmodis"  level="5" grid_ref="grid_out"/>
+                <field field_ref="lwpmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="iwpmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="clmodis" level="5" grid_ref="grid4Dtau_out"/>
+                <field field_ref="crimodis" level="10" grid_ref="grid4Dreffi_out"/>
+                <field field_ref="crlmodis" level="10" grid_ref="grid4Dreffl_out"/>
             </field_group>
-
+          </field_group>
         </file>
      </file_group>
Index: /LMDZ6/branches/Ocean_skin/DefLists/file_def_histdayCOSPv2_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/file_def_histdayCOSPv2_lmdz.xml	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/DefLists/file_def_histdayCOSPv2_lmdz.xml	(revision 3605)
@@ -0,0 +1,147 @@
+<file_definition>
+      <file_group id="defile">
+        <file id="histdayCOSP" name="histdayCOSP" output_freq="1d" output_level="1" type="one_file" enabled=".TRUE.">
+            <!-- VARS LIDAR -->
+            <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
+            <!-- VARS CALIPSO -->
+                <field field_ref="cllcalipso"           level="1" />
+                <field field_ref="clmcalipso"           level="1" />
+                <field field_ref="clhcalipso"           level="1" />
+                <field field_ref="cltcalipso"           level="1" />
+                <field field_ref="pcllcalipso"          level="10" />
+                <field field_ref="pclmcalipso"          level="10" />
+                <field field_ref="pclhcalipso"          level="10" />
+                <field field_ref="pcltcalipso"          level="10" />
+                <field field_ref="cllcalipsoice"        level="1" />
+                <field field_ref="clmcalipsoice"        level="1" />
+                <field field_ref="clhcalipsoice"        level="1" />
+                <field field_ref="cltcalipsoice"        level="1" />
+                <field field_ref="cllcalipsoliq"        level="1" />
+                <field field_ref="clmcalipsoliq"        level="1" />
+                <field field_ref="clhcalipsoliq"        level="1" />
+                <field field_ref="cltcalipsoliq"        level="1" />
+                <field field_ref="cllcalipsoun"         level="1" />
+                <field field_ref="clmcalipsoun"         level="1" />
+                <field field_ref="clhcalipsoun"         level="1" />
+                <field field_ref="cltcalipsoun"         level="1" />
+                <field field_ref="clcalipso"            level="1" />
+                <field field_ref="clcalipsoice"         level="1" />
+                <field field_ref="clcalipsoliq"         level="1" />
+                <field field_ref="clcalipsoun"          level="1" />
+                <field field_ref="clcalipsotmp"         level="1" />
+                <field field_ref="clcalipsotmpice"      level="1" />
+                <field field_ref="clcalipsotmpliq"      level="1" />
+                <field field_ref="clcalipsotmpun"       level="1" />
+       		<field field_ref="cfadLidarsr532"       level="1" />
+                <field field_ref="atb532"               level="1" />
+                <field field_ref="lidarBetaMol532"      level="1" />
+                <field field_ref="clopaquecalipso"      level="1" />
+                <field field_ref="clthincalipso"        level="1" />
+                <field field_ref="clzopaquecalipso"     level="1" />
+                <field field_ref="clcalipsoopaque"      level="1" />
+                <field field_ref="clcalipsothin"        level="1" />
+                <field field_ref="clcalipsozopaque"     level="1" />
+                <field field_ref="clcalipsoopacity"     level="1" />
+                <field field_ref="clopaquetemp"         level="1" />
+                <field field_ref="clthintemp"           level="1" />
+                <field field_ref="clzopaquetemp"        level="1" />
+                <field field_ref="clopaquemeanz"        level="1" />
+                <field field_ref="clthinmeanz"          level="1" />
+                <field field_ref="clthinemis"           level="1" />
+                <field field_ref="clopaquemeanzse"      level="1" />
+                <field field_ref="clthinmeanzse"        level="1" />
+                <field field_ref="clzopaquecalipsose"   level="1" />
+            <!-- VARS GROUND LIDAR 532 nm -->
+                <field field_ref="cllgrLidar532"        level="1" />
+                <field field_ref="clmgrLidar532"        level="1" />
+                <field field_ref="clhgrLidar532"        level="1" />
+                <field field_ref="cltgrLidar532"        level="1" />
+                <field field_ref="clgrLidar532"         level="1" />
+       		<field field_ref="cfadLidarsr532gr"     level="1" />
+                <field field_ref="atb532gr"             level="1" />
+                <field field_ref="lidarBetaMol532gr"    level="1" />
+            <!-- VARS ATLID -->
+                <field field_ref="cllatlid"             level="1" />
+                <field field_ref="clmatlid"             level="1" />
+                <field field_ref="clhatlid"             level="1" />
+                <field field_ref="cltatlid"             level="1" />
+                <field field_ref="clatlid"              level="1" />
+       		<field field_ref="cfadLidarsr355"       level="1" />
+                <field field_ref="atb355"               level="1" />
+                <field field_ref="lidarBetaMol355"      level="1" />
+              </field_group>
+             <!-- VARS PARASOL -->
+            <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
+                <field field_ref="parasolPix_refl"      level="1" />
+                <field field_ref="parasolGrid_refl"     level="1" />
+<!--                <field field_ref="Ncrefl"  level="1" /> -->
+              </field_group>
+             <!-- VARS CLOUDSAT et/ou CALIPSO -->
+            <field_group operation="average" freq_op="3h" detect_missing_value=".true."> 
+               <field field_ref="cltlidarradar"         level="1"/>
+               <field field_ref="clcalipso2"            level="1" />
+               <field field_ref="cloudsat_tcc"          level="1" />
+               <field field_ref="cloudsat_tcc2"         level="1" />
+              </field_group>
+             <!-- VARS CLOUDSAT -->
+            <field_group operation="average" freq_op="3h" detect_missing_value=".true."> 
+               <field field_ref="cfadDbze94"            level="1" />
+               <field field_ref="dbze94"                level="1" />
+               <field field_ref="ptradarflag0"          level="1" />
+               <field field_ref="ptradarflag1"          level="1" />
+               <field field_ref="ptradarflag2"          level="1" />
+               <field field_ref="ptradarflag3"          level="1" />
+               <field field_ref="ptradarflag4"          level="1" />
+               <field field_ref="ptradarflag5"          level="1" />
+               <field field_ref="ptradarflag6"          level="1" />
+               <field field_ref="ptradarflag7"          level="1" />
+               <field field_ref="ptradarflag8"          level="1" />
+               <field field_ref="ptradarflag9"          level="1" />
+               <field field_ref="radarpia"              level="1" />
+              </field_group>
+             <!-- VARS ISCCP -->
+            <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
+<!--                <field field_ref="sunlit" level="1" /> -->
+                <field field_ref="clisccp"             level="1" />
+                <field field_ref="boxtauisccp"         level="1" />
+                <field field_ref="boxptopisccp"        level="1" />
+                <field field_ref="cltisccp"            level="1" />
+                <field field_ref="pctisccp"            level="1" />
+                <field field_ref="tauisccp"            level="1" /> 
+                <field field_ref="albisccp"            level="1" />
+                <field field_ref="meantbisccp"         level="1" />
+                <field field_ref="meantbclrisccp"      level="1" />
+             </field_group>
+             <!-- VARS MISR -->
+            <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
+                <field field_ref="misr_fq"             level="1" />
+                <field field_ref="misr_meanztop"       level="1" />
+                <field field_ref="misr_cldarea"        level="1" />
+            </field_group>
+             <!-- VARS MODIS -->
+            <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
+                <field field_ref="cllmodis"            level="1" />
+                <field field_ref="clmmodis"            level="1" />
+                <field field_ref="clhmodis"            level="1" />
+                <field field_ref="cltmodis"            level="1" />
+                <field field_ref="clwmodis"            level="1" />
+                <field field_ref="climodis"            level="1" />
+                <field field_ref="tautmodis"           level="1" />
+                <field field_ref="tauwmodis"           level="1" />
+                <field field_ref="tauimodis"           level="1" />
+                <field field_ref="tautlogmodis"        level="1" />
+                <field field_ref="tauilogmodis"        level="1" />
+                <field field_ref="tauwlogmodis"        level="1" />
+                <field field_ref="reffclwmodis"        level="1" />
+                <field field_ref="reffclimodis"        level="1" />
+                <field field_ref="pctmodis"            level="1" />
+                <field field_ref="lwpmodis"            level="1" />
+                <field field_ref="iwpmodis"            level="1" />
+                <field field_ref="modis_ot_vs_ctp"     level="1" />
+                <field field_ref="modis_ot_vs_reffice" level="1" />
+                <field field_ref="modis_ot_vs_reffliq" level="1" />
+            </field_group>
+
+        </file>
+     </file_group>
+</file_definition>
Index: /LMDZ6/branches/Ocean_skin/DefLists/file_def_histdayNMC_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/file_def_histdayNMC_lmdz.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/file_def_histdayNMC_lmdz.xml	(revision 3605)
@@ -1,5 +1,5 @@
 <file_definition>
     <file_group id="defile">
-        <file id="histdayNMC" name="histdayNMC" output_freq="1d" output_level="5" enabled="_AUTO_">
+        <file id="histdayNMC" name="histdayNMC" output_freq="1d" output_level="5" enabled="_AUTO_" compression_level="4">
 
             <!-- VARS 3D -->
Index: /LMDZ6/branches/Ocean_skin/DefLists/file_def_histday_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/file_def_histday_lmdz.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/file_def_histday_lmdz.xml	(revision 3605)
@@ -1,5 +1,6 @@
-<file_definition>
+<!-- $Id$ -->
+<file_definition type="one_file">
     <file_group id="defile">
-        <file id="histday" name="histday" output_freq="1d" output_level="2" enabled="_AUTO_">
+        <file id="histday" name="histday" output_freq="1d" output_level="_AUTO_" enabled="_AUTO_" compression_level="2" sync_freq="1d">
             
             <!-- VARS 1D -->
@@ -11,5 +12,7 @@
         
             <!-- VARS 2D -->
-            <field_group operation="average" freq_op="1ts">
+           <field_group group_ref="remap_1d">
+           
+              <field_group operation="average" grid_ref="grid_out" >
                 <field field_ref="phis" level="1" />
                 <field field_ref="aire" level="1" operation="once" />
@@ -81,12 +84,12 @@
                 <field field_ref="SWdnTOAclr" level="4" />
                 <field field_ref="nettop" level="4" />
-                <field field_ref="SWup200" level="10" />
-                <field field_ref="SWup200clr" level="1" />
-                <field field_ref="SWdn200" level="10" />
-                <field field_ref="SWdn200clr" level="1" />
-                <field field_ref="LWup200" level="10" />
-                <field field_ref="LWup200clr" level="10" />
-                <field field_ref="LWdn200" level="10" />
-                <field field_ref="LWdn200clr" level="10" />
+                <field field_ref="SWup200" level="15" />
+                <field field_ref="SWup200clr" level="15" />
+                <field field_ref="SWdn200" level="15" />
+                <field field_ref="SWdn200clr" level="15" />
+                <field field_ref="LWup200" level="15" />
+                <field field_ref="LWup200clr" level="15" />
+                <field field_ref="LWdn200" level="15" />
+                <field field_ref="LWdn200clr" level="15" />
                 <field field_ref="sols" level="1" />
                 <field field_ref="sols0" level="5" />
@@ -193,4 +196,5 @@
                 <field field_ref="cdrh" level="10" />
                 <field field_ref="cldl" level="1" />
+                <field field_ref="cumCO2" level="5" />
                 <field field_ref="cldm" level="1" />
                 <field field_ref="cldh" level="1" />
@@ -242,47 +246,47 @@
                 <field field_ref="colO3_trop"  level="6" />     <!-- Added ThL -->
 
-                <field_group operation="average" freq_op="1ts" detect_missing_value=".true.">
-                    <field field_ref="u850" level="7" />
-                    <field field_ref="u700" level="7" />
-                    <field field_ref="u500" level="7" />
-                    <field field_ref="u200" level="7" />
-                    <field field_ref="u100" level="7" />
-                    <field field_ref="u50" level="7" />
-                    <field field_ref="u10" level="7" />
-                    <field field_ref="v850" level="7" />
-                    <field field_ref="v700" level="7" />
-                    <field field_ref="v500" level="7" />
-                    <field field_ref="v200" level="7" />
-                    <field field_ref="v100" level="7" />
-                    <field field_ref="v50" level="7" />
-                    <field field_ref="v10" level="7" />
-                    <field field_ref="w850" level="7" />
-                    <field field_ref="w700" level="7" />
-                    <field field_ref="w500" level="7" />
-                    <field field_ref="w200" level="7" />
-                    <field field_ref="w100" level="7" />
-                    <field field_ref="w50" level="7" />
-                    <field field_ref="w10" level="7" />
-                    <field field_ref="t850" level="7" />
-                    <field field_ref="t700" level="7" />
-                    <field field_ref="t500" level="7" />
-                    <field field_ref="t200" level="7" />
-                    <field field_ref="t100" level="7" />
-                    <field field_ref="t50" level="7" />
-                    <field field_ref="t10" level="7" />
-                    <field field_ref="q850" level="7" />
-                    <field field_ref="q700" level="7" />
-                    <field field_ref="q500" level="7" />
-                    <field field_ref="q200" level="7" />
-                    <field field_ref="q100" level="7" />
-                    <field field_ref="q50" level="7" />
-                    <field field_ref="q10" level="7" />
-                    <field field_ref="z850" level="7" />
-                    <field field_ref="z700" level="7" />
-                    <field field_ref="z500" level="7" />
-                    <field field_ref="z200" level="7" />
-                    <field field_ref="z100" level="7" />
-                    <field field_ref="z50" level="7" />
-                    <field field_ref="z10" level="7" />
+                <field_group operation="average" detect_missing_value=".true.">
+                    <field field_ref="u850" level="10" />
+                    <field field_ref="u700" level="10" />
+                    <field field_ref="u500" level="10" />
+                    <field field_ref="u200" level="10" />
+                    <field field_ref="u100" level="10" />
+                    <field field_ref="u50" level="10" />
+                    <field field_ref="u10" level="10" />
+                    <field field_ref="v850" level="10" />
+                    <field field_ref="v700" level="10" />
+                    <field field_ref="v500" level="10" />
+                    <field field_ref="v200" level="10" />
+                    <field field_ref="v100" level="10" />
+                    <field field_ref="v50" level="10" />
+                    <field field_ref="v10" level="10" />
+                    <field field_ref="w850" level="10" />
+                    <field field_ref="w700" level="10" />
+                    <field field_ref="w500" level="10" />
+                    <field field_ref="w200" level="10" />
+                    <field field_ref="w100" level="10" />
+                    <field field_ref="w50" level="10" />
+                    <field field_ref="w10" level="10" />
+                    <field field_ref="t850" level="10" />
+                    <field field_ref="t700" level="10" />
+                    <field field_ref="t500" level="10" />
+                    <field field_ref="t200" level="10" />
+                    <field field_ref="t100" level="10" />
+                    <field field_ref="t50" level="10" />
+                    <field field_ref="t10" level="10" />
+                    <field field_ref="q850" level="10" />
+                    <field field_ref="q700" level="10" />
+                    <field field_ref="q500" level="10" />
+                    <field field_ref="q200" level="10" />
+                    <field field_ref="q100" level="10" />
+                    <field field_ref="q50" level="10" />
+                    <field field_ref="q10" level="10" />
+                    <field field_ref="z850" level="10" />
+                    <field field_ref="z700" level="10" />
+                    <field field_ref="z500" level="10" />
+                    <field field_ref="z200" level="10" />
+                    <field field_ref="z100" level="10" />
+                    <field field_ref="z50" level="10" />
+                    <field field_ref="z10" level="10" />
                 </field_group>
 
@@ -305,4 +309,5 @@
                 <field field_ref="tpote" level="5" />
                 <field field_ref="SWnetOR" level="10" />
+                <field field_ref="SWdownOR" level="10" />
                 <field field_ref="LWdownOR" level="10" />
                 <field field_ref="snowl" level="1" />
@@ -316,12 +321,12 @@
                 <field field_ref="z0m" level="10" />
                 <field field_ref="z0h" level="10" />
-                <field field_ref="topswad" level="10" />
-                <field field_ref="topswad0" level="10" />
+                <field field_ref="topswad" level="1" />
+                <field field_ref="topswad0" level="1" />
                 <field field_ref="topswai" level="10" />
                 <field field_ref="solswad" level="10" />
                 <field field_ref="solswad0" level="10" />
                 <field field_ref="solswai" level="10" />
-                <field field_ref="toplwad" level="10" />
-                <field field_ref="toplwad0" level="10" />
+                <field field_ref="toplwad" level="1" />
+                <field field_ref="toplwad0" level="1" />
                 <field field_ref="toplwai" level="10" />
                 <field field_ref="sollwad" level="10" />
@@ -438,5 +443,9 @@
 
             <!-- VARS 3D -->
-            <field_group operation="average" freq_op="1ts" grid_ref="grid_glo_presnivs">
+            <field_group operation="average" grid_ref="grid_out_presnivs">
+                <field field_ref="CO2" level="5" />
+                <field field_ref="dCO2_vdf" level="5" />
+                <field field_ref="dCO2_the" level="5" />
+                <field field_ref="dCO2_con" level="5" />
                 <field field_ref="cldtau" level="5" />
                 <field field_ref="cldemi" level="5" />
@@ -630,4 +639,6 @@
                 <field field_ref="ozone_daylight" level="10" />
             </field_group>
+            
+          </field_group>
         </file>
     </file_group>
Index: /LMDZ6/branches/Ocean_skin/DefLists/file_def_histdaystrataer_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/file_def_histdaystrataer_lmdz.xml	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/DefLists/file_def_histdaystrataer_lmdz.xml	(revision 3605)
@@ -0,0 +1,12 @@
+<file_definition>
+    <file_group id="defile">
+        <file id="histdaystrataer" name="histdaystrataer" output_freq="1d" output_level="5" enabled="_AUTO_" compression_level="4">
+
+            <field_group group_ref="fields_strataer_3D" operation="average" freq_op="1ts" level="1" />
+            <field_group group_ref="fields_strataer_2D" operation="average" freq_op="1ts" level="1" />
+            <field_group group_ref="fields_strataer_trac_3D" operation="average" freq_op="1ts" level="1" />
+            <field_group group_ref="fields_strataer_trac_2D" operation="average" freq_op="1ts" level="1" />
+            
+        </file>
+    </file_group>
+</file_definition>
Index: /LMDZ6/branches/Ocean_skin/DefLists/file_def_histhfCOSP_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/file_def_histhfCOSP_lmdz.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/file_def_histhfCOSP_lmdz.xml	(revision 3605)
@@ -1,38 +1,38 @@
 <file_definition>
      <file_group id="defile">
-        <file id="histhfCOSP" name="histhfCOSP" output_freq="3h" output_level="1"  enabled=".TRUE.">
+        <file id="histhfCOSP" name="histhfCOSP" output_freq="3h" output_level="0"  enabled=".TRUE." compression_level="4">
             <!-- VARS Calipso and PARASOL -->
             <field_group operation="instant" freq_op="3h" detect_missing_value=".true.">
-                <field field_ref="cllcalipso"         level="1" />
-                <field field_ref="clmcalipso"         level="1" />
-                <field field_ref="clhcalipso"         level="1" />
-                <field field_ref="cltcalipso"         level="1" />
-                <field field_ref="pcllcalipso"         level="1" />
-                <field field_ref="pclmcalipso"         level="1" />
-                <field field_ref="pclhcalipso"         level="1" />
-                <field field_ref="pcltcalipso"         level="1" />
-                <field field_ref="cllcalipsoice"         level="1" />
-                <field field_ref="clmcalipsoice"         level="1" />
-                <field field_ref="clhcalipsoice"         level="1" />
-                <field field_ref="cltcalipsoice"         level="1" />
-                <field field_ref="cllcalipsoliq"         level="1" />
-                <field field_ref="clmcalipsoliq"         level="1" />
-                <field field_ref="clhcalipsoliq"         level="1" />
-                <field field_ref="cltcalipsoliq"         level="1" />
-                <field field_ref="cllcalipsoun"         level="1" />
-                <field field_ref="clmcalipsoun"         level="1" />
-                <field field_ref="clhcalipsoun"         level="1" />
-                <field field_ref="cltcalipsoun"         level="1" />
-                <field field_ref="clcalipso"  level="1" />
-                <field field_ref="clcalipsoice"  level="1" />
-                <field field_ref="clcalipsoliq"  level="1" />
-                <field field_ref="clcalipsoun"  level="1" />
-                <field field_ref="clcalipsotmp"  level="1" />
-                <field field_ref="clcalipsotmpice"  level="1" />
-                <field field_ref="clcalipsotmpliq"  level="1" />
-                <field field_ref="clcalipsotmpun"  level="1" />
-                <field field_ref="parasol_refl"  level="1" />
-                <field field_ref="parasol_crefl"  level="1" />
-                <field field_ref="Ncrefl"  level="1" />
+                <field field_ref="cllcalipso"         level="5" />
+                <field field_ref="clmcalipso"         level="5" />
+                <field field_ref="clhcalipso"         level="5" />
+                <field field_ref="cltcalipso"         level="5" />
+                <field field_ref="pcllcalipso"         level="5" />
+                <field field_ref="pclmcalipso"         level="5" />
+                <field field_ref="pclhcalipso"         level="5" />
+                <field field_ref="pcltcalipso"         level="5" />
+                <field field_ref="cllcalipsoice"         level="5" />
+                <field field_ref="clmcalipsoice"         level="5" />
+                <field field_ref="clhcalipsoice"         level="5" />
+                <field field_ref="cltcalipsoice"         level="5" />
+                <field field_ref="cllcalipsoliq"         level="5" />
+                <field field_ref="clmcalipsoliq"         level="5" />
+                <field field_ref="clhcalipsoliq"         level="5" />
+                <field field_ref="cltcalipsoliq"         level="5" />
+                <field field_ref="cllcalipsoun"         level="5" />
+                <field field_ref="clmcalipsoun"         level="5" />
+                <field field_ref="clhcalipsoun"         level="5" />
+                <field field_ref="cltcalipsoun"         level="5" />
+                <field field_ref="clcalipso"  level="5" />
+                <field field_ref="clcalipsoice"  level="5" />
+                <field field_ref="clcalipsoliq"  level="5" />
+                <field field_ref="clcalipsoun"  level="5" />
+                <field field_ref="clcalipsotmp"  level="5" />
+                <field field_ref="clcalipsotmpice"  level="5" />
+                <field field_ref="clcalipsotmpliq"  level="5" />
+                <field field_ref="clcalipsotmpun"  level="5" />
+                <field field_ref="parasol_refl"  level="5" />
+                <field field_ref="parasol_crefl"  level="5" />
+                <field field_ref="Ncrefl"  level="5" />
        		    <field field_ref="cfad_lidarsr532"  level="10" />
                 <field field_ref="atb532" level="10" />
@@ -45,11 +45,11 @@
                 <field field_ref="clcalipsozopaque"  level="10" />
                 <field field_ref="clcalipsoopacity"  level="10" />
-                <field field_ref="proftemp"  level="1" />
-                <field field_ref="profSR"  level="1" />
+                <field field_ref="proftemp"  level="5" />
+                <field field_ref="profSR"  level="5" />
               </field_group>
              <!-- VARS CLOUDSAT et/ou Calipso -->
             <field_group operation="instant" freq_op="3h" detect_missing_value=".true."> 
-               <field field_ref="cltlidarradar"  level="1"/>
-               <field field_ref="clcalipso2"  level="1" />
+               <field field_ref="cltlidarradar"  level="5"/>
+               <field field_ref="clcalipso2"  level="5" />
                <field field_ref="cfadDbze94"  level="10" />
                <field field_ref="dbze94" level="10" />
@@ -57,12 +57,12 @@
              <!-- VARS ISCCP -->
             <field_group operation="instant" freq_op="3h" detect_missing_value=".true.">
-                <field field_ref="sunlit" level="1" />
-                <field field_ref="clisccp2" level="1" />
-                <field field_ref="boxtauisccp" level="1" />
-                <field field_ref="boxptopisccp" level="1" />
-                <field field_ref="tclisccp" level="1" />
-                <field field_ref="ctpisccp" level="1" />
-                <field field_ref="tauisccp" level="1" /> 
-                <field field_ref="albisccp" level="1" />
+                <field field_ref="sunlit" level="5" />
+                <field field_ref="clisccp2" level="5" />
+                <field field_ref="boxtauisccp" level="5" />
+                <field field_ref="boxptopisccp" level="5" />
+                <field field_ref="tclisccp" level="5" />
+                <field field_ref="ctpisccp" level="5" />
+                <field field_ref="tauisccp" level="5" /> 
+                <field field_ref="albisccp" level="5" />
                 <field field_ref="meantbisccp" level="10" />
                 <field field_ref="meantbclrisccp" level="10" />
@@ -70,25 +70,25 @@
              <!-- VARS MISR -->
             <field_group operation="instant" freq_op="3h" detect_missing_value=".true.">
-                <field field_ref="clMISR" level="1" />
+                <field field_ref="clMISR" level="5" />
             </field_group>
             <field_group operation="instant" freq_op="3h" detect_missing_value=".true.">
-                <field field_ref="cllmodis" level="1" />
-                <field field_ref="clmmodis" level="1" />
-                <field field_ref="clhmodis" level="1" />
-                <field field_ref="cltmodis" level="1" />
-                <field field_ref="clwmodis" level="1" />
-                <field field_ref="climodis" level="1" />
-                <field field_ref="tautmodis" level="1" />
-                <field field_ref="tauwmodis" level="1" />
-                <field field_ref="tauimodis" level="1" />
-                <field field_ref="tautlogmodis" level="1" />
-                <field field_ref="tauilogmodis" level="1" />
-                <field field_ref="tauwlogmodis" level="1" />
-                <field field_ref="reffclwmodis" level="1" />
-                <field field_ref="reffclimodis" level="1" />
-                <field field_ref="pctmodis"  level="1" />
-                <field field_ref="lwpmodis" level="1" />
-                <field field_ref="iwpmodis" level="1" />
-                <field field_ref="clmodis" level="1" />
+                <field field_ref="cllmodis" level="5" />
+                <field field_ref="clmmodis" level="5" />
+                <field field_ref="clhmodis" level="5" />
+                <field field_ref="cltmodis" level="5" />
+                <field field_ref="clwmodis" level="5" />
+                <field field_ref="climodis" level="5" />
+                <field field_ref="tautmodis" level="5" />
+                <field field_ref="tauwmodis" level="5" />
+                <field field_ref="tauimodis" level="5" />
+                <field field_ref="tautlogmodis" level="5" />
+                <field field_ref="tauilogmodis" level="5" />
+                <field field_ref="tauwlogmodis" level="5" />
+                <field field_ref="reffclwmodis" level="5" />
+                <field field_ref="reffclimodis" level="5" />
+                <field field_ref="pctmodis"  level="5" />
+                <field field_ref="lwpmodis" level="5" />
+                <field field_ref="iwpmodis" level="5" />
+                <field field_ref="clmodis" level="5" />
                 <field field_ref="crimodis" level="10" />
                 <field field_ref="crlmodis" level="10" />
Index: /LMDZ6/branches/Ocean_skin/DefLists/file_def_histhfCOSPv2_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/file_def_histhfCOSPv2_lmdz.xml	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/DefLists/file_def_histhfCOSPv2_lmdz.xml	(revision 3605)
@@ -0,0 +1,147 @@
+<file_definition>
+     <file_group id="defile">
+        <file id="histhfCOSP" name="histhfCOSP" output_freq="3h" output_level="0" type="one_file" enabled=".TRUE.">
+            <!-- VARS LIDAR -->
+            <field_group operation="instant" freq_op="3h" detect_missing_value=".true.">
+            <!-- VARS CALIPSO -->
+                <field field_ref="cllcalipso"           level="1" />
+                <field field_ref="clmcalipso"           level="1" />
+                <field field_ref="clhcalipso"           level="1" />
+                <field field_ref="cltcalipso"           level="1" />
+                <field field_ref="pcllcalipso"          level="10" />
+                <field field_ref="pclmcalipso"          level="10" />
+                <field field_ref="pclhcalipso"          level="10" />
+                <field field_ref="pcltcalipso"          level="10" />
+                <field field_ref="cllcalipsoice"        level="1" />
+                <field field_ref="clmcalipsoice"        level="1" />
+                <field field_ref="clhcalipsoice"        level="1" />
+                <field field_ref="cltcalipsoice"        level="1" />
+                <field field_ref="cllcalipsoliq"        level="1" />
+                <field field_ref="clmcalipsoliq"        level="1" />
+                <field field_ref="clhcalipsoliq"        level="1" />
+                <field field_ref="cltcalipsoliq"        level="1" />
+                <field field_ref="cllcalipsoun"         level="1" />
+                <field field_ref="clmcalipsoun"         level="1" />
+                <field field_ref="clhcalipsoun"         level="1" />
+                <field field_ref="cltcalipsoun"         level="1" />
+                <field field_ref="clcalipso"            level="1" />
+                <field field_ref="clcalipsoice"         level="1" />
+                <field field_ref="clcalipsoliq"         level="1" />
+                <field field_ref="clcalipsoun"          level="1" />
+                <field field_ref="clcalipsotmp"         level="1" />
+                <field field_ref="clcalipsotmpice"      level="1" />
+                <field field_ref="clcalipsotmpliq"      level="1" />
+                <field field_ref="clcalipsotmpun"       level="1" />
+       		<field field_ref="cfadLidarsr532"       level="1" />
+                <field field_ref="atb532"               level="1" />
+                <field field_ref="lidarBetaMol532"      level="1" />
+                <field field_ref="clopaquecalipso"      level="1" />
+                <field field_ref="clthincalipso"        level="1" />
+                <field field_ref="clzopaquecalipso"     level="1" />
+                <field field_ref="clcalipsoopaque"      level="1" />
+                <field field_ref="clcalipsothin"        level="1" />
+                <field field_ref="clcalipsozopaque"     level="1" />
+                <field field_ref="clcalipsoopacity"     level="1" />
+                <field field_ref="clopaquetemp"         level="1" />
+                <field field_ref="clthintemp"           level="1" />
+                <field field_ref="clzopaquetemp"        level="1" />
+                <field field_ref="clopaquemeanz"        level="1" />
+                <field field_ref="clthinmeanz"          level="1" />
+                <field field_ref="clthinemis"           level="1" />
+                <field field_ref="clopaquemeanzse"      level="1" />
+                <field field_ref="clthinmeanzse"        level="1" />
+                <field field_ref="clzopaquecalipsose"   level="1" />
+            <!-- VARS GROUND LIDAR 532 nm -->
+                <field field_ref="cllgrLidar532"        level="1" />
+                <field field_ref="clmgrLidar532"        level="1" />
+                <field field_ref="clhgrLidar532"        level="1" />
+                <field field_ref="cltgrLidar532"        level="1" />
+                <field field_ref="clgrLidar532"         level="1" />
+       		<field field_ref="cfadLidarsr532gr"     level="1" />
+                <field field_ref="atb532gr"             level="1" />
+                <field field_ref="lidarBetaMol532gr"    level="1" />
+            <!-- VARS ATLID -->
+                <field field_ref="cllatlid"             level="1" />
+                <field field_ref="clmatlid"             level="1" />
+                <field field_ref="clhatlid"             level="1" />
+                <field field_ref="cltatlid"             level="1" />
+                <field field_ref="clatlid"              level="1" />
+       		<field field_ref="cfadLidarsr355"       level="1" />
+                <field field_ref="atb355"               level="1" />
+                <field field_ref="lidarBetaMol355"      level="1" />
+              </field_group>
+             <!-- VARS PARASOL -->
+            <field_group operation="instant" freq_op="3h" detect_missing_value=".true.">
+                <field field_ref="parasolPix_refl"      level="1" />
+                <field field_ref="parasolGrid_refl"     level="1" />
+<!--                <field field_ref="Ncrefl"  level="1" /> -->
+              </field_group>
+             <!-- VARS CLOUDSAT et/ou CALIPSO -->
+            <field_group operation="instant" freq_op="3h" detect_missing_value=".true."> 
+               <field field_ref="cltlidarradar"         level="1"/>
+               <field field_ref="clcalipso2"            level="1" />
+               <field field_ref="cloudsat_tcc"          level="1" />
+               <field field_ref="cloudsat_tcc2"         level="1" />
+              </field_group>
+             <!-- VARS CLOUDSAT -->
+            <field_group operation="instant" freq_op="3h" detect_missing_value=".true."> 
+               <field field_ref="cfadDbze94"            level="1" />
+               <field field_ref="dbze94"                level="1" />
+               <field field_ref="ptradarflag0"          level="1" />
+               <field field_ref="ptradarflag1"          level="1" />
+               <field field_ref="ptradarflag2"          level="1" />
+               <field field_ref="ptradarflag3"          level="1" />
+               <field field_ref="ptradarflag4"          level="1" />
+               <field field_ref="ptradarflag5"          level="1" />
+               <field field_ref="ptradarflag6"          level="1" />
+               <field field_ref="ptradarflag7"          level="1" />
+               <field field_ref="ptradarflag8"          level="1" />
+               <field field_ref="ptradarflag9"          level="1" />
+               <field field_ref="radarpia"              level="1" />
+              </field_group>
+             <!-- VARS ISCCP -->
+            <field_group operation="instant" freq_op="3h" detect_missing_value=".true.">
+<!--                <field field_ref="sunlit" level="1" /> -->
+                <field field_ref="clisccp"             level="1" />
+                <field field_ref="boxtauisccp"         level="1" />
+                <field field_ref="boxptopisccp"        level="1" />
+                <field field_ref="cltisccp"            level="1" />
+                <field field_ref="pctisccp"            level="1" />
+                <field field_ref="tauisccp"            level="1" /> 
+                <field field_ref="albisccp"            level="1" />
+                <field field_ref="meantbisccp"         level="1" />
+                <field field_ref="meantbclrisccp"      level="1" />
+             </field_group>
+             <!-- VARS MISR -->
+            <field_group operation="instant" freq_op="3h" detect_missing_value=".true.">
+                <field field_ref="misr_fq"             level="1" />
+                <field field_ref="misr_meanztop"       level="1" />
+                <field field_ref="misr_cldarea"        level="1" />
+            </field_group>
+             <!-- VARS MODIS -->
+            <field_group operation="instant" freq_op="3h" detect_missing_value=".true.">
+                <field field_ref="cllmodis"            level="1" />
+                <field field_ref="clmmodis"            level="1" />
+                <field field_ref="clhmodis"            level="1" />
+                <field field_ref="cltmodis"            level="1" />
+                <field field_ref="clwmodis"            level="1" />
+                <field field_ref="climodis"            level="1" />
+                <field field_ref="tautmodis"           level="1" />
+                <field field_ref="tauwmodis"           level="1" />
+                <field field_ref="tauimodis"           level="1" />
+                <field field_ref="tautlogmodis"        level="1" />
+                <field field_ref="tauilogmodis"        level="1" />
+                <field field_ref="tauwlogmodis"        level="1" />
+                <field field_ref="reffclwmodis"        level="1" />
+                <field field_ref="reffclimodis"        level="1" />
+                <field field_ref="pctmodis"            level="1" />
+                <field field_ref="lwpmodis"            level="1" />
+                <field field_ref="iwpmodis"            level="1" />
+                <field field_ref="modis_ot_vs_ctp"     level="1" />
+                <field field_ref="modis_ot_vs_reffice" level="1" />
+                <field field_ref="modis_ot_vs_reffliq" level="1" />
+            </field_group>
+
+        </file>
+     </file_group>
+</file_definition>
Index: /LMDZ6/branches/Ocean_skin/DefLists/file_def_histhfNMC_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/file_def_histhfNMC_lmdz.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/file_def_histhfNMC_lmdz.xml	(revision 3605)
@@ -1,8 +1,11 @@
+<!-- $Id$ -->
 <file_definition>
     <file_group id="defile">
-        <file id="histhfNMC" name="histhfNMC" output_freq="6h" output_level="5" enabled="_AUTO_">
+        <file id="histhfNMC" name="histhfNMC" output_freq="6h" output_level="_AUTO_" enabled="_AUTO_" compression_level="2">
+
+            <field_group group_ref="remap_6h">
 
             <!-- VARS 3D -->
-            <field_group operation="instant" freq_op="1ts" detect_missing_value=".true." >
+              <field_group operation="instant" grid_ref="grid_out_plev" detect_missing_value=".true.">
 <!--            <field field_ref="tnondef" level="5" />  -->
                 <field field_ref="ta" level="1" />
@@ -25,4 +28,5 @@
                 <field field_ref="v2" level="6" />
                 <field field_ref="T2" level="6" />
+              </field_group>
             </field_group>
         </file>
Index: /LMDZ6/branches/Ocean_skin/DefLists/file_def_histhf_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/file_def_histhf_lmdz.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/file_def_histhf_lmdz.xml	(revision 3605)
@@ -1,5 +1,6 @@
+<!-- $Id$ -->
 <file_definition>
     <file_group id="defile">
-        <file id="histhf" name="histhf" output_freq="6h" output_level="5" enabled="_AUTO_">
+        <file id="histhf" name="histhf" output_freq="3h" output_level="_AUTO_" enabled="_AUTO_" compression_level="2" sync_freq="3h">
             
             <!-- VARS 1D -->
@@ -11,15 +12,16 @@
         
             <!-- VARS 2D -->
-            <field_group operation="average" freq_op="1ts">
-                <field field_ref="phis" level="5" />
+            <field_group group_ref="remap_3h" >
+              <field_group grid_ref="grid_out" > 
+                <field field_ref="phis" level="10" />
                 <field field_ref="aire" level="10" operation="once" />
-                <field field_ref="contfracATM" level="10" operation="once" />
-                <field field_ref="contfracOR" level="10" />
-                <field field_ref="flat" level="5" />
+                <field field_ref="contfracATM" level="5" operation="once" />
+                <field field_ref="contfracOR" level="5" />
+                <field field_ref="flat" level="10" />
                 <field field_ref="slp" level="10" />
                 <field field_ref="sza" level="10" />
                 <field field_ref="ptstar" level="10" />
                 <field field_ref="pt0" level="10" />
-                <field field_ref="tsol" level="5" />
+                <field field_ref="tsol" level="10" />
                 <field field_ref="t2m" level="5" />
                 <field field_ref="t2m_min" level="10" operation="minimum" />
@@ -34,9 +36,9 @@
                 <field field_ref="sicf" level="10" />
                 <field field_ref="q2m" level="5" />
-                <field field_ref="ustar" level="5" />
+                <field field_ref="ustar" level="10" />
                 <field field_ref="u10m" level="5" />
                 <field field_ref="v10m" level="5" />
                 <field field_ref="psol" level="5" />
-                <field field_ref="qsurf" level="10" />
+                <field field_ref="qsurf" level="5" />
                 <field field_ref="ustar_ter" level="10" />
                 <field field_ref="ustar_lic" level="10" />
@@ -58,5 +60,5 @@
                 <field field_ref="qsol" level="10" />
                 <field field_ref="ndayrain" level="10" operation="instant" />
-                <field field_ref="precip" level="10" />
+                <field field_ref="precip" level="5" />
                 <field field_ref="rain_fall" level="10" />
                 <field field_ref="rain_con" level="10" />
@@ -64,5 +66,5 @@
                 <field field_ref="plun" level="10" />
                 <field field_ref="pluc" level="10" />
-                <field field_ref="snow" level="10" />
+                <field field_ref="snow" level="5" />
                 <field field_ref="evap" level="10" />
                 <field field_ref="evap_ter" level="10" />
@@ -74,5 +76,5 @@
                 <field field_ref="tops" level="10" />
                 <field field_ref="tops0" level="10" />
-                <field field_ref="topl" level="5" />
+                <field field_ref="topl" level="10" />
                 <field field_ref="topl0" level="10" />
                 <field field_ref="SWupTOA" level="10" />
@@ -81,12 +83,12 @@
                 <field field_ref="SWdnTOAclr" level="10" />
                 <field field_ref="nettop" level="10" />
-                <field field_ref="SWup200" level="10" />
-                <field field_ref="SWup200clr" level="10" />
-                <field field_ref="SWdn200" level="10" />
-                <field field_ref="SWdn200clr" level="10" />
-                <field field_ref="LWup200" level="10" />
-                <field field_ref="LWup200clr" level="10" />
-                <field field_ref="LWdn200" level="10" />
-                <field field_ref="LWdn200clr" level="10" />
+                <field field_ref="SWup200" level="15" />
+                <field field_ref="SWup200clr" level="15" />
+                <field field_ref="SWdn200" level="15" />
+                <field field_ref="SWdn200clr" level="15" />
+                <field field_ref="LWup200" level="15" />
+                <field field_ref="LWup200clr" level="15" />
+                <field field_ref="LWdn200" level="15" />
+                <field field_ref="LWdn200clr" level="15" />
                 <field field_ref="sols" level="10" />
                 <field field_ref="sols0" level="10" />
@@ -102,12 +104,12 @@
                 <field field_ref="LWdnSFC" level="10" />
                 <field field_ref="LWdnSFCclr" level="10" />
-                <field field_ref="bils" level="5" />
-                <field field_ref="bils_tke" level="5" />
-                <field field_ref="bils_diss" level="5" />
-                <field field_ref="bils_ec" level="5" />
-                <field field_ref="bils_kinetic" level="5" />
-                <field field_ref="bils_enthalp" level="5" />
-                <field field_ref="bils_latent" level="5" />
-                <field field_ref="sens" level="5" />
+                <field field_ref="bils" level="10" />
+                <field field_ref="bils_tke" level="10" />
+                <field field_ref="bils_diss" level="10" />
+                <field field_ref="bils_ec" level="10" />
+                <field field_ref="bils_kinetic" level="10" />
+                <field field_ref="bils_enthalp" level="10" />
+                <field field_ref="bils_latent" level="10" />
+                <field field_ref="sens" level="10" />
                 <field field_ref="sens_x" level="11" />
                 <field field_ref="sens_w" level="11" />
@@ -303,5 +305,6 @@
                 <field field_ref="tpote" level="10" />
                 <field field_ref="SWnetOR" level="10" />
-                <field field_ref="LWdownOR" level="10" />
+                <field field_ref="SWdownOR" level="5" />
+                <field field_ref="LWdownOR" level="5" />
                 <field field_ref="snowl" level="10" />
                 <field field_ref="cape_max" level="10" operation="maximum" />
@@ -406,5 +409,5 @@
                 <field field_ref="ftime_deepcv" level="10" />
                 <field field_ref="f0_th" level="10" />
-                <field field_ref="zmax_th" level="5" />
+                <field field_ref="zmax_th" level="10" />
                 <field field_ref="rsut4co2" level="10" />
                 <field field_ref="rlut4co2" level="10" />
@@ -459,5 +462,27 @@
 
             <!-- VARS 3D -->
-            <field_group operation="average" freq_op="1ts" grid_ref="grid_glo_presnivs">
+            <field_group operation="average" grid_ref="grid_out_presnivs">
+                <field field_ref="tke" level="10" />
+                <field field_ref="tke_ter" level="10" />
+                <field field_ref="tke_lic" level="10" />
+                <field field_ref="tke_oce" level="10" />
+                <field field_ref="tke_sic" level="10" />
+                <field field_ref="tke_max_ter" level="10" operation="maximum" />
+                <field field_ref="tke_max_lic" level="10" operation="maximum" />
+                <field field_ref="tke_max_oce" level="10" operation="maximum" />
+                <field field_ref="tke_max_sic" level="10" operation="maximum" />
+                <field field_ref="l_mix_ter" level="10" />
+                <field field_ref="l_mix_lic" level="10" />
+                <field field_ref="l_mix_oce" level="10" />
+                <field field_ref="l_mix_sic" level="10" />
+                <field field_ref="l_mixmin_ter" level="10" />
+                <field field_ref="l_mixmin_lic" level="10" />
+                <field field_ref="l_mixmin_oce" level="10" />
+                <field field_ref="l_mixmin_sic" level="10" />
+                <field field_ref="treedrg_ter" level="10" />
+                <field field_ref="treedrg_lic" level="10" />
+                <field field_ref="treedrg_oce" level="10" />
+                <field field_ref="treedrg_sic" level="10" />
+
                 <field field_ref="cldtau" level="10" />
                 <field field_ref="cldemi" level="10" />
@@ -475,5 +500,5 @@
                 <field field_ref="iwcon" level="10" />
                 <field field_ref="temp" level="10" />
-                <field field_ref="theta" level="5" />
+                <field field_ref="theta" level="10" />
                 <field field_ref="ovap" level="10" />
                 <field field_ref="ovapinit" level="10" />
@@ -482,6 +507,6 @@
                 <field field_ref="geop" level="10" />
                 <field field_ref="geoph" level="10" />
-                <field field_ref="vitu" level="5" />
-                <field field_ref="vitv" level="5" />
+                <field field_ref="vitu" level="10" />
+                <field field_ref="vitv" level="10" />
                 <field field_ref="vitw" level="6" />
                 <field field_ref="pres" level="10" />
@@ -513,10 +538,10 @@
                 <field field_ref="reffclwc" level="10" />
                 <field field_ref="lcc3d" level="10" />
-                <field field_ref="lcc3dcon" level="5" />
-                <field field_ref="lcc3dstra" level="5" />
-                <field field_ref="cldwatmxrat" level="5" />
-                <field field_ref="icc3dcon" level="5" />
-                <field field_ref="icc3dstra" level="5" />
-                <field field_ref="cldicemxrat" level="5" />
+                <field field_ref="lcc3dcon" level="10" />
+                <field field_ref="lcc3dstra" level="10" />
+                <field field_ref="cldwatmxrat" level="10" />
+                <field field_ref="icc3dcon" level="10" />
+                <field field_ref="icc3dstra" level="10" />
+                <field field_ref="cldicemxrat" level="10" />
                 <field field_ref="clwcon" level="10" />
                 <field field_ref="Ma" level="10" />
@@ -584,6 +609,6 @@
                 <field field_ref="dtlw0" level="10" />
                 <field field_ref="dtec" level="10" />
-                <field field_ref="duvdf" level="5" />
-                <field field_ref="dvvdf" level="5" />
+                <field field_ref="duvdf" level="10" />
+                <field field_ref="dvvdf" level="10" />
                 <field field_ref="duoro" level="10" />
                 <field field_ref="dvoro" level="10" />
@@ -628,34 +653,14 @@
                 <field field_ref="rsdcs4co2" level="10" />
                 <field field_ref="rldcs4co2" level="10" />
-                <field field_ref="treedrg_ter" level="5" />
-                <field field_ref="treedrg_lic" level="5" />
-                <field field_ref="treedrg_oce" level="5" />
-                <field field_ref="treedrg_sic" level="5" />
-                <field field_ref="tke" level="5" />
-                <field field_ref="tke_ter" level="10" />
-                <field field_ref="tke_lic" level="10" />
-                <field field_ref="tke_oce" level="10" />
-                <field field_ref="tke_sic" level="10" />
-                <field field_ref="tke_max_ter" level="10" operation="maximum" />
-                <field field_ref="tke_max_lic" level="10" operation="maximum" />
-                <field field_ref="tke_max_oce" level="10" operation="maximum" />
-                <field field_ref="tke_max_sic" level="10" operation="maximum" />
-                <field field_ref="l_mix_ter" level="10" />
-                <field field_ref="l_mix_lic" level="10" />
-                <field field_ref="l_mix_oce" level="10" />
-                <field field_ref="l_mix_sic" level="10" />
-                <field field_ref="l_mixmin_ter" level="10" />
-                <field field_ref="l_mixmin_lic" level="10" />
-                <field field_ref="l_mixmin_oce" level="10" />
-                <field field_ref="l_mixmin_sic" level="10" />
-                <field field_ref="ozone_daylight" level="10" />
-            </field_group>
+              </field_group>
 
-            <!-- VARS 3D -->
-            <field_group operation="average" freq_op="1ts" grid_ref="grid_glo_spectband">
-                <field field_ref="solbnd" level="4" />
-            </field_group>
-
+              <!-- VARS 3D -->
+              <field_group operation="average" grid_ref="grid_out_spectband" >
+                <field field_ref="solbnd" level="10" />
+              </field_group>
+          </field_group>
+        
         </file>
+    
     </file_group>
 </file_definition>
Index: /LMDZ6/branches/Ocean_skin/DefLists/file_def_histins_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/file_def_histins_lmdz.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/file_def_histins_lmdz.xml	(revision 3605)
@@ -1,5 +1,6 @@
+<!-- $Id$ -->
 <file_definition>
     <file_group id="defile">
-        <file id="histins" name="Xhistins" output_freq="1ts" output_level="4" enabled=".FALSE.">
+        <file id="histins" name="Xhistins" output_freq="1ts" output_level="11" enabled="false" compression_level="0">
             
             <!-- VARS 1D -->
@@ -11,5 +12,7 @@
         
             <!-- VARS 2D -->
-            <field_group operation="instant" freq_op="1ts">
+           <field_group >
+
+             <field_group operation="instant"freq_op="1ts" grid_ref="grid_out" >
                 <field field_ref="phis" level="10" />
                 <field field_ref="aire" level="10" operation="once" />
@@ -81,12 +84,12 @@
                 <field field_ref="SWdnTOAclr" level="10" />
                 <field field_ref="nettop" level="10" />
-                <field field_ref="SWup200" level="10" />
-                <field field_ref="SWup200clr" level="10" />
-                <field field_ref="SWdn200" level="10" />
-                <field field_ref="SWdn200clr" level="10" />
-                <field field_ref="LWup200" level="10" />
-                <field field_ref="LWup200clr" level="10" />
-                <field field_ref="LWdn200" level="10" />
-                <field field_ref="LWdn200clr" level="10" />
+                <field field_ref="SWup200" level="15" />
+                <field field_ref="SWup200clr" level="15" />
+                <field field_ref="SWdn200" level="15" />
+                <field field_ref="SWdn200clr" level="15" />
+                <field field_ref="LWup200" level="15" />
+                <field field_ref="LWup200clr" level="15" />
+                <field field_ref="LWdn200" level="15" />
+                <field field_ref="LWdn200clr" level="15" />
                 <field field_ref="sols" level="10" />
                 <field field_ref="sols0" level="10" />
@@ -96,5 +99,5 @@
                 <field field_ref="SWupSFC" level="10" />
                 <field field_ref="SWupSFCclr" level="10" />
-                <field field_ref="SWdnSFC" level="2" />
+                <field field_ref="SWdnSFC" level="10" />
                 <field field_ref="SWdnSFCclr" level="10" />
                 <field field_ref="LWupSFC" level="10" />
@@ -196,4 +199,5 @@
                 <field field_ref="cldh" level="10" />
                 <field field_ref="cldt" level="2" />
+                <field field_ref="cumCO2" level="10" />
                 <field field_ref="cldq" level="10" />
                 <field field_ref="lwp" level="10" />
@@ -241,46 +245,46 @@
 
                 <field_group operation="instant" freq_op="1ts" detect_missing_value=".true.">
-                    <field field_ref="u850" level="7" />
-                    <field field_ref="u700" level="7" />
-                    <field field_ref="u500" level="7" />
-                    <field field_ref="u200" level="7" />
-                    <field field_ref="u100" level="7" />
-                    <field field_ref="u50" level="7" />
-                    <field field_ref="u10" level="7" />
-                    <field field_ref="v850" level="7" />
-                    <field field_ref="v700" level="7" />
-                    <field field_ref="v500" level="7" />
-                    <field field_ref="v200" level="7" />
-                    <field field_ref="v100" level="7" />
-                    <field field_ref="v50" level="7" />
-                    <field field_ref="v10" level="7" />
-                    <field field_ref="w850" level="7" />
-                    <field field_ref="w700" level="7" />
-                    <field field_ref="w500" level="7" />
-                    <field field_ref="w200" level="7" />
-                    <field field_ref="w100" level="7" />
-                    <field field_ref="w50" level="7" />
-                    <field field_ref="w10" level="7" />
-                    <field field_ref="t850" level="7" />
-                    <field field_ref="t700" level="7" />
-                    <field field_ref="t500" level="7" />
-                    <field field_ref="t200" level="7" />
-                    <field field_ref="t100" level="7" />
-                    <field field_ref="t50" level="7" />
-                    <field field_ref="t10" level="7" />
-                    <field field_ref="q850" level="7" />
-                    <field field_ref="q700" level="7" />
-                    <field field_ref="q500" level="7" />
-                    <field field_ref="q200" level="7" />
-                    <field field_ref="q100" level="7" />
-                    <field field_ref="q50" level="7" />
-                    <field field_ref="q10" level="7" />
-                    <field field_ref="z850" level="7" />
-                    <field field_ref="z700" level="7" />
-                    <field field_ref="z500" level="7" />
-                    <field field_ref="z200" level="7" />
-                    <field field_ref="z100" level="7" />
-                    <field field_ref="z50" level="7" />
-                    <field field_ref="z10" level="7" />
+                    <field field_ref="u850" level="10" />
+                    <field field_ref="u700" level="10" />
+                    <field field_ref="u500" level="10" />
+                    <field field_ref="u200" level="10" />
+                    <field field_ref="u100" level="10" />
+                    <field field_ref="u50" level="10" />
+                    <field field_ref="u10" level="10" />
+                    <field field_ref="v850" level="10" />
+                    <field field_ref="v700" level="10" />
+                    <field field_ref="v500" level="10" />
+                    <field field_ref="v200" level="10" />
+                    <field field_ref="v100" level="10" />
+                    <field field_ref="v50" level="10" />
+                    <field field_ref="v10" level="10" />
+                    <field field_ref="w850" level="10" />
+                    <field field_ref="w700" level="10" />
+                    <field field_ref="w500" level="10" />
+                    <field field_ref="w200" level="10" />
+                    <field field_ref="w100" level="10" />
+                    <field field_ref="w50" level="10" />
+                    <field field_ref="w10" level="10" />
+                    <field field_ref="t850" level="10" />
+                    <field field_ref="t700" level="10" />
+                    <field field_ref="t500" level="10" />
+                    <field field_ref="t200" level="10" />
+                    <field field_ref="t100" level="10" />
+                    <field field_ref="t50" level="10" />
+                    <field field_ref="t10" level="10" />
+                    <field field_ref="q850" level="10" />
+                    <field field_ref="q700" level="10" />
+                    <field field_ref="q500" level="10" />
+                    <field field_ref="q200" level="10" />
+                    <field field_ref="q100" level="10" />
+                    <field field_ref="q50" level="10" />
+                    <field field_ref="q10" level="10" />
+                    <field field_ref="z850" level="10" />
+                    <field field_ref="z700" level="10" />
+                    <field field_ref="z500" level="10" />
+                    <field field_ref="z200" level="10" />
+                    <field field_ref="z100" level="10" />
+                    <field field_ref="z50" level="10" />
+                    <field field_ref="z10" level="10" />
                 </field_group>
 
@@ -302,22 +306,6 @@
                 <field field_ref="tpot" level="10" />
                 <field field_ref="tpote" level="10" />
-                <field field_ref="tke" level="10" />
-                <field field_ref="tke_ter" level="10" />
-                <field field_ref="tke_lic" level="10" />
-                <field field_ref="tke_oce" level="10" />
-                <field field_ref="tke_sic" level="10" />
-                <field field_ref="tke_max_ter" level="10" operation="maximum" />
-                <field field_ref="tke_max_lic" level="10" operation="maximum" />
-                <field field_ref="tke_max_oce" level="10" operation="maximum" />
-                <field field_ref="tke_max_sic" level="10" operation="maximum" />
-                <field field_ref="l_mix_ter" level="10" />
-                <field field_ref="l_mix_lic" level="10" />
-                <field field_ref="l_mix_oce" level="10" />
-                <field field_ref="l_mix_sic" level="10" />
-                <field field_ref="l_mixmin_ter" level="10" />
-                <field field_ref="l_mixmin_lic" level="10" />
-                <field field_ref="l_mixmin_oce" level="10" />
-                <field field_ref="l_mixmin_sic" level="10" />
                 <field field_ref="SWnetOR" level="2" />
+                <field field_ref="SWdownOR" level="2" />
                 <field field_ref="LWdownOR" level="2" />
                 <field field_ref="snowl" level="10" />
@@ -447,5 +435,27 @@
 
             <!-- VARS 3D -->
-            <field_group operation="instant" freq_op="1ts" grid_ref="grid_glo_presnivs">
+            <field_group operation="instant" freq_op="1ts"  grid_ref="grid_out_presnivs" >
+                <field field_ref="tke" level="10" />
+                <field field_ref="tke_ter" level="10" />
+                <field field_ref="tke_lic" level="10" />
+                <field field_ref="tke_oce" level="10" />
+                <field field_ref="tke_sic" level="10" />
+                <field field_ref="tke_max_ter" level="10" operation="maximum" />
+                <field field_ref="tke_max_lic" level="10" operation="maximum" />
+                <field field_ref="tke_max_oce" level="10" operation="maximum" />
+                <field field_ref="tke_max_sic" level="10" operation="maximum" />
+                <field field_ref="l_mix_ter" level="10" />
+                <field field_ref="l_mix_lic" level="10" />
+                <field field_ref="l_mix_oce" level="10" />
+                <field field_ref="l_mix_sic" level="10" />
+                <field field_ref="l_mixmin_ter" level="10" />
+                <field field_ref="l_mixmin_lic" level="10" />
+                <field field_ref="l_mixmin_oce" level="10" />
+                <field field_ref="l_mixmin_sic" level="10" />
+                <field field_ref="CO2" level="10" />
+                <field field_ref="dCO2_vdf" level="10" />
+                <field field_ref="dCO2_the" level="10" />
+                <field field_ref="dCO2_con" level="10" />
+                
                 <field field_ref="cldtau" level="10" />
                 <field field_ref="cldemi" level="10" />
@@ -617,4 +627,5 @@
                 <field field_ref="rldcs4co2" level="10" />
             </field_group>
+          </field_group>
         </file>
     </file_group>
Index: /LMDZ6/branches/Ocean_skin/DefLists/file_def_histmthCOSP_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/file_def_histmthCOSP_lmdz.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/file_def_histmthCOSP_lmdz.xml	(revision 3605)
@@ -1,99 +1,101 @@
 <file_definition>
      <file_group id="defile">
-        <file id="histmthCOSP" name="histmthCOSP" output_freq="1mo" output_level="1"  enabled=".TRUE.">
+        <file id="histmthCOSP" name="histmthCOSP" output_freq="1mo" output_level="_AUTO_"  enabled="_AUTO_" compression_level="0">
 
+            <field_group group_ref="remap_1mo">
+            
             <!-- VARS Calipso and PARASOL -->
-            <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
-                <field field_ref="cllcalipso"         level="1" />
-                <field field_ref="clmcalipso"         level="1" />
-                <field field_ref="clhcalipso"         level="1" />
-                <field field_ref="cltcalipso"         level="1" />
-                <field field_ref="pcllcalipso"         level="1" />
-                <field field_ref="pclmcalipso"         level="1" />
-                <field field_ref="pclhcalipso"         level="1" />
-                <field field_ref="pcltcalipso"         level="1" />
-                <field field_ref="cllcalipsoice"         level="1" />
-                <field field_ref="clmcalipsoice"         level="1" />
-                <field field_ref="clhcalipsoice"         level="1" />
-                <field field_ref="cltcalipsoice"         level="1" />
-                <field field_ref="cllcalipsoliq"         level="1" />
-                <field field_ref="clmcalipsoliq"         level="1" />
-                <field field_ref="clhcalipsoliq"         level="1" />
-                <field field_ref="cltcalipsoliq"         level="1" />
-                <field field_ref="cllcalipsoun"         level="1" />
-                <field field_ref="clmcalipsoun"         level="1" />
-                <field field_ref="clhcalipsoun"         level="1" />
-                <field field_ref="cltcalipsoun"         level="1" />
-                <field field_ref="clcalipso"  level="1" />
-                <field field_ref="clcalipsoice"  level="1" />
-                <field field_ref="clcalipsoliq"  level="1" />
-                <field field_ref="clcalipsoun"  level="1" />
-                <field field_ref="clcalipsotmp"  level="1" />
-                <field field_ref="clcalipsotmpice"  level="1" />
-                <field field_ref="clcalipsotmpliq"  level="1" />
-                <field field_ref="clcalipsotmpun"  level="1" />
-                <field field_ref="parasol_refl"  level="1" />
-                <field field_ref="parasol_crefl"  level="1" />
-                <field field_ref="Ncrefl"  level="1" />
-       		    <field field_ref="cfad_lidarsr532"  level="10" />
-                <field field_ref="atb532" level="10" />
-                <field field_ref="beta_mol532" level="10" />
-                <field field_ref="clopaquecalipso"       level="1" />
-                <field field_ref="clthincalipso"         level="1" />
-                <field field_ref="clzopaquecalipso"      level="1" />
-                <field field_ref="clcalipsoopaque"   level="1" />
-                <field field_ref="clcalipsothin"     level="1" />
-                <field field_ref="clcalipsozopaque"  level="1" />
-                <field field_ref="clcalipsoopacity"  level="1" />
-                <field field_ref="proftemp"  level="1" />
-                <field field_ref="profSR"  level="1" />
+              <field_group operation="average" freq_op="3h" detect_missing_value=".true." >
+                <field field_ref="cllcalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clmcalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clhcalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="cltcalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="pcllcalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="pclmcalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="pclhcalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="pcltcalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="cllcalipsoice"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clmcalipsoice"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clhcalipsoice"         level="5" grid_ref="grid_out"/>
+                <field field_ref="cltcalipsoice"         level="5" grid_ref="grid_out"/>
+                <field field_ref="cllcalipsoliq"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clmcalipsoliq"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clhcalipsoliq"         level="5" grid_ref="grid_out"/>
+                <field field_ref="cltcalipsoliq"         level="5" grid_ref="grid_out"/>
+                <field field_ref="cllcalipsoun"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clmcalipsoun"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clhcalipsoun"         level="5" grid_ref="grid_out"/>
+                <field field_ref="cltcalipsoun"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clcalipso"  level="5" grid_ref="grid_out_height"/>
+                <field field_ref="clcalipsoice"  level="5" grid_ref="grid_out_height"/>
+                <field field_ref="clcalipsoliq"  level="5" grid_ref="grid_out_height"/>
+                <field field_ref="clcalipsoun"  level="5" grid_ref="grid_out_height"/>
+                <field field_ref="clcalipsotmp"  level="5" grid_ref="grid_out_temp"/>
+                <field field_ref="clcalipsotmpice"  level="5" grid_ref="grid_out_temp"/>
+                <field field_ref="clcalipsotmpliq"  level="5" grid_ref="grid_out_temp"/>
+                <field field_ref="clcalipsotmpun"  level="5" grid_ref="grid_out_temp"/>
+                <field field_ref="parasol_refl"  level="5" grid_ref="grid_out_sza"/>
+                <field field_ref="parasol_crefl"  level="5" grid_ref="grid_out_sza"/>
+                <field field_ref="Ncrefl"  level="5" grid_ref="grid_out_sza"/>
+		<field field_ref="cfad_lidarsr532"  level="10" grid_ref="grid4Dsrbin_out"/>
+                <field field_ref="atb532" level="10" grid_ref="grid4Dcol_out"/>
+                <field field_ref="beta_mol532" level="10" grid_ref="grid_out_heightmlev"/>
+                <field field_ref="clopaquecalipso"       level="5" grid_ref="grid_out"/>
+                <field field_ref="clthincalipso"         level="5" grid_ref="grid_out"/>
+                <field field_ref="clzopaquecalipso"      level="5" grid_ref="grid_out"/>
+                <field field_ref="clcalipsoopaque"   level="5" grid_ref="grid_out_height"/>
+                <field field_ref="clcalipsothin"     level="5" grid_ref="grid_out_height"/>
+                <field field_ref="clcalipsozopaque"  level="5" grid_ref="grid_out_height"/>
+                <field field_ref="clcalipsoopacity"  level="5" grid_ref="grid_out_height"/>
+                <field field_ref="proftemp"  level="5" grid_ref="grid_out_height"/>
+                <field field_ref="profSR"  level="5" grid_ref="grid4Dcol2_out"/>
               </field_group>
              <!-- VARS CLOUDSAT et/ou Calipso -->
-            <field_group operation="average" freq_op="3h" detect_missing_value=".true."> 
-               <field field_ref="cltlidarradar"  level="1"/>
-               <field field_ref="clcalipso2"  level="1" />
-               <field field_ref="cfadDbze94"  level="10" />
-               <field field_ref="dbze94" level="10" />
+              <field_group operation="instant" freq_op="3h" detect_missing_value=".true.">                        
+                 <field field_ref="cltlidarradar"  level="5" grid_ref="grid_out"/>
+                 <field field_ref="clcalipso2"  level="5" grid_ref="grid_out_height"/>
+                 <field field_ref="cfadDbze94"  level="10" grid_ref="grid4Ddbze_out"/>
+                 <field field_ref="dbze94" level="10" grid_ref="grid4Dcol_out"/>
               </field_group>
              <!-- VARS ISCCP -->
-            <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
-                <field field_ref="sunlit" level="1" />
-                <field field_ref="clisccp2" level="1" />
-                <field field_ref="boxtauisccp" level="10" />
-                <field field_ref="boxptopisccp" level="10" />
-                <field field_ref="tclisccp" level="1" />
-                <field field_ref="ctpisccp" level="1" />
-                <field field_ref="tauisccp" level="1" /> 
-                <field field_ref="albisccp" level="1" />
-                <field field_ref="meantbisccp" level="10" />
-                <field field_ref="meantbclrisccp" level="10" />
+             <field_group operation="instant" freq_op="3h" detect_missing_value=".true.">
+                <field field_ref="sunlit" level="5" grid_ref="grid_out"/>
+                <field field_ref="clisccp2" level="5" grid_ref="grid4Dtau_out"/>
+                <field field_ref="boxtauisccp" level="10" grid_ref="grid_out_column"/>
+                <field field_ref="boxptopisccp" level="10" grid_ref="grid_out_column"/>
+                <field field_ref="tclisccp" level="5" grid_ref="grid_out"/>
+                <field field_ref="ctpisccp" level="5" grid_ref="grid_out"/>
+                <field field_ref="tauisccp" level="5" grid_ref="grid_out"/> 
+                <field field_ref="albisccp" level="5" grid_ref="grid_out"/>
+                <field field_ref="meantbisccp" level="10" grid_ref="grid_out"/>
+                <field field_ref="meantbclrisccp" level="10" grid_ref="grid_out"/>
+              </field_group>
+             <!-- VARS MISR -->
+             <field_group operation="instant" freq_op="3h" detect_missing_value=".true.">
+                <field field_ref="clMISR" level="5" grid_ref="grid4Dmisr_out"/>
              </field_group>
-             <!-- VARS MISR -->
-            <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
-                <field field_ref="clMISR" level="1" />
-            </field_group>
-            <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
-                <field field_ref="cllmodis" level="1" />
-                <field field_ref="clmmodis" level="1" />
-                <field field_ref="clhmodis" level="1" />
-                <field field_ref="cltmodis" level="1" />
-                <field field_ref="clwmodis" level="1" />
-                <field field_ref="climodis" level="1" />
-                <field field_ref="tautmodis" level="1" />
-                <field field_ref="tauwmodis" level="1" />
-                <field field_ref="tauimodis" level="1" />
-                <field field_ref="tautlogmodis" level="1" />
-                <field field_ref="tauilogmodis" level="1" />
-                <field field_ref="tauwlogmodis" level="1" />
-                <field field_ref="reffclwmodis" level="1" />
-                <field field_ref="reffclimodis" level="1" />
-                <field field_ref="pctmodis"  level="1" />
-                <field field_ref="lwpmodis" level="1" />
-                <field field_ref="iwpmodis" level="1" />
-                <field field_ref="clmodis" level="1" />
-                <field field_ref="crimodis" level="10" />
-                <field field_ref="crlmodis" level="10" />
-            </field_group>
-
+             <field_group operation="instant" freq_op="3h" detect_missing_value=".true.">
+                <field field_ref="cllmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="clmmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="clhmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="cltmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="clwmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="climodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="tautmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="tauwmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="tauimodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="tautlogmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="tauilogmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="tauwlogmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="reffclwmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="reffclimodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="pctmodis"  level="5" grid_ref="grid_out"/>
+                <field field_ref="lwpmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="iwpmodis" level="5" grid_ref="grid_out"/>
+                <field field_ref="clmodis" level="5" grid_ref="grid4Dtau_out"/>
+                <field field_ref="crimodis" level="10" grid_ref="grid4Dreffi_out"/>
+                <field field_ref="crlmodis" level="10" grid_ref="grid4Dreffl_out"/>
+             </field_group>
+           </field_group> 
         </file>
      </file_group>
Index: /LMDZ6/branches/Ocean_skin/DefLists/file_def_histmthCOSPv2_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/file_def_histmthCOSPv2_lmdz.xml	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/DefLists/file_def_histmthCOSPv2_lmdz.xml	(revision 3605)
@@ -0,0 +1,148 @@
+<file_definition>
+     <file_group id="defile">
+        <file id="histmthCOSP" name="histmthCOSP" output_freq="1mo" output_level="1"  enabled=".TRUE." compression_level="4">
+
+            <!-- VARS LIDAR -->
+            <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
+            <!-- VARS CALIPSO -->
+                <field field_ref="cllcalipso"           level="1" />
+                <field field_ref="clmcalipso"           level="1" />
+                <field field_ref="clhcalipso"           level="1" />
+                <field field_ref="cltcalipso"           level="1" />
+                <field field_ref="pcllcalipso"          level="10" />
+                <field field_ref="pclmcalipso"          level="10" />
+                <field field_ref="pclhcalipso"          level="10" />
+                <field field_ref="pcltcalipso"          level="10" />
+                <field field_ref="cllcalipsoice"        level="1" />
+                <field field_ref="clmcalipsoice"        level="1" />
+                <field field_ref="clhcalipsoice"        level="1" />
+                <field field_ref="cltcalipsoice"        level="1" />
+                <field field_ref="cllcalipsoliq"        level="1" />
+                <field field_ref="clmcalipsoliq"        level="1" />
+                <field field_ref="clhcalipsoliq"        level="1" />
+                <field field_ref="cltcalipsoliq"        level="1" />
+                <field field_ref="cllcalipsoun"         level="1" />
+                <field field_ref="clmcalipsoun"         level="1" />
+                <field field_ref="clhcalipsoun"         level="1" />
+                <field field_ref="cltcalipsoun"         level="1" />
+                <field field_ref="clcalipso"            level="1" />
+                <field field_ref="clcalipsoice"         level="1" />
+                <field field_ref="clcalipsoliq"         level="1" />
+                <field field_ref="clcalipsoun"          level="10" />
+                <field field_ref="clcalipsotmp"         level="10" />
+                <field field_ref="clcalipsotmpice"      level="10" />
+                <field field_ref="clcalipsotmpliq"      level="10" />
+                <field field_ref="clcalipsotmpun"       level="10" />
+        		<field field_ref="cfadLidarsr532"       level="10" />
+                <field field_ref="atb532"               level="10" />
+                <field field_ref="lidarBetaMol532"      level="10" />
+                <field field_ref="clopaquecalipso"      level="1" />
+                <field field_ref="clthincalipso"        level="1" />
+                <field field_ref="clzopaquecalipso"     level="1" />
+                <field field_ref="clcalipsoopaque"      level="1" />
+                <field field_ref="clcalipsothin"        level="1" />
+                <field field_ref="clcalipsozopaque"     level="1" />
+                <field field_ref="clcalipsoopacity"     level="1" />
+                <field field_ref="clopaquetemp"         level="1" />
+                <field field_ref="clthintemp"           level="1" />
+                <field field_ref="clzopaquetemp"        level="1" />
+                <field field_ref="clopaquemeanz"        level="1" />
+                <field field_ref="clthinmeanz"          level="1" />
+                <field field_ref="clthinemis"           level="1" />
+                <field field_ref="clopaquemeanzse"      level="1" />
+                <field field_ref="clthinmeanzse"        level="1" />
+                <field field_ref="clzopaquecalipsose"   level="1" />
+            <!-- VARS GROUND LIDAR 532 nm -->
+                <field field_ref="cllgrLidar532"        level="1" />
+                <field field_ref="clmgrLidar532"        level="1" />
+                <field field_ref="clhgrLidar532"        level="1" />
+                <field field_ref="cltgrLidar532"        level="1" />
+                <field field_ref="clgrLidar532"         level="10" />
+        		<field field_ref="cfadLidarsr532gr"     level="10" />
+                <field field_ref="atb532gr"             level="10" />
+                <field field_ref="lidarBetaMol532gr"    level="10" />
+            <!-- VARS ATLID -->
+                <field field_ref="cllatlid"             level="1" />
+                <field field_ref="clmatlid"             level="1" />
+                <field field_ref="clhatlid"             level="1" />
+                <field field_ref="cltatlid"             level="1" />
+                <field field_ref="clatlid"              level="1" />
+        		<field field_ref="cfadLidarsr355"       level="10" />
+                <field field_ref="atb355"               level="10" />
+                <field field_ref="lidarBetaMol355"      level="10" />
+              </field_group>
+             <!-- VARS PARASOL -->
+            <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
+                <field field_ref="parasolPix_refl"      level="1" />
+                <field field_ref="parasolGrid_refl"     level="1" />
+<!--                <field field_ref="Ncrefl"  level="1" /> -->
+            </field_group>
+             <!-- VARS CLOUDSAT et/ou CALIPSO -->
+            <field_group operation="average" freq_op="3h" detect_missing_value=".true."> 
+               <field field_ref="cltlidarradar"         level="10"/>
+               <field field_ref="clcalipso2"            level="10" />
+               <field field_ref="cloudsat_tcc"          level="1" />
+               <field field_ref="cloudsat_tcc2"         level="1" />
+            </field_group>
+             <!-- VARS CLOUDSAT -->
+            <field_group operation="average" freq_op="3h" detect_missing_value=".true."> 
+               <field field_ref="cfadDbze94"            level="1" />
+               <field field_ref="dbze94"                level="10" />
+               <field field_ref="ptradarflag0"          level="1" />
+               <field field_ref="ptradarflag1"          level="1" />
+               <field field_ref="ptradarflag2"          level="1" />
+               <field field_ref="ptradarflag3"          level="1" />
+               <field field_ref="ptradarflag4"          level="1" />
+               <field field_ref="ptradarflag5"          level="1" />
+               <field field_ref="ptradarflag6"          level="1" />
+               <field field_ref="ptradarflag7"          level="1" />
+               <field field_ref="ptradarflag8"          level="1" />
+               <field field_ref="ptradarflag9"          level="1" />
+               <field field_ref="radarpia"              level="1" />
+             </field_group>
+             <!-- VARS ISCCP -->
+            <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
+<!--                <field field_ref="sunlit" level="1" /> -->
+                <field field_ref="clisccp"             level="1" />
+                <field field_ref="boxtauisccp"         level="1" />
+                <field field_ref="boxptopisccp"        level="1" />
+                <field field_ref="cltisccp"            level="1" />
+                <field field_ref="pctisccp"            level="1" />
+                <field field_ref="tauisccp"            level="1" /> 
+                <field field_ref="albisccp"            level="1" />
+                <field field_ref="meantbisccp"         level="1" />
+                <field field_ref="meantbclrisccp"      level="1" />
+            </field_group>
+             <!-- VARS MISR -->
+            <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
+                <field field_ref="misr_fq"             level="1" />
+                <field field_ref="misr_meanztop"       level="10" />
+                <field field_ref="misr_cldarea"        level="1" />
+            </field_group>
+             <!-- VARS MODIS -->
+            <field_group operation="average" freq_op="3h" detect_missing_value=".true.">
+                <field field_ref="cllmodis"            level="10" />
+                <field field_ref="clmmodis"            level="10" />
+                <field field_ref="clhmodis"            level="10" />
+                <field field_ref="cltmodis"            level="10" />
+                <field field_ref="clwmodis"            level="10" />
+                <field field_ref="climodis"            level="10" />
+                <field field_ref="tautmodis"           level="10" />
+                <field field_ref="tauwmodis"           level="10" />
+                <field field_ref="tauimodis"           level="10" />
+                <field field_ref="tautlogmodis"        level="10" />
+                <field field_ref="tauilogmodis"        level="10" />
+                <field field_ref="tauwlogmodis"        level="10" />
+                <field field_ref="reffclwmodis"        level="10" />
+                <field field_ref="reffclimodis"        level="10" />
+                <field field_ref="pctmodis"            level="10" />
+                <field field_ref="lwpmodis"            level="10" />
+                <field field_ref="iwpmodis"            level="10" />
+                <field field_ref="modis_ot_vs_ctp"     level="10" />
+                <field field_ref="modis_ot_vs_reffice" level="10" />
+                <field field_ref="modis_ot_vs_reffliq" level="10" />
+            </field_group>
+
+        </file>
+     </file_group>
+</file_definition>
Index: /LMDZ6/branches/Ocean_skin/DefLists/file_def_histmthNMC_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/file_def_histmthNMC_lmdz.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/file_def_histmthNMC_lmdz.xml	(revision 3605)
@@ -1,8 +1,10 @@
 <file_definition>
     <file_group id="defile">
-        <file id="histmthNMC" name="histmthNMC" output_freq="1mo" output_level="5" enabled="_AUTO_">
+        <file id="histmthNMC" name="histmthNMC" output_freq="1mo" output_level="_AUTO_" enabled="_AUTO_" compression_level="2">
+
+            <field_group group_ref="remap_1mo">
 
             <!-- VARS 3D -->
-            <field_group operation="average" freq_op="1ts" detect_missing_value=".true.">
+              <field_group operation="average" grid_ref="grid_out_plev" freq_op="1ts" detect_missing_value=".true.">
 <!--            <field field_ref="tnondef" level="5" />  -->
                 <field field_ref="ta" level="1" />
@@ -25,4 +27,5 @@
                 <field field_ref="v2" level="6" />
                 <field field_ref="T2" level="6" />
+              </field_group>
             </field_group>
         </file>
Index: /LMDZ6/branches/Ocean_skin/DefLists/file_def_histmth_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/file_def_histmth_lmdz.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/file_def_histmth_lmdz.xml	(revision 3605)
@@ -1,5 +1,6 @@
+<!-- $Id$ --> 
 <file_definition>
         <file_group id="defile">
-        <file id="histmth" name="histmth" output_freq="1mo" output_level="5"  enabled="_AUTO_">
+        <file id="histmth" name="histmth" output_freq="1mo" output_level="_AUTO_"  enabled="_AUTO_" compression_level="2">
 
             <!-- VARS 1D -->
@@ -11,10 +12,12 @@
 
             <field_group operation="once">
-              <field field_ref="io_lon" level="1" />
-              <field field_ref="io_lat" level="1" />
               <field field_ref="Ahyb" level="1" />
-              <field field_ref="Ahyb_inter" level="1" />
+              <field field_ref="Ahyb_bounds" level="1" />
               <field field_ref="Bhyb" level="1" />
-              <field field_ref="Bhyb_inter" level="1" />
+              <field field_ref="Bhyb_bounds" level="1" />
+              <field field_ref="Ahyb_mid" level="1" />
+              <field field_ref="Ahyb_mid_bounds" level="1" />
+              <field field_ref="Bhyb_mid" level="1" />
+              <field field_ref="Bhyb_mid_bounds" level="1" />
             </field_group>
 
@@ -38,10 +41,15 @@
                 <field field_ref="CFC12_ppt" level="1" name="CFC12_ppt" />
             </field_group>
-
-            <!-- VARS 2D -->
-            <field_group operation="average" freq_op="1ts">
-                <field field_ref="phis"         level="1" />
-                <field field_ref="aire"         level="1"   operation="once"/>
-                <field field_ref="contfracATM"  level="10"  operation="once"/>
+            
+
+           <field_group group_ref="remap_1mo">
+             <!-- VARS 2D -->
+             <field_group operation="average" grid_ref="grid_out">
+                <field field_ref="io_lon" level="1" operation="once"/>
+                <field field_ref="io_lat" level="1" operation="once"/>
+    
+                <field field_ref="phis"         level="1"  />
+                <field field_ref="aire"         level="1"  />
+                <field field_ref="contfracATM"  level="10" />
                 <field field_ref="contfracOR"   level="10" />
                 <field field_ref="flat"         level="5" />
@@ -52,6 +60,6 @@
                 <field field_ref="tsol"         level="1" />
                 <field field_ref="t2m"          level="1" />
-                <field id="ave_t2m_daily_min" field_ref="t2m_min" name="ave_t2m_daily_min" level="1" operation="average" freq_op="1d"> @t2m_min </field>
-                <field id="ave_t2m_daily_max" field_ref="t2m_max" name="ave_t2m_daily_max" level="1" operation="average" freq_op="1d"> @t2m_max </field>
+                <field id="ave_t2m_daily_min" field_ref="t2m_min" name="ave_t2m_daily_min" level="1" operation="average" freq_op="1d" expr="@t2m_min" />
+                <field id="ave_t2m_daily_max" field_ref="t2m_max" name="ave_t2m_daily_max" level="1" operation="average" freq_op="1d" expr="@t2m_max" />
                 <field field_ref="t2m_ter" level="10" />
                 <field field_ref="t2m_lic" level="10" />
@@ -110,12 +118,12 @@
                 <field field_ref="SWdnTOAclr"   level="1" />
                 <field field_ref="nettop"       level="1" />
-                <field field_ref="SWup200"      level="1" />
-                <field field_ref="SWup200clr"   level="10" />
-                <field field_ref="SWdn200"      level="1" />
-                <field field_ref="SWdn200clr"   level="10" />
-                <field field_ref="LWup200"      level="1" />
-                <field field_ref="LWup200clr"   level="1" />
-                <field field_ref="LWdn200"      level="1" />
-                <field field_ref="LWdn200clr"   level="1" />
+                <field field_ref="SWup200"      level="15" />
+                <field field_ref="SWup200clr"   level="15" />
+                <field field_ref="SWdn200"      level="15" />
+                <field field_ref="SWdn200clr"   level="15" />
+                <field field_ref="LWup200"      level="15" />
+                <field field_ref="LWup200clr"   level="15" />
+                <field field_ref="LWdn200"      level="15" />
+                <field field_ref="LWdn200clr"   level="15" />
                 <field field_ref="sols"  level="1" />
                 <field field_ref="sols0" level="1" />
@@ -273,47 +281,47 @@
                 <field field_ref="colO3_trop"  level="2" />     <!-- Added ThL -->
 
-                <field_group operation="average" freq_op="1ts" detect_missing_value=".true.">
-                    <field field_ref="u850" level="1" />
-                    <field field_ref="u700" level="1" />
-                    <field field_ref="u500" level="1" />
-                    <field field_ref="u200" level="1" />
-                    <field field_ref="u100" level="1" />
-                    <field field_ref="u50" level="1" />
-                    <field field_ref="u10" level="1" />
-                    <field field_ref="v850" level="1" />
-                    <field field_ref="v700" level="1" />
-                    <field field_ref="v500" level="1" />
-                    <field field_ref="v200" level="1" />
-                    <field field_ref="v100" level="1" />
-                    <field field_ref="v50" level="1" />
-                    <field field_ref="v10" level="1" />
-                    <field field_ref="w850" level="1" />
-                    <field field_ref="w700" level="1" />
-                    <field field_ref="w500" level="1" />
-                    <field field_ref="w200" level="1" />
-                    <field field_ref="w100" level="1" />
-                    <field field_ref="w50" level="1" />
-                    <field field_ref="w10" level="1" />
-                    <field field_ref="t850" level="1" />
-                    <field field_ref="t700" level="1" />
-                    <field field_ref="t500" level="1" />
-                    <field field_ref="t200" level="1" />
-                    <field field_ref="t100" level="1" />
-                    <field field_ref="t50" level="1" />
-                    <field field_ref="t10" level="1" />
-                    <field field_ref="q850" level="1" />
-                    <field field_ref="q700" level="1" />
-                    <field field_ref="q500" level="1" />
-                    <field field_ref="q200" level="1" />
-                    <field field_ref="q100" level="1" />
-                    <field field_ref="q50" level="1" />
-                    <field field_ref="q10" level="1" />
-                    <field field_ref="z850" level="1" />
-                    <field field_ref="z700" level="1" />
-                    <field field_ref="z500" level="1" />
-                    <field field_ref="z200" level="1" />
-                    <field field_ref="z100" level="1" />
-                    <field field_ref="z50" level="1" />
-                    <field field_ref="z10" level="1" />
+                <field_group operation="average" detect_missing_value=".true.">
+                    <field field_ref="u850" level="10" />
+                    <field field_ref="u700" level="10" />
+                    <field field_ref="u500" level="10" />
+                    <field field_ref="u200" level="10" />
+                    <field field_ref="u100" level="10" />
+                    <field field_ref="u50" level="10" />
+                    <field field_ref="u10" level="10" />
+                    <field field_ref="v850" level="10" />
+                    <field field_ref="v700" level="10" />
+                    <field field_ref="v500" level="10" />
+                    <field field_ref="v200" level="10" />
+                    <field field_ref="v100" level="10" />
+                    <field field_ref="v50" level="10" />
+                    <field field_ref="v10" level="10" />
+                    <field field_ref="w850" level="10" />
+                    <field field_ref="w700" level="10" />
+                    <field field_ref="w500" level="10" />
+                    <field field_ref="w200" level="10" />
+                    <field field_ref="w100" level="10" />
+                    <field field_ref="w50" level="10" />
+                    <field field_ref="w10" level="10" />
+                    <field field_ref="t850" level="10" />
+                    <field field_ref="t700" level="10" />
+                    <field field_ref="t500" level="10" />
+                    <field field_ref="t200" level="10" />
+                    <field field_ref="t100" level="10" />
+                    <field field_ref="t50" level="10" />
+                    <field field_ref="t10" level="10" />
+                    <field field_ref="q850" level="10" />
+                    <field field_ref="q700" level="10" />
+                    <field field_ref="q500" level="10" />
+                    <field field_ref="q200" level="10" />
+                    <field field_ref="q100" level="10" />
+                    <field field_ref="q50" level="10" />
+                    <field field_ref="q10" level="10" />
+                    <field field_ref="z850" level="10" />
+                    <field field_ref="z700" level="10" />
+                    <field field_ref="z500" level="10" />
+                    <field field_ref="z200" level="10" />
+                    <field field_ref="z100" level="10" />
+                    <field field_ref="z50" level="10" />
+                    <field field_ref="z10" level="10" />
                 </field_group>
 
@@ -336,4 +344,5 @@
                 <field field_ref="tpote" level="10" />
                 <field field_ref="SWnetOR" level="10" />
+                <field field_ref="SWdownOR" level="10" />
                 <field field_ref="LWdownOR" level="10" />
                 <field field_ref="snowl" level="10" />
@@ -347,12 +356,12 @@
                 <field field_ref="z0m" level="10" />
                 <field field_ref="z0h" level="10" />
-                <field field_ref="topswad" level="10" />
-                <field field_ref="topswad0" level="10" />
+                <field field_ref="topswad" level="1" />
+                <field field_ref="topswad0" level="1" />
                 <field field_ref="topswai" level="10" />
                 <field field_ref="solswad" level="10" />
                 <field field_ref="solswad0" level="10" />
                 <field field_ref="solswai" level="10" />
-                <field field_ref="toplwad" level="10" />
-                <field field_ref="toplwad0" level="10" />
+                <field field_ref="toplwad" level="1" />
+                <field field_ref="toplwad0" level="1" />
                 <field field_ref="toplwai" level="10" />
                 <field field_ref="sollwad" level="10" />
@@ -482,5 +491,28 @@
 
             <!-- VARS 3D -->
-            <field_group operation="average" freq_op="1ts" grid_ref="grid_glo_presnivs">
+            <field_group operation="average" grid_ref="grid_out_presnivs">
+                <field field_ref="tke" level="7" />
+                <field field_ref="tke_ter" level="10" />
+                <field field_ref="tke_lic" level="10" />
+                <field field_ref="tke_oce" level="10" />
+                <field field_ref="tke_sic" level="10" />
+                <field field_ref="tke_max_ter" level="10" operation="maximum" />
+                <field field_ref="tke_max_lic" level="10" operation="maximum" />
+                <field field_ref="tke_max_oce" level="10" operation="maximum" />
+                <field field_ref="tke_max_sic" level="10" operation="maximum" />
+                <field field_ref="l_mix_ter" level="10" />
+                <field field_ref="l_mix_lic" level="10" />
+                <field field_ref="l_mix_oce" level="10" />
+                <field field_ref="l_mix_sic" level="10" />
+                <field field_ref="l_mixmin_ter" level="10" />
+                <field field_ref="l_mixmin_lic" level="10" />
+                <field field_ref="l_mixmin_oce" level="10" />
+                <field field_ref="l_mixmin_sic" level="10" />
+                <field field_ref="treedrg_ter" level="10" />
+                <field field_ref="treedrg_lic" level="10" />
+                <field field_ref="treedrg_oce" level="10" />
+                <field field_ref="treedrg_sic" level="10" />
+                
+                
                 <field field_ref="cldtau" level="10" />
                 <field field_ref="cldemi" level="10" />
@@ -519,4 +551,5 @@
                 <field field_ref="rhum" level="1" />
                 <field field_ref="ozone" level="3" />
+                <field field_ref="ozone_daylight" level="2" />
                 <field field_ref="upwd" level="7" />
                 <field field_ref="ep" level="7" />
@@ -651,32 +684,15 @@
                 <field field_ref="rsdcs4co2" level="10" />
                 <field field_ref="rldcs4co2" level="10" />
-                <field field_ref="treedrg_ter" level="10" />
-                <field field_ref="treedrg_lic" level="10" />
-                <field field_ref="treedrg_oce" level="10" />
-                <field field_ref="treedrg_sic" level="10" />
-                <field field_ref="tke" level="7" />
-                <field field_ref="tke_ter" level="10" />
-                <field field_ref="tke_lic" level="10" />
-                <field field_ref="tke_oce" level="10" />
-                <field field_ref="tke_sic" level="10" />
-                <field field_ref="tke_max_ter" level="10" operation="maximum" />
-                <field field_ref="tke_max_lic" level="10" operation="maximum" />
-                <field field_ref="tke_max_oce" level="10" operation="maximum" />
-                <field field_ref="tke_max_sic" level="10" operation="maximum" />
-                <field field_ref="l_mix_ter" level="10" />
-                <field field_ref="l_mix_lic" level="10" />
-                <field field_ref="l_mix_oce" level="10" />
-                <field field_ref="l_mix_sic" level="10" />
-                <field field_ref="l_mixmin_ter" level="10" />
-                <field field_ref="l_mixmin_lic" level="10" />
-                <field field_ref="l_mixmin_oce" level="10" />
-                <field field_ref="l_mixmin_sic" level="10" />
-                <field field_ref="ozone_daylight" level="2" />
+                <field field_ref="stratomask" level="1" />
+                <field field_ref="cool_volc" level="1" />
+                <field field_ref="heat_volc" level="1" />
             </field_group>
 
             <!-- VARS 3D -->
-            <field_group operation="average" freq_op="1ts" grid_ref="grid_glo_spectband">
+            <field_group operation="average" grid_ref="grid_out_spectband">
                 <field field_ref="solbnd" level="10" />
             </field_group>
+         
+          </field_group>
 
         </file>
Index: /LMDZ6/branches/Ocean_skin/DefLists/file_def_histstn_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/file_def_histstn_lmdz.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/file_def_histstn_lmdz.xml	(revision 3605)
@@ -1,5 +1,5 @@
 <file_definition>
     <file_group id="defile">
-        <file id="histstn" name="histstn" output_freq="1800s" output_level="5" enabled="_AUTO_">
+        <file id="histstn" name="histstn" output_freq="1800s" output_level="_AUTO_" enabled="_AUTO_" compression_level="2">
 
             <!-- VARS 1D -->
@@ -11,5 +11,7 @@
         
             <!-- VARS 2D -->
-            <field_group operation="average" freq_op="1ts">
+           <field_group group_ref="remap_1800s">
+
+             <field_group operation="average" grid_ref="grid_out">
                 <field field_ref="phis" level="1" />
                 <field field_ref="aire" level="1" operation="once" />
@@ -81,12 +83,12 @@
                 <field field_ref="SWdnTOAclr" level="10" />
                 <field field_ref="nettop" level="10" />
-                <field field_ref="SWup200" level="10" />
-                <field field_ref="SWup200clr" level="10" />
-                <field field_ref="SWdn200" level="10" />
-                <field field_ref="SWdn200clr" level="10" />
-                <field field_ref="LWup200" level="10" />
-                <field field_ref="LWup200clr" level="10" />
-                <field field_ref="LWdn200" level="10" />
-                <field field_ref="LWdn200clr" level="10" />
+                <field field_ref="SWup200" level="15" />
+                <field field_ref="SWup200clr" level="15" />
+                <field field_ref="SWdn200" level="15" />
+                <field field_ref="SWdn200clr" level="15" />
+                <field field_ref="LWup200" level="15" />
+                <field field_ref="LWup200clr" level="15" />
+                <field field_ref="LWdn200" level="15" />
+                <field field_ref="LWdn200clr" level="15" />
                 <field field_ref="sols" level="10" />
                 <field field_ref="sols0" level="10" />
@@ -240,5 +242,5 @@
                 <field field_ref="alp_bl_stat" level="10" />
 
-                <field_group operation="average" freq_op="1ts" detect_missing_value=".true.">
+                <field_group operation="average" detect_missing_value=".true.">
                     <field field_ref="u850" level="10" />
                     <field field_ref="u700" level="10" />
@@ -302,22 +304,6 @@
                 <field field_ref="tpot" level="10" />
                 <field field_ref="tpote" level="10" />
-                <field field_ref="tke" level="10" />
-                <field field_ref="tke_ter" level="10" />
-                <field field_ref="tke_lic" level="10" />
-                <field field_ref="tke_oce" level="10" />
-                <field field_ref="tke_sic" level="10" />
-                <field field_ref="tke_max_ter" level="10" operation="maximum" />
-                <field field_ref="tke_max_lic" level="10" operation="maximum" />
-                <field field_ref="tke_max_oce" level="10" operation="maximum" />
-                <field field_ref="tke_max_sic" level="10" operation="maximum" />
-                <field field_ref="l_mix_ter" level="10" />
-                <field field_ref="l_mix_lic" level="10" />
-                <field field_ref="l_mix_oce" level="10" />
-                <field field_ref="l_mix_sic" level="10" />
-                <field field_ref="l_mixmin_ter" level="10" />
-                <field field_ref="l_mixmin_lic" level="10" />
-                <field field_ref="l_mixmin_oce" level="10" />
-                <field field_ref="l_mixmin_sic" level="10" />
                 <field field_ref="SWnetOR" level="10" />
+                <field field_ref="SWdownOR" level="10" />
                 <field field_ref="LWdownOR" level="10" />
                 <field field_ref="snowl" level="10" />
@@ -386,5 +372,4 @@
                 <field field_ref="lcc" level="10" />
                 <field field_ref="wvapp" level="10" />
-                <field field_ref="ozone_daylight" level="10" />
                 <field field_ref="albe_ter" level="10" />
                 <field field_ref="albe_lic" level="10" />
@@ -447,5 +432,23 @@
 
             <!-- VARS 3D -->
-            <field_group operation="average" freq_op="1ts" grid_ref="grid_glo_presnivs">
+            <field_group operation="average" grid_ref="grid_out_presnivs" >
+                <field field_ref="tke" level="10" />
+                <field field_ref="tke_ter" level="10" />
+                <field field_ref="tke_lic" level="10" />
+                <field field_ref="tke_oce" level="10" />
+                <field field_ref="tke_sic" level="10" />
+                <field field_ref="tke_max_ter" level="10" operation="maximum" />
+                <field field_ref="tke_max_lic" level="10" operation="maximum" />
+                <field field_ref="tke_max_oce" level="10" operation="maximum" />
+                <field field_ref="tke_max_sic" level="10" operation="maximum" />
+                <field field_ref="l_mix_ter" level="10" />
+                <field field_ref="l_mix_lic" level="10" />
+                <field field_ref="l_mix_oce" level="10" />
+                <field field_ref="l_mix_sic" level="10" />
+                <field field_ref="l_mixmin_ter" level="10" />
+                <field field_ref="l_mixmin_lic" level="10" />
+                <field field_ref="l_mixmin_oce" level="10" />
+                <field field_ref="l_mixmin_sic" level="10" />
+
                 <field field_ref="cldtau" level="10" />
                 <field field_ref="cldemi" level="10" />
@@ -484,4 +487,5 @@
                 <field field_ref="rhum" level="10" />
                 <field field_ref="ozone" level="10" />
+                <field field_ref="ozone_daylight" level="10" />
                 <field field_ref="upwd" level="10" />
                 <field field_ref="ep" level="10" />
@@ -617,4 +621,6 @@
                 <field field_ref="rldcs4co2" level="10" />
             </field_group>
+          </field_group>
+          
         </file>
     </file_group>
Index: /LMDZ6/branches/Ocean_skin/DefLists/file_def_histstrataer_lmdz.xml
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/file_def_histstrataer_lmdz.xml	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/file_def_histstrataer_lmdz.xml	(revision 3605)
@@ -1,11 +1,14 @@
+<!-- $Id$ -->
 <file_definition>
     <file_group id="defile">
-        <file id="histstrataer" name="histstrataer" output_freq="1mo" output_level="5" enabled="_AUTO_">
+        <file id="histstrataer" name="histstrataer" output_freq="1mo" output_level="_AUTO_" enabled="_AUTO_" compression_level="2">
 
-            <field_group group_ref="fields_strataer_3D" operation="average" freq_op="1ts" level="1" />
-            <field_group group_ref="fields_strataer_2D" operation="average" freq_op="1ts" level="1" />
-            <field_group group_ref="fields_strataer_trac_3D" operation="average" freq_op="1ts" level="1" />
-            <field_group group_ref="fields_strataer_trac_2D" operation="average" freq_op="1ts" level="1" />
-            
+            <field_group group_ref="remap_1d">
+              <field_group group_ref="fields_strataer_3D" grid_ref="grid_out_presnivs" level="1" />
+              <field_group group_ref="fields_strataer_2D" grid_ref="grid_out"  level="1" />
+              <field_group group_ref="fields_strataer_trac_3D"  grid_ref="grid_out_presnivs" level="1" />
+              <field_group group_ref="fields_strataer_trac_2D" grid_ref="grid_out" level="1" />
+           </field_group> 
+           
         </file>
     </file_group>
Index: /LMDZ6/branches/Ocean_skin/DefLists/gcm.def
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/gcm.def	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/gcm.def	(revision 3605)
@@ -1,9 +1,8 @@
-## $Id: gcm.def 1403 2010-07-01 09:02:53Z fairhead $
-## nombre de pas par jour (multiple de iperiod) ( ici pour  dt = 1 min )      
-day_step=480
+## $Id: gcm.def_144x142_NPv6.1 3668 2018-03-20 14:55:33Z lfairhead $
+## nombre de pas par jour (multiple de iperiod) 
+## ( day_step=672 => dt=2.15min or 15mn/7, physique toutes les 15 mn )
+day_step=672
 ## periode pour le pas Matsuno (en pas)
-iperiod=5
-## periode de la dissipation (en pas)
-## dissip_period=0
+iperiod=7
 ## choix de l'operateur de dissipation (star ou  non star )
 lstardis=y
@@ -15,9 +14,9 @@
 niterh=2
 ## temps de dissipation des plus petites long.d ondes pour u,v (gradiv)  
-tetagdiv=5400.
+tetagdiv=3600.
 ## temps de dissipation des plus petites long.d ondes pour u,v(nxgradrot)
-tetagrot=5400.
+tetagrot=21600.
 ## temps de dissipation des plus petites long.d ondes pour  h ( divgrad) 
-tetatemp=5400.
+tetatemp=10800.
 ## coefficient pour gamdissip                                            
 coefdis=0.
@@ -34,11 +33,5 @@
 read_start=y
 ## periode de la physique (en pas dynamiques, n'a de sens que si iflag_phys=1)                                       
-iphysiq=10
-##  Avec ou sans strato
-ok_strato=y 
-#  Couche eponge dans les couches de pression plus faible que 100 fois la pression de la derniere couche
-iflag_top_bound=2
-#  Coefficient pour la couche eponge (valeur derniere couche)
-tau_top_bound=5.e-5
+iphysiq=7
 ## longitude en degres du centre du zoom                                 
 clon=0.
@@ -61,2 +54,4 @@
 ##  Fonction  f(y) avec y = Sin(latit.) si = .true. , sinon y = latit.         
 ysinus=y
+##
+ngroup=4
Index: /LMDZ6/branches/Ocean_skin/DefLists/output.def
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/output.def	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/output.def	(revision 3605)
@@ -1,791 +1,123 @@
-######## Abderrahmane le 20 11 08 ########################
-# Niveaux de sorties et nom pour chaque variable dans les#
-# fichiers histmth histday histhf histins histLES        #
-##########################################################
-# Surface geop.height
-flag_phis         =  1, 1, 10, 1, 1    
-name_phis         =  phis
-# Grid area
-flag_aire         =  1, 1, 10,  1, 1    
-name_aire         =  aire
-# Surfac ter+lic
-flag_contfracATM  =  10, 1,  1, 10, 10    
-name_contfracATM  =  contfracATM
-# Surface terre OR  
-flag_contfracOR   =  10, 1,  1, 10, 10    
-name_contfracOR   =  contfracOR
-# Grid area CONT
-flag_aireTER      =  10, 10, 1, 10, 10    
-name_aireTER      =  aireTER
-# Latent heat flux
-flag_flat         =  10, 1, 10, 10, 1    
-name_flat         =  flat
-# Sea Level Pressure
-flag_slp          =  1, 1, 1, 10, 1    
-name_slp          =  slp
-# Surface Temperature
-flag_tsol         =  1, 1, 1, 1, 1    
-name_tsol         =  tsol
-# Temperature 2m
-flag_t2m          =  1, 1, 1, 1, 1    
-name_t2m          =  t2m
-# Temperature min 2m
-flag_t2m_min      =  1, 1, 10, 10, 10    
-name_t2m_min      =  t2m_min
-# Temperature max 2m
-flag_t2m_max      =  1, 1, 10, 10, 10    
-name_t2m_max      =  t2m_max
-# Temperature ter lic oce sic at 2m
-flag_t2m_ter      =  10, 4, 10, 10, 10    
-name_t2m_ter      =  t2m_ter 
-flag_t2m_lic      =  10, 4, 10, 10, 10    
-name_t2m_lic      =  t2m_lic
-flag_t2m_oce      =  10, 4, 10, 10, 10    
-name_t2m_oce      =  t2m_oce
-flag_t2m_sic      =  10, 4, 10, 10, 10    
-name_t2m_sic      =  t2m_sic 
-# 10-m wind speed
-flag_wind10m      =  1, 1, 1, 10, 10    
-name_wind10m      =  wind10m
-# 10-m wind speed max
-flag_wind10max    =  10, 1, 10, 10, 10    
-name_wind10max    =  wind10max
-# Sea-ice fraction
-flag_sicf         =  1, 1, 10, 10, 10    
-name_sicf         =  sicf
-# Specific humidity 2m
-flag_q2m          =  1, 1, 1, 1, 1    
-name_q2m          =  q2m
-# 10m zonal wind
-flag_u10m         =  1, 1, 1, 1, 1    
-name_u10m         =  u10m
-# 10m meridional wind
-flag_v10m         =  1, 1, 1, 1, 1    
-name_v10m         =  v10m
-# Surface Pressure
-flag_psol         =  1, 1, 1, 1, 1    
-name_psol         =  psol
-# Surface Air humidity
-flag_qsurf        =  1, 10, 10, 10, 10    
-name_qsurf        =  qsurf
-# 10m zonal wind (ter lic oce sic)
-flag_u10m_ter     =  10, 4, 10, 10, 10    
-name_u10m_ter     =  u10m_ter
-flag_u10m_lic     =  10, 4, 10, 10, 10    
-name_u10m_lic     =  u10m_lic
-flag_u10m_oce     =  10, 4, 10, 10, 10    
-name_u10m_oce     =  u10m_oce
-flag_u10m_sic     =  10, 4, 10, 10, 10    
-name_u10m_sic     =  u10m_sic
-# 10m meridien  wind (ter oce ice lic)
-flag_v10m_ter     =  10, 4, 10, 10, 10    
-name_v10m_ter     =  v10m_ter
-flag_v10m_lic     =  10, 4, 10, 10, 10    
-name_v10m_lic     =  v10m_lic
-flag_v10m_oce     =  10, 4, 10, 10, 10    
-name_v10m_oce     =  v10m_oce
-flag_v10m_sic     =  10, 4, 10, 10, 10    
-name_v10m_sic     =  v10m_sic
-# Soil watter content
-flag_qsol         =  1, 10, 10, 1, 1    
-name_qsol         =  qsol
-# Number of dayrain(liq+sol)
-flag_ndayrain     =  1, 10, 10, 10, 10    
-name_ndayrain     =  ndayrain
-# Precip Totale liq+sol
-flag_precip       =  1, 1, 1, 1, 1    
-name_precip       =  precip
-# Large-scale Precip
-flag_plul         =  1, 1, 1, 1, 10    
-name_plul         =  plul 
-# Convective Precip
-flag_pluc         =  1, 1, 1, 1, 10    
-name_pluc         =  pluc
-# Snow fall
-flag_snow         =  1, 1, 10, 1, 10    
-name_snow         =  snow
-# Evaporation
-flag_evap         =  1, 1, 10, 1, 10    
-name_evap         =  evap
-# Solar rad. at TOA
-flag_tops         =  1, 1, 10, 10, 10    
-name_tops         =  tops
-# CS Solar rad. at TOA
-flag_tops0        =  1, 5, 10, 10, 10    
-name_tops0        =  tops0
-# IR rad. at TOA
-flag_topl         =  1, 1, 10, 1, 10    
-name_topl         =  topl
-# CR IR rad. at TOA
-flag_topl0        =  1, 5, 10, 10, 10    
-name_topl0        =  topl0
-# SWup at TOA
-flag_SWupTOA      =  1, 4, 10, 10, 10    
-name_SWupTOA      =  SWupTOA
-# CR SWup at TOA
-flag_SWupTOAclr   =  1, 4, 10, 10, 10    
-name_SWupTOAclr   =  SWupTOAclr
-# SWdn at TOA
-flag_SWdnTOA      =  1, 4, 10, 10, 10    
-name_SWdnTOA      =  SWdnTOA
-# CR SWdn at TOA
-flag_SWdnTOAclr   =  1, 4, 10, 10, 10    
-name_SWdnTOAclr   =  SWdnTOAclr
-# SWup at 200hPa
-flag_SWup200      =  1, 10, 10, 10, 10    
-name_SWup200      =  SWup200
-# CR SWup at 200hPa
-flag_SWup200clr   =  10, 1, 10, 10, 10    
-name_SWup200clr   =  SWup200clr
-# SWdn at 200hPa
-flag_SWdn200      =  1, 10, 10, 10, 10    
-name_SWdn200      =  SWdn200
-# CR SWdn at 200hPa
-flag_SWdn200clr   =  10, 1, 10, 10, 10    
-name_SWdn200clr   =  SWdn200clr
-# LWup at 200mb
-flag_LWup200      =  1, 10, 10, 10, 10    
-name_LWup200      =  LWup200
-# CR LWup at 200mb
-flag_LWup200clr   =  1, 10, 10, 10, 10    
-name_LWup200clr   =  LWup200clr
-# LWdn at 200mb
-flag_LWdn200      =  1, 10, 10, 10, 10    
-name_LWdn200      =  LWdn200
-# CR LWdn at 200mb
-flag_LWdn200clr   =  1, 10, 10, 10, 10    
-name_LWdn200clr   =  LWdn200clr
-# Solar rad. at surf
-flag_sols         =  1, 1, 10, 1, 10    
-name_sols         =  sols
-# CR Solar rad. at surf
-flag_sols0        =  1, 5, 10, 10, 10    
-name_sols0        =  sols0
-# IR rad. at surface
-flag_soll         =  1, 1, 10, 1, 10    
-name_soll         =  soll
-# CR IR rad. at surface
-flag_soll0        =  1, 5, 10, 10, 10    
-name_soll0        =  soll0
-# Rayonnement au sol
-flag_radsol       =  1, 1, 10, 10, 10    
-name_radsol       =  radsol
-# SWup at surface
-flag_SWupSFC      =  1, 4, 10, 10, 10    
-name_SWupSFC      =  SWupSFC
-# CR SWup at surface
-flag_SWupSFCclr   =  1, 4, 10, 10, 10    
-name_SWupSFCclr   =  SWupSFCclr
-# SWdn at surface
-flag_SWdnSFC      =  1, 1, 10, 10, 10    
-name_SWdnSFC      =  SWdnSFC
-# CR at surface
-flag_SWdnSFCclr   =  1, 4, 10, 10, 10    
-name_SWdnSFCclr   =  SWdnSFCclr
-# LWup at surface
-flag_LWupSFC      =  1, 4, 10, 10, 10    
-name_LWupSFC      =  LWupSFC
-# CR LWup at surface
-flag_LWupSFCclr   =  1, 4, 10, 10, 10    
-name_LWupSFCclr   =  LWupSFCclr
-# LWdn  at surface
-flag_LWdnSFC      =  1, 4, 10, 10, 10    
-name_LWdnSFC      =  LWdnSFC
-# CR LWdn  at surface
-flag_LWdnSFCclr   =  1, 4, 10, 10, 10    
-name_LWdnSFCclr   =  LWdnSFCclr
-# Surf. total heat flux
-flag_bils         =  1, 2, 10, 1, 10    
-name_bils         =  bils
-# Sensible heat flux
-flag_sens         =  1, 1, 10, 1, 1    
-name_sens         =  sens
-# Heat flux derivation
-flag_fder         =  1, 2, 10, 1, 10    
-name_fder         =  fder
-# Thermal flux for snow melting
-flag_ffonte       =  1, 10, 10, 10, 10    
-name_ffonte       =  ffonte
-# Ice Calving
-flag_fqcalving    =  1, 10, 10, 10, 10    
-name_fqcalving    =  fqcalving
-# Land ice melt
-flag_fqfonte      =  1, 10, 10, 10, 10    
-name_fqfonte      =  fqfonte
-# Zonal wind stress (ter ice liq oce)
-flag_taux_ter     =  1, 4, 10, 1, 10    
-name_taux_ter     =  taux_ter
-flag_taux_lic     =  1, 4, 10, 1, 10    
-name_taux_lic     =  taux_lic                                          
-flag_taux_oce     =  1, 4, 10, 1, 10    
-name_taux_oce     =  taux_oce
-flag_taux_sic     =  1, 4, 10, 1, 10    
-name_taux_sic     =  taux_sic
-# Meridien wind stress (ter ice liq oce)
-flag_tauy_ter     =  1, 4, 10, 1, 10    
-name_tauy_ter     =  tauy_ter
-flag_tauy_lic     =  1, 4, 10, 1, 10    
-name_tauy_lic     =  tauy_lic
-flag_tauy_oce     =  1, 4, 10, 1, 10    
-name_tauy_oce     =  tauy_oce
-flag_tauy_sic     =  1, 4, 10, 1, 10    
-name_tauy_sic     =  tauy_sic
-# % surface (ter ice liq oce)
-flag_pourc_ter    =  1, 4, 10, 1, 10    
-name_pourc_ter    =  pourc_ter  
-flag_pourc_lic    =  1, 4, 10, 1, 10    
-name_pourc_lic    =  pourc_lic
-flag_pourc_oce    =  1, 4, 10, 1, 10    
-name_pourc_oce    =  pourc_oce
-flag_pourc_sic    =  1, 4, 10, 1, 10    
-name_pourc_sic    =  pourc_sic
-# Fraction (ter ice liq oce)
-flag_fract_ter    =  1, 4, 10, 1, 10    
-name_fract_ter    =  fract_ter
-flag_fract_lic    =  1, 4, 10, 1, 10    
-name_fract_lic    =  fract_lic
-flag_fract_oce     =  1, 4, 10, 1, 10    
-name_fract_oce    =  fract_oce
-flag_fract_sic    =  1, 4, 10, 1, 10    
-name_fract_sic    =  fract_sic
-# Surface temperature (ter ice liq oce)
-flag_tsol_ter     =  1, 4, 10, 1, 10    
-name_tsol_ter     =  tsol_ter
-flag_tsol_lic     =  1, 4, 10, 1, 10    
-name_tsol_lic     =  tsol_lic
-flag_tsol_oce     =  1, 4, 10, 1, 10    
-name_tsol_oce     =  tsol_oce
-flag_tsol_sic     =  1, 4, 10, 1, 10    
-name_tsol_sic     =  tsol_sic
-# Sensible heat flux (ter ice liq oce)
-flag_sens_ter     =  1, 4, 10, 1, 10    
-name_sens_ter     =  sens_ter
-flag_sens_lic     =  1, 4, 10, 1, 10    
-name_sens_lic     =  sens_lic
-flag_sens_oce     =  1, 4, 10, 1, 10    
-name_sens_oce     =  sens_oce
-flag_sens_sic     =  1, 4, 10, 1, 10    
-name_sens_sic     =  sens_sic
-# Latent heat flux (ter ice liq oce)
-flag_lat_ter      =  1, 4, 10, 1, 10    
-name_lat_ter      =  lat_ter 
-flag_lat_lic      =  1, 4, 10, 1, 10    
-name_lat_lic      =  lat_lic
-flag_lat_oce      =  1, 4, 10, 1, 10    
-name_lat_oce      =  lat_oce
-flag_lat_sic      =  1, 4, 10, 1, 10    
-name_lat_sic      =  lat_sic 
-# LW (ter ice liq oce)
-flag_flw_ter      =  1, 10, 10, 10, 10    
-name_flw_ter      =  flw_ter
-flag_flw_lic      =  1, 10, 10, 10, 10    
-name_flw_lic      =  flw_lic
-flag_flw_oce      =  1, 10, 10, 10, 10    
-name_flw_oce      =  flw_oce
-flag_flw_sic      =  1, 10, 10, 10, 10    
-name_flw_sic      =  flw_sic
-# SW (ter ice liq oce)
-flag_fsw_ter      =  1, 10, 10, 10, 10    
-name_fsw_ter      =  fsw_ter
-flag_fsw_lic      =  1, 10, 10, 10, 10    
-name_fsw_lic      =  fsw_lic
-flag_fsw_oce      =  1, 10, 10, 10, 10    
-name_fsw_oce      =  fsw_oce
-flag_fsw_sic      =  1, 10, 10, 10, 10    
-name_fsw_sic      =  fsw_sic
-# Bilan sol (ter ice liq oce)
-flag_wbils_ter    =  1, 10, 10, 10, 10    
-name_wbils_ter    =  wbils_ter
-flag_wbils_lic    =  1, 10, 10, 10, 10    
-name_wbils_lic    =  wbils_lic
-flag_wbils_oce    =  1, 10, 10, 10, 10    
-name_wbils_oce    =  wbils_oce
-flag_wbils_sic   =  1, 10, 10, 10, 10    
-name_wbils_sic    =  wbils_sic 
-# Bilan eau (ter ice liq oce)
-flag_wbilo_ter    =  1, 10, 10, 10, 10    
-name_wbilo_ter    =  wbilo_ter
-flag_wbilo_lic    =  1, 10, 10, 10, 10    
-name_wbilo_lic    =  wbilo_lic
-flag_wbilo_oce    =  1, 10, 10, 10, 10    
-name_wbilo_oce    =  wbilo_oce
-flag_wbilo_sic    =  1, 10, 10, 10, 10    
-name_wbilo_sic    =  wbilo_sic
-# Momentum drag coef
-flag_cdrm         =  1, 10, 10, 1, 10    
-name_cdrm         =  cdrm
-# Heat drag coef
-flag_cdrh         =  1, 10, 10, 1, 10    
-name_cdrh         =  cdrh 
-# Low-level cloudiness
-flag_cldl         =  1, 1, 10, 10, 10    
-name_cldl         =  cldl
-# Mid-level cloudiness
-flag_cldm         =  1, 1, 10, 10, 10    
-name_cldm         =  cldm
-# High-level cloudiness
-flag_cldh         =  1, 1, 10, 10, 10    
-name_cldh         =  cldh
-# Total cloudiness
-flag_cldt         =  1, 1, 2, 10, 10    
-name_cldt         =  cldt
-# Cloud liquid water path
-flag_cldq         =  1, 1, 10, 10, 10    
-name_cldq         =  cldq
-# Cloud water path
-flag_lwp          =  1, 5, 10, 10, 10    
-name_lwp          =  lwp
-# Cloud ice water path
-flag_iwp          =  1, 5, 10, 10, 10    
-name_iwp          =  iwp
-# Zonal energy transport
-flag_ue           =  1, 10, 10, 10, 10    
-name_ue           =  ue
-# Merid energy transport
-flag_ve           =  1, 10, 10, 10, 10    
-name_ve           =  ve
-# Zonal humidity transport
-flag_uq           =  1, 10, 10, 10, 10    
-name_uq           =  uq
-# Merid humidity transport
-flag_vq           =  1, 10, 10, 10, 10    
-name_vq           =  vq
-# Conv avlbl pot ener
-flag_cape         =  1, 10, 10, 10, 10    
-name_cape         =  cape
-# Cld base pressure
-flag_pbase        =  1, 10, 10, 10, 10    
-name_pbase        =  pbase
-# Cld top pressure
-flag_ptop         =  1, 4, 10, 10, 10    
-name_ptop         =  ptop
-# Cld base mass flux
-flag_fbase        =  1, 10, 10, 10, 10    
-name_fbase        =  fbase
-# Precipitable water
-flag_prw          =  1, 1, 10, 10, 10    
-name_prw          =  prw
-# Boundary Layer Height
-flag_s_pblh       =  1, 10, 10, 1, 1    
-name_s_pblh       =  pblh
-# t at Boundary Layer Height
-flag_s_pblt       =  1, 10, 10, 1, 1    
-name_s_pblt       =  pblt
-# Condensation level
-flag_s_lcl        =  1, 10, 10, 1, 10    
-name_s_lcl        =  lcl
-# Conv avlbl pot enerfor ABL
-flag_s_capCL      =  1, 10, 10, 1, 10    
-name_s_capCL      =  capCL
-# Liq Water in BL
-flag_s_oliqCL     =  1, 10, 10, 1, 10    
-name_s_oliqCL     =  oliqCL
-# Instability criteria(ABL)
-flag_s_cteiCL     =  1, 10, 10, 1, 1    
-name_s_cteiCL     =  cteiCL
-# Exces du thermique
-flag_s_therm      =  1, 10, 10, 1, 1    
-name_s_therm      =  therm
-# deep_cape(HBTM2)
-flag_s_trmb1      =  1, 10, 10, 1, 10    
-name_s_trmb1      =  trmb1
-# inhibition (HBTM2)
-flag_s_trmb2      =  1, 10, 10, 1, 10    
-name_s_trmb2      =  trmb2
-# Point Omega (HBTM2)
-flag_s_trmb3      =  1, 10, 10, 1, 10    
-name_s_trmb3      =  trmb3
-# Bilan au sol sur ocean slab
-flag_slab_bils    =  1, 1, 10, 10, 10    
-name_slab_bils    =  slab_bils 
-# ALE BL
-flag_ale_bl       =  1, 1, 1, 1, 10    
-name_ale_bl       =  ale_bl 
-# alp_bl
-flag_alp_bl       =  1, 1, 1, 1, 10    
-name_alp_bl       =  alp_bl
-# ale_wk
-flag_ale_wk       =  1, 1, 1, 1, 10    
-name_ale_wk       =  ale_wk
-# alp_wk
-flag_alp_wk       =  1, 1, 1, 1, 10    
-name_alp_wk       =  alp_wk
-# ale
-flag_ale          =  1, 1, 1, 1, 10    
-name_ale          =  ale
-# alp
-flag_alp          =  1, 1, 1, 1, 10    
-name_alp          =  alp
-# Convective INhibition
-flag_cin          =  1, 1, 1, 1, 10    
-name_cin          =  cin
-# WAPE
-flag_wape         =  1, 1, 1, 1, 10    
-name_wape         =  wape
-# u, v w t q et phi aux niveaux 200, 500, 700 et 850 hPa
-flag_u850         =  1, 1, 3, 10, 10    
-name_u850         =  u850 
-flag_u700         =  1, 1, 3, 10, 10    
-name_u700         =  u700
-flag_u500         =  1, 1, 3, 10, 10    
-name_u500         =  u500
-flag_u200         =  1, 1, 3, 10, 10    
-name_u200         =  u200
-flag_v850         =  1, 1, 3, 10, 10    
-name_v850         =  v850 
-flag_v700         =  1, 1, 3, 10, 10    
-name_v700         =  v700
-flag_v500         =  1, 1, 3, 10, 10    
-name_v500         =  v500
-flag_v200         =  1, 1, 3, 10, 10    
-name_v200         =  v200
-flag_w850         =  1, 1, 3, 10, 10    
-name_w850         =  w850
-flag_w700         =  1, 1, 3, 10, 10    
-name_w700         =  w700
-flag_w500         =  1, 1, 3, 10, 10    
-name_w500         =  w500
-flag_w200         =  1, 1, 3, 10, 10    
-name_w200         =  w200
-flag_t850         =  1, 1, 3, 10, 10    
-name_t850         =  t850
-flag_t700         =  1, 1, 3, 10, 10    
-name_t700         =  t700
-flag_t500         =  1, 1, 3, 10, 10    
-name_t500         =  t500
-flag_t200         =  1, 1, 3, 10, 10    
-name_t200         =  t200
-flag_q850         =  1, 1, 3, 10, 10    
-name_q850         =  q850
-flag_q700         =  1, 1, 3, 10, 10    
-name_q700         =  q700
-flag_q500         =  1, 1, 3, 10, 10    
-name_q500         =  q500
-flag_q200         =  1, 1, 3, 10, 10    
-name_q200         =  q200
-flag_phi850       =  1, 1, 3, 10, 10    
-name_phi850       =  phi850 
-flag_phi700       =  1, 1, 3, 10, 10    
-name_phi700       =  phi700
-flag_phi500       =  1, 1, 3, 10, 10    
-name_phi500       =  phi500
-flag_phi200       =  1, 1, 3, 10, 10    
-name_phi200       =  phi200
-# Temp mixte oce-sic
-flag_t_oce_sic    =  1, 10, 10, 10, 10    
-name_t_oce_sic    =  t_oce_sic
-# Weak inversion
-flag_weakinv      =  10, 1, 10, 10, 10    
-name_weakinv      =  weakinv
-# dTheta mini
-flag_dthmin       =  10, 1, 10, 10, 10    
-name_dthmin       =  dthmin
-# 10m zonal and meriden wind (ter sic lic oce)
-flag_u10_ter      =  10, 4, 10, 10, 10    
-name_u10_ter      =  u10_ter 
-flag_u10_lic      =  10, 4, 10, 10, 10    
-name_u10_lic      =  u10_lic
-flag_u10_oce      =  10, 4, 10, 10, 10    
-name_u10_oce      =  u10_oce
-flag_u10_sic      =  10, 4, 10, 10, 10    
-name_u10_sic      =  u10_sic 
-flag_v10_ter      =  10, 4, 10, 10, 10    
-name_v10_ter      =  v10_ter
-flag_v10_lic      =  10, 4, 10, 10, 10    
-name_v10_lic      =  v10_lic
-flag_v10_oce      =  10, 4, 10, 10, 10    
-name_v10_oce      =  v10_oce
-flag_v10_sic      =  10, 4, 10, 10, 10    
-name_v10_sic      =  v10_sic
-# Cloud optical thickness
-flag_cldtau       =  10, 5, 10, 10, 10    
-name_cldtau       =  cldtau
-# Cloud optical emissivity
-flag_cldemi       =  10, 5, 10, 10, 10    
-name_cldemi       =  cldemi
-# Relative humidity at 2m
-flag_rh2m         =  10, 5, 10, 10, 10    
-name_rh2m         =  rh2m
-# Saturant humidity at 2m
-flag_qsat2m       =  10, 5, 10, 10, 10    
-name_qsat2m       =  qsat2m
-# Surface air potential temperature
-flag_tpot         =  10, 5, 10, 10, 10    
-name_tpot         =  tpot
-# Surface air equivalent potential temperature
-flag_tpote        =  10, 5, 10, 10, 10    
-name_tpote        =  tpote
-# TKE, tke max and tke (ter sic lic oce)
-flag_tke          =  4, 10, 10, 10, 10    
-name_tke          =  tke
-flag_tke_max      =  4, 10, 10, 10, 10    
-name_tke_max      =  tke_max
-flag_tke_ter      =  10, 4, 10, 10, 10    
-name_tke_ter      =  tke_ter 
-flag_tke_lic      =  10, 4, 10, 10, 10    
-name_tke_lic      =  tke_lic
-flag_tke_oce      =  10, 4, 10, 10, 10    
-name_tke_oce      =  tke_oce
-flag_tke_sic      =  10, 4, 10, 10, 10    
-name_tke_sic      =  tke_sic
-flag_tke_max_ter  =  10, 4, 10, 10, 10    
-name_tke_max_ter  =  tke_max_ter
-flag_tke_max_lic  =  10, 4, 10, 10, 10    
-name_tke_max_lic  =  tke_max_lic
-flag_tke_max_oce  =  10, 4, 10, 10, 10    
-name_tke_max_oce  =  tke_max_oce
-flag_tke_max_sic  =  10, 4, 10, 10, 10    
-name_tke_max_sic  =  tke_max_sic
-# Kz melange
-flag_kz           =  4, 10, 10, 10, 10    
-name_kz           =  kz
-# Kz max melange
-flag_kz_max       =  4, 10, 10, 10, 10    
-name_kz_max       =  kz_max
-# Sfce net SW radiation OR
-flag_SWnetOR      =  10, 10, 2, 10, 10    
-name_SWnetOR      =  SWnetOR
-# Sfce incident LW radiation OR
-flag_LWdownOR     =  10, 10, 2, 10, 10    
-name_LWdownOR     =  LWdownOR
-# Solid Large-scale Precip
-flag_snowl        =  10, 1, 10, 10, 10    
-name_snowl        =  snowl
-# cape max
-flag_cape_max     =  10, 1, 10, 10, 10    
-name_cape_max     =  cape_max
-# Down. IR rad. at surface
-flag_solldown     =  10, 1, 10, 1, 10    
-name_solldown     =  solldown
-# Boundary-layer dTs(o)
-flag_dtsvdfo      =  10, 10, 10, 1, 10    
-name_dtsvdfo      =  dtsvdfo
-# Boundary-layer dTs(t)
-flag_dtsvdft      =  10, 10, 10, 1, 10    
-name_dtsvdft      =  dtsvdft
-# Boundary-layer dTs(g)
-flag_dtsvdfg      =  10, 10, 10, 1, 10    
-name_dtsvdfg      =  dtsvdfg
-# Boundary-layer dTs(g)
-flag_dtsvdfi      =  10, 10, 10, 1, 10    
-name_dtsvdfi      =  dtsvdfi
-# rugosity
-flag_rugs         =  10, 10, 10, 1, 1    
-name_rugs         =  rugs
-# Cloud liquid water content
-flag_lwcon        =  2, 5, 10, 10, 1    
-name_lwcon        =  lwcon
-# Cloud ice water content
-flag_iwcon        =  2, 5, 10, 10, 10    
-name_iwcon        =  iwcon
-# Air temperature
-flag_temp         =  2, 3, 4, 1, 1    
-name_temp         =  temp
-# Potential air temperature
-flag_theta        =  2, 3, 4, 1, 1    
-name_theta        =  theta
-# Specific humidity
-flag_ovap         =  2, 3, 4, 1, 1    
-name_ovap         =  ovap
-# ?
-flag_ovapinit     =  2, 3, 4, 1, 1
-name_ovapinit     =  ovapinit
-# ?
-flag_wvapp        =  2, 10, 10, 10, 10    
-name_wvapp        =  wvapp
-# Geopotential height
-flag_geop         =  2, 3, 10, 1, 1    
-name_geop         =  geop
-# Zonal wind
-flag_vitu         =  2, 3, 4, 1, 1    
-name_vitu         =  vitu
-# Meridional wind
-flag_vitv         =  2, 3, 4, 1, 1    
-name_vitv         =  vitv
-# Vertical wind
-flag_vitw         =  2, 3, 10, 10, 1    
-name_vitw         =  vitw
-# Air pressure
-flag_pres         =  2, 3, 10, 1, 1    
-name_pres         =  pres
-# Cloud Fraction
-flag_rneb         =  2, 5, 10, 10, 1    
-name_rneb         =  rneb
-# Convective Cloud Fraction
-flag_rnebcon      =  2, 5, 10, 10, 1    
-name_rnebcon      =  rnebcon
-# Relative humidity
-flag_rhum         =  2, 10, 10, 10, 10    
-name_rhum         =  rhum
-# Ozone concentration
-flag_ozone        =  2, 10, 10, 10, 10    
-name_ozone        =  ozone
-# saturated updraft
-flag_upwd         =  2, 10, 10, 10, 10    
-name_upwd         =  upwd
-# Physics dT
-flag_dtphy        =  2, 10, 10, 10, 1    
-name_dtphy        =  dtphy
-# Physics dq
-flag_dqphy        =  2, 10, 10, 10, 1    
-name_dqphy        =  dqphy
-# Convective precipitation lic and ice
-flag_pr_con_l     =  2, 10, 10, 10, 10    
-name_pr_con_l     =  pr_con_l
-flag_pr_con_i     =  2, 10, 10, 10, 10    
-name_pr_con_i     =  pr_con_i
-# Large scale precipitation lic and ice
-flag_pr_lsc_l     =  2, 10, 10, 10, 10    
-name_pr_lsc_l     =  pr_lsc_l
-flag_pr_lsc_i     =  2, 10, 10, 10, 10    
-name_pr_lsc_i     =  pr_lsc_i
-# Albedo surf, Snow age and rugosity (ter sic lic oce)
-flag_albe_ter     =  3, 4, 10, 1, 10    
-name_albe_ter     =  albe_ter 
-flag_albe_lic     =  3, 4, 10, 1, 10    
-name_albe_lic     =  albe_lic
-flag_albe_oce     =  3, 4, 10, 1, 10    
-name_albe_oce     =  albe_oce
-flag_albe_sic     =  3, 4, 10, 1, 10    
-name_albe_sic     =  albe_sic 
-flag_ages_ter     =  3, 10, 10, 10, 10    
-name_ages_ter     =  ages_ter
-flag_ages_lic     =  3, 10, 10, 10, 10    
-name_ages_lic     =  ages_lic
-flag_ages_oce     =  3, 10, 10, 10, 10    
-name_ages_oce     =  ages_oce
-flag_ages_sic     =  3, 10, 10, 10, 10    
-name_ages_sic     =  ages_sic
-flag_rugs_ter     =  3, 4, 10, 1, 10    
-name_rugs_ter     =  rugs_ter 
-flag_rugs_lic     =  3, 4, 10, 1, 10    
-name_rugs_lic     =  rugs_lic
-flag_rugs_oce     =  3, 4, 10, 1, 10    
-name_rugs_oce     =  rugs_oce
-flag_rugs_sic     =  3, 4, 10, 1, 10    
-name_rugs_sic     =  rugs_sic
-# Surface albedo
-flag_albs         =  3, 10, 10, 1, 10    
-name_albs         =  albs
-# Surface albedo LW
-flag_albslw       =  3, 10, 10, 1, 10    
-name_albslw       =  albslw
-# Convective Cloud Liquid water content
-flag_clwcon       =  4, 10, 10, 10, 10    
-name_clwcon       =  clwcon
-# undilute adiab updraft
-flag_Ma           =  4, 10, 10, 10, 10    
-name_Ma           =  Ma
-# saturated downdraft
-flag_dnwd         =  4, 10, 10, 10, 10    
-name_dnwd         =  dnwd
-# unsat. downdraft
-flag_dnwd0        =  4, 10, 10, 10, 10    
-name_dnwd0        =  dnwd0
-# Dynamics dT dQ dU dV, .....
-flag_dtdyn        =  4, 10, 10, 10, 1
-name_dtdyn        =  dtdyn
-flag_dqdyn        =  4, 10, 10, 10, 1    
-name_dqdyn        =  dqdyn
-flag_dudyn        =  4, 10, 10, 10, 1    
-name_dudyn        =  dudyn
-flag_dvdyn        =  4, 10, 10, 10, 1    
-name_dvdyn        =  dvdyn 
-flag_dtcon        =  4, 5, 10, 10, 10    
-name_dtcon        =  dtcon
-flag_ducon        =  4, 10, 10, 10, 10    
-name_ducon        =  ducon
-flag_dqcon        =  4, 5, 10, 10, 10    
-name_dqcon        =  dqcon
-flag_dtwak        =  4, 5, 10, 10, 10    
-name_dtwak        =  dtwak
-flag_dqwak        =  4, 5, 10, 10, 10    
-name_dqwak        =  dqwak
-flag_wake_h       =  4, 5, 10, 10, 10    
-name_wake_h       =  wake_h
-flag_wake_s       =  4, 5, 10, 10, 10    
-name_wake_s       =  wake_s
-flag_wake_deltat  =  4, 5, 10, 10, 10    
-name_wake_deltat  =  wake_deltat
-flag_wake_deltaq  =  4, 5, 10, 10, 10    
-name_wake_deltaq  =  wake_deltaq
-flag_wake_omg     =  4, 5, 10, 10, 10    
-name_wake_omg     =  wake_omg 
-flag_Vprecip      =  10, 10, 10, 10, 10    
-name_Vprecip      =  Vprecip
-flag_ftd          =  4, 5, 10, 10, 10    
-name_ftd          =  ftd
-flag_fqd          =  4, 5, 10, 10, 10    
-name_fqd          =  fqd
-flag_dtlsc        =  4, 10, 10, 10, 10    
-name_dtlsc        =  dtlsc
-flag_dtlschr      =  4, 10, 10, 10, 10    
-name_dtlschr      =  dtlschr
-flag_dqlsc        =  4, 10, 10, 10, 10    
-name_dqlsc        =  dqlsc
-flag_dtvdf        =  4, 10, 10, 1, 10    
-name_dtvdf        =  dtvdf
-flag_dqvdf        =  4, 10, 10, 1, 10    
-name_dqvdf        =  dqvdf
-flag_dteva        =  4, 10, 10, 10, 10    
-name_dteva        =  dteva
-flag_dqeva        =  4, 10, 10, 10, 10    
-name_dqeva        =  dqeva
-flag_ptconv       =  4, 10, 10, 10, 10    
-name_ptconv       =  ptconv
-flag_ratqs        =  4, 10, 10, 10, 10    
-name_ratqs        =  ratqs
-flag_dtthe        =  4, 10, 10, 10, 10    
-name_dtthe        =  dtthe
-flag_f_th         =  4, 10, 10, 10, 10    
-name_f_th         =  f_th
-flag_e_th         =  4, 10, 10, 10, 10    
-name_e_th         =  e_th
-flag_w_th         =  4, 10, 10, 10, 10    
-name_w_th         =  w_th
-flag_lambda_th    =  4, 10, 10, 10, 10    
-name_lambda_th    =  lambda_th
-flag_q_th         =  4, 10, 10, 10, 10    
-name_q_th         =  q_th
-flag_a_th         =  4, 10, 10, 10, 10    
-name_a_th         =  a_th
-flag_d_th         =  4, 10, 10, 10, 10    
-name_d_th         =  d_th
-flag_f0_th        =  4, 10, 10, 10, 10    
-name_f0_th        =  f0_th
-flag_zmax_th      =  4, 10, 10, 10, 10    
-name_zmax_th      =  zmax_th
-flag_dqthe        =  4, 10, 10, 10, 1    
-name_dqthe        =  dqthe
-flag_dtajs        =  4, 10, 10, 10, 10    
-name_dtajs        =  dtajs
-flag_dqajs        =  4, 10, 10, 10, 10    
-name_dqajs        =  dqajs
-flag_dtswr        =  4, 10, 10, 10, 1    
-name_dtswr        =  dtswr
-flag_dtsw0        =  4, 10, 10, 10, 10    
-name_dtsw0        =  dtsw0 
-flag_dtlwr        =  4, 10, 10, 10, 1    
-name_dtlwr        =  dtlwr
-flag_dtlw0        =  4, 10, 10, 10, 10    
-name_dtlw0        =  dtlw0
-flag_dtec         =  4, 10, 10, 10, 10    
-name_dtec         =  dtec
-flag_duvdf        =  4, 10, 10, 10, 10    
-name_duvdf        =  duvdf
-flag_dvvdf        =  4, 10, 10, 10, 10    
-name_dvvdf        =  dvvdf
-flag_duoro        =  4, 10, 10, 10, 10    
-name_duoro        =  duoro
-flag_dvoro        =  4, 10, 10, 10, 10    
-name_dvoro        =  dvoro
-flag_dulif        =  4, 10, 10, 10, 10    
-name_dulif        =  dulif
-flag_dvlif        =  4, 10, 10, 10, 10    
-name_dvlif        =  dvlif
-###! Attention a refaire correctement
-flag_trac01       =  4, 10, 10, 10, 10    
-name_trac01       =  trac01 
-flag_trac02       =  4, 10, 10, 10, 10    
-name_trac02       =  trac02
+phys_out_filekeys__00001 = TRUE
+phys_out_filelevels__00001 =            1
 
+phys_out_filekeys__00002 = TRUE 
+phys_out_levmax__00002 = 42
+phys_out_filenames__00002 = histday_ave
+phys_out_filelevels__00002 =  2
+
+flag_t2m_max__00002 =            10
+flag_wind10max__00002 =            10
+flag_tke_max_ter__00002 =            10
+flag_tke_max_lic__00002 =            10
+flag_tke_max_oce__00002 =            10
+flag_tke_max_sic__00002 =            10
+flag_cape_max__00002 =            10
+flag_t2m_min__00002 =            10
+ flag_taux_oce__00002 =            2
+ flag_tauy_oce__00002 =            2
+ flag_tsol_oce__00002 =            2
+ flag_evappot_oce__00002 =            2
+ flag_ustar_oce__00002 =            2
+ flag_u10m_oce__00002 =            2
+ flag_v10m_oce__00002 =            2
+ flag_t2m_oce__00002 =            2
+ flag_evap_oce__00002 =            2
+ flag_sens_oce__00002 =            2
+ flag_lat_oce__00002 =            2
+ flag_sens_rain_oce__00002 =            2
+ flag_sens_snow_oce__00002 =            2
+ flag_lat_rain_oce__00002 =            2
+ flag_lat_snow_oce__00002 =            2
+ flag_wstar_oce__00002 =            2
+ flag_z0m_oce__00002 =            2
+ flag_z0h_oce__00002 =            2
+
+phys_out_filekeys__00003 = FALSE
+phys_out_levmax__00003 = 42
+phys_out_filetimesteps__00003 = 1hours
+phys_out_filetypes__00003 = ave(X)
+phys_out_filenames__00003 = histhf_ave
+
+flag_precip__00003 = 1
+flag_sens_oce__00003 = 1
+flag_lat_oce__00003 = 1
+flag_flw_oce__00003 = 1
+flag_fsw_oce__00003 = 1
+flag_taux_oce__00003 = 1
+flag_tauy_oce__00003 = 1
+flag_rf__00003 = 1
+flag_taur__00003 = 1
+flag_slp__00003 = 10
+flag_tsol__00003 = 10
+flag_t2m__00003 = 10
+flag_wind10m__00003 = 10
+flag_gusts__00003 = 10
+flag_q2m__00003 = 10
+flag_u10m__00003 = 10
+flag_v10m__00003 = 10
+flag_psol__00003 = 10
+flag_ale_bl__00003 = 10
+flag_alp_bl__00003 = 10
+flag_ale_wk__00003 = 10
+flag_ale__00003 = 10
+flag_alp__00003 = 10
+flag_cin__00003 = 10
+flag_wape__00003 = 10
+flag_alp_bl_det__00003 = 10
+flag_alp_bl_fluct_m__00003 = 10
+flag_alp_bl_fluct_tke__00003 = 10
+flag_alp_bl_conv__00003 = 10
+flag_alp_bl_stat__00003 = 10
+
+phys_out_levmax__00004 = 42
+phys_out_filekeys__00004 = FALSE
+phys_out_filetimesteps__00004 = 1hours
+phys_out_filenames__00004 = histhf_ins
+phys_out_filelevels__00004 = 1
+
+flag_u10m_oce__00004 = 1
+flag_v10m_oce__00004 = 1
+flag_tsol_oce__00004 = 1
+flag_psol__00004 = 1
+flag_temp__00004 = 2
+flag_ovap__00004 = 2
+flag_dtvdf__00004 =           2
+flag_dtthe__00004 =           2
+flag_dtcon__00004 =           2
+flag_dqvdf__00004 =           2
+flag_dqthe__00004 =           2
+flag_dqcon__00004 =           2
+flag_rf__00004 =            10
+flag_taur__00004 =            10
+flag_JrNt__00004 =            1
+flag_rhum__00004 =            2
+flag_slp__00004 = 1
+flag_t2m__00004 = 1
+flag_wind10m__00004 = 1
+flag_gusts__00004 = 1
+flag_q2m__00004 = 1
+
+phys_out_levmax__00005 = 42
+phys_out_filekeys__00005 = TRUE
+phys_out_filetypes__00005 = t_max(X)
+phys_out_filetimesteps__00005 = 1days
+phys_out_filenames__00005 = histday_max
+phys_out_filelevels__00005 =  1
+
+flag_T_int__00005 =           1
+flag_t2m__00005 =            1
+flag_wind10m__00005 =            1
+flag_cape__00005 =            1
+flag_phis__00005 =            10
+
+phys_out_levmax__00006 = 42
+phys_out_filekeys__00006 = TRUE
+phys_out_filenames__00006 = histday_min
+phys_out_filetypes__00006 = t_min(X)
+phys_out_filetimesteps__00006 = 1days
+phys_out_filelevels__00006 =  1
+
+flag_T_int__00006 =           1
+flag_t2m__00006 =            1
+flag_phis__00006 =            10
Index: /LMDZ6/branches/Ocean_skin/DefLists/physiq.def_NPv6.1
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/physiq.def_NPv6.1	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/physiq.def_NPv6.1	(revision 3605)
@@ -1,4 +1,4 @@
 #
-# $Id: physiq.def_NPv6.1 3668 2018-03-20 14:55:33Z lfairhead $
+# $Id: physiq.def_NPv6.0.15_S 3593 2018-02-20 10:07:02Z jgipsl $
 #
 
@@ -369,4 +369,149 @@
 ptcrit=500
 
+          # Precipitation ejection from adiabatic ascents
+          # cvflag_prec_eject: when TRUE ejection is activated. Default: False
+          # ejectliq : 0. =>liquid precipitation is carried up in the adiab updraughts
+          #            1. =>liquid precipitation is ejected from adiab updraughts
+          # ejectice   0. =>solid precipitation is carried up in the adiab updraughts
+          #            1. =>solid precipitation is ejected from adiab updraughts
+          # ejectliq may take only 0. and 1. values
+          # ejectice may take any value between 0. and 1.
+          #   Default : cvflag_prec_eject=n, ejectliq=0., ejectice=0.
+cvflag_prec_eject=n
+ejectliq=0.
+ejectice=0.
+
+
+          # Check whether parcel level temperature and specific humidity
+          # are reasonable and demand that LCL be high enough
+cv_flag_feed=2
+
+          # save 20% CPU 
+ok_optim_yield=y
+
+          # Convective clouds
+iflag_cld_cv=0
+
+          # To get back to bug where convective output variables
+          # were set to 0 at the start of the physics
+ok_bug_cv_trac=n
+
+           # solving of the temperature equation for the adiabatic ascent
+           # 0 -> AJ scheme in two loops ; ice fraction given by envt. temp.
+           # 1 -> JYG scheme in one loop ; ice fraction given by envt. temp.
+           # 2 -> JYG scheme in one loop ; ice fraction given by adiab. asc. temp.
+           # Default: 0
+           # 2 is costly and ill tested; experts only.
+icvflag_Tpa=0
+
+           # taking into account the dependence of qv on qt at saturation
+           # Default: n
+qsat_depends_on_qt=n
+
+##########################################################
+# Fermeture convective et couplages
+##########################################################
+
+          # Appel separe des thermiques 
+iflag_pbl_split=10
+
+          #rendement sur la puissance fournie par les thermiques a la convection
+alp_bl_k=0.5
+
+          #Constant value to be added to Alp (D: 0.)
+alp_offset=0
+
+          #Convection must reach a level at which T<t_top_max to be active
+t_top_max=1000
+
+          ### nrlmd le 10/04/2012: Declenchement ###
+          #Declenchement par couche-limite (0: deterministe, 1: stochastique)
+iflag_trig_bl=1
+
+          #Surface critique au LCL
+s_trig=12000000
+
+          #Temps de decorrelation entre scenes de cumulus
+tau_trig_shallow=1200
+
+          #Temps de decorrelation entre scenes de cumulonimbus
+tau_trig_deep=1200
+
+          # Pour la stabilisation
+random_notrig_max=0.99
+
+          # Temperature a la quelle on fond les descentes glacees
+tmax_fonte_cv=278.15
+
+          #Fermeture par couche-limite (Nicolas Rochetin)
+          #(0: deterministe, 1: statistique, 2: statistique+convergence
+          # grande echelle)
+iflag_clos_bl=1
+
+          #coefficient in Wape->C_star formula: C_star=stark*sqrt(2*Wape),
+          # def: 0.33
+stark=0.33
+
+          #lifting efficiency of wakes; Alp=Alpk*Fip, Fip=power provided
+          # by wakes, def: 0.25
+alpk=0.25
+
+#
+##########################################################
+# Couche limite convective / modele du thermique
+##########################################################
+
+          # Convection seche (D:0, 0:ajustement sec,=>1:modele du thermique) 
+iflag_thermals=18
+
+          # pas de temps du spliting pour les thermiques
+          # TOURNE MAIS POSE PLUS DE PROBLEME QU ELLE N EN RESOUD
+nsplit_thermals=1
+
+          # tau_thermals pour avoir une constante de temps sur les thermiques.
+          # Non valide
+tau_thermals=0
+
+          # Flag controlant le detrainement et l entrainement
+iflag_thermals_ed=8
+
+          # On va chercher l air a z * ( 1+fact_thermals_ed_dz) pour calculer
+          # le detrainement (A. Jam)
+fact_thermals_ed_dz=0.07
+
+          # Une option de plus sur les thermiques.
+iflag_thermals_optflux=0
+
+          #couplage ou non avec la convection
+iflag_coupl=5
+
+          # Seuil pour desactiver les thermiques en cas de forte inversion
+          # en sommet de couche limite. Actif si iflag_thermals impair.
+seuil_inversion=-0.08
+
+          # Reactivation du calcul d un zmax continu pour les thermiques
+          # reactivation d une fermeture humide des thermiques
+          # iflag_thermals_closure=2 (D=1)
+iflag_thermals_closure=2
+
+
+##########################################################
+# Flags wakes
+##########################################################
+
+          #Wake scheme switch (D:0, 0:AR4, 1:New Physics)
+iflag_wake=1
+
+          #multiplicative factor of the damping by gravity waves, def: 4.
+coefgw=4
+
+          #wake density = number of wake centers per m2, def: 8.E-12
+          #wdens_ref=8.E-12
+wdens_ref_o=1e-09
+wdens_ref_l=8e-12
+
+          # Ajustement convectif prealable au calcul des poches
+ok_adjwk=y
+
           # Prevent some crashes
           # Filter out bad wakes
@@ -375,123 +520,4 @@
 iflag_alp_wk_cond=1
 
-
-          # Check whether parcel level temperature and specific humidity
-          # are reasonable and demand that LCL be high enough
-cv_flag_feed=2
-
-          # save 20% CPU 
-ok_optim_yield=y
-
-          # Convective clouds
-iflag_cld_cv=0
-
-          # To get back to bug where convective output variables
-          # were set to 0 at the start of the physics
-ok_bug_cv_trac=n
-
-##########################################################
-# Fermeture convective et couplages
-##########################################################
-
-          # Appel separe des thermiques 
-iflag_pbl_split=10
-
-          #rendement sur la puissance fournie par les thermiques a la convection
-alp_bl_k=0.5
-
-          #Constant value to be added to Alp (D: 0.)
-alp_offset=0
-
-          #Convection must reach a level at which T<t_top_max to be active
-t_top_max=1000
-
-          ### nrlmd le 10/04/2012: Declenchement ###
-          #Declenchement par couche-limite (0: deterministe, 1: stochastique)
-iflag_trig_bl=1
-
-          #Surface critique au LCL
-s_trig=12000000
-
-          #Temps de decorrelation entre scenes de cumulus
-tau_trig_shallow=1200
-
-          #Temps de decorrelation entre scenes de cumulonimbus
-tau_trig_deep=1200
-
-          # Pour la stabilisation
-random_notrig_max=0.99
-
-          # Temperature a la quelle on fond les descentes glacees
-tmax_fonte_cv=278.15
-
-          #Fermeture par couche-limite (Nicolas Rochetin)
-          #(0: deterministe, 1: statistique, 2: statistique+convergence
-          # grande echelle)
-iflag_clos_bl=1
-
-          #coefficient in Wape->C_star formula: C_star=stark*sqrt(2*Wape),
-          # def: 0.33
-stark=0.33
-
-          #lifting efficiency of wakes; Alp=Alpk*Fip, Fip=power provided
-          # by wakes, def: 0.25
-alpk=0.25
-
-#
-##########################################################
-# Couche limite convective / modele du thermique
-##########################################################
-
-          # Convection seche (D:0, 0:ajustement sec,=>1:modele du thermique) 
-iflag_thermals=18
-
-          # pas de temps du spliting pour les thermiques
-          # TOURNE MAIS POSE PLUS DE PROBLEME QU ELLE N EN RESOUD
-nsplit_thermals=1
-
-          # tau_thermals pour avoir une constante de temps sur les thermiques.
-          # Non valide
-tau_thermals=0
-
-          # Flag controlant le detrainement et l entrainement
-iflag_thermals_ed=8
-
-          # On va chercher l air a z * ( 1+fact_thermals_ed_dz) pour calculer
-          # le detrainement (A. Jam)
-fact_thermals_ed_dz=0.07
-
-          # Une option de plus sur les thermiques.
-iflag_thermals_optflux=0
-
-          #couplage ou non avec la convection
-iflag_coupl=5
-
-          # Seuil pour desactiver les thermiques en cas de forte inversion
-          # en sommet de couche limite. Actif si iflag_thermals impair.
-seuil_inversion=-0.08
-
-          # Reactivation du calcul d un zmax continu pour les thermiques
-          # reactivation d une fermeture humide des thermiques
-          # iflag_thermals_closure=2 (D=1)
-iflag_thermals_closure=2
-
-
-##########################################################
-# Flags wakes
-##########################################################
-
-          #Wake scheme switch (D:0, 0:AR4, 1:New Physics)
-iflag_wake=1
-
-          #multiplicative factor of the damping by gravity waves, def: 4.
-coefgw=4
-
-          #wake density = number of wake centers per m2, def: 8.E-12
-          #wdens_ref=8.E-12
-wdens_ref_o=1e-09
-wdens_ref_l=8e-12
-
-          # Ajustement convectif prealable au calcul des poches
-ok_adjwk=y
 
 
@@ -531,2 +557,4 @@
 
 cdnc_min=10.
+flag_ocean_skin=3
+activate_ocean_skin = 2
Index: /LMDZ6/branches/Ocean_skin/DefLists/run.def
===================================================================
--- /LMDZ6/branches/Ocean_skin/DefLists/run.def	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/DefLists/run.def	(revision 3605)
@@ -4,20 +4,18 @@
 INCLUDEDEF=gcm.def
 INCLUDEDEF=vert.def
-INCLUDEDEF=orchidee.def
 INCLUDEDEF=config.def
-INCLUDEDEF=reprobus.def
-INCLUDEDEF=guide.def
-INCLUDEDEF=inca.def
+INCLUDEDEF=output.def
+
 ## Type de calendrier utilise
 ## valeur possible: earth_360d (defaut), earth_365d, earth_366d
 calend= gregorian
 ## Jour de l etat initial ( = 350  si 20 Decembre ,par expl. ,comme ici )
-dayref= 1
+dayref= 32
 ##  Annee de l etat  initial (   avec  4  chiffres   )
-anneeref= 1979
+anneeref= 1989
 ## Nombre de jours d integration
-nday= 365
+nday= 31
 ## Remise a zero de la date initiale
-raz_date= 0
+raz_date= 1
 ## periode de sortie des variables de controle (en pas)
 iconser=240
@@ -44,5 +42,5 @@
 ### VEGET= y si ORCHIDEE, =n si bucket
 ### VEGET is modified automatically by the lmdz.driver 
-VEGET= y
+VEGET= betaclim
 ### Choice of tracers type_trac=lmdz/inca/repr
 ### type_trac is set automatically by the lmdz.driver
@@ -51,5 +49,5 @@
 config_inca= none
 ### To activate XIOS ouputs only, set n to use IOIPSL
-ok_all_xml= y
+ok_all_xml= n
 ### Only read by ce0l : Do not set land points on Antartic
 no_ter_antartique=y
Index: /LMDZ6/branches/Ocean_skin/arch/arch-X64_ADA.fcm
===================================================================
--- /LMDZ6/branches/Ocean_skin/arch/arch-X64_ADA.fcm	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/arch/arch-X64_ADA.fcm	(revision 3605)
@@ -11,7 +11,7 @@
 %DEBUG_FFLAGS        -p -g -O0 -fpe-all=0 -traceback -ftrapuv -fp-stack-check -check bounds,format,output_conversion,pointers,uninit -debug -ftz
 %MPI_FFLAGS
-%OMP_FFLAGS          -openmp
-%BASE_LD             -L/smplocal/pub/FFTW/3.3.3_dyn/lib -lfftw3 -shared-intel  -lmkl_intel_lp64 -lmkl_sequential -lmkl_core -lpthread -Wl,-rpath=/smplocal/pub/NetCDF/4.1.3/mpi/lib:/smplocal/pub/HDF5/1.8.9/par/lib:/smplocal/pub/FFTW/3.3.3_dyn/lib
-%MPI_LD              
-%OMP_LD              -openmp
+%OMP_FFLAGS          -qopenmp
+%BASE_LD             -L/smplocal/pub/FFTW/3.3.3_dyn/lib -lfftw3 -shared-intel  -lmkl_intel_lp64 -lmkl_sequential -lmkl_core -lpthread -Wl,-rpath=/smplocal/pub/FFTW/3.3.3_dyn/lib
+%MPI_LD              -L/smplocal/pub/IdrMemMPI/1.4/lib -lidrmem
+%OMP_LD              -qopenmp
 
Index: /LMDZ6/branches/Ocean_skin/arch/arch-X64_ADA.path
===================================================================
--- /LMDZ6/branches/Ocean_skin/arch/arch-X64_ADA.path	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/arch/arch-X64_ADA.path	(revision 3605)
@@ -1,6 +1,6 @@
 NETCDF_LIBDIR="${NETCDF_LDFLAGS:--L/smplocal/pub/NetCDF/4.1.3/mpi/lib -lnetcdff -lnetcdf -L/smplocal/pub/HDF5/1.8.9/par/lib -Bstatic -lhdf5hl_fortran -lhdf5_hl -lhdf5_fortran -lhdf5 -Bdynamic -lz}"
 NETCDF_INCDIR="${NETCDF_FFLAGS:--I/smplocal/pub/HDF5/1.8.9/par/include -I/smplocal/pub/NetCDF/4.1.3/mpi/include}"
-IOIPSL_INCDIR=$LMDGCM/../../lib
-IOIPSL_LIBDIR=$LMDGCM/../../lib
+IOIPSL_INCDIR=${workdir}/build/IOIPSL_trunk_ifort_fast
+IOIPSL_LIBDIR=${workdir}/build/IOIPSL_trunk_ifort_fast
 XIOS_INCDIR=$LMDGCM/../XIOS/inc
 XIOS_LIBDIR=$LMDGCM/../XIOS/lib
Index: /LMDZ6/branches/Ocean_skin/arch/arch-X64_IRENE.fcm
===================================================================
--- /LMDZ6/branches/Ocean_skin/arch/arch-X64_IRENE.fcm	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/arch/arch-X64_IRENE.fcm	(revision 3605)
@@ -11,4 +11,5 @@
 %DEV_FFLAGS          -fp-model strict -p -g -O2 -traceback -fp-stack-check
 %DEBUG_FFLAGS        -fp-model strict -p -g -traceback -fp-stack-check -ftrapuv
+#%DEBUG_FFLAGS        -fp-model strict -p -g -traceback -fp-stack-check -ftrapuv -check bounds,noarg_temp_created,pointers,stack,uninit -debug full -init=arrays -init=snan
 %MPI_FFLAGS
 %OMP_FFLAGS          -qopenmp
Index: /LMDZ6/branches/Ocean_skin/arch/arch-X64_IRENE.path
===================================================================
--- /LMDZ6/branches/Ocean_skin/arch/arch-X64_IRENE.path	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/arch/arch-X64_IRENE.path	(revision 3605)
@@ -1,12 +1,12 @@
 NETCDF_LIBDIR="-L$NETCDFFORTRAN_LIBDIR -L$NETCDF_LIBDIR -lnetcdf -lnetcdff"
 NETCDF_INCDIR=-I$NETCDFFORTRAN_INCDIR
-IOIPSL_INCDIR=$LMDGCM/../../lib
-IOIPSL_LIBDIR=$LMDGCM/../../lib
+IOIPSL_INCDIR="$LMDGCM/../../lib -I$LMDGCM/../IOIPSL/inc"
+IOIPSL_LIBDIR="$LMDGCM/../../lib -lioipsl -L$LMDGCM/../IOIPSL/lib"
 ORCH_INCDIR=$LMDGCM/../../lib
 ORCH_LIBDIR=$LMDGCM/../../lib
 OASIS_INCDIR=$LMDGCM/../../oasis3-mct/BLD/build/lib/psmile.MPI1
 OASIS_LIBDIR=$LMDGCM/../../oasis3-mct/BLD/lib
-INCA_LIBDIR=$LMDGCM/../INCA/config/lib
-INCA_INCDIR=$LMDGCM/../INCA/config/inc
+INCA_LIBDIR=$LMDGCM/../INCA/build/lib
+INCA_INCDIR=$LMDGCM/../INCA/build/inc
 XIOS_INCDIR=$LMDGCM/../XIOS/inc
 XIOS_LIBDIR=$LMDGCM/../XIOS/lib
Index: /LMDZ6/branches/Ocean_skin/arch/arch-X64_JEANZAY.env
===================================================================
--- /LMDZ6/branches/Ocean_skin/arch/arch-X64_JEANZAY.env	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/arch/arch-X64_JEANZAY.env	(revision 3605)
@@ -0,0 +1,8 @@
+module purge
+module load intel-compilers/19.0.4
+module load intel-mpi/19.0.4
+module load intel-mkl/19.0.4
+module load hdf5/1.10.5/intel-19.0.4-mpi
+module load netcdf/4.7.0/intel-19.0.4-mpi
+module load netcdf-fortran/4.4.5/intel-19.0.4-mpi
+
Index: /LMDZ6/branches/Ocean_skin/arch/arch-X64_JEANZAY.fcm
===================================================================
--- /LMDZ6/branches/Ocean_skin/arch/arch-X64_JEANZAY.fcm	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/arch/arch-X64_JEANZAY.fcm	(revision 3605)
@@ -0,0 +1,17 @@
+# $Id$
+%COMPILER            mpiifort
+%LINK                mpiifort
+%AR                  ar
+%ARFLAGS             rs
+%MAKE                gmake
+%FPP_FLAGS           -P -traditional
+%FPP_DEF             NC_DOUBLE FFT_MKL
+%BASE_FFLAGS         -i4 -r8 -auto -align all -fp-model strict
+%PROD_FFLAGS         -O3 -xHost -qopt-zmm-usage=high
+%DEV_FFLAGS          -p -g -O2 -traceback -fp-stack-check
+%DEBUG_FFLAGS        -p -g -O0 -traceback -fp-stack-check -ftrapuv -check bounds,noarg_temp_created,pointers,stack,uninit -debug full -init=arrays -init=snan
+%MPI_FFLAGS
+%OMP_FFLAGS          -qopenmp
+%BASE_LD             -i4 -r8 -auto -lmkl_intel_lp64 -lmkl_core -lmkl_sequential -lpthread
+%MPI_LD
+%OMP_LD              -qopenmp
Index: /LMDZ6/branches/Ocean_skin/arch/arch-X64_JEANZAY.path
===================================================================
--- /LMDZ6/branches/Ocean_skin/arch/arch-X64_JEANZAY.path	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/arch/arch-X64_JEANZAY.path	(revision 3605)
@@ -0,0 +1,15 @@
+# $Id$
+#NETCDF_LIBDIR="-L$NETCDFFORTRAN_LIBDIR -L$NETCDF_LIBDIR -lnetcdf -lnetcdff"
+#NETCDF_INCDIR=-I$NETCDFFORTRAN_INCDIR
+NETCDF_LIBDIR="-lnetcdf -lnetcdff"
+NETCDF_INCDIR=
+IOIPSL_INCDIR=$WORK/build/IOIPSL_trunk
+IOIPSL_LIBDIR=$WORK/build/IOIPSL_trunk
+ORCH_INCDIR=$LMDGCM/../../lib
+ORCH_LIBDIR=$LMDGCM/../../lib
+OASIS_INCDIR=$LMDGCM/../../oasis3-mct/BLD/build/lib/psmile.MPI1
+OASIS_LIBDIR=$LMDGCM/../../oasis3-mct/BLD/lib
+INCA_LIBDIR=$LMDGCM/../INCA/build/lib
+INCA_INCDIR=$LMDGCM/../INCA/build/inc
+XIOS_INCDIR=$LMDGCM/../XIOS/inc
+XIOS_LIBDIR=$LMDGCM/../XIOS/lib
Index: /LMDZ6/branches/Ocean_skin/arch/arch-gfortran.path
===================================================================
--- /LMDZ6/branches/Ocean_skin/arch/arch-gfortran.path	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/arch/arch-gfortran.path	(revision 3605)
@@ -1,6 +1,6 @@
-NETCDF_LIBDIR="-L/usr/local/lib -lnetcdf"
-NETCDF_INCDIR=-I/usr/local/include
-IOIPSL_INCDIR=$LMDGCM/../../lib
-IOIPSL_LIBDIR=$LMDGCM/../../lib
+NETCDF_LIBDIR="-lnetcdff -lnetcdf"
+NETCDF_INCDIR=-I/usr/include
+IOIPSL_INCDIR=/home/guez/Downloads/Compil_prod/IOIPSL
+IOIPSL_LIBDIR=/home/guez/Downloads/Compil_prod/IOIPSL
 ORCH_INCDIR=$LMDGCM/../../lib
 ORCH_LIBDIR=$LMDGCM/../../lib
Index: /LMDZ6/branches/Ocean_skin/bld.cfg
===================================================================
--- /LMDZ6/branches/Ocean_skin/bld.cfg	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/bld.cfg	(revision 3605)
@@ -47,5 +47,5 @@
 dir::root            %CONFIG_PATH
 #dir::lib             %BASE_CONFIG_PATH
-dir::bin             %ROOT_PATH/bin
+dir::bin             %LIBO
 
 #search_src           1
Index: /LMDZ6/branches/Ocean_skin/libf/dyn3d/conf_gcm.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dyn3d/conf_gcm.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dyn3d/conf_gcm.F90	(revision 3605)
@@ -21,5 +21,5 @@
   USE serre_mod, ONLY: clon,clat,grossismx,grossismy,dzoomx,dzoomy, &
                        alphax,alphay,taux,tauy
-  USE temps_mod, ONLY: calend
+  USE temps_mod, ONLY: calend, year_len
 
   IMPLICIT NONE
@@ -115,4 +115,14 @@
   calend = 'earth_360d'
   CALL getin('calend', calend)
+! initialize year_len for aquaplanets and 1D
+      if (calend == 'earth_360d') then
+        year_len=360
+      else if (calend == 'earth_365d') then
+        year_len=365
+      else if (calend == 'earth_366d') then
+        year_len=366
+      else 
+        year_len=1
+      endif
 
   !Config  Key  = dayref
Index: /LMDZ6/branches/Ocean_skin/libf/dyn3d/gcm.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dyn3d/gcm.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dyn3d/gcm.F90	(revision 3605)
@@ -241,4 +241,6 @@
        'GCM: AVANT iniacademic AVANT AVANT AVANT AVANT'
   if (.not.read_start) then
+     start_time=0.
+     annee_ref=anneeref
      CALL iniacademic(vcov,ucov,teta,q,masse,ps,phis,time_0)
   endif
@@ -377,4 +379,28 @@
        tetagdiv, tetagrot , tetatemp, vert_prof_dissip)
 
+  !  numero de stockage pour les fichiers de redemarrage:
+
+  !-----------------------------------------------------------------------
+  !   Initialisation des I/O :
+  !   ------------------------
+
+
+  if (nday>=0) then
+     day_end = day_ini + nday
+  else
+     day_end = day_ini - nday/day_step
+  endif
+  WRITE(lunout,300)day_ini,day_end
+300 FORMAT('1'/,15x,'run du jour',i7,2x,'au jour',i7//)
+
+#ifdef CPP_IOIPSL
+  call ju2ymds(jD_ref + day_ini - day_ref, an, mois, jour, heure)
+  write (lunout,301)jour, mois, an
+  call ju2ymds(jD_ref + day_end - day_ref, an, mois, jour, heure)
+  write (lunout,302)jour, mois, an
+301 FORMAT('1'/,15x,'run du ', i2,'/',i2,'/',i4)
+302 FORMAT('1'/,15x,'    au ', i2,'/',i2,'/',i4)
+#endif
+
   !-----------------------------------------------------------------------
   !   Initialisation de la physique :
@@ -391,28 +417,4 @@
 #endif
   ENDIF ! of IF ((iflag_phys==1).or.(iflag_phys>=100))
-
-  !  numero de stockage pour les fichiers de redemarrage:
-
-  !-----------------------------------------------------------------------
-  !   Initialisation des I/O :
-  !   ------------------------
-
-
-  if (nday>=0) then
-     day_end = day_ini + nday
-  else
-     day_end = day_ini - nday/day_step
-  endif
-  WRITE(lunout,300)day_ini,day_end
-300 FORMAT('1'/,15x,'run du jour',i7,2x,'au jour',i7//)
-
-#ifdef CPP_IOIPSL
-  call ju2ymds(jD_ref + day_ini - day_ref, an, mois, jour, heure)
-  write (lunout,301)jour, mois, an
-  call ju2ymds(jD_ref + day_end - day_ref, an, mois, jour, heure)
-  write (lunout,302)jour, mois, an
-301 FORMAT('1'/,15x,'run du ', i2,'/',i2,'/',i4)
-302 FORMAT('1'/,15x,'    au ', i2,'/',i2,'/',i4)
-#endif
 
   !      if (planet_type.eq."earth") then
Index: /LMDZ6/branches/Ocean_skin/libf/dyn3d/temps_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dyn3d/temps_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dyn3d/temps_mod.F90	(revision 3605)
@@ -13,4 +13,5 @@
   INTEGER   annee_ref
   INTEGER   day_ref
+  INTEGER   year_len
   REAL      dt ! (dynamics) time step (changes if doing Matsuno or LF step)
   REAL      jD_ref ! reference julian day date (beginning of experiment)
Index: /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/caladvtrac_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/caladvtrac_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/caladvtrac_mod.F90	(revision 3605)
@@ -44,5 +44,7 @@
     CALL allocate_u(massem,llm,d)
     CALL allocate_u(pbaruc,llm,d)
+    pbaruc(:,:)=0
     CALL allocate_v(pbarvc,llm,d)
+    pbarvc(:,:)=0
     CALL allocate_u(pbarug,llm,d)
     CALL allocate_v(pbarvg,llm,d)
Index: /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/call_calfis_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/call_calfis_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/call_calfis_mod.F90	(revision 3605)
@@ -52,5 +52,7 @@
     CALL allocate_u(p,llmp1,d)
     CALL allocate_u(pks,d)
+    pks(:)=0
     CALL allocate_u(pk,llm,d)
+    pk(:,:)=0
     CALL allocate_u(pkf,llm,d)
     CALL allocate_u(phi,llm,d)
Index: /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/call_dissip_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/call_dissip_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/call_dissip_mod.F90	(revision 3605)
@@ -31,5 +31,7 @@
 
     CALL allocate_u(ucov,llm,d)
+    ucov(:,:)=0
     CALL allocate_v(vcov,llm,d)
+    vcov(:,:)=0
     CALL allocate_u(teta,llm,d)
     CALL allocate_u(p,llmp1,d)
Index: /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/conf_gcm.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/conf_gcm.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/conf_gcm.F90	(revision 3605)
@@ -25,5 +25,5 @@
   USE serre_mod, ONLY: clon,clat,grossismx,grossismy,dzoomx,dzoomy, &
                        alphax,alphay,taux,tauy
-  USE temps_mod, ONLY: calend
+  USE temps_mod, ONLY: calend, year_len
 
   IMPLICIT NONE
@@ -144,5 +144,16 @@
   !Config         
   calend = 'earth_360d'
+! initialize year_len for aquaplanets and 1D
   CALL getin('calend', calend)
+     if (calend == 'earth_360d') then
+        year_len=360
+      else if (calend == 'earth_365d') then
+        year_len=365
+      else if (calend == 'earth_366d') then
+        year_len=366
+      else 
+        year_len=1
+      endif
+  
 
   !Config  Key  = dayref
Index: /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/gcm.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/gcm.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/gcm.F90	(revision 3605)
@@ -233,4 +233,6 @@
        'GCM: AVANT iniacademic AVANT AVANT AVANT AVANT'
   if (.not.read_start) then
+     start_time=0.
+     annee_ref=anneeref
      CALL iniacademic_loc(vcov,ucov,teta,q,masse,ps,phis,time_0)
   endif
@@ -368,4 +370,27 @@
 
   !-----------------------------------------------------------------------
+  !   Initialisation des I/O :
+  !   ------------------------
+
+
+  if (nday>=0) then
+     day_end = day_ini + nday
+  else
+     day_end = day_ini - nday/day_step
+  endif
+
+  WRITE(lunout,300)day_ini,day_end
+300 FORMAT('1'/,15x,'run du jour',i7,2x,'au jour',i7//)
+
+#ifdef CPP_IOIPSL
+  call ju2ymds(jD_ref + day_ini - day_ref, an, mois, jour, heure)
+  write (lunout,301)jour, mois, an
+  call ju2ymds(jD_ref + day_end - day_ref, an, mois, jour, heure)
+  write (lunout,302)jour, mois, an
+301 FORMAT('1'/,15x,'run du ', i2,'/',i2,'/',i4)
+302 FORMAT('1'/,15x,'    au ', i2,'/',i2,'/',i4)
+#endif
+
+  !-----------------------------------------------------------------------
   !   Initialisation de la physique :
   !   -------------------------------
@@ -381,27 +406,4 @@
   ENDIF ! of IF ((iflag_phys==1).or.(iflag_phys>=100))
 
-
-  !-----------------------------------------------------------------------
-  !   Initialisation des I/O :
-  !   ------------------------
-
-
-  if (nday>=0) then
-     day_end = day_ini + nday
-  else
-     day_end = day_ini - nday/day_step
-  endif
-
-  WRITE(lunout,300)day_ini,day_end
-300 FORMAT('1'/,15x,'run du jour',i7,2x,'au jour',i7//)
-
-#ifdef CPP_IOIPSL
-  call ju2ymds(jD_ref + day_ini - day_ref, an, mois, jour, heure)
-  write (lunout,301)jour, mois, an
-  call ju2ymds(jD_ref + day_end - day_ref, an, mois, jour, heure)
-  write (lunout,302)jour, mois, an
-301 FORMAT('1'/,15x,'run du ', i2,'/',i2,'/',i4)
-302 FORMAT('1'/,15x,'    au ', i2,'/',i2,'/',i4)
-#endif
 
   !      if (planet_type.eq."earth") then
Index: /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/guide_loc_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/guide_loc_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/guide_loc_mod.F90	(revision 3605)
@@ -1212,5 +1212,5 @@
               enddo
             endif
-            if (pole_nord) then
+            if (pole_sud) then
               do i=1,iip1
                 qgui1(ip1jm+i,l)=qgui1(ip1jm+1,l) 
Index: /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/iniacademic_loc.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/iniacademic_loc.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/iniacademic_loc.F90	(revision 3605)
@@ -101,5 +101,5 @@
   time_0=0.
   day_ref=1
-  annee_ref=0
+  ! annee_ref=0
 
   im         = iim
Index: /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/integrd_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/integrd_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/integrd_mod.F90	(revision 3605)
@@ -23,4 +23,5 @@
     CALL allocate_u(deltap,llm,d)
     CALL allocate_u(ps,d)
+    ps(:)=0
 
     
Index: /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/leapfrog_loc.F
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/leapfrog_loc.F	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/leapfrog_loc.F	(revision 3605)
@@ -29,5 +29,9 @@
        USE call_dissip_mod, ONLY : call_dissip
        USE call_calfis_mod, ONLY : call_calfis
-       USE leapfrog_mod
+       USE leapfrog_mod, ONLY : ucov,vcov,teta,ps,masse,phis,q,dq
+     & ,ucovm1,vcovm1,tetam1,massem1,psm1,p,pks,pk,pkf,flxw
+     & ,pbaru,pbarv,du,dv,dteta,phi,dp,w
+     & ,leapfrog_allocate,leapfrog_switch_caldyn,leapfrog_switch_dissip
+
        use exner_hyb_loc_m, only: exner_hyb_loc
        use exner_milieu_loc_m, only: exner_milieu_loc
@@ -1535,5 +1539,7 @@
 
 #ifdef INCA
-         call finalize_inca
+         if (type_trac == 'inca') then 
+            call finalize_inca
+         endif
 #endif
 
@@ -1583,5 +1589,7 @@
 
 #ifdef INCA
-              call finalize_inca
+              if (type_trac == 'inca') then 
+                 call finalize_inca
+              endif
 #endif
 
@@ -1732,5 +1740,7 @@
 
 #ifdef INCA
-                 call finalize_inca
+                 if (type_trac == 'inca') then 
+                    call finalize_inca
+                 endif
 #endif
 
@@ -1820,5 +1830,7 @@
 
 #ifdef INCA
-      call finalize_inca
+      if (type_trac == 'inca') then 
+         call finalize_inca
+      endif
 #endif
 
Index: /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/temps_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/temps_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/temps_mod.F90	(revision 3605)
@@ -13,4 +13,5 @@
   INTEGER   annee_ref
   INTEGER   day_ref
+  INTEGER   year_len
   REAL      dt ! (dynamics) time step (changes if doing Matsuno or LF step)
   REAL      jD_ref ! reference julian day date (beginning of experiment)
Index: /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/vlsplt_loc.F
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/vlsplt_loc.F	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dyn3dmem/vlsplt_loc.F	(revision 3605)
@@ -19,4 +19,5 @@
       include "dimensions.h"
       include "paramet.h"
+      include "iniprint.h"
 c
 c
@@ -872,4 +873,5 @@
       include "dimensions.h"
       include "paramet.h"
+      include "iniprint.h"
 c
 c
@@ -1027,5 +1029,7 @@
       ELSE ! countcfl>=1
 
-      PRINT*,'vlz passage dans le non local'
+      IF (prt_level>9) THEN
+        WRITE(lunout,*)'vlz passage dans le non local'
+      ENDIF
 c ---------------------------------------------------------------
 c  Debut du traitement du cas ou on viole le CFL : w > masse
@@ -1059,5 +1063,7 @@
 c  le critère
       DO WHILE (countcfl>=1) 
-      print*,'On viole le CFL Vertical sur ',countcfl,' pts'
+        IF (prt_level>9) THEN
+          WRITE(lunout,*)'On viole le CFL Vertical sur ',countcfl,' pts'
+        ENDIF
       countcfl=0
 
Index: /LMDZ6/branches/Ocean_skin/libf/dynphy_lonlat/inigeomphy_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dynphy_lonlat/inigeomphy_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dynphy_lonlat/inigeomphy_mod.F90	(revision 3605)
@@ -76,5 +76,6 @@
   REAL,ALLOCATABLE,SAVE :: boundslonfi(:,:)
   REAL,ALLOCATABLE,SAVE :: boundslatfi(:,:)
-!$OMP THREADPRIVATE (latfi,lonfi,cufi,cvfi,airefi,boundslonfi,boundslatfi)
+  INTEGER,ALLOCATABLE,SAVE :: ind_cell_glo_fi(:)
+!$OMP THREADPRIVATE (latfi,lonfi,cufi,cvfi,airefi,boundslonfi,boundslatfi,ind_cell_glo_fi)
 
   ! Initialize Physics distibution and parameters and interface with dynamics
@@ -93,6 +94,6 @@
   
   DO i=1,iim
+   boundslon_reg(i,east)=rlonu(i+1) 
    boundslon_reg(i,west)=rlonu(i) 
-   boundslon_reg(i,east)=rlonu(i+1) 
   ENDDO
 
@@ -204,4 +205,5 @@
   ALLOCATE(boundslonfi(klon_omp,4))
   ALLOCATE(boundslatfi(klon_omp,4))
+  ALLOCATE(ind_cell_glo_fi(klon_omp))
 
 
@@ -214,8 +216,9 @@
   boundslonfi(1:klon_omp,:) = boundslonfi_glo(offset+klon_omp_begin:offset+klon_omp_end,:)
   boundslatfi(1:klon_omp,:) = boundslatfi_glo(offset+klon_omp_begin:offset+klon_omp_end,:)
+  ind_cell_glo_fi(1:klon_omp)=(/ (i,i=offset+klon_omp_begin,offset+klon_omp_end) /)
 
   ! copy over local grid longitudes and latitudes
   CALL init_geometry(klon_omp,lonfi,latfi,boundslonfi,boundslatfi, &
-                     airefi,cufi,cvfi)
+                     airefi,ind_cell_glo_fi,cufi,cvfi)
 
   ! copy over preff , ap(), bp(), etc 
Index: /LMDZ6/branches/Ocean_skin/libf/dynphy_lonlat/phydev/iniphysiq_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dynphy_lonlat/phydev/iniphysiq_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dynphy_lonlat/phydev/iniphysiq_mod.F90	(revision 3605)
@@ -71,7 +71,4 @@
   CALL inifis(prad,pg,pr,pcpp)
   
-  ! Initialize dimphy module
-  CALL Init_dimphy(klon_omp,nlayer)
-
   ! Initialize tracer names, numbers, etc. for physics
   CALL init_infotrac_phy(nqtot,type_trac)
Index: /LMDZ6/branches/Ocean_skin/libf/dynphy_lonlat/phylmd/etat0dyn_netcdf.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dynphy_lonlat/phylmd/etat0dyn_netcdf.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dynphy_lonlat/phylmd/etat0dyn_netcdf.F90	(revision 3605)
@@ -100,5 +100,6 @@
 
   deg2rad = pi/180.0
-
+  y(:,:,:)=0  !ym warning unitialized variable
+  
 ! Compute psol AND tsol, knowing phis.
 !*******************************************************************************
Index: /LMDZ6/branches/Ocean_skin/libf/dynphy_lonlat/phylmd/etat0phys_netcdf.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dynphy_lonlat/phylmd/etat0phys_netcdf.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dynphy_lonlat/phylmd/etat0phys_netcdf.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 MODULE etat0phys
 !
@@ -40,9 +43,12 @@
   USE phys_state_var_mod, ONLY: zmea, zstd, zsig, zgam, zthe, zpic, zval, z0m, &
           solsw, radsol, t_ancien, wake_deltat, wake_s,  rain_fall, qsol, z0h, &
-          sollw, rugoro, q_ancien, wake_deltaq, wake_pe, snow_fall, ratqs,w01, &
+          sollw,sollwdown, rugoro, q_ancien, wake_deltaq, wake_pe, snow_fall, ratqs,w01, &
     sig1, ftsol, clwcon, fm_therm, wake_Cstar,  pctsrf,  entr_therm,radpas, f0,&
-    zmax0,fevap, rnebcon,falb_dir, wake_fip,    agesno,  detr_therm, pbl_tke,  &
+    zmax0,fevap, rnebcon,falb_dir, falb_dif, wake_fip,    agesno,  detr_therm, pbl_tke,  &
     phys_state_var_init, ql_ancien, qs_ancien, prlw_ancien, prsw_ancien, &
-    prw_ancien
+    prw_ancien, u10m,v10m, treedrg, u_ancien, v_ancien, wake_delta_pbl_TKE, wake_dens, &
+    ale_bl, ale_bl_trig, alp_bl, &
+    ale_wake, ale_bl_stat
+
   USE comconst_mod, ONLY: pi, dtvr
 
@@ -110,5 +116,5 @@
   INTEGER :: iflag_radia, iflag_cldcon, iflag_ratqs
   REAL    :: ratqsbas, ratqshaut, tau_ratqs
-  LOGICAL :: ok_ade, ok_aie, ok_alw, ok_cdnc, aerosol_couple, chemistry_couple
+  LOGICAL :: ok_ade, ok_aie, ok_volcan, ok_alw, ok_cdnc, aerosol_couple, chemistry_couple
   INTEGER :: flag_aerosol
   INTEGER :: flag_aerosol_strat
@@ -133,5 +139,6 @@
                    iflag_cldcon,                                        &
                    iflag_ratqs,ratqsbas,ratqshaut,tau_ratqs,            &
-                   ok_ade, ok_aie, ok_alw, ok_cdnc, aerosol_couple,     &
+                   ok_ade, ok_aie, ok_alw, ok_cdnc, ok_volcan,          &
+                   aerosol_couple,                                      &
                    chemistry_couple, flag_aerosol, flag_aerosol_strat,  & 
                    flag_aer_feedback,                                   &
@@ -194,4 +201,12 @@
   falb_dir(:, :, is_oce) = 0.5
   falb_dir(:, :, is_sic) = 0.6
+
+!ym warning missing init for falb_dif => set to 0
+  falb_dif(:,:,:)=0
+
+  u10m(:,:)=0  
+  v10m(:,:)=0  
+  treedrg(:,:,:)=0
+
   fevap(:,:) = 0.
   DO i=1,nbsrf; qsolsrf(:,i)=150.; END DO
@@ -201,4 +216,6 @@
   solsw      = 165.
   sollw      = -53.
+!ym warning missing init for sollwdown => set to 0
+  sollwdown  = 0.
   t_ancien   = 273.15
   q_ancien   = 0.
@@ -209,5 +226,17 @@
   prw_ancien = 0.
   agesno     = 0.
-
+  
+  u_ancien = 0.
+  v_ancien = 0.
+  wake_delta_pbl_TKE(:,:,:)=0
+  wake_dens(:)=0
+  ale_bl = 0.
+  ale_bl_trig =0.
+  alp_bl=0.
+  ale_wake=0.
+  ale_bl_stat=0.
+  
+  z0m(:,:)=0 ! ym missing 5th subsurface initialization
+ 
   z0m(:,is_oce) = rugmer(:)
   z0m(:,is_ter) = MAX(1.0e-05,zstd(:)*zsig(:)/2.0)
@@ -315,5 +344,8 @@
   ALLOCATE(zmea0(iml,jml),zstd0(iml,jml)) !--- Mean orography and std deviation
   ALLOCATE(zsig0(iml,jml),zgam0(iml,jml)) !--- Slope and nisotropy
+  zsig0(:,:)=0   !ym uninitialized variable
+  zgam0(:,:)=0   !ym uninitialized variable
   ALLOCATE(zthe0(iml,jml))                !--- Highest slope orientation
+  zthe0(:,:)=0   !ym uninitialized variable
   ALLOCATE(zpic0(iml,jml),zval0(iml,jml)) !--- Peaks and valley heights
 
Index: /LMDZ6/branches/Ocean_skin/libf/dynphy_lonlat/phylmd/iniphysiq_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/dynphy_lonlat/phylmd/iniphysiq_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/dynphy_lonlat/phylmd/iniphysiq_mod.F90	(revision 3605)
@@ -31,8 +31,9 @@
   USE inifis_mod, ONLY: inifis
   USE time_phylmdz_mod, ONLY: init_time
-  USE temps_mod, ONLY: annee_ref, day_ini, day_ref, start_time, calend
+  USE temps_mod, ONLY: annee_ref, day_ini, day_ref, start_time, calend, year_len
   USE infotrac_phy, ONLY: init_infotrac_phy
   USE phystokenc_mod, ONLY: init_phystokenc
   USE phyaqua_mod, ONLY: iniaqua
+  USE comconst_mod, ONLY: omeg, rad
 #ifdef INCA
   USE indice_sol_mod, ONLY: nbsrf, is_oce, is_sic, is_ter, is_lic
@@ -118,5 +119,5 @@
 
   ! Initialize dimphy module (unless in 1D where it has already been done)
-  IF (klon_glo>1) CALL Init_dimphy(klon_omp,nlayer)
+!  IF (klon_glo>1) CALL Init_dimphy(klon_omp,nlayer)
 
   ! Copy over "offline" settings
@@ -134,5 +135,5 @@
                                   cu,cuvsurcv,cv,cvusurcu, &
                                   aire,apoln,apols, &
-                                  aireu,airev,rlatvdyn) 
+                                  aireu,airev,rlatvdyn,rad,omeg) 
   END IF
 
@@ -172,5 +173,5 @@
   ! Additional initializations for aquaplanets 
   IF (iflag_phys>=100) THEN
-    CALL iniaqua(klon_omp,iflag_phys)
+    CALL iniaqua(klon_omp,year_len,iflag_phys)
   END IF
 
Index: /LMDZ6/branches/Ocean_skin/libf/misc/handle_err_m.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/misc/handle_err_m.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/misc/handle_err_m.F90	(revision 3605)
@@ -39,5 +39,5 @@
           end if
        end if
-       call abort_gcm("NetCDF95 handle_err", "", 1)
+       call abort_physic("NetCDF95 handle_err", "", 1)
     end if
 
Index: /LMDZ6/branches/Ocean_skin/libf/misc/regr1_step_av_m.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/misc/regr1_step_av_m.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/misc/regr1_step_av_m.F90	(revision 3605)
@@ -0,0 +1,268 @@
+! $Id: regr1_step_av_m.F90 3065 2017-11-10 13:25:09Z fairhead $
+module regr1_step_av_m
+
+  ! Author: Lionel GUEZ
+
+  implicit none
+
+  interface regr1_step_av
+
+     ! Each procedure regrids a step function by averaging it.
+     ! The regridding operation is done on the first dimension of the
+     ! input array.
+     ! Source grid contains edges of steps.
+     ! Target grid contains positions of cell edges.
+     ! The target grid should be included in the source grid: no
+     ! extrapolation is allowed.
+     ! The difference between the procedures is the rank of the first argument.
+
+     module procedure regr11_step_av, regr12_step_av, regr13_step_av, &
+          regr14_step_av
+  end interface
+
+  private
+  public regr1_step_av
+
+contains
+
+  function regr11_step_av(vs, xs, xt) result(vt)
+
+    ! "vs" has rank 1.
+
+    use assert_eq_m, only: assert_eq
+    use assert_m, only: assert
+    use interpolation, only: locate
+
+    real, intent(in):: vs(:) ! values of steps on the source grid
+    ! (Step "is" is between "xs(is)" and "xs(is + 1)".)
+
+    real, intent(in):: xs(:)
+    ! (edges of of steps on the source grid, in strictly increasing order)
+
+    real, intent(in):: xt(:)
+    ! (edges of cells of the target grid, in strictly increasing order)
+
+    real vt(size(xt) - 1) ! average values on the target grid
+    ! (Cell "it" is between "xt(it)" and "xt(it + 1)".)
+
+    ! Variables local to the procedure:
+    integer is, it, ns, nt
+    real left_edge
+
+    !---------------------------------------------
+
+    ns = assert_eq(size(vs), size(xs) - 1, "regr11_step_av ns")
+    nt = size(xt) - 1
+    ! Quick check on sort order:
+    call assert(xs(1) < xs(2), "regr11_step_av xs bad order")
+    call assert(xt(1) < xt(2), "regr11_step_av xt bad order")
+
+    call assert(xs(1) <= xt(1) .and. xt(nt + 1) <= xs(ns + 1), &
+         "regr11_step_av extrapolation")
+
+    is = locate(xs, xt(1)) ! 1 <= is <= ns, because we forbid extrapolation
+    do it = 1, nt
+       ! 1 <= is <= ns
+       ! xs(is) <= xt(it) < xs(is + 1)
+       ! Compute "vt(it)":
+       left_edge = xt(it)
+       vt(it) = 0.
+       do while (xs(is + 1) < xt(it + 1))
+          ! 1 <= is <= ns - 1
+          vt(it) = vt(it) + (xs(is + 1) - left_edge) * vs(is)
+          is = is + 1
+          left_edge = xs(is)
+       end do
+       ! 1 <= is <= ns
+       vt(it) = (vt(it) + (xt(it + 1) - left_edge) * vs(is)) &
+            / (xt(it + 1) - xt(it))
+       if (xs(is + 1) == xt(it + 1)) is = is + 1
+       ! 1 <= is <= ns .or. it == nt
+    end do
+
+  end function regr11_step_av
+
+  !********************************************
+
+  function regr12_step_av(vs, xs, xt) result(vt)
+
+    ! "vs" has rank 2.
+
+    use assert_eq_m, only: assert_eq
+    use assert_m, only: assert
+    use interpolation, only: locate
+
+    real, intent(in):: vs(:, :) ! values of steps on the source grid
+    ! (Step "is" is between "xs(is)" and "xs(is + 1)".)
+
+    real, intent(in):: xs(:)
+    ! (edges of steps on the source grid, in strictly increasing order)
+
+    real, intent(in):: xt(:)
+    ! (edges of cells of the target grid, in strictly increasing order)
+
+    real vt(size(xt) - 1, size(vs, 2)) ! average values on the target grid
+    ! (Cell "it" is between "xt(it)" and "xt(it + 1)".)
+
+    ! Variables local to the procedure:
+    integer is, it, ns, nt
+    real left_edge
+
+    !---------------------------------------------
+
+    ns = assert_eq(size(vs, 1), size(xs) - 1, "regr12_step_av ns")
+    nt = size(xt) - 1
+
+    ! Quick check on sort order:
+    call assert(xs(1) < xs(2), "regr12_step_av xs bad order")
+    call assert(xt(1) < xt(2), "regr12_step_av xt bad order")
+
+    call assert(xs(1) <= xt(1) .and. xt(nt + 1) <= xs(ns + 1), &
+         "regr12_step_av extrapolation")
+
+    is = locate(xs, xt(1)) ! 1 <= is <= ns, because we forbid extrapolation
+    do it = 1, nt
+       ! 1 <= is <= ns
+       ! xs(is) <= xt(it) < xs(is + 1)
+       ! Compute "vt(it, :)":
+       left_edge = xt(it)
+       vt(it, :) = 0.
+       do while (xs(is + 1) < xt(it + 1))
+          ! 1 <= is <= ns - 1
+          vt(it, :) = vt(it, :) + (xs(is + 1) - left_edge) * vs(is, :)
+          is = is + 1
+          left_edge = xs(is)
+       end do
+       ! 1 <= is <= ns
+       vt(it, :) = (vt(it, :) + (xt(it + 1) - left_edge) * vs(is, :)) &
+            / (xt(it + 1) - xt(it))
+       if (xs(is + 1) == xt(it + 1)) is = is + 1
+       ! 1 <= is <= ns .or. it == nt
+    end do
+
+  end function regr12_step_av
+
+  !********************************************
+
+  function regr13_step_av(vs, xs, xt) result(vt)
+
+    ! "vs" has rank 3.
+
+    use assert_eq_m, only: assert_eq
+    use assert_m, only: assert
+    use interpolation, only: locate
+
+    real, intent(in):: vs(:, :, :) ! values of steps on the source grid
+    ! (Step "is" is between "xs(is)" and "xs(is + 1)".)
+
+    real, intent(in):: xs(:)
+    ! (edges of steps on the source grid, in strictly increasing order)
+
+    real, intent(in):: xt(:)
+    ! (edges of cells of the target grid, in strictly increasing order)
+
+    real vt(size(xt) - 1, size(vs, 2), size(vs, 3)) 
+    ! (average values on the target grid)
+    ! (Cell "it" is between "xt(it)" and "xt(it + 1)".)
+
+    ! Variables local to the procedure:
+    integer is, it, ns, nt
+    real left_edge
+
+    !---------------------------------------------
+
+    ns = assert_eq(size(vs, 1), size(xs) - 1, "regr13_step_av ns")
+    nt = size(xt) - 1
+
+    ! Quick check on sort order:
+    call assert(xs(1) < xs(2), "regr13_step_av xs bad order")
+    call assert(xt(1) < xt(2), "regr13_step_av xt bad order")
+
+    call assert(xs(1) <= xt(1) .and. xt(nt + 1) <= xs(ns + 1), &
+         "regr13_step_av extrapolation")
+
+    is = locate(xs, xt(1)) ! 1 <= is <= ns, because we forbid extrapolation
+    do it = 1, nt
+       ! 1 <= is <= ns
+       ! xs(is) <= xt(it) < xs(is + 1)
+       ! Compute "vt(it, :, :)":
+       left_edge = xt(it)
+       vt(it, :, :) = 0.
+       do while (xs(is + 1) < xt(it + 1))
+          ! 1 <= is <= ns - 1
+          vt(it, :, :) = vt(it, :, :) + (xs(is + 1) - left_edge) * vs(is, :, :)
+          is = is + 1
+          left_edge = xs(is)
+       end do
+       ! 1 <= is <= ns
+       vt(it, :, :) = (vt(it, :, :) &
+            + (xt(it + 1) - left_edge) * vs(is, :, :)) / (xt(it + 1) - xt(it))
+       if (xs(is + 1) == xt(it + 1)) is = is + 1
+       ! 1 <= is <= ns .or. it == nt
+    end do
+
+  end function regr13_step_av
+
+  !********************************************
+
+  function regr14_step_av(vs, xs, xt) result(vt)
+
+    ! "vs" has rank 4.
+
+    use assert_eq_m, only: assert_eq
+    use assert_m, only: assert
+    use interpolation, only: locate
+
+    real, intent(in):: vs(:, :, :, :) ! values of steps on the source grid
+    ! (Step "is" is between "xs(is)" and "xs(is + 1)".)
+
+    real, intent(in):: xs(:)
+    ! (edges of steps on the source grid, in strictly increasing order)
+
+    real, intent(in):: xt(:)
+    ! (edges of cells of the target grid, in strictly increasing order)
+
+    real vt(size(xt) - 1, size(vs, 2), size(vs, 3), size(vs, 4))
+    ! (average values on the target grid)
+    ! (Cell "it" is between "xt(it)" and "xt(it + 1)".)
+
+    ! Variables local to the procedure:
+    integer is, it, ns, nt
+    real left_edge
+
+    !---------------------------------------------
+
+    ns = assert_eq(size(vs, 1), size(xs) - 1, "regr14_step_av ns")
+    nt = size(xt) - 1
+
+    ! Quick check on sort order:
+    call assert(xs(1) < xs(2), "regr14_step_av xs bad order")
+    call assert(xt(1) < xt(2), "regr14_step_av xt bad order")
+
+    call assert(xs(1) <= xt(1) .and. xt(nt + 1) <= xs(ns + 1), &
+         "regr14_step_av extrapolation")
+
+    is = locate(xs, xt(1)) ! 1 <= is <= ns, because we forbid extrapolation
+    do it = 1, nt
+       ! 1 <= is <= ns
+       ! xs(is) <= xt(it) < xs(is + 1)
+       ! Compute "vt(it, :, :, :)":
+       left_edge = xt(it)
+       vt(it, :, :, :) = 0.
+       do while (xs(is + 1) < xt(it + 1))
+          ! 1 <= is <= ns - 1
+          vt(it, :, :, :) = vt(it, :, :, :) + (xs(is + 1) - left_edge) &
+               * vs(is, :, :, :)
+          is = is + 1
+          left_edge = xs(is)
+       end do
+       ! 1 <= is <= ns
+       vt(it, :, :, :) = (vt(it, :, :, :) + (xt(it + 1) - left_edge) &
+            * vs(is, :, :, :)) / (xt(it + 1) - xt(it))
+       if (xs(is + 1) == xt(it + 1)) is = is + 1
+       ! 1 <= is <= ns .or. it == nt
+    end do
+
+  end function regr14_step_av
+
+end module regr1_step_av_m
Index: /LMDZ6/branches/Ocean_skin/libf/misc/wxios.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/misc/wxios.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/misc/wxios.F90	(revision 3605)
@@ -15,5 +15,5 @@
     
     INTEGER, SAVE :: g_comm
-    CHARACTER(len=100), SAVE :: g_ctx_name
+    CHARACTER(len=100), SAVE :: g_ctx_name ="LMDZ"
     TYPE(xios_context), SAVE :: g_ctx
 !$OMP THREADPRIVATE(g_comm,g_cts_name,g_ctx)
@@ -136,8 +136,8 @@
         g_ctx_name = xios_ctx_name
         
-        ! Si couple alors init fait dans cpl_init
-        IF (.not. PRESENT(type_ocean)) THEN
-            CALL wxios_context_init()
-        ENDIF
+!        ! Si couple alors init fait dans cpl_init
+!        IF (.not. PRESENT(type_ocean)) THEN
+!            CALL wxios_context_init()
+!        ENDIF
 
     END SUBROUTINE wxios_init
@@ -145,5 +145,5 @@
     SUBROUTINE wxios_context_init()
         USE print_control_mod, ONLY : prt_level, lunout
-!        USE mod_phys_lmdz_mpi_data, ONLY : COMM_LMDZ_PHY
+        USE mod_phys_lmdz_mpi_data, ONLY : COMM_LMDZ_PHY
         IMPLICIT NONE
 
@@ -152,5 +152,6 @@
 !$OMP MASTER
         !Initialisation du contexte:
-        CALL xios_context_initialize(g_ctx_name, g_comm)
+        !!CALL xios_context_initialize(g_ctx_name, g_comm)
+        CALL xios_context_initialize(g_ctx_name, COMM_LMDZ_PHY)
         CALL xios_get_handle(g_ctx_name, xios_ctx)    !Récupération
         CALL xios_set_current_context(xios_ctx)            !Activation
@@ -165,4 +166,16 @@
 !$OMP END MASTER
     END SUBROUTINE wxios_context_init
+
+
+    SUBROUTINE wxios_set_context()
+        IMPLICIT NONE
+        TYPE(xios_context) :: xios_ctx
+
+       !$OMP MASTER
+        CALL xios_get_handle(g_ctx_name, xios_ctx)    !Récupération
+        CALL xios_set_current_context(xios_ctx)            !Activation
+       !$OMP END MASTER
+
+    END SUBROUTINE wxios_set_context
 
     !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
@@ -203,5 +216,5 @@
             CASE DEFAULT
                 abort_message = 'wxios_set_cal: Mauvais choix de calendrier'
-                CALL abort_gcm('Gcm:Xios',abort_message,1)
+                CALL abort_physic('Gcm:Xios',abort_message,1)
         END SELECT
         
@@ -237,56 +250,61 @@
     ! Pour initialiser un domaine !!!!!!!!!!!!!!!!!!!!
     !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-    SUBROUTINE wxios_domain_param(dom_id, is_sequential, ni, nj, ni_glo, nj_glo,        &
-                                    ibegin, iend, ii_begin, ii_end, jbegin, jend,       &
-                                    data_ni, data_ibegin, data_iend,                    &
-                                    io_lat, io_lon,is_south_pole,mpi_rank)
-         
-
-        USE print_control_mod, ONLY : prt_level, lunout
-        IMPLICIT NONE
-
+    SUBROUTINE wxios_domain_param(dom_id)
+       USE dimphy, only: klon
+       USE mod_phys_lmdz_transfert_para, ONLY: gather, bcast
+       USE mod_phys_lmdz_para, only: jj_nb, jj_begin, jj_end, ii_begin, ii_end, &
+                                     mpi_size, mpi_rank, klon_mpi, &
+                                     is_sequential, is_south_pole_dyn
+       USE mod_grid_phy_lmdz, only: nbp_lon, nbp_lat, klon_glo         
+       USE print_control_mod, ONLY : prt_level, lunout
+       USE geometry_mod
+
+       IMPLICIT NONE
         CHARACTER(len=*),INTENT(IN) :: dom_id ! domain identifier
-        LOGICAL,INTENT(IN) :: is_sequential ! flag
-        INTEGER,INTENT(IN) :: ni ! local MPI domain number of longitudes
-        INTEGER,INTENT(IN) :: nj ! local MPI domain number of latitudes
-        INTEGER,INTENT(IN) :: ni_glo ! global grid number of longitudes
-        INTEGER,INTENT(IN) :: nj_glo ! global grid number of latitudes
-        INTEGER,INTENT(IN) :: ibegin ! start index, on global grid, of local MPI domain 
-        INTEGER,INTENT(IN) :: iend ! end index, on global grid, of local MPI domain
-        INTEGER,INTENT(IN) :: ii_begin ! i index at which local data starts (first row)
-        INTEGER,INTENT(IN) :: ii_end ! i index at which local data ends (last row)
-        INTEGER,INTENT(IN) :: jbegin ! start index, on global grid, of local MPI domain 
-        INTEGER,INTENT(IN) :: jend ! end index, on global grid, of local MPI domain
-        INTEGER,INTENT(IN) :: data_ni
-        INTEGER,INTENT(IN) :: data_ibegin
-        INTEGER,INTENT(IN) :: data_iend
-        REAL,INTENT(IN) :: io_lat(:) ! latitudes (of global grid)
-        REAL,INTENT(IN) :: io_lon(:) ! longitudes (of global grid)
-        logical,intent(in) :: is_south_pole ! does this process include the south pole?
-        integer,intent(in) :: mpi_rank ! rank of process
-        
+
+        REAL   :: rlat_glo(klon_glo)
+        REAL   :: rlon_glo(klon_glo)
+        REAL   :: io_lat(nbp_lat)
+        REAL   :: io_lon(nbp_lon)
+        LOGICAL :: mask(nbp_lon,jj_nb) !Masque pour les problèmes de recouvrement MPI
         TYPE(xios_domain) :: dom
+        INTEGER :: i
         LOGICAL :: boool
         
-        !Masque pour les problèmes de recouvrement MPI:
-        LOGICAL :: mask(ni,nj)
+
+
+        CALL gather(latitude_deg,rlat_glo) 
+        CALL bcast(rlat_glo)
+        CALL gather(longitude_deg,rlon_glo)
+        CALL bcast(rlon_glo)
+    
+  !$OMP MASTER  
+        io_lat(1)=rlat_glo(1)
+        io_lat(nbp_lat)=rlat_glo(klon_glo)
+        IF ((nbp_lon*nbp_lat) > 1) then
+          DO i=2,nbp_lat-1
+            io_lat(i)=rlat_glo(2+(i-2)*nbp_lon)
+          ENDDO
+        ENDIF
+
+        IF (klon_glo == 1) THEN
+          io_lon(1)=rlon_glo(1)
+        ELSE 
+          io_lon(1:nbp_lon)=rlon_glo(2:nbp_lon+1)
+        ENDIF
+
         
         !On récupère le handle:
         CALL xios_get_domain_handle(dom_id, dom)
         
-        IF (prt_level >= 10) THEN
-          WRITE(lunout,*) "wxios_domain_param: mpirank=",mpi_rank," ni:",ni," ni_glo:", ni_glo, " nj:", nj, " nj_glo:", nj_glo
-          WRITE(lunout,*) "wxios_domain_param: mpirank=",mpi_rank," ibegin:",ibegin," iend:", iend, " jbegin:", jbegin, " jend:", jend
-          WRITE(lunout,*) "wxios_domain_param: mpirank=",mpi_rank," ii_begin:",ii_begin," ii_end:", ii_end
-          WRITE(lunout,*) "wxios_domain_param: mpirank=",mpi_rank," Size io_lon:", SIZE(io_lon(ibegin:iend)), " io_lat:", SIZE(io_lat(jbegin:jend))
-        ENDIF
-        
         !On parametrise le domaine:
-        CALL xios_set_domain_attr_hdl(dom, ni_glo=ni_glo, ibegin=ibegin-1, ni=ni, type="rectilinear")
-        CALL xios_set_domain_attr_hdl(dom, nj_glo=nj_glo, jbegin=jbegin-1, nj=nj, data_dim=2)
-        CALL xios_set_domain_attr_hdl(dom, lonvalue_1d=io_lon(ibegin:iend), latvalue_1d=io_lat(jbegin:jend))
+        CALL xios_set_domain_attr_hdl(dom, ni_glo=nbp_lon, ibegin=0, ni=nbp_lon, type="rectilinear")
+        CALL xios_set_domain_attr_hdl(dom, nj_glo=nbp_lat, jbegin=jj_begin-1, nj=jj_nb, data_dim=2)
+        CALL xios_set_domain_attr_hdl(dom, lonvalue_1d=io_lon(1:nbp_lon), latvalue_1d=io_lat(jj_begin:jj_end))
+        CALL xios_set_domain_attr("dom_out", domain_ref=dom_id)
+
         !On definit un axe de latitudes pour les moyennes zonales
         IF (xios_is_valid_axis("axis_lat")) THEN
-           CALL xios_set_axis_attr( "axis_lat", n_glo=nj_glo, n=nj, begin=jbegin-1, value=io_lat(jbegin:jend))
+           CALL xios_set_axis_attr( "axis_lat", n_glo=nbp_lat, n=jj_nb, begin=jj_begin-1, value=io_lat(jj_begin:jj_end))
         ENDIF
 
@@ -294,10 +312,10 @@
             mask(:,:)=.TRUE.
             if (ii_begin>1) mask(1:ii_begin-1,1) = .FALSE.
-            if (ii_end<ni) mask(ii_end+1:ni,nj) = .FALSE.
+            if (ii_end<nbp_lon) mask(ii_end+1:nbp_lon,jj_nb) = .FALSE.
             ! special case for south pole
-            if ((ii_end.eq.1).and.(is_south_pole)) mask(1:ni,nj)=.true.
+            if ((ii_end==1).and.(is_south_pole_dyn)) mask(1:nbp_lon,jj_nb)=.true.
             IF (prt_level >= 10) THEN
               WRITE(lunout,*) "wxios_domain_param: mpirank=",mpi_rank," mask(:,1)=",mask(:,1)
-              WRITE(lunout,*) "wxios_domain_param: mpirank=",mpi_rank," mask(:,nj)=",mask(:,nj)
+              WRITE(lunout,*) "wxios_domain_param: mpirank=",mpi_rank," mask(:,jj_nb)=",mask(:,jj_nb)
             ENDIF
             CALL xios_set_domain_attr_hdl(dom, mask_2d=mask)
@@ -311,6 +329,60 @@
             IF (prt_level >= 10) WRITE(lunout,*) "wxios_domain_param: Invalid domain: ", trim(dom_id)
         END IF
+!$OMP END MASTER
+        
     END SUBROUTINE wxios_domain_param
     
+
+    SUBROUTINE wxios_domain_param_unstructured(dom_id)
+        USE geometry_mod, ONLY : longitude, latitude, boundslon, boundslat,ind_cell_glo
+        USE mod_grid_phy_lmdz, ONLY : nvertex, klon_glo
+        USE mod_phys_lmdz_para 
+        USE nrtype, ONLY : PI
+        USE ioipsl_getin_p_mod, ONLY : getin_p
+        IMPLICIT NONE
+        CHARACTER(len=*),INTENT(IN) :: dom_id ! domain identifier
+        REAL :: lon_mpi(klon_mpi)
+        REAL :: lat_mpi(klon_mpi)
+        REAL :: boundslon_mpi(klon_mpi,nvertex)
+        REAL :: boundslat_mpi(klon_mpi,nvertex)
+        INTEGER :: ind_cell_glo_mpi(klon_mpi)
+        TYPE(xios_domain) :: dom
+        
+        LOGICAL :: remap_output
+
+        CALL gather_omp(longitude*180/PI,lon_mpi)
+        CALL gather_omp(latitude*180/PI,lat_mpi)
+        CALL gather_omp(boundslon*180/PI,boundslon_mpi)
+        CALL gather_omp(boundslat*180/PI,boundslat_mpi)
+        CALL gather_omp(ind_cell_glo,ind_cell_glo_mpi)
+        
+        remap_output=.TRUE.
+        CALL getin_p("remap_output",remap_output)
+
+!$OMP MASTER
+        CALL xios_get_domain_handle(dom_id, dom)
+        
+        !On parametrise le domaine:
+        CALL xios_set_attr(dom, ni_glo=klon_glo, ibegin=ij_begin-1, ni=ij_nb, type="unstructured")
+        CALL xios_set_attr(dom, nvertex=nvertex, lonvalue_1d=lon_mpi, latvalue_1d=lat_mpi, &
+                           bounds_lon_1d=TRANSPOSE(boundslon_mpi), bounds_lat_1d=TRANSPOSE(boundslat_mpi) )
+        CALL xios_set_attr(dom, i_index=ind_cell_glo_mpi(:)-1)
+        IF (remap_output) THEN
+          CALL xios_set_domain_attr("dom_out", domain_ref="dom_regular")
+          CALL xios_set_fieldgroup_attr("remap_expr", expr="@this_ref")
+          CALL xios_set_fieldgroup_attr("remap_1800s", freq_op=xios_duration_convert_from_string("1800s"))
+          CALL xios_set_fieldgroup_attr("remap_1h",    freq_op=xios_duration_convert_from_string("1h"))
+          CALL xios_set_fieldgroup_attr("remap_3h",    freq_op=xios_duration_convert_from_string("3h"))
+          CALL xios_set_fieldgroup_attr("remap_6h",    freq_op=xios_duration_convert_from_string("6h"))
+          CALL xios_set_fieldgroup_attr("remap_1d",    freq_op=xios_duration_convert_from_string("1d"))
+          CALL xios_set_fieldgroup_attr("remap_1mo",   freq_op=xios_duration_convert_from_string("1mo"))
+        ENDIF
+!$OMP END MASTER
+
+    END SUBROUTINE wxios_domain_param_unstructured
+
+
+
+
     !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
     ! Pour déclarer un axe vertical !!!!!!!!!!!!!!!
Index: /LMDZ6/branches/Ocean_skin/libf/phy_common/geometry_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phy_common/geometry_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phy_common/geometry_mod.F90	(revision 3605)
@@ -30,4 +30,6 @@
 !$OMP THREADPRIVATE(cell_area)
 
+  INTEGER,SAVE,ALLOCATABLE :: ind_cell_glo(:)      ! global indice of a local cell
+!$OMP THREADPRIVATE(ind_cell_glo)
 
 CONTAINS
@@ -35,5 +37,5 @@
   SUBROUTINE init_geometry(klon,longitude_,latitude_, &
                            boundslon_,boundslat_, &
-                           cell_area_,dx_,dy_)
+                           cell_area_,ind_cell_glo_,dx_,dy_)
   USE mod_grid_phy_lmdz, ONLY: nvertex
   USE nrtype, ONLY : PI
@@ -45,4 +47,5 @@
     REAL,INTENT(IN) :: boundslat_(klon,nvertex)
     REAL,INTENT(IN) :: cell_area_(klon)
+    INTEGER,OPTIONAL,INTENT(IN) :: ind_cell_glo_(klon)
     REAL,OPTIONAL,INTENT(IN) :: dx_(klon)
     REAL,OPTIONAL,INTENT(IN) :: dy_(klon)
@@ -55,4 +58,5 @@
     ALLOCATE(boundslat(klon,nvertex))
     ALLOCATE(cell_area(klon))
+    IF (PRESENT(ind_cell_glo_)) ALLOCATE(ind_cell_glo(klon))
     IF (PRESENT(dx_)) ALLOCATE(dx(klon))
     IF (PRESENT(dy_))ALLOCATE(dy(klon))
@@ -65,4 +69,5 @@
     boundslat(:,:) = boundslat_(:,:)
     cell_area(:) = cell_area_(:)
+    IF (PRESENT(ind_cell_glo_)) ind_cell_glo(:) = ind_cell_glo_(:)
     IF (PRESENT(dx_)) dx(:) = dx_(:)
     IF (PRESENT(dy_)) dy(:) = dy_(:)
Index: /LMDZ6/branches/Ocean_skin/libf/phy_common/init_print_control_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phy_common/init_print_control_mod.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phy_common/init_print_control_mod.F90	(revision 3605)
@@ -0,0 +1,67 @@
+MODULE init_print_control_mod
+
+! init_print_control to initialize print_control_mod variables
+! not included there because of circular dependecy issues
+
+CONTAINS
+
+  SUBROUTINE init_print_control
+  USE print_control_mod, ONLY : set_print_control
+  USE ioipsl_getin_p_mod, ONLY : getin_p
+  USE mod_phys_lmdz_para, ONLY: is_omp_root, is_master
+  IMPLICIT NONE
+
+    INTEGER :: lunout ! default output file identifier (6==screen)
+    INTEGER :: prt_level ! Output level
+    LOGICAL :: debug ! flag to specify if in "debug mode"
+    LOGICAL :: opened
+    INTEGER :: number
+    
+    !Config  Key  = prt_level
+    !Config  Desc = niveau d'impressions de débogage
+    !Config  Def  = 0
+    !Config  Help = Niveau d'impression pour le débogage
+    !Config         (0 = minimum d'impression)
+    prt_level = 0
+    CALL getin_p('prt_level',prt_level)
+
+    !Config  Key  = lunout
+    !Config  Desc = unite de fichier pour les impressions
+    !Config  Def  = 6
+    !Config  Help = unite de fichier pour les impressions 
+    !Config         (defaut sortie standard = 6)
+    lunout=6
+    CALL getin_p('lunout', lunout)
+
+    IF (is_omp_root) THEN
+      IF (lunout /= 5 .and. lunout /= 6) THEN
+         INQUIRE(FILE='lmdz.out_0000',OPENED=opened,NUMBER=number)
+         IF (opened) THEN
+           lunout=number
+         ELSE
+           OPEN(UNIT=lunout,FILE='lmdz.out_0000',ACTION='write',  &
+                STATUS='unknown',FORM='formatted')
+         ENDIF
+      ENDIF
+    ENDIF
+
+    !Config  Key  = debug
+    !Config  Desc = mode debogage
+    !Config  Def  = false
+    !Config  Help = positionne le mode debogage
+
+    debug = .FALSE.
+    CALL getin_p('debug',debug)
+    
+    IF (is_master) THEN
+      WRITE(lunout,*)"init_print_control: prt_level=",prt_level
+      WRITE(lunout,*)"init_print_control: lunout=",lunout
+      WRITE(lunout,*)"init_print_control: debug=",debug      
+    ENDIF
+    
+    CALL set_print_control(lunout,prt_level,debug)
+
+  END SUBROUTINE init_print_control  
+
+END MODULE init_print_control_mod
+
Index: /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_mpi_data.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_mpi_data.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_mpi_data.F90	(revision 3605)
@@ -3,5 +3,4 @@
 !
 MODULE mod_phys_lmdz_mpi_data
-!  USE mod_const_mpi
   
   INTEGER,SAVE :: ii_begin
@@ -36,11 +35,8 @@
   INTEGER,SAVE :: mpi_size
   INTEGER,SAVE :: mpi_master
-!  INTEGER,SAVE :: mpi_root
   LOGICAL,SAVE :: is_mpi_root
   LOGICAL,SAVE :: is_using_mpi
   
   
-!  LOGICAL,SAVE :: is_north_pole
-!  LOGICAL,SAVE :: is_south_pole
   LOGICAL,SAVE :: is_north_pole_dyn
   LOGICAL,SAVE :: is_south_pole_dyn
@@ -50,15 +46,13 @@
 CONTAINS
   
-!  SUBROUTINE Init_phys_lmdz_mpi_data(iim,jjp1,nb_proc,distrib)
   SUBROUTINE init_phys_lmdz_mpi_data(nbp, nbp_lon, nbp_lat, communicator)
-!  USE mod_const_mpi, ONLY : COMM_LMDZ
   IMPLICIT NONE
 #ifdef CPP_MPI
     INCLUDE 'mpif.h'
 #endif
-    INTEGER,INTENT(in) :: nbp
-    INTEGER,INTENT(in) :: nbp_lon
-    INTEGER,INTENT(in) :: nbp_lat
-    INTEGER,INTENT(in) :: communicator
+    INTEGER,INTENT(IN) :: nbp
+    INTEGER,INTENT(IN) :: nbp_lon
+    INTEGER,INTENT(IN) :: nbp_lat
+    INTEGER,INTENT(IN) :: communicator
     
     INTEGER,ALLOCATABLE :: distrib(:)
@@ -189,7 +183,7 @@
 
   SUBROUTINE print_module_data
-!  USE print_control_mod, ONLY: lunout
+  USE print_control_mod, ONLY: lunout
   IMPLICIT NONE
-  INCLUDE "iniprint.h" 
+!  INCLUDE "iniprint.h" 
   
     WRITE(lunout,*) 'ii_begin =', ii_begin
Index: /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_mpi_transfert.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_mpi_transfert.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_mpi_transfert.F90	(revision 3605)
@@ -42,4 +42,9 @@
   END INTERFACE 
 
+  INTERFACE reduce_min_mpi
+    MODULE PROCEDURE reduce_min_mpi_i,reduce_min_mpi_i1,reduce_min_mpi_i2,reduce_min_mpi_i3,reduce_min_mpi_i4, &
+                     reduce_min_mpi_r,reduce_min_mpi_r1,reduce_min_mpi_r2,reduce_min_mpi_r3,reduce_min_mpi_r4
+  END INTERFACE 
+
  INTERFACE grid1dTo2d_mpi
     MODULE PROCEDURE grid1dTo2d_mpi_i,grid1dTo2d_mpi_i1,grid1dTo2d_mpi_i2,grid1dTo2d_mpi_i3, &
@@ -986,4 +991,129 @@
   END SUBROUTINE reduce_sum_mpi_r4 
   
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! Definition des reduce_min   --> 4D   !!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+  SUBROUTINE reduce_min_mpi_i(VarIn, VarOut)
+    USE mod_phys_lmdz_mpi_data, ONLY :  is_mpi_root
+    IMPLICIT NONE
+  
+    INTEGER,INTENT(IN)  :: VarIn
+    INTEGER,INTENT(OUT) :: VarOut
+    INTEGER             :: VarIn_tmp(1)
+    INTEGER             :: VarOut_tmp(1)
+    
+    VarIn_tmp(1)=VarIn    
+    CALL reduce_min_mpi_igen(VarIn_tmp,Varout_tmp,1)
+    VarOut=VarOut_tmp(1)
+    
+  END SUBROUTINE reduce_min_mpi_i
+
+  SUBROUTINE reduce_min_mpi_i1(VarIn, VarOut)
+    USE mod_phys_lmdz_mpi_data, ONLY :  is_mpi_root
+    IMPLICIT NONE
+  
+    INTEGER,INTENT(IN),DIMENSION(:)  :: VarIn
+    INTEGER,INTENT(OUT),DIMENSION(:) :: VarOut
+    
+    CALL reduce_min_mpi_igen(VarIn,Varout,SIZE(VarIn))
+  
+  END SUBROUTINE reduce_min_mpi_i1
+
+  SUBROUTINE reduce_min_mpi_i2(VarIn, VarOut)
+    USE mod_phys_lmdz_mpi_data, ONLY :  is_mpi_root
+    IMPLICIT NONE
+  
+    INTEGER,INTENT(IN),DIMENSION(:,:)  :: VarIn
+    INTEGER,INTENT(OUT),DIMENSION(:,:) :: VarOut
+    
+    CALL reduce_min_mpi_igen(VarIn,Varout,SIZE(VarIn))
+  
+  END SUBROUTINE reduce_min_mpi_i2
+
+  SUBROUTINE reduce_min_mpi_i3(VarIn, VarOut)
+    USE mod_phys_lmdz_mpi_data, ONLY :  is_mpi_root
+    IMPLICIT NONE
+  
+    INTEGER,INTENT(IN),DIMENSION(:,:,:)  :: VarIn
+    INTEGER,INTENT(OUT),DIMENSION(:,:,:) :: VarOut
+    
+    CALL reduce_min_mpi_igen(VarIn,Varout,SIZE(VarIn))
+  
+  END SUBROUTINE reduce_min_mpi_i3
+
+  SUBROUTINE reduce_min_mpi_i4(VarIn, VarOut)
+    USE mod_phys_lmdz_mpi_data, ONLY :  is_mpi_root
+    IMPLICIT NONE
+  
+    INTEGER,INTENT(IN),DIMENSION(:,:,:,:)  :: VarIn
+    INTEGER,INTENT(OUT),DIMENSION(:,:,:,:) :: VarOut
+    
+    CALL reduce_min_mpi_igen(VarIn,Varout,SIZE(VarIn))
+  
+  END SUBROUTINE reduce_min_mpi_i4                  
+  
+  
+  SUBROUTINE reduce_min_mpi_r(VarIn, VarOut)
+    USE mod_phys_lmdz_mpi_data, ONLY :  is_mpi_root
+    IMPLICIT NONE
+  
+    REAL,INTENT(IN)  :: VarIn
+    REAL,INTENT(OUT) :: VarOut
+    REAL             :: VarIn_tmp(1)
+    REAL             :: VarOut_tmp(1)
+    
+    VarIn_tmp(1)=VarIn    
+    CALL reduce_min_mpi_rgen(VarIn_tmp,Varout_tmp,1)
+    VarOut=VarOut_tmp(1)
+  
+  END SUBROUTINE reduce_min_mpi_r
+
+  SUBROUTINE reduce_min_mpi_r1(VarIn, VarOut)
+    USE mod_phys_lmdz_mpi_data, ONLY :  is_mpi_root
+    IMPLICIT NONE
+  
+    REAL,INTENT(IN),DIMENSION(:)  :: VarIn
+    REAL,INTENT(OUT),DIMENSION(:) :: VarOut
+    
+    CALL reduce_min_mpi_rgen(VarIn,Varout,SIZE(VarIn))
+     
+  END SUBROUTINE reduce_min_mpi_r1
+
+  SUBROUTINE reduce_min_mpi_r2(VarIn, VarOut)
+    USE mod_phys_lmdz_mpi_data, ONLY :  is_mpi_root
+    IMPLICIT NONE
+  
+    REAL,INTENT(IN),DIMENSION(:,:)  :: VarIn
+    REAL,INTENT(OUT),DIMENSION(:,:) :: VarOut
+    
+    CALL reduce_min_mpi_rgen(VarIn,Varout,SIZE(VarIn))
+  
+  END SUBROUTINE reduce_min_mpi_r2
+
+  SUBROUTINE reduce_min_mpi_r3(VarIn, VarOut)
+    USE mod_phys_lmdz_mpi_data, ONLY :  is_mpi_root
+    IMPLICIT NONE
+  
+    REAL,INTENT(IN),DIMENSION(:,:,:)  :: VarIn
+    REAL,INTENT(OUT),DIMENSION(:,:,:) :: VarOut
+    
+    CALL reduce_min_mpi_rgen(VarIn,Varout,SIZE(VarIn))
+  
+  END SUBROUTINE reduce_min_mpi_r3
+
+  SUBROUTINE reduce_min_mpi_r4(VarIn, VarOut)
+    USE mod_phys_lmdz_mpi_data, ONLY :  is_mpi_root
+    IMPLICIT NONE
+  
+    REAL,INTENT(IN),DIMENSION(:,:,:,:)  :: VarIn
+    REAL,INTENT(OUT),DIMENSION(:,:,:,:) :: VarOut
+    
+    CALL reduce_min_mpi_rgen(VarIn,Varout,SIZE(VarIn))
+  
+  END SUBROUTINE reduce_min_mpi_r4 
+
+
 
 
@@ -1678,4 +1808,62 @@
 
 
+  SUBROUTINE reduce_min_mpi_igen(VarIn,VarOut,nb)
+    USE mod_phys_lmdz_mpi_data 
+    USE mod_grid_phy_lmdz
+    IMPLICIT NONE
+    
+#ifdef CPP_MPI
+    INCLUDE 'mpif.h'
+#endif
+   
+    INTEGER,INTENT(IN) :: nb
+    INTEGER,DIMENSION(nb),INTENT(IN) :: VarIn
+    INTEGER,DIMENSION(nb),INTENT(OUT) :: VarOut    
+    INTEGER :: ierr
+   
+    IF (.not.is_using_mpi) THEN
+      VarOut(:)=VarIn(:)
+      RETURN
+    ENDIF
+
+
+#ifdef CPP_MPI
+    CALL MPI_REDUCE(VarIn,VarOut,nb,MPI_INTEGER,MPI_MIN,mpi_master,COMM_LMDZ_PHY,ierr)
+#endif
+            
+  END SUBROUTINE reduce_min_mpi_igen
+  
+  SUBROUTINE reduce_min_mpi_rgen(VarIn,VarOut,nb)
+    USE mod_phys_lmdz_mpi_data 
+    USE mod_grid_phy_lmdz
+
+    IMPLICIT NONE
+
+#ifdef CPP_MPI
+    INCLUDE 'mpif.h'
+#endif
+    
+    INTEGER,INTENT(IN) :: nb
+    REAL,DIMENSION(nb),INTENT(IN) :: VarIn
+    REAL,DIMENSION(nb),INTENT(OUT) :: VarOut    
+    INTEGER :: ierr
+ 
+    IF (.not.is_using_mpi) THEN
+      VarOut(:)=VarIn(:)
+      RETURN
+    ENDIF
+   
+#ifdef CPP_MPI
+    CALL MPI_REDUCE(VarIn,VarOut,nb,MPI_REAL_LMDZ,MPI_MIN,mpi_master,COMM_LMDZ_PHY,ierr)
+#endif
+        
+  END SUBROUTINE reduce_min_mpi_rgen
+
+
+
+
+
+
+
   SUBROUTINE grid1dTo2d_mpi_igen(VarIn,VarOut,dimsize)
     USE mod_phys_lmdz_mpi_data
Index: /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_omp_data.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_omp_data.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_omp_data.F90	(revision 3605)
@@ -7,4 +7,5 @@
   INTEGER,SAVE :: omp_rank
   LOGICAL,SAVE :: is_omp_root
+  LOGICAL,SAVE :: is_omp_master  ! alias of is_omp_root
   LOGICAL,SAVE :: is_using_omp
   LOGICAL,SAVE :: is_north_pole_phy, is_south_pole_phy
@@ -17,5 +18,5 @@
   INTEGER,SAVE :: klon_omp_begin
   INTEGER,SAVE :: klon_omp_end
-!$OMP  THREADPRIVATE(omp_rank,klon_omp,is_omp_root,klon_omp_begin,klon_omp_end)
+!$OMP  THREADPRIVATE(omp_rank,klon_omp,is_omp_root,is_omp_master,klon_omp_begin,klon_omp_end)
 !$OMP  THREADPRIVATE(is_north_pole_phy, is_south_pole_phy)
 
@@ -60,8 +61,8 @@
    ELSE
      abort_message = 'ANORMAL : OMP_MASTER /= 0'
-     CALL abort_gcm (modname,abort_message,1)
+     CALL abort_physic (modname,abort_message,1)
    ENDIF
 !$OMP END MASTER
-
+   is_omp_master=is_omp_root
 
 !$OMP MASTER 
@@ -106,6 +107,7 @@
 
   SUBROUTINE Print_module_data
+  USE print_control_mod, ONLY: lunout
   IMPLICIT NONE
-  INCLUDE "iniprint.h"
+!  INCLUDE "iniprint.h"
 
 !$OMP CRITICAL  
Index: /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_omp_transfert.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_omp_transfert.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_omp_transfert.F90	(revision 3605)
@@ -47,6 +47,11 @@
   END INTERFACE 
 
-
-  PUBLIC bcast_omp,scatter_omp,gather_omp,reduce_sum_omp, omp_barrier
+  INTERFACE reduce_min_omp
+    MODULE PROCEDURE reduce_min_omp_i,reduce_min_omp_i1,reduce_min_omp_i2,reduce_min_omp_i3,reduce_min_omp_i4, &
+                     reduce_min_omp_r,reduce_min_omp_r1,reduce_min_omp_r2,reduce_min_omp_r3,reduce_min_omp_r4
+  END INTERFACE 
+
+
+  PUBLIC bcast_omp,scatter_omp,gather_omp,reduce_sum_omp, reduce_min_omp, omp_barrier
 
 CONTAINS
@@ -710,4 +715,134 @@
   END SUBROUTINE reduce_sum_omp_r4
 
+
+
+  SUBROUTINE reduce_min_omp_i(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    INTEGER,INTENT(IN)  :: VarIn
+    INTEGER,INTENT(OUT) :: VarOut
+    INTEGER             :: VarIn_tmp(1)
+    INTEGER             :: VarOut_tmp(1)
+    
+    VarIn_tmp(1)=VarIn
+    CALL Check_buffer_i(1)   
+    CALL reduce_min_omp_igen(VarIn_tmp,Varout_tmp,1,buffer_i)
+    VarOut=VarOut_tmp(1)
+    
+  END SUBROUTINE reduce_min_omp_i
+
+  SUBROUTINE reduce_min_omp_i1(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    INTEGER,INTENT(IN),DIMENSION(:)  :: VarIn
+    INTEGER,INTENT(OUT),DIMENSION(:) :: VarOut
+    
+    CALL Check_buffer_i(size(VarIn))   
+    CALL reduce_min_omp_igen(VarIn,Varout,Size(VarIn),buffer_i)
+   
+  END SUBROUTINE reduce_min_omp_i1
+  
+  
+  SUBROUTINE reduce_min_omp_i2(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    INTEGER,INTENT(IN),DIMENSION(:,:)  :: VarIn
+    INTEGER,INTENT(OUT),DIMENSION(:,:) :: VarOut
+
+    CALL Check_buffer_i(size(VarIn))   
+    CALL reduce_min_omp_igen(VarIn,Varout,Size(VarIn),buffer_i)
+  
+  END SUBROUTINE reduce_min_omp_i2
+
+
+  SUBROUTINE reduce_min_omp_i3(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    INTEGER,INTENT(IN),DIMENSION(:,:,:)  :: VarIn
+    INTEGER,INTENT(OUT),DIMENSION(:,:,:) :: VarOut
+    
+    CALL Check_buffer_i(size(VarIn))   
+    CALL reduce_min_omp_igen(VarIn,Varout,Size(VarIn),buffer_i)
+  
+  END SUBROUTINE reduce_min_omp_i3
+
+
+  SUBROUTINE reduce_min_omp_i4(VarIn, VarOut)
+    IMPLICIT NONE
+
+    INTEGER,INTENT(IN),DIMENSION(:,:,:,:)  :: VarIn
+    INTEGER,INTENT(OUT),DIMENSION(:,:,:,:) :: VarOut
+  
+    CALL Check_buffer_i(size(VarIn))   
+    CALL reduce_min_omp_igen(VarIn,Varout,Size(VarIn),buffer_i)
+  
+  END SUBROUTINE reduce_min_omp_i4
+
+
+  SUBROUTINE reduce_min_omp_r(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    REAL,INTENT(IN)  :: VarIn
+    REAL,INTENT(OUT) :: VarOut
+    REAL             :: VarIn_tmp(1)
+    REAL             :: VarOut_tmp(1)
+    
+    VarIn_tmp(1)=VarIn
+    CALL Check_buffer_r(1)   
+    CALL reduce_min_omp_rgen(VarIn_tmp,Varout_tmp,1,buffer_r)
+    VarOut=VarOut_tmp(1)
+  
+  END SUBROUTINE reduce_min_omp_r
+
+  SUBROUTINE reduce_min_omp_r1(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    REAL,INTENT(IN),DIMENSION(:)  :: VarIn
+    REAL,INTENT(OUT),DIMENSION(:) :: VarOut
+    
+    CALL Check_buffer_r(size(VarIn))   
+    CALL reduce_min_omp_rgen(VarIn,Varout,Size(VarIn),buffer_r)
+   
+  END SUBROUTINE reduce_min_omp_r1
+  
+  
+  SUBROUTINE reduce_min_omp_r2(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    REAL,INTENT(IN),DIMENSION(:,:)  :: VarIn
+    REAL,INTENT(OUT),DIMENSION(:,:) :: VarOut
+    
+    CALL Check_buffer_r(size(VarIn))   
+    CALL reduce_min_omp_rgen(VarIn,Varout,Size(VarIn),buffer_r)
+  
+  END SUBROUTINE reduce_min_omp_r2
+
+
+  SUBROUTINE reduce_min_omp_r3(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    REAL,INTENT(IN),DIMENSION(:,:,:)  :: VarIn
+    REAL,INTENT(OUT),DIMENSION(:,:,:) :: VarOut
+    
+    CALL Check_buffer_r(size(VarIn))   
+    CALL reduce_min_omp_rgen(VarIn,Varout,Size(VarIn),buffer_r)
+  
+  END SUBROUTINE reduce_min_omp_r3
+
+
+  SUBROUTINE reduce_min_omp_r4(VarIn, VarOut)
+    IMPLICIT NONE
+
+    REAL,INTENT(IN),DIMENSION(:,:,:,:)  :: VarIn
+    REAL,INTENT(OUT),DIMENSION(:,:,:,:) :: VarOut
+  
+    CALL Check_buffer_r(size(VarIn))   
+    CALL reduce_min_omp_rgen(VarIn,Varout,Size(VarIn),buffer_r)
+  
+  END SUBROUTINE reduce_min_omp_r4
+
+
+
+
 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 !    LES ROUTINES GENERIQUES    !
@@ -1062,3 +1197,69 @@
   END SUBROUTINE reduce_sum_omp_rgen
 
+
+  SUBROUTINE reduce_min_omp_igen(VarIn,VarOut,dimsize,Buff)
+  IMPLICIT NONE
+
+    INTEGER,INTENT(IN) :: dimsize
+    INTEGER,INTENT(IN),DIMENSION(dimsize) :: VarIn
+    INTEGER,INTENT(OUT),DIMENSION(dimsize) :: VarOut
+    INTEGER,INTENT(INOUT),DIMENSION(dimsize) :: Buff
+
+    INTEGER :: i
+    INTEGER :: var
+
+  !$OMP MASTER
+    Buff(:)=HUGE(var)
+  !$OMP END MASTER
+  !$OMP BARRIER
+  
+  !$OMP CRITICAL     
+    DO i=1,dimsize
+      Buff(i)=MIN(Buff(i),VarIn(i))
+    ENDDO
+  !$OMP END CRITICAL
+  !$OMP BARRIER  
+  
+  !$OMP MASTER
+    DO i=1,dimsize
+      VarOut(i)=Buff(i)
+    ENDDO
+  !$OMP END MASTER
+  !$OMP BARRIER
+  
+  END SUBROUTINE reduce_min_omp_igen
+
+  SUBROUTINE reduce_min_omp_rgen(VarIn,VarOut,dimsize,Buff)
+  IMPLICIT NONE
+
+    INTEGER,INTENT(IN) :: dimsize
+    REAL,INTENT(IN),DIMENSION(dimsize) :: VarIn
+    REAL,INTENT(OUT),DIMENSION(dimsize) :: VarOut
+    REAL,INTENT(INOUT),DIMENSION(dimsize) :: Buff
+
+    INTEGER :: i
+    REAL :: var
+
+  !$OMP MASTER
+    Buff(:)=HUGE(var)
+  !$OMP END MASTER
+  !$OMP BARRIER
+  
+  !$OMP CRITICAL     
+    DO i=1,dimsize
+      Buff(i)=MIN(Buff(i),VarIn(i))
+    ENDDO
+  !$OMP END CRITICAL
+  !$OMP BARRIER  
+  
+  !$OMP MASTER
+    DO i=1,dimsize
+      VarOut(i)=Buff(i)
+    ENDDO
+  !$OMP END MASTER
+  !$OMP BARRIER
+  
+  END SUBROUTINE reduce_min_omp_rgen
+
+
 END MODULE mod_phys_lmdz_omp_transfert
Index: /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_para.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_para.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_para.F90	(revision 3605)
@@ -33,5 +33,5 @@
        is_master=.FALSE.
      ENDIF
-     CALL Test_transfert
+!ym     CALL Test_transfert
 !$OMP END PARALLEL    
      IF (is_using_mpi .OR. is_using_omp) THEN
@@ -49,6 +49,7 @@
   SUBROUTINE Test_transfert
   USE mod_grid_phy_lmdz
+  USE print_control_mod, ONLY: lunout
   IMPLICIT NONE
-    INCLUDE "iniprint.h"
+!    INCLUDE "iniprint.h"
  
     REAL :: Test_Field1d_glo(klon_glo,nbp_lev)
Index: /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_transfert_para.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_transfert_para.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phy_common/mod_phys_lmdz_transfert_para.F90	(revision 3605)
@@ -1,4 +1,4 @@
 !
-!$Header$
+!$Id$
 !
 MODULE mod_phys_lmdz_transfert_para
@@ -46,4 +46,8 @@
   END INTERFACE 
 
+  INTERFACE reduce_min
+    MODULE PROCEDURE reduce_min_i,reduce_min_i1,reduce_min_i2,reduce_min_i3,reduce_min_i4, &
+                     reduce_min_r,reduce_min_r1,reduce_min_r2,reduce_min_r3,reduce_min_r4
+  END INTERFACE 
    
 CONTAINS
@@ -1271,4 +1275,173 @@
   END SUBROUTINE reduce_sum_r4  
 
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! Definition des reduce_min   --> 4D   !!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+! Les entiers
+
+  SUBROUTINE reduce_min_i(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    INTEGER,INTENT(IN)  :: VarIn
+    INTEGER,INTENT(OUT) :: VarOut
+    
+    INTEGER             :: Var_tmp
+           
+    CALL reduce_min_omp(VarIn,Var_tmp)
+!$OMP MASTER      
+    CALL reduce_min_mpi(Var_tmp,VarOut)
+!$OMP END MASTER
+  
+  END SUBROUTINE reduce_min_i  
+
+
+  SUBROUTINE reduce_min_i1(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    INTEGER,INTENT(IN),DIMENSION(:)  :: VarIn
+    INTEGER,INTENT(OUT),DIMENSION(:) :: VarOut
+    
+    INTEGER,DIMENSION(SIZE(VarIn))   :: Var_tmp
+           
+    CALL reduce_min_omp(VarIn,Var_tmp)
+!$OMP MASTER      
+    CALL reduce_min_mpi(Var_tmp,VarOut)
+!$OMP END MASTER
+  
+  END SUBROUTINE reduce_min_i1  
+
+
+  SUBROUTINE reduce_min_i2(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    INTEGER,INTENT(IN),DIMENSION(:,:)  :: VarIn
+    INTEGER,INTENT(OUT),DIMENSION(:,:) :: VarOut
+    
+    INTEGER,DIMENSION(SIZE(VarIn,1),SIZE(VarIn,2)) :: Var_tmp
+           
+    CALL reduce_min_omp(VarIn,Var_tmp)
+!$OMP MASTER      
+    CALL reduce_min_mpi(Var_tmp,VarOut)
+!$OMP END MASTER
+  
+  END SUBROUTINE reduce_min_i2  
+  
+
+  SUBROUTINE reduce_min_i3(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    INTEGER,INTENT(IN),DIMENSION(:,:,:)  :: VarIn
+    INTEGER,INTENT(OUT),DIMENSION(:,:,:) :: VarOut
+    
+    INTEGER,DIMENSION(SIZE(VarIn,1),SIZE(VarIn,2),SIZE(VarIn,3))  :: Var_tmp
+           
+    CALL reduce_min_omp(VarIn,Var_tmp)
+!$OMP MASTER      
+    CALL reduce_min_mpi(Var_tmp,VarOut)
+!$OMP END MASTER
+  
+  END SUBROUTINE reduce_min_i3  
+
+
+  SUBROUTINE reduce_min_i4(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    INTEGER,INTENT(IN),DIMENSION(:,:,:,:)  :: VarIn
+    INTEGER,INTENT(OUT),DIMENSION(:,:,:,:) :: VarOut
+    
+    INTEGER,DIMENSION(SIZE(VarIn,1),SIZE(VarIn,2),SIZE(VarIn,3),SIZE(VarIn,4))  :: Var_tmp
+           
+    CALL reduce_min_omp(VarIn,Var_tmp)
+!$OMP MASTER      
+    CALL reduce_min_mpi(Var_tmp,VarOut)
+!$OMP END MASTER
+  
+  END SUBROUTINE reduce_min_i4  
+
+
+! Les reels
+
+  SUBROUTINE reduce_min_r(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    REAL,INTENT(IN)  :: VarIn
+    REAL,INTENT(OUT) :: VarOut
+    
+    REAL             :: Var_tmp
+           
+    CALL reduce_min_omp(VarIn,Var_tmp)
+!$OMP MASTER      
+    CALL reduce_min_mpi(Var_tmp,VarOut)
+!$OMP END MASTER
+  
+  END SUBROUTINE reduce_min_r  
+
+
+  SUBROUTINE reduce_min_r1(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    REAL,INTENT(IN),DIMENSION(:)  :: VarIn
+    REAL,INTENT(OUT),DIMENSION(:) :: VarOut
+    
+    REAL,DIMENSION(SIZE(VarIn))   :: Var_tmp
+           
+    CALL reduce_min_omp(VarIn,Var_tmp)
+!$OMP MASTER      
+    CALL reduce_min_mpi(Var_tmp,VarOut)
+!$OMP END MASTER
+  
+  END SUBROUTINE reduce_min_r1  
+
+
+  SUBROUTINE reduce_min_r2(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    REAL,INTENT(IN),DIMENSION(:,:)  :: VarIn
+    REAL,INTENT(OUT),DIMENSION(:,:) :: VarOut
+    
+    REAL,DIMENSION(SIZE(VarIn,1),SIZE(VarIn,2)) :: Var_tmp
+           
+    CALL reduce_min_omp(VarIn,Var_tmp)
+!$OMP MASTER      
+    CALL reduce_min_mpi(Var_tmp,VarOut)
+!$OMP END MASTER
+  
+  END SUBROUTINE reduce_min_r2  
+  
+
+  SUBROUTINE reduce_min_r3(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    REAL,INTENT(IN),DIMENSION(:,:,:)  :: VarIn
+    REAL,INTENT(OUT),DIMENSION(:,:,:) :: VarOut
+    
+    REAL,DIMENSION(SIZE(VarIn,1),SIZE(VarIn,2),SIZE(VarIn,3))  :: Var_tmp
+           
+    CALL reduce_min_omp(VarIn,Var_tmp)
+!$OMP MASTER      
+    CALL reduce_min_mpi(Var_tmp,VarOut)
+!$OMP END MASTER
+  
+  END SUBROUTINE reduce_min_r3  
+
+
+  SUBROUTINE reduce_min_r4(VarIn, VarOut)
+    IMPLICIT NONE
+  
+    REAL,INTENT(IN),DIMENSION(:,:,:,:)  :: VarIn
+    REAL,INTENT(OUT),DIMENSION(:,:,:,:) :: VarOut
+    
+    REAL,DIMENSION(SIZE(VarIn,1),SIZE(VarIn,2),SIZE(VarIn,3),SIZE(VarIn,4))  :: Var_tmp
+           
+    CALL reduce_min_omp(VarIn,Var_tmp)
+!$OMP MASTER      
+    CALL reduce_min_mpi(Var_tmp,VarOut)
+!$OMP END MASTER
+  
+  END SUBROUTINE reduce_min_r4  
+
+
    
 END MODULE mod_phys_lmdz_transfert_para
Index: /LMDZ6/branches/Ocean_skin/libf/phy_common/physics_distribution_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phy_common/physics_distribution_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phy_common/physics_distribution_mod.F90	(revision 3605)
@@ -10,6 +10,12 @@
                                        nbp, nbp_lon, nbp_lat, nbp_lev, &
                                        communicator)
-  USE mod_phys_lmdz_para, ONLY: init_phys_lmdz_para
+  USE mod_phys_lmdz_para, ONLY: init_phys_lmdz_para, klon_omp
   USE mod_grid_phy_lmdz, ONLY: init_grid_phy_lmdz
+  USE dimphy, ONLY : Init_dimphy
+  USE infotrac_phy, ONLY : type_trac
+#ifdef REPROBUS
+  USE CHEM_REP, ONLY : Init_chem_rep_phys
+#endif
+
   IMPLICIT NONE
     INTEGER,INTENT(IN) :: grid_type 
@@ -24,4 +30,15 @@
     CALL init_grid_phy_lmdz(grid_type,nvertex, nbp_lon,nbp_lat,nbp_lev)
     CALL init_phys_lmdz_para(nbp,nbp_lon, nbp_lat, communicator)
+!$OMP PARALLEL
+    CALL init_dimphy(klon_omp,nbp_lev)
+
+! Initialization of Reprobus
+    IF (type_trac == 'repr') THEN
+#ifdef REPROBUS
+       CALL Init_chem_rep_phys(klon_omp,nbp_lev)
+#endif
+    END IF
+
+!$OMP END PARALLEL
 
   END SUBROUTINE init_physics_distribution  
Index: /LMDZ6/branches/Ocean_skin/libf/phy_common/print_control_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phy_common/print_control_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phy_common/print_control_mod.F90	(revision 3605)
@@ -7,57 +7,21 @@
 !$OMP THREADPRIVATE(lunout,prt_level,debug)
 
+  ! NB: Module variable Initializations done by set_print_control
+  !     routine from init_print_control_mod to avoid circular
+  !     module dependencies
+
 CONTAINS
 
-  SUBROUTINE init_print_control
-  USE ioipsl_getin_p_mod, ONLY : getin_p
-  USE mod_phys_lmdz_para, ONLY: is_omp_root, is_master
+  SUBROUTINE set_print_control(lunout_,prt_level_,debug_)
   IMPLICIT NONE
-
-    LOGICAL :: opened
-    INTEGER :: number
+    INTEGER :: lunout_
+    INTEGER :: prt_level_
+    LOGICAL :: debug_
+      
+    lunout = lunout_
+    prt_level = prt_level_
+    debug = debug_
     
-    !Config  Key  = prt_level
-    !Config  Desc = niveau d'impressions de débogage
-    !Config  Def  = 0
-    !Config  Help = Niveau d'impression pour le débogage
-    !Config         (0 = minimum d'impression)
-    prt_level = 0
-    CALL getin_p('prt_level',prt_level)
-
-    !Config  Key  = lunout
-    !Config  Desc = unite de fichier pour les impressions
-    !Config  Def  = 6
-    !Config  Help = unite de fichier pour les impressions 
-    !Config         (defaut sortie standard = 6)
-    lunout=6
-    CALL getin_p('lunout', lunout)
-
-    IF (is_omp_root) THEN
-      IF (lunout /= 5 .and. lunout /= 6) THEN
-         INQUIRE(FILE='lmdz.out_0000',OPENED=opened,NUMBER=number)
-         IF (opened) THEN
-           lunout=number
-         ELSE
-           OPEN(UNIT=lunout,FILE='lmdz.out_0000',ACTION='write',  &
-                STATUS='unknown',FORM='formatted')
-         ENDIF
-      ENDIF
-    ENDIF
-
-    !Config  Key  = debug
-    !Config  Desc = mode debogage
-    !Config  Def  = false
-    !Config  Help = positionne le mode debogage
-
-    debug = .FALSE.
-    CALL getin_p('debug',debug)
-    
-    IF (is_master) THEN
-      WRITE(lunout,*)"init_print_control: prt_level=",prt_level
-      WRITE(lunout,*)"init_print_control: lunout=",lunout
-      WRITE(lunout,*)"init_print_control: debug=",debug      
-    ENDIF
-    
-  END SUBROUTINE init_print_control  
+  END SUBROUTINE set_print_control
 
 END MODULE print_control_mod
Index: /LMDZ6/branches/Ocean_skin/libf/phydev/inifis_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phydev/inifis_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phydev/inifis_mod.F90	(revision 3605)
@@ -1,3 +1,3 @@
-! $Id: $
+! $Id$
 MODULE inifis_mod
 
@@ -6,5 +6,5 @@
   SUBROUTINE inifis(prad, pg, pr, pcpp)
   ! Initialize some physical constants and settings
-  USE print_control_mod, ONLY: init_print_control
+  USE init_print_control_mod, ONLY: init_print_control
   USE comcstphy, ONLY: rradius, & ! planet radius (m)
                        rr, & ! recuced gas constant: R/molar mass of atm
Index: /LMDZ6/branches/Ocean_skin/libf/phydev/phyredem.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phydev/phyredem.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phydev/phyredem.F90	(revision 3605)
@@ -5,5 +5,6 @@
 
   USE geometry_mod, ONLY : longitude_deg, latitude_deg
-  USE iostart, ONLY: open_restartphy, close_restartphy, put_var, put_field
+  USE iostart, ONLY: open_restartphy, close_restartphy, enddef_restartphy, put_field, put_var
+
 
   IMPLICIT NONE
@@ -13,4 +14,5 @@
   INTEGER,PARAMETER :: tab_cntrl_len=100
   REAL :: tab_cntrl(tab_cntrl_len)
+  INTEGER :: pass
 
   ! open file
@@ -21,14 +23,19 @@
 
   tab_cntrl(:)=0.0
- 
 
-  CALL put_var("controle", "Control parameters", tab_cntrl)
+  DO pass=1,2   ! pass=1 netcdf definition ; pass=2 netcdf write
+
+    CALL put_var(pass, "controle", "Control parameters", tab_cntrl)
 
   ! coordinates
 
-  CALL put_field("longitude", "Longitudes on physics grid", longitude_deg)
+    CALL put_field(pass, "longitude", "Longitudes on physics grid", longitude_deg)
      
-  CALL put_field("latitude", "Latitudes on physics grid", latitude_deg)
+    CALL put_field(pass, "latitude", "Latitudes on physics grid", latitude_deg)
 
+    IF (pass==1) CALL enddef_restartphy
+    IF (pass==2) CALL close_restartphy
+
+  ENDDO
   ! close file
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/aer_sedimnt.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/aer_sedimnt.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/aer_sedimnt.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 SUBROUTINE AER_SEDIMNT(pdtphys, t_seri, pplay, paprs, tr_seri, dens_aer)
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/calcaerosolstrato_rrtm.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/calcaerosolstrato_rrtm.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/calcaerosolstrato_rrtm.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 SUBROUTINE calcaerosolstrato_rrtm(pplay,t_seri,paprs,debut)
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/coagulate.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/coagulate.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/coagulate.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 SUBROUTINE COAGULATE(pdtcoag,mdw,tr_seri,t_seri,pplay,dens_aer,is_strato)
   !     -----------------------------------------------------------------------
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/cond_evap_tstep_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/cond_evap_tstep_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/cond_evap_tstep_mod.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 MODULE cond_evap_tstep_mod
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/interp_sulf_input.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/interp_sulf_input.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/interp_sulf_input.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 SUBROUTINE interp_sulf_input(debutphy,pdtphys,paprs,tr_seri)
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/micphy_tstep.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/micphy_tstep.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/micphy_tstep.F90	(revision 3605)
@@ -1,4 +1,8 @@
+!
+! $Id$
+!
 SUBROUTINE micphy_tstep(pdtphys,tr_seri,t_seri,pplay,paprs,rh,is_strato)
 
+  USE geometry_mod, ONLY : latitude_deg !NL- latitude corr. to local domain
   USE dimphy, ONLY : klon,klev
   USE aerophys
@@ -9,5 +13,7 @@
   USE sulfate_aer_mod, ONLY : STRAACT
   USE YOMCST, ONLY : RPI, RD, RG
-
+  USE print_control_mod, ONLY: lunout
+  USE strataer_mod
+  
   IMPLICIT NONE
 
@@ -89,5 +95,12 @@
       ! compute nucleation rate in kg(H2SO4)/kgA/s
       CALL nucleation_rate(rhoa,t_seri(ilon,ilev),pplay(ilon,ilev),rh(ilon,ilev), &
-             & a_xm,b_xm,c_xm,nucl_rate,ntot,x)
+           & a_xm,b_xm,c_xm,nucl_rate,ntot,x)
+      !NL - add nucleation box (if flag on)
+      IF (flag_nuc_rate_box) THEN
+         IF (latitude_deg(ilon).LE.nuclat_min .OR. latitude_deg(ilon).GE.nuclat_max &
+              .OR. pplay(ilon,ilev).GE.nucpres_max .AND. pplay(ilon,ilev).LE.nucpres_min) THEN
+            nucl_rate=0.0
+         ENDIF
+      ENDIF
       ! compute cond/evap rate in kg(H2SO4)/kgA/s
       CALL condens_evapor_rate(rhoa,t_seri(ilon,ilev),pplay(ilon,ilev), &
@@ -160,5 +173,5 @@
     DO it=1, nbtr
       IF (tr_seri(ilon,ilev,it).LT.0.0) THEN
-        PRINT *, 'micphy_tstep: negative concentration', tr_seri(ilon,ilev,it), ilon, ilev, it
+         WRITE(lunout,*) 'micphy_tstep: negative concentration', tr_seri(ilon,ilev,it), ilon, ilev, it
       ENDIF
     ENDDO
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/miecalc_aer.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/miecalc_aer.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/miecalc_aer.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 SUBROUTINE MIECALC_AER(tau_strat, piz_strat, cg_strat, tau_strat_wave, tau_lw_abs_rrtm, paprs, debut)
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/minmaxsimple.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/minmaxsimple.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/minmaxsimple.F90	(revision 3605)
@@ -1,4 +1,4 @@
 !
-! $Id: minmaxsimple.F90 1910 2013-11-29 08:40:25Z fairhead $
+! $Id$
 !
 SUBROUTINE minmaxsimple(zq,qmin,qmax,comment)
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/nucleation_tstep_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/nucleation_tstep_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/nucleation_tstep_mod.F90	(revision 3605)
@@ -1,46 +1,68 @@
+!
+! $Id$
+!
 MODULE nucleation_tstep_mod
 
 CONTAINS
 
-SUBROUTINE nucleation_rate(rhoa,t_seri,pplay,rh,a_xm,b_xm,c_xm,nucl_rate,ntot,x)
+SUBROUTINE nucleation_rate(rhoa,t_seri,pplay,rh,a_xm,b_xm,c_xm,nucl_rate,ntot_n,x_n)
 
   USE aerophys
   USE infotrac
-  USE YOMCST, ONLY : RPI, RD
+  USE YOMCST, ONLY : RPI, RD, RMD, RKBOL, RNAVO
 
   IMPLICIT NONE
 
   ! input variables
-  REAL rhoa !H2SO4 number density [molecules/cm3]
-  REAL t_seri
-  REAL pplay
-  REAL rh
+  LOGICAL, PARAMETER :: flag_new_nucl=.TRUE.
+  REAL rhoa    ! H2SO4 number density [molecules/cm3]
+  REAL t_seri  ! temperature (K)
+  REAL pplay   ! pressure (Pa)
+  REAL rh      ! relative humidity (between 0 and 1)
   REAL a_xm, b_xm, c_xm
 
   ! output variables
   REAL nucl_rate
-  REAL ntot ! total number of molecules in the critical cluster
-  REAL x    ! molefraction of H2SO4 in the critical cluster
+  REAL ntot_n ! total number of molecules in the critical cluster for neutral nucleation
+  REAL x_n    ! mole fraction of H2SO4 in the critical cluster for neutral nucleation
 
   ! local variables
-  REAL, PARAMETER                               :: k_B=1.3806E-23  ! Boltzmann constant [J/K]
-  REAL                                          :: jnuc !nucleation rate in 1/cm3s (10^-7-10^10 1/cm3s)
-  REAL                                          :: rc   !radius of the critical cluster in nm 
+  REAL jnuc_n ! nucleation rate in 1/cm3s (10^-7-10^10 1/cm3s) for neutral nucleation
+  REAL rc_n   ! radius of the critical cluster in nm for neutral nucleation
+  REAL na_n   ! sulfuric acid molecules in the neutral critical cluster (NOT IN USE)
+  LOGICAL kinetic_n ! true if kinetic neutral nucleation (NOT IN USE)
+  LOGICAL kinetic_i ! true if kinetic ion-induced nucleation (NOT IN USE)
+  REAL rhoatres ! threshold concentration of H2SO4 (1/cm^3) for neutral kinetic nucleation (NOT IN USE)
   REAL VH2SO4mol
+  REAL ntot_i, x_i, jnuc_i, rc_i, na_i, n_i ! quantities for charged nucleation (NOT IN USE)
+  REAL csi     ! Ion condensation sink (s-1) NOT IN USE
+  REAL airn    ! Air molecule concentration in (cm-3) NOT IN USE
+  REAL ipr     ! Ion pair production rate (cm-3 s-1) NOT IN USE
 
   ! call nucleation routine
-  CALL binapara(t_seri,rh,rhoa,jnuc,x,ntot,rc)
-
-  IF (ntot < 4.0) THEN
-    !set jnuc to collision rate of two H2SO4 molecules (following personal communication of Ulrike Niemeier and Hanna Vehkamäki)
-    VH2SO4mol=mH2SO4mol/(1.e-3*(a_xm+t_seri*(b_xm+t_seri*c_xm))) !cm3
-    jnuc = rhoa**2. *(3./4.*RPI)**(1./6.) *(12.*k_B*t_seri/mH2SO4mol)**0.5 &
-         & *100.*(2.*VH2SO4mol**(1./3.))**2. !1/(cm3s)
-    ntot=2.0
-    x=1.0
-  ENDIF
-
-  ! convert jnuc from particles/cm3/s to kg(H2SO4)/kgA/s
-  nucl_rate=jnuc*ntot*x*mH2SO4mol/(pplay/t_seri/RD/1.E6)
+  IF (.NOT.flag_new_nucl) THEN
+    ! Use older routine from Hanna Vehkamäki (FMI)
+    CALL binapara(t_seri,rh,rhoa,jnuc_n,x_n,ntot_n,rc_n)
+    ! when total number of molecules is too small 
+    ! then set jnuc_n to collision rate of two H2SO4 molecules (following personal communication of Ulrike Niemeier and Hanna Vehkamäki)
+    IF (ntot_n < 4.0) THEN
+      VH2SO4mol=mH2SO4mol/(1.E-3*(a_xm+t_seri*(b_xm+t_seri*c_xm))) !cm3
+      jnuc_n = rhoa**2. *(3./4.*RPI)**(1./6.) *(12.*RKBOL*t_seri/mH2SO4mol)**0.5 &
+           & *100.*(2.*VH2SO4mol**(1./3.))**2. !1/(cm3s)
+      ntot_n=2.0
+      x_n=1.0
+    ENDIF
+  ELSE
+    ! Use new routine from Anni Maattanen (LATMOS)
+    csi=0.0   ! no charged nucleation for now
+    ipr=-1.0  ! dummy value to make sure charged nucleation does not occur
+    airn=0.0  ! NOT IN USE
+!   airn=pplay/t_seri/RD/1.E3*RNAVO/RMD ! molec cm-3 (for future use, to be confirmed)
+    CALL newbinapara(t_seri,rh,rhoa,csi,airn,ipr,jnuc_n,ntot_n,jnuc_i,ntot_i, &
+                   & x_n,x_i,na_n,na_i,rc_n,rc_i,n_i,kinetic_n,kinetic_i,rhoatres)
+  ENDIF
+
+  ! convert jnuc_n from particles/cm3/s to kg(H2SO4)/kgA/s
+  nucl_rate=jnuc_n*ntot_n*x_n*mH2SO4mol/(pplay/t_seri/RD/1.E6)
 
 END SUBROUTINE nucleation_rate
@@ -55,15 +77,15 @@
   IMPLICIT NONE
 
-  ! input variables
+  ! input variable
   REAL nucl_rate
   REAL ntot ! total number of molecules in the critical cluster
-  REAL x    ! molefraction of H2SO4 in the critical cluster
+  REAL x    ! mole raction of H2SO4 in the critical cluster
   REAL dt
   REAL Vbin(nbtr_bin)
 
-  ! output variables
+  ! output variable
   REAL tr_seri(nbtr)
 
-  ! local variables
+  ! local variable
   INTEGER k
   REAL Vnew
@@ -77,5 +99,5 @@
   DO k=1, nbtr_bin 
   ! CK 20160531: bug fix for first bin
-    IF (k.LE.(nbtr_bin-1)) THEN 
+    IF (k.LE.nbtr_bin-1) THEN 
       IF (Vbin(k).LE.Vnew.AND.Vnew.LT.Vbin(k+1)) THEN
         ff(k)= Vbin(k)/Vnew*(Vbin(k+1)-Vnew)/(Vbin(k+1)-Vbin(k))
@@ -132,15 +154,15 @@
 
   REAL :: pt,t     !temperature in K (190.15-300.15K)
-  REAL :: prh,rh    !saturatio ratio of water (0.0001-1)
-  REAL,intent(in) :: rhoa_in    !sulfuric acid concentration in 1/cm3 (10^4-10^11 1/cm3)
-  REAL,intent(out) :: jnuc    !nucleation rate in 1/cm3s (10^-7-10^10 1/cm3s)
-  REAL,intent(out) :: ntot !total number of molecules in the critical cluster (ntot>4)
-  REAL,intent(out) :: x    ! molefraction of H2SO4 in the critical cluster       
-  REAL,intent(out) :: rc    !radius of the critical cluster in nm     
-  REAL :: rhotres    ! treshold concentration of h2so4 (1/cm^3)
+  REAL :: prh,rh    !saturation ratio of water (0.0001-1)
+  REAL,INTENT(IN) :: rhoa_in    !sulfuric acid concentration in 1/cm3 (10^4-10^11 1/cm3)
+  REAL,INTENT(OUT) :: jnuc    !nucleation rate in 1/cm3s (10^-7-10^10 1/cm3s)
+  REAL,INTENT(OUT) :: ntot !total number of molecules in the critical cluster (ntot>4)
+  REAL,INTENT(OUT) :: x    ! mole fraction of H2SO4 in the critical cluster       
+  REAL,INTENT(OUT) :: rc    !radius of the critical cluster in nm     
+  REAL :: rhotres    ! threshold concentration of h2so4 (1/cm^3)
                      ! which produces nucleation rate   1/(cm^3 s) as a function of rh and t 
   REAL rhoa
 
-! CK: use intermediate variables to avoid overwriting
+! CK: use intermediate variable to avoid overwriting
   t=pt
   rh=prh
@@ -178,86 +200,86 @@
   ENDIF
 
-  x=  0.7409967177282139 - 0.002663785665140117*t + 0.002010478847383187*Log(rh)  &
-       & - 0.0001832894131464668*t*Log(rh) + 0.001574072538464286*Log(rh)**2      &
-       & - 0.00001790589121766952*t*Log(rh)**2 + 0.0001844027436573778*Log(rh)**3 & 
-       & -  1.503452308794887e-6*t*Log(rh)**3 - 0.003499978417957668*Log(rhoa)    &
-       & + 0.0000504021689382576*t*Log(rhoa)
+  x=  0.7409967177282139 - 0.002663785665140117*t + 0.002010478847383187*LOG(rh)  &
+       & - 0.0001832894131464668*t*LOG(rh) + 0.001574072538464286*LOG(rh)**2      &
+       & - 0.00001790589121766952*t*LOG(rh)**2 + 0.0001844027436573778*LOG(rh)**3 &
+       & -  1.503452308794887E-6*t*LOG(rh)**3 - 0.003499978417957668*LOG(rhoa)    &
+       & + 0.0000504021689382576*t*LOG(rhoa)
 
   jnuc= 0.1430901615568665 + 2.219563673425199*t - 0.02739106114964264*t**2 +  &
        &  0.00007228107239317088*t**3 + 5.91822263375044/x +                   &
-       &  0.1174886643003278*Log(rh) + 0.4625315047693772*t*Log(rh) -          &
-       &  0.01180591129059253*t**2*Log(rh) +                                   &
-       &  0.0000404196487152575*t**3*Log(rh) + (15.79628615047088*Log(rh))/x - &
-       &  0.215553951893509*Log(rh)**2 - 0.0810269192332194*t*Log(rh)**2 +     &
-       &  0.001435808434184642*t**2*Log(rh)**2 -                               &
-       &  4.775796947178588e-6*t**3*Log(rh)**2 -                               &
-       &  (2.912974063702185*Log(rh)**2)/x - 3.588557942822751*Log(rh)**3 +    &
-       &  0.04950795302831703*t*Log(rh)**3 -                                   &
-       &  0.0002138195118737068*t**2*Log(rh)**3 +                              &
-       &  3.108005107949533e-7*t**3*Log(rh)**3 -                               &
-       &  (0.02933332747098296*Log(rh)**3)/x +                                 &
-       &  1.145983818561277*Log(rhoa) -                                        &
-       &  0.6007956227856778*t*Log(rhoa) +                                     &
-       &  0.00864244733283759*t**2*Log(rhoa) -                                 &
-       &  0.00002289467254710888*t**3*Log(rhoa) -                              &
-       &  (8.44984513869014*Log(rhoa))/x +                                     &
-       &  2.158548369286559*Log(rh)*Log(rhoa) +                                &
-       &  0.0808121412840917*t*Log(rh)*Log(rhoa) -                             &
-       &  0.0004073815255395214*t**2*Log(rh)*Log(rhoa) -                       &
-       &  4.019572560156515e-7*t**3*Log(rh)*Log(rhoa) +                        &
-       &  (0.7213255852557236*Log(rh)*Log(rhoa))/x +                           &
-       &  1.62409850488771*Log(rh)**2*Log(rhoa) -                              &
-       &  0.01601062035325362*t*Log(rh)**2*Log(rhoa) +                         &
-       &  0.00003771238979714162*t**2*Log(rh)**2*Log(rhoa) +                   &
-       &  3.217942606371182e-8*t**3*Log(rh)**2*Log(rhoa) -                     &
-       &  (0.01132550810022116*Log(rh)**2*Log(rhoa))/x +                       &
-       &  9.71681713056504*Log(rhoa)**2 -                                      &
-       &  0.1150478558347306*t*Log(rhoa)**2 +                                  &
-       &  0.0001570982486038294*t**2*Log(rhoa)**2 +                            &
-       &  4.009144680125015e-7*t**3*Log(rhoa)**2 +                             &
-       &  (0.7118597859976135*Log(rhoa)**2)/x -                                &
-       &  1.056105824379897*Log(rh)*Log(rhoa)**2 +                             &
-       &  0.00903377584628419*t*Log(rh)*Log(rhoa)**2 -                         &
-       &  0.00001984167387090606*t**2*Log(rh)*Log(rhoa)**2 +                   &
-       &  2.460478196482179e-8*t**3*Log(rh)*Log(rhoa)**2 -                     &
-       &  (0.05790872906645181*Log(rh)*Log(rhoa)**2)/x -                       &
-       &  0.1487119673397459*Log(rhoa)**3 +                                    &
-       &  0.002835082097822667*t*Log(rhoa)**3 -                                &
-       &  9.24618825471694e-6*t**2*Log(rhoa)**3 +                              &
-       &  5.004267665960894e-9*t**3*Log(rhoa)**3 -                             &
-       &  (0.01270805101481648*Log(rhoa)**3)/x
-  jnuc=exp(jnuc) !1/(cm3s)
-
-  ntot =-0.002954125078716302 - 0.0976834264241286*t + 0.001024847927067835*t**2 - 2.186459697726116e-6*t**3 -    &
-       &   0.1017165718716887/x - 0.002050640345231486*Log(rh) - 0.007585041382707174*t*Log(rh) +                 &
-       &   0.0001926539658089536*t**2*Log(rh) - 6.70429719683894e-7*t**3*Log(rh) -                                &
-       &   (0.2557744774673163*Log(rh))/x + 0.003223076552477191*Log(rh)**2 + 0.000852636632240633*t*Log(rh)**2 - &
-       &   0.00001547571354871789*t**2*Log(rh)**2 + 5.666608424980593e-8*t**3*Log(rh)**2 +                        &
-       &   (0.03384437400744206*Log(rh)**2)/x + 0.04743226764572505*Log(rh)**3 -                                  &
-       &   0.0006251042204583412*t*Log(rh)**3 + 2.650663328519478e-6*t**2*Log(rh)**3 -                            &
-       &   3.674710848763778e-9*t**3*Log(rh)**3 - (0.0002672510825259393*Log(rh)**3)/x -                          &
-       &   0.01252108546759328*Log(rhoa) + 0.005806550506277202*t*Log(rhoa) -                                     &
-       &   0.0001016735312443444*t**2*Log(rhoa) + 2.881946187214505e-7*t**3*Log(rhoa) +                           &
-       &   (0.0942243379396279*Log(rhoa))/x - 0.0385459592773097*Log(rh)*Log(rhoa) -                              &
-       &   0.0006723156277391984*t*Log(rh)*Log(rhoa) + 2.602884877659698e-6*t**2*Log(rh)*Log(rhoa) +              &
-       &   1.194163699688297e-8*t**3*Log(rh)*Log(rhoa) - (0.00851515345806281*Log(rh)*Log(rhoa))/x -              &
-       &   0.01837488495738111*Log(rh)**2*Log(rhoa) + 0.0001720723574407498*t*Log(rh)**2*Log(rhoa) -              &
-       &   3.717657974086814e-7*t**2*Log(rh)**2*Log(rhoa) -                                                       &
-       &   5.148746022615196e-10*t**3*Log(rh)**2*Log(rhoa) +                                                      &
-       &   (0.0002686602132926594*Log(rh)**2*Log(rhoa))/x - 0.06199739728812199*Log(rhoa)**2 +                    &
-       &   0.000906958053583576*t*Log(rhoa)**2 - 9.11727926129757e-7*t**2*Log(rhoa)**2 -                          &
-       &   5.367963396508457e-9*t**3*Log(rhoa)**2 - (0.007742343393937707*Log(rhoa)**2)/x +                       &
-       &   0.0121827103101659*Log(rh)*Log(rhoa)**2 - 0.0001066499571188091*t*Log(rh)*Log(rhoa)**2 +               &
-       &   2.534598655067518e-7*t**2*Log(rh)*Log(rhoa)**2 -                                                       &
-       &   3.635186504599571e-10*t**3*Log(rh)*Log(rhoa)**2 +                                                      &
-       &   (0.0006100650851863252*Log(rh)*Log(rhoa)**2)/x + 0.0003201836700403512*Log(rhoa)**3 -                  &
-       &   0.0000174761713262546*t*Log(rhoa)**3 + 6.065037668052182e-8*t**2*Log(rhoa)**3 -                        &
-       &   1.421771723004557e-11*t**3*Log(rhoa)**3 + (0.0001357509859501723*Log(rhoa)**3)/x
-  ntot=exp(ntot)
-
-  rc=exp(-1.6524245+0.42316402*x+0.33466487*log(ntot)) !nm
-
-  IF (jnuc < 1.e-7) THEN
-!     print *,'Warning (ilon=',ilon,'ilev=',ilev'): nucleation rate < 1e-7/cm3s, using 0.0/cm3s,'
+       &  0.1174886643003278*LOG(rh) + 0.4625315047693772*t*LOG(rh) -          &
+       &  0.01180591129059253*t**2*LOG(rh) +                                   &
+       &  0.0000404196487152575*t**3*LOG(rh) + (15.79628615047088*LOG(rh))/x - &
+       &  0.215553951893509*LOG(rh)**2 - 0.0810269192332194*t*LOG(rh)**2 +     &
+       &  0.001435808434184642*t**2*LOG(rh)**2 -                               &
+       &  4.775796947178588E-6*t**3*LOG(rh)**2 -                               &
+       &  (2.912974063702185*LOG(rh)**2)/x - 3.588557942822751*LOG(rh)**3 +    &
+       &  0.04950795302831703*t*LOG(rh)**3 -                                   &
+       &  0.0002138195118737068*t**2*LOG(rh)**3 +                              &
+       &  3.108005107949533E-7*t**3*LOG(rh)**3 -                               &
+       &  (0.02933332747098296*LOG(rh)**3)/x +                                 &
+       &  1.145983818561277*LOG(rhoa) -                                        &
+       &  0.6007956227856778*t*LOG(rhoa) +                                     &
+       &  0.00864244733283759*t**2*LOG(rhoa) -                                 &
+       &  0.00002289467254710888*t**3*LOG(rhoa) -                              &
+       &  (8.44984513869014*LOG(rhoa))/x +                                     &
+       &  2.158548369286559*LOG(rh)*LOG(rhoa) +                                &
+       &  0.0808121412840917*t*LOG(rh)*LOG(rhoa) -                             &
+       &  0.0004073815255395214*t**2*LOG(rh)*LOG(rhoa) -                       &
+       &  4.019572560156515E-7*t**3*LOG(rh)*LOG(rhoa) +                        &
+       &  (0.7213255852557236*LOG(rh)*LOG(rhoa))/x +                           &
+       &  1.62409850488771*LOG(rh)**2*LOG(rhoa) -                              &
+       &  0.01601062035325362*t*LOG(rh)**2*LOG(rhoa) +                         &
+       &  0.00003771238979714162*t**2*LOG(rh)**2*LOG(rhoa) +                   &
+       &  3.217942606371182E-8*t**3*LOG(rh)**2*LOG(rhoa) -                     &
+       &  (0.01132550810022116*LOG(rh)**2*LOG(rhoa))/x +                       &
+       &  9.71681713056504*LOG(rhoa)**2 -                                      &
+       &  0.1150478558347306*t*LOG(rhoa)**2 +                                  &
+       &  0.0001570982486038294*t**2*LOG(rhoa)**2 +                            &
+       &  4.009144680125015E-7*t**3*LOG(rhoa)**2 +                             &
+       &  (0.7118597859976135*LOG(rhoa)**2)/x -                                &
+       &  1.056105824379897*LOG(rh)*LOG(rhoa)**2 +                             &
+       &  0.00903377584628419*t*LOG(rh)*LOG(rhoa)**2 -                         &
+       &  0.00001984167387090606*t**2*LOG(rh)*LOG(rhoa)**2 +                   &
+       &  2.460478196482179E-8*t**3*LOG(rh)*LOG(rhoa)**2 -                     &
+       &  (0.05790872906645181*LOG(rh)*LOG(rhoa)**2)/x -                       &
+       &  0.1487119673397459*LOG(rhoa)**3 +                                    &
+       &  0.002835082097822667*t*LOG(rhoa)**3 -                                &
+       &  9.24618825471694E-6*t**2*LOG(rhoa)**3 +                              &
+       &  5.004267665960894E-9*t**3*LOG(rhoa)**3 -                             &
+       &  (0.01270805101481648*LOG(rhoa)**3)/x
+  jnuc=EXP(jnuc) !1/(cm3s)
+
+  ntot =-0.002954125078716302 - 0.0976834264241286*t + 0.001024847927067835*t**2 - 2.186459697726116E-6*t**3 -    &
+       &   0.1017165718716887/x - 0.002050640345231486*LOG(rh) - 0.007585041382707174*t*LOG(rh) +                 &
+       &   0.0001926539658089536*t**2*LOG(rh) - 6.70429719683894E-7*t**3*LOG(rh) -                                &
+       &   (0.2557744774673163*LOG(rh))/x + 0.003223076552477191*LOG(rh)**2 + 0.000852636632240633*t*LOG(rh)**2 - &
+       &   0.00001547571354871789*t**2*LOG(rh)**2 + 5.666608424980593E-8*t**3*LOG(rh)**2 +                        &
+       &   (0.03384437400744206*LOG(rh)**2)/x + 0.04743226764572505*LOG(rh)**3 -                                  &
+       &   0.0006251042204583412*t*LOG(rh)**3 + 2.650663328519478E-6*t**2*LOG(rh)**3 -                            &
+       &   3.674710848763778E-9*t**3*LOG(rh)**3 - (0.0002672510825259393*LOG(rh)**3)/x -                          &
+       &   0.01252108546759328*LOG(rhoa) + 0.005806550506277202*t*LOG(rhoa) -                                     &
+       &   0.0001016735312443444*t**2*LOG(rhoa) + 2.881946187214505E-7*t**3*LOG(rhoa) +                           &
+       &   (0.0942243379396279*LOG(rhoa))/x - 0.0385459592773097*LOG(rh)*LOG(rhoa) -                              &
+       &   0.0006723156277391984*t*LOG(rh)*LOG(rhoa) + 2.602884877659698E-6*t**2*LOG(rh)*LOG(rhoa) +              &
+       &   1.194163699688297E-8*t**3*LOG(rh)*LOG(rhoa) - (0.00851515345806281*LOG(rh)*LOG(rhoa))/x -              &
+       &   0.01837488495738111*LOG(rh)**2*LOG(rhoa) + 0.0001720723574407498*t*LOG(rh)**2*LOG(rhoa) -              &
+       &   3.717657974086814E-7*t**2*LOG(rh)**2*LOG(rhoa) -                                                       &
+       &   5.148746022615196E-10*t**3*LOG(rh)**2*LOG(rhoa) +                                                      &
+       &   (0.0002686602132926594*LOG(rh)**2*LOG(rhoa))/x - 0.06199739728812199*LOG(rhoa)**2 +                    &
+       &   0.000906958053583576*t*LOG(rhoa)**2 - 9.11727926129757E-7*t**2*LOG(rhoa)**2 -                          &
+       &   5.367963396508457E-9*t**3*LOG(rhoa)**2 - (0.007742343393937707*LOG(rhoa)**2)/x +                       &
+       &   0.0121827103101659*LOG(rh)*LOG(rhoa)**2 - 0.0001066499571188091*t*LOG(rh)*LOG(rhoa)**2 +               &
+       &   2.534598655067518E-7*t**2*LOG(rh)*LOG(rhoa)**2 -                                                       &
+       &   3.635186504599571E-10*t**3*LOG(rh)*LOG(rhoa)**2 +                                                      &
+       &   (0.0006100650851863252*LOG(rh)*LOG(rhoa)**2)/x + 0.0003201836700403512*LOG(rhoa)**3 -                  &
+       &   0.0000174761713262546*t*LOG(rhoa)**3 + 6.065037668052182E-8*t**2*LOG(rhoa)**3 -                        &
+       &   1.421771723004557E-11*t**3*LOG(rhoa)**3 + (0.0001357509859501723*LOG(rhoa)**3)/x
+  ntot=EXP(ntot)
+
+  rc=EXP(-1.6524245+0.42316402*x+0.33466487*LOG(ntot)) !nm
+
+  IF (jnuc < 1.E-7) THEN
+!     print *,'Warning (ilon=',ilon,'ilev=',ilev'): nucleation rate < 1E-7/cm3s, using 0.0/cm3s,'
      jnuc=0.0
   ENDIF
@@ -269,9 +291,9 @@
   ENDIF
 
-  rhotres=exp( -279.2430007512709 + 11.73439886096903*rh + 22700.92970508331/t &
+  rhotres=EXP( -279.2430007512709 + 11.73439886096903*rh + 22700.92970508331/t &
        & - (1088.644983466801*rh)/t + 1.144362942094912*t                      &
        & - 0.03023314602163684*rh*t - 0.001302541390154324*t**2                &
-       & - 6.386965238433532*Log(rh) + (854.980361026715*Log(rh))/t            &
-       & + 0.00879662256826497*t*Log(rh)) !1/cm3
+       & - 6.386965238433532*LOG(rh) + (854.980361026715*LOG(rh))/t            &
+       & + 0.00879662256826497*t*LOG(rh)) !1/cm3
 
   RETURN
@@ -279,3 +301,560 @@
 END SUBROUTINE binapara
 
+!---------------------------------------------------------------------------------------------------
+
+SUBROUTINE newbinapara(t,satrat,rhoa,csi,airn,ipr,jnuc_n_real,ntot_n_real,jnuc_i_real,ntot_i_real,        &
+                   &   x_n_real,x_i_real,na_n_real,na_i_real,rc_n_real,rc_i_real,n_i_real,                & 
+                   &   kinetic_n,kinetic_i,rhoatres_real)
+
+  !    Fortran 90 subroutine newbinapara
+  !
+  !    Calculates parametrized values for neutral and ion-induced sulfuric acid-water particle formation rate
+  !    of critical clusters, 
+  !    number of particle in the critical clusters, the radii of the critical clusters
+  !    in H2O-H2SO4-ion system if temperature, saturation ratio of water, sulfuric acid concentration, 
+  !    and, optionally, either condensation sink due to pre-existing particle and ion pair production rate,
+  !    or atmospheric concentration of negative ions are given. 
+  !
+  !    The code calculates also the kinetic limit and the particle formation rate
+  !    above this limit (in which case we set ntot=1 and na=1)
+  !
+  !    Copyright (C)2018 Määttänen et al. 2018
+  !    
+  !    anni.maattanen@latmos.ipsl.fr
+  !    joonas.merikanto@fmi.fi
+  !    hanna.vehkamaki@helsinki.fi
+  !
+  !    References
+  !    A. Määttänen, J. Merikanto, H. Henschel, J. Duplissy, R. Makkonen, 
+  !    I. K. Ortega and H. Vehkamäki (2018), New parameterizations for 
+  !    neutral and ion-induced sulfuric acid-water particle formation in 
+  !    nucleation and kinetic regimes, J. Geophys. Res. Atmos., 122, doi:10.1002/2017JD027429.
+  !
+  !    Brasseur, G., and A.  Chatel (1983),  paper  presented  at  the  9th  Annual  Meeting  of  the  
+  !    European Geophysical Society, Leeds, Great Britain, August 1982.
+  !  
+  !    Dunne, Eimear M., et al.(2016), Global atmospheric particle formation from CERN CLOUD measurements,
+  !    Science 354.6316, 1119-1124.   
+  !
+
+  USE aerophys
+  USE YOMCST, ONLY : RPI, RKBOL
+
+  IMPLICIT NONE 
+
+  !----------------------------------------------------
+  
+  !Global intent in
+  REAL,INTENT(IN) :: t         ! temperature in K 
+  REAL,INTENT(IN) :: satrat    ! saturatio ratio of water (between zero and 1)
+  REAL,INTENT(IN) :: rhoa      ! sulfuric acid concentration in 1/cm3
+  REAL,INTENT(IN) :: csi       ! Ion condensation sink (s-1)
+  REAL,INTENT(IN) :: airn      ! Air molecule concentration in (cm-3)
+  REAL,INTENT(IN) :: ipr       ! Ion pair production rate (cm-3 s-1)
+  !Global intent out
+  REAL,INTENT(OUT) :: jnuc_n_real   ! Neutral nucleation rate in 1/cm3s (J>10^-7 1/cm3s)
+  REAL,INTENT(OUT) :: ntot_n_real   ! total number of molecules in the neutral critical cluster
+  REAL,INTENT(OUT) :: jnuc_i_real   ! Charged nucleation rate in 1/cm3s (J>10^-7 1/cm3s)
+  REAL,INTENT(OUT) :: ntot_i_real   ! total number of molecules in the charged critical cluster
+  REAL,INTENT(OUT) :: x_n_real      ! mole fraction of H2SO4 in the neutral critical cluster 
+  REAL,INTENT(OUT) :: x_i_real      ! mole fraction of H2SO4 in the charged critical cluster 
+                                           ! (note that x_n=x_i in nucleation regime) 
+  REAL,INTENT(OUT) :: na_n_real     ! sulfuric acid molecules in the neutral critical cluster
+  REAL,INTENT(OUT) :: na_i_real     ! sulfuric molecules in the charged critical cluster
+  REAL,INTENT(OUT) :: rc_n_real     ! radius of the charged critical cluster in nm 
+  REAL,INTENT(OUT) :: rc_i_real     ! radius of the charged critical cluster in nm 
+  REAL,INTENT(OUT) :: n_i_real      ! number of ion pairs in air (cm-3) 
+  REAL,INTENT(OUT) :: rhoatres_real ! threshold concentration of H2SO4 (1/cm^3) for neutral kinetic nucleation
+  LOGICAL,INTENT(OUT)  :: kinetic_n        ! true if kinetic neutral nucleation
+  LOGICAL,INTENT(OUT)  :: kinetic_i        ! true if kinetic ion-induced nucleation
+
+  ! Local
+  DOUBLE PRECISION :: jnuc_n      ! Neutral nucleation rate in 1/cm3s (J>10^-7 1/cm3s)
+  DOUBLE PRECISION :: ntot_n      ! total number of molecules in the neutral critical cluster
+  DOUBLE PRECISION :: jnuc_i      ! Charged nucleation rate in 1/cm3s (J>10^-7 1/cm3s)
+  DOUBLE PRECISION :: ntot_i      ! total number of molecules in the charged critical cluster
+  DOUBLE PRECISION :: x_n         ! mole fraction of H2SO4 in the neutral critical cluster 
+  DOUBLE PRECISION :: x_i         ! mole fraction of H2SO4 in the charged critical cluster 
+                                              ! (note that x_n=x_i in nucleation regime) 
+  DOUBLE PRECISION :: na_n        ! sulfuric acid molecules in the neutral critical cluster
+  DOUBLE PRECISION :: na_i        ! sulfuric molecules in the charged critical cluster
+  DOUBLE PRECISION :: rc_n        ! radius of the charged critical cluster in nm 
+  DOUBLE PRECISION :: rc_i        ! radius of the charged critical cluster in nm 
+  DOUBLE PRECISION :: n_i         ! number of ion pairs in air (cm-3) 
+  DOUBLE PRECISION :: rhoatres    ! threshold concentration of H2SO4 (1/cm^3) for neutral kinetic nucleation
+  DOUBLE PRECISION :: x           ! mole fraction of H2SO4 in the critical cluster 
+  DOUBLE PRECISION :: satratln    ! bounded water saturation ratio for neutral case (between 5.E-6 - 1.0)
+  DOUBLE PRECISION :: satratli    ! bounded water saturation ratio for ion-induced case (between 1.E-7 - 0.95)
+  DOUBLE PRECISION :: rhoaln      ! bounded concentration of h2so4 for neutral case (between 10^10 - 10^19 m-3)
+  DOUBLE PRECISION :: rhoali      ! bounded concentration of h2so4 for ion-induced case (between 10^10 - 10^22 m-3)
+  DOUBLE PRECISION :: tln         ! bounded temperature for neutral case (between 165-400 K)
+  DOUBLE PRECISION :: tli         ! bounded temperature for ion-induced case (195-400 K)
+  DOUBLE PRECISION :: kinrhotresn ! threshold sulfuric acid for neutral kinetic nucleation   
+  DOUBLE PRECISION :: kinrhotresi ! threshold sulfuric acid for ion-induced kinetic nucleation 
+  DOUBLE PRECISION :: jnuc_i1     ! Ion-induced rate for n_i=1 cm-3 
+  DOUBLE PRECISION :: xloss       ! Ion loss rate 
+  DOUBLE PRECISION :: recomb      ! Ion-ion recombination rate 
+
+  !--- 0) Initializations:
+
+  kinetic_n=.FALSE.
+  kinetic_i=.FALSE.
+  jnuc_n=0.0
+  jnuc_i=0.0
+  ntot_n=0.0
+  ntot_i=0.0
+  na_n=0.0
+  na_i=0.0
+  rc_n=0.0
+  rc_i=0.0
+  x=0.0
+  x_n=0.0
+  x_i=0.0
+  satratln=satrat
+  satratli=satrat
+  rhoaln=rhoa
+  rhoali=rhoa
+  tln=t
+  tli=t
+  n_i=0.0
+
+  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+  !Boundary values according to parameterization limits   
+
+  !Temperature bounds
+  IF (t.LE.165.) THEN
+!     print *,'Warning: temperature < 165.0 K, using 165.0 K in neutral nucleation calculation'
+     tln=165.0
+  ENDIF
+  IF (t.LE.195.) THEN
+!     print *,'Warning: temperature < 195.0 K, using 195.0 K in ion-induced nucleation calculation'
+     tli=195.0
+  ENDIF
+  IF (t.GE.400.) THEN
+!     print *,'Warning: temperature > 400. K, using 400. K in nucleation calculations'
+     tln=400.
+     tli=400.
+  ENDIF
+  
+  ! Saturation ratio bounds
+  IF (satrat.LT.1.E-7) THEN
+!     print *,'Warning: saturation ratio of water < 1.E-7, using 1.E-7 in ion-induced nucleation calculation'
+     satratli=1.E-7
+  ENDIF
+  IF (satrat.LT.1.E-5) THEN
+!     print *,'Warning: saturation ratio of water < 1.E-5, using 1.E-5 in neutral nucleation calculation'
+     satratln=1.E-5
+  ENDIF
+  IF (satrat.GT.0.95) THEN
+!     print *,'Warning: saturation ratio of water > 0.95, using 0.95 in ion-induced nucleation calculation'
+     satratli=0.95
+  ENDIF
+  IF (satrat.GT.1.0) THEN
+!     print *,'Warning: saturation ratio of water > 1 using 1 in neutral nucleation calculation'
+     satratln=1.0
+  ENDIF
+  
+  ! Sulfuric acid concentration bounds
+  IF (rhoa.LE.1.E4) THEN
+!     print *,'Warning: sulfuric acid < 1e4 1/cm3, using 1e4 1/cm3 in nucleation calculation'
+     rhoaln=1.E4
+     rhoali=1.E4
+  ENDIF
+  IF (rhoa.GT.1.E13) THEN
+!     print *,'Warning: sulfuric acid > 1e13 1/cm3, using 1e13 1/cm3 in neutral nucleation calculation'
+     rhoaln=1.E13
+  ENDIF
+  IF (rhoa.GT.1.E16) THEN
+!     print *,'Warning: sulfuric acid concentration > 1e16 1/cm3, using 1e16 1/cm3 in ion-induced nucleation calculation'
+     rhoali=1.E16
+  ENDIF
+  
+  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+  
+  !Critical cluster composition (valid for both cases, bounds not used here) 
+  x_n=  7.9036365428891719E-1 - 2.8414059650092153E-3*tln + 1.4976802556584141E-2*LOG(satratln)  &
+       & - 2.4511581740839115E-4*tln*LOG(satratln) + 3.4319869471066424E-3 *LOG(satratln)**2     &
+       & - 2.8799393617748428E-5*tln*LOG(satratln)**2 + 3.0174314126331765E-4*LOG(satratln)**3   &
+       & - 2.2673492408841294E-6*tln*LOG(satratln)**3 - 4.3948464567032377E-3*LOG(rhoaln)        &
+       & + 5.3305314722492146E-5*tln*LOG(rhoaln)
+  x_i=  7.9036365428891719E-1 - 2.8414059650092153E-3*tli + 1.4976802556584141E-2*LOG(satratli)  &
+       & - 2.4511581740839115E-4*tli*LOG(satratli) + 3.4319869471066424E-3 *LOG(satratli)**2     &
+       & - 2.8799393617748428E-5*tli*LOG(satratli)**2 + 3.0174314126331765E-4*LOG(satratli)**3   &
+       & - 2.2673492408841294E-6*tli*LOG(satratli)**3 - 4.3948464567032377E-3*LOG(rhoali)        &
+       & + 5.3305314722492146E-5*tli*LOG(rhoali)
+       
+  x_n=MIN(MAX(x_n,1.E-30),1.) 
+  x_i=MIN(MAX(x_i,1.E-30),1.) 
+  
+  !Neutral nucleation
+  
+  !Kinetic limit check
+  IF (satratln .GE. 1.E-2 .AND. satratln .LE. 1.) THEN
+     kinrhotresn=EXP(7.8920778706888086E+1 + 7.3665492897447082*satratln - 1.2420166571163805E+4/tln &
+          & + (-6.1831234251470971E+2*satratln)/tln - 2.4501159970109945E-2*tln                      &
+          & -1.3463066443605762E-2*satratln*tln + 8.3736373989909194E-06*tln**2                      &
+          & -1.4673887785408892*LOG(satratln) + (-3.2141890006517094E+1*LOG(satratln))/tln           &
+          & + 2.7137429081917556E-3*tln*LOG(satratln)) !1/cm3     
+     IF (kinrhotresn.LT.rhoaln) kinetic_n=.TRUE.
+  ENDIF
+
+  IF (satratln .GE. 1.E-4  .AND. satratln .LT. 1.E-2) THEN     
+     kinrhotresn=EXP(7.9074383049843647E+1 - 2.8746005462158347E+1*satratln - 1.2070272068458380E+4/tln &
+          & + (-5.9205040320056632E+3*satratln)/tln - 2.4800372593452726E-2*tln                         &
+          & -4.3983007681295948E-2*satratln*tln + 2.5943854791342071E-5*tln**2                          &
+          & -2.3141363245211317*LOG(satratln) + (9.9186787997857735E+1*LOG(satratln))/tln               &
+          & + 5.6819382556144681E-3*tln*LOG(satratln)) !1/cm3
+     IF (kinrhotresn.LT.rhoaln) kinetic_n=.TRUE.
+  ENDIF
+
+  IF (satratln .GE. 5.E-6  .AND. satratln .LT. 1.E-4) THEN
+     kinrhotresn=EXP(8.5599712000361677E+1 + 2.7335119660796581E+3*satratln - 1.1842350246291651E+4/tln &
+          & + (-1.2439843468881438E+6*satratln)/tln - 5.4536964974944230E-2*tln                         &
+          & + 5.0886987425326087*satratln*tln + 7.1964722655507067E-5*tln**2                            &
+          & -2.4472627526306372*LOG(satratln) + (1.7561478001423779E+2*LOG(satratln))/tln               &
+          & + 6.2640132818141811E-3*tln*LOG(satratln)) !1/cm3
+     IF (kinrhotresn.LT.rhoaln) kinetic_n=.TRUE. 
+  ENDIF
+  
+  IF (kinetic_n) THEN    
+     ! Dimer formation rate
+     jnuc_n=1.E6*(2.*0.3E-9)**2.*SQRT(8.*RPI*RKBOL*(1./mH2SO4mol+1./mH2SO4mol))/2.*SQRT(t)*rhoa**2.
+!     jnuc_n=1.E6*(2.*0.3E-9)**2.*SQRT(8.*3.141593*1.38E-23*(1./(1.661E-27*98.07)+1./(1.661E-27*98.07)))/2.*SQRT(t)*rhoa**2.
+     ntot_n=1. !set to 1 
+     na_n=1.   ! The critical cluster contains one molecules but the produced cluster contains 2 molecules
+     x_n=na_n/ntot_n  ! so also set this to 1
+     rc_n=0.3E-9
+  ELSE
+     jnuc_n= 2.1361182605986115E-1 + 3.3827029855551838*tln -3.2423555796175563E-2*tln**2 +         &
+          &  7.0120069477221989E-5*tln**3 +8.0286874752695141/x_n +                                 &
+          &  -2.6939840579762231E-1*LOG(satratln) +1.6079879299099518*tln*LOG(satratln) +           &
+          &  -1.9667486968141933E-2*tln**2*LOG(satratln) +                                          &
+          &  5.5244755979770844E-5*tln**3*LOG(satratln) + (7.8884704837892468*LOG(satratln))/x_n +  &
+          &  4.6374659198909596*LOG(satratln)**2 - 8.2002809894792153E-2*tln*LOG(satratln)**2 +     &
+          &  8.5077424451172196E-4*tln**2*LOG(satratln)**2 +                                        &
+          &  -2.6518510168987462E-6*tln**3*LOG(satratln)**2 +                                       &
+          &  (-1.4625482500575278*LOG(satratln)**2)/x_n - 5.2413002989192037E-1*LOG(satratln)**3 +  &
+          &  5.2755117653715865E-3*tln*LOG(satratln)**3 +                                           &
+          &  -2.9491061332113830E-6*tln**2*LOG(satratln)**3 +                                       &
+          &  -2.4815454194486752E-8*tln**3*LOG(satratln)**3 +                                       &
+          &  (-5.2663760117394626E-2*LOG(satratln)**3)/x_n +                                        &
+          &  1.6496664658266762*LOG(rhoaln) +                                                       &
+          &  -8.0809397859218401E-1*tln*LOG(rhoaln) +                                               &
+          &  8.9302927091946642E-3*tln**2*LOG(rhoaln) +                                             &
+          &  -1.9583649496497497E-5*tln**3*LOG(rhoaln) +                                            &
+          &  (-8.9505572676891685*LOG(rhoaln))/x_n +                                                &
+          &  -3.0025283601622881E+1*LOG(satratln)*LOG(rhoaln) +                                     &
+          &  3.0783365644763633E-1*tln*LOG(satratln)*LOG(rhoaln) +                                  &
+          &  -7.4521756337984706E-4*tln**2*LOG(satratln)*LOG(rhoaln) +                              &
+          &  -5.7651433870681853E-7*tln**3*LOG(satratln)*LOG(rhoaln) +                              &
+          &  (1.2872868529673207*LOG(satratln)*LOG(rhoaln))/x_n +                                   &
+          &  -6.1739867501526535E-1*LOG(satratln)**2*LOG(rhoaln) +                                  &
+          &  7.2347385705333975E-3*tln*LOG(satratln)**2*LOG(rhoaln) +                               &
+          &  -3.0640494530822439E-5*tln**2*LOG(satratln)**2*LOG(rhoaln) +                           &
+          &  6.5944609194346214E-8*tln**3*LOG(satratln)**2*LOG(rhoaln) +                            &
+          &  (-2.8681650332461055E-2*LOG(satratln)**2*LOG(rhoaln))/x_n +                            &
+          &  6.5213802375160306*LOG(rhoaln)**2 +                                                    &
+          &  -4.7907162004793016E-2*tln*LOG(rhoaln)**2 +                                            &
+          &  -1.0727890114215117E-4*tln**2*LOG(rhoaln)**2 +                                         &
+          &  5.6401818280534507E-7*tln**3*LOG(rhoaln)**2 +                                          &
+          &  (5.4113070888923009E-1*LOG(rhoaln)**2)/x_n +                                           &
+          &  5.2062808476476330E-1*LOG(satratln)*LOG(rhoaln)**2 +                                   &
+          &  -6.0696882500824584E-3*tln*LOG(satratln)*LOG(rhoaln)**2 +                              &
+          &  2.3851383302608477E-5*tln**2*LOG(satratln)*LOG(rhoaln)**2 +                            &
+          &  -1.5243837103067096E-8*tln**3*LOG(satratln)*LOG(rhoaln)**2 +                           &
+          &  (-5.6543192378015687E-2*LOG(satratln)*LOG(rhoaln)**2)/x_n +                            &
+          &  -1.1630806410696815E-1*LOG(rhoaln)**3 +                                                &
+          &  1.3806404273119610E-3*tln*LOG(rhoaln)**3 +                                             &
+          &  -2.0199865087650833E-6*tln**2*LOG(rhoaln)**3 +                                         &
+          &  -3.0200284885763192E-9*tln**3*LOG(rhoaln)**3 +                                         &
+          &  (-6.9425267104126316E-3*LOG(rhoaln)**3)/x_n
+     jnuc_n=EXP(jnuc_n) 
+     
+     ntot_n =-3.5863435141979573E-3 - 1.0098670235841110E-1*tln + 8.9741268319259721E-4*tln**2 - 1.4855098605195757E-6*tln**3 &
+          &   - 1.2080330016937095E-1/x_n + 1.1902674923928015E-3*LOG(satratln) - 1.9211358507172177E-2*tln*LOG(satratln) +   &
+          &   2.4648094311204255E-4*tln**2*LOG(satratln) - 7.5641448594711666E-7*tln**3*LOG(satratln) +                       &
+          &   (-2.0668639384228818E-02*LOG(satratln))/x_n - 3.7593072011595188E-2*LOG(satratln)**2 +                          &
+          &   9.0993182774415718E-4 *tln*LOG(satratln)**2 +                                                                   &
+          &   -9.5698412164297149E-6*tln**2*LOG(satratln)**2 + 3.7163166416110421E-8*tln**3*LOG(satratln)**2 +                &
+          &   (1.1026579525210847E-2*LOG(satratln)**2)/x_n + 1.1530844115561925E-2 *LOG(satratln)**3 +                        &
+          &   - 1.8083253906466668E-4 *tln*LOG(satratln)**3 + 8.0213604053330654E-7*tln**2*LOG(satratln)**3 +                 &
+          &   -8.5797885383051337E-10*tln**3*LOG(satratln)**3 + (1.0243693899717402E-3*LOG(satratln)**3)/x_n +                &
+          &   -1.7248695296299649E-2*LOG(rhoaln) + 1.1294004162437157E-2*tln*LOG(rhoaln) +                                    &
+          &   -1.2283640163189278E-4*tln**2*LOG(rhoaln) + 2.7391732258259009E-7*tln**3*LOG(rhoaln) +                          &
+          &   (6.8505583974029602E-2*LOG(rhoaln))/x_n +2.9750968179523635E-1*LOG(satratln)*LOG(rhoaln) +                      &
+          &   -3.6681154503992296E-3 *tln*LOG(satratln)*LOG(rhoaln) + 1.0636473034653114E-5*tln**2*LOG(satratln)*LOG(rhoaln)+ &
+          &   5.8687098466515866E-9*tln**3*LOG(satratln)*LOG(rhoaln) + (-5.2028866094191509E-3*LOG(satratln)*LOG(rhoaln))/x_n+&
+          &   7.6971988880587231E-4*LOG(satratln)**2*LOG(rhoaln) - 2.4605575820433763E-5*tln*LOG(satratln)**2*LOG(rhoaln) +   &
+          &   2.3818484400893008E-7*tln**2*LOG(satratln)**2*LOG(rhoaln) +                                                     &
+          &   -8.8474102392445200E-10*tln**3*LOG(satratln)**2*LOG(rhoaln) +                                                   &
+          &   (-1.6640566678168968E-4*LOG(satratln)**2*LOG(rhoaln))/x_n - 7.7390093776705471E-2*LOG(rhoaln)**2 +              &
+          &   5.8220163188828482E-4*tln*LOG(rhoaln)**2 + 1.2291679321523287E-6*tln**2*LOG(rhoaln)**2 +                        &
+          &   -7.4690997508075749E-9*tln**3*LOG(rhoaln)**2 + (-5.6357941220497648E-3*LOG(rhoaln)**2)/x_n +                    &
+          &   -4.7170109625089768E-3*LOG(satratln)*LOG(rhoaln)**2 + 6.9828868534370193E-5*tln*LOG(satratln)*LOG(rhoaln)**2 +  &
+          &   -3.1738912157036403E-7*tln**2*LOG(satratln)*LOG(rhoaln)**2 +                                                    &
+          &   2.3975538706787416E-10*tln**3*LOG(satratln)*LOG(rhoaln)**2 +                                                    &
+          &   (4.2304213386288567E-4*LOG(satratln)*LOG(rhoaln)**2)/x_n + 1.3696520973423231E-3*LOG(rhoaln)**3 +               &
+          &   -1.6863387574788199E-5*tln*LOG(rhoaln)**3 + 2.7959499278844516E-8*tln**2*LOG(rhoaln)**3 +                       &
+          &   3.9423927013227455E-11*tln**3*LOG(rhoaln)**3 + (8.6136359966337272E-5*LOG(rhoaln)**3)/x_n
+     ntot_n=EXP(ntot_n)
+     
+     rc_n=EXP(-22.378268374023630+0.44462953606125100*x_n+0.33499495707849131*LOG(ntot_n)) !in meters
+     
+     na_n=x_n*ntot_n
+     IF (na_n .LT. 1.) THEN
+        print *, 'Warning: number of acid molecules < 1 in nucleation regime, setting na_n=1'
+        na_n=1.0
+     ENDIF
+  ENDIF
+  
+  ! Set the neutral nucleation rate to 0.0 if less than 1.0E-7      
+  IF (jnuc_n.LT.1.E-7) THEN
+     jnuc_n=0.0
+  ENDIF
+  
+  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+  
+  ! Threshold neutral nucleation rate (j > 1/cm3s) parameterization (can be commented out if not needed)
+  IF (tln .GE. 310.) THEN
+     rhoatres=EXP(-2.8220714121794250 + 1.1492362322651116E+1*satratln -3.3034839106184218E+3/tln &
+          & + (-7.1828571490168133E+2*satratln)/tln + 1.4649510835204091E-1*tln                   &
+          & -3.0442736551916524E-2*satratln*tln -9.3258567137451497E-5*tln**2                     &
+          & -1.1583992506895649E+1*LOG(satratln) + (1.5184848765906165E+3*LOG(satratln))/tln      &
+          & + 1.8144983916747057E-2*tln*LOG(satratln)) !1/cm3
+  ENDIF
+
+  IF (tln .GT. 190. .AND. tln .LT. 310.) THEN
+     rhoatres=EXP(-3.1820396091231999E+2 + 7.2451289153199676*satratln + 2.6729355170089486E+4/tln &
+          & + (-7.1492506076423069E+2*satratln)/tln + 1.2617291148391978*tln                       &
+          & - 1.6438112080468487E-2*satratln*tln -1.4185518234553220E-3*tln**2                     &
+          & -9.2864597847386694*LOG(satratln) + (1.2607421852455602E+3*LOG(satratln))/tln          &
+          & + 1.3324434472218746E-2*tln*LOG(satratln)) !1/cm3
+  ENDIF
+
+  IF (tln .LT. 185. .AND. tln .GT. 155.) THEN
+     rhoatres=1.1788859232398459E+5 - 1.0244255702550814E+4*satratln +   &
+          & 4.6815029684321962E+3*satratln**2 -1.6755952338499657E+2*tln
+  ENDIF
+  
+  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+  
+  ! Ion-induced nucleation parameterization 
+ 
+  IF (ipr.GT.0.0) THEN ! if the ion production rate is above zero
+     
+     ! Calculate the ion induced nucleation rate wrt. concentration of 1 ion/cm3
+     
+     kinrhotresi = 5.3742280876674478E1  - 6.6837931590012266E-3 *LOG(satratli)**(-2)                                     &
+          & - 1.0142598385422842E-01 * LOG(satratli)**(-1) - 6.4170597272606873E+00 * LOG(satratli)                       &
+          & - 6.4315798914824518E-01 * LOG(satratli)**2 - 2.4428391714772721E-02 * LOG(satratli)**3                       &
+          & - 3.5356658734539019E-04 * LOG(satratli)**4 + 2.5400015099140506E-05 * tli * LOG(satratli)**(-2)              &
+          & - 2.7928900816637790E-04 * tli * LOG(satratli)**(-1) + 4.4108573484923690E-02 * tli * LOG(satratli)           &
+          & + 6.3943789012475532E-03 * tli * LOG(satratli)**(2) + 2.3164296174966580E-04 * tli * LOG(satratli)**(3)       &
+          & + 3.0372070669934950E-06 * tli * LOG(satratli)**4 + 3.8255873977423475E-06 * tli**2 * LOG(satratli)**(-1)     &
+          & - 1.2344793083561629E-04 * tli**2 * LOG(satratli) - 1.7959048869810192E-05 * tli**2 * LOG(satratli)**(2)      &
+          & - 3.2165622558722767E-07 * tli**2 * LOG(satratli)**3 - 4.7136923780988659E-09 * tli**3 * LOG(satratli)**(-1)  &
+          & + 1.1873317184482216E-07 * tli**3 * LOG(satratli) + 1.5685860354866621E-08 * tli**3 * LOG(satratli)**2        &
+          & - 1.4329645891059557E+04 * tli**(-1) + 1.3842599842575321E-01 * tli                                           &
+          & - 4.1376265912842938E-04 * tli**(2) + 3.9147639775826004E-07 * tli**3
+     
+     kinrhotresi=EXP(kinrhotresi) !1/cm3
+     
+     IF (kinrhotresi.LT.rhoali) kinetic_i=.true.
+     
+     IF (kinetic_i) THEN    
+!        jnuc_i1=1.0E6*(0.3E-9 + 0.487E-9)**2.*SQRT(8.*3.141593*1.38E-23*(1./(1.661E-27*98.07)+1./(1.661E-27*98.07)))*  &
+        jnuc_i1=1.0E6*(0.3E-9 + 0.487E-9)**2.*SQRT(8.*RPI*RKBOL*(1./mH2SO4mol+1./mH2SO4mol))*  &
+             &  SQRT(tli)*rhoali !1/cm3s  
+        ntot_i=1. !set to 1 
+        na_i=1.
+        x_i=na_i/ntot_i  ! so also set this to 1
+        rc_i=0.487E-9
+     ELSE
+        jnuc_i1 = 3.0108954259038608E+01+tli*6.1176722090512577E+01+(tli**2)*8.7240333618891663E-01+(tli**3)*                 &
+             & -4.6191788649375719E-03+(tli**(-1))*8.3537059107024481E-01 +                                                   &
+             & (1.5028549216690628E+01+tli*-1.9310989753720623E-01+(tli**2)*8.0155514634860480E-04+(tli**3)*                  &
+             & -1.0832730707799128E-06+(tli**(-1))*1.7577660457989019)*(LOG(satratli)**(-2)) +                                &
+             & (-2.0487870170216488E-01 +  tli * 1.3263949252910405E-03 +  (tli**2) * -8.4195688402450274E-06 +               &
+             & (tli**3)*1.6154895940993287E-08 + (tli**(-1))*3.8734212545203874E+01) * (LOG(satratli)**(-2)*LOG(rhoali)) +    &
+             & (1.4955918863858371 +  tli * 9.2290004245522454E+01 +  (tli**2) * -8.9006965195392618E-01 +                    &
+             & (tli**3) * 2.2319123411013099E-03 + (tli**(-1)) * 4.0180079996840852E-03) *                                    &
+             & (LOG(satratli)**(-1) * LOG(rhoali)**(-1)) +                                                                    &
+             & (7.9018031228561085 +  tli * -1.1649433968658949E+01 +  (tli**2) * 1.1400827854910951E-01 +                    &
+             & (tli**3) * -3.1941526492127755E-04 + (tli**(-1)) * -3.7662115740271446E-01) * (LOG(satratli)**(-1)) +          &
+             & (1.5725237111225979E+02 +  tli * -1.0051649979836277 +  (tli**2) * 1.1866484014507624E-03 +                    &
+             & (tli**3) * 7.3557614998540389E-06 + (tli**(-1)) * 2.6270197023115189) * (LOG(satratli)**(-1) * LOG(rhoali)) +  &
+             & (-1.6973840122470968E+01 +  tli * 1.1258423691432135E-01 +  (tli**2) * -2.9850139351463793E-04 + (tli**3) *    &
+             & 1.4301286324827064E-07 + (tli**(-1)) * 1.3163389235253725E+01) * (LOG(satratli)**(-1) * LOG(rhoali)**2) +      &
+             & (-1.0399591631839757 +  tli * 2.7022055588257691E-03 +  (tli**2) * -2.1507467231330936E-06 + (tli**3) *        &
+             & 3.8059489037584171E-10 + (tli**(-1)) * 1.5000492788553410E+02) * (LOG(satratli)**(-1) * LOG(rhoali)**3) +      &
+             & (1.2250990965305315 +  tli * 3.0495946490079444E+01 +  (tli**2) * 2.1051563135187106E+01 + (tli**3) *          &
+             & -8.2200682916580878E-02 + (tli**(-1)) * 2.9965871386685029E-02) * (LOG(rhoali)**(-2)) +                        &
+             & (4.8281605955680433 +  tli * 1.7346551710836445E+02 +  (tli**2) * -1.0113602140796010E+01 + (tli**3) *         &
+             & 3.7482518458685089E-02 + (tli**(-1)) * -1.4449998158558205E-01) * (LOG(rhoali)**(-1)) +                        &
+             & (2.3399230964451237E+02 +  tli * -2.3099267235261948E+01 +  (tli**2) * 8.0122962140916354E-02 +                &
+             & (tli**3) * 6.1542576994557088E-05 + (tli**(-1)) * 5.3718413254843007) * (LOG(rhoali)) +                        &
+             & (1.0299715519499360E+02 +  tli * -6.4663357203364136E-02 +  (tli**2) * -2.0487150565050316E-03 +               &
+             & (tli**3) * 8.7935289055530897E-07 + (tli**(-1)) * 3.6013204601215229E+01) * (LOG(rhoali)**2) +                 &
+             & (-3.5452115439584042 +  tli * 1.7083445731159330E-02 +  (tli**2) * -1.2552625290862626E-05 + (tli**3) *        &
+             & 1.2968447449182847E-09 + (tli**(-1)) * 1.5748687512056560E+02) * (LOG(rhoali)**3) +                            &
+             & (2.2338490119517975 +  tli * 1.0229410216045540E+02 +  (tli**2) * -3.2103611955174052 + (tli**3) *             &
+             & 1.3397152304977591E-02 + (tli**(-1)) * -2.4155187776460030E-02) * (LOG(satratli)* LOG(rhoali)**(-2)) +         &
+             & (3.7592282990713963 +  tli * -1.5257988769009816E+02 +  (tli**2) * 2.6113805420558802 + (tli**3) *             &
+             & -9.0380721653694363E-03 + (tli**(-1)) * -1.3974197138171082E-01) * (LOG(satratli)* LOG(rhoali)**(-1)) +        &
+             & (1.8293600730573988E+01 +  tli * 1.8344728606002992E+01 +  (tli**2) * -4.0063363221106751E-01 + (tli**3)       &
+             & * 1.4842749371258522E-03 + (tli**(-1)) * 1.1848846003282287) * (LOG(satratli)) +                               &
+             & (-1.7634531623032314E+02 +  tli * 4.9011762441271278 +  (tli**2) * -1.3195821562746339E-02 + (tli**3) *        &
+             & -2.8668619526430859E-05 + (tli**(-1)) * -2.9823396976393551E-01) * (LOG(satratli)* LOG(rhoali)) +              &
+             & (-3.2944043694275727E+01 +  tli * 1.2517571921051887E-01 +  (tli**2) * 8.3239769771186714E-05 + (tli**3) *     &
+             & 2.8191859341519507E-07 + (tli**(-1)) * -2.7352880736682319E+01) * (LOG(satratli)* LOG(rhoali)**2) +            &
+             & (-1.1451811137553243 +  tli * 2.0625997485732494E-03 +  (tli**2) * -3.4225389469233624E-06 + (tli**3) *        &
+             & 4.4437613496984567E-10 + (tli**(-1)) * 1.8666644332606754E+02) * (LOG(satratli)* LOG(rhoali)**3) +             &
+             & (3.2270897099493567E+01 +  tli * 7.7898447327513687E-01 +  (tli**2) * -6.5662738484679626E-03 + (tli**3) *     &
+             & 3.7899330796456790E-06 + (tli**(-1)) * 7.1106427501756542E-01) * (LOG(satratli)**2 * LOG(rhoali)**(-1)) +      &
+             & (-2.8901906781697811E+01 +  tli * -1.5356398793054860 +  (tli**2) * 1.9267271774384788E-02 + (tli**3) *        &
+             & -5.3886270475516162E-05 + (tli**(-1)) * 5.0490415975693426E-01) * (LOG(satratli)**2) +                         &
+             & (3.3365683645733924E+01 +  tli * -3.6114561564894537E-01 +  (tli**2) * 9.2977354471929262E-04 + (tli**3) *     &
+             & 1.9549769069511355E-07 + (tli**(-1)) * -8.8865930095112855) * (LOG(satratli)**2 * LOG(rhoali)) +               &
+             & (2.4592563042806375 +  tli * -8.3227071743101084E-03 +  (tli**2) * 8.2563338043447783E-06 + (tli**3) *         &
+             & -8.4374976698593496E-09 + (tli**(-1)) * -2.0938173949893473E+02) * (LOG(satratli)**2 * LOG(rhoali)**2) +       &
+             & (4.4099823444352317E+01 +  tli * 2.5915665826835252 +  (tli**2) * -1.6449091819482634E-02 + (tli**3) *         &
+             & 2.6797249816144721E-05 + (tli**(-1)) * 5.5045672663909995E-01)* satratli
+        jnuc_i1=EXP(jnuc_i1)
+        
+        ntot_i = ABS((-4.8324296064013375E+04 +  tli * 5.0469120697428906E+02 +  (tli**2) * -1.1528940488496042E+00 +         &
+             & (tli**(-1)) * -8.6892744676239192E+02 + (tli**(3)) * 4.0030302028120469E-04) +                                 &
+             & (-6.7259105232039847E+03 +  tli * 1.9197488157452008E+02 +  (tli**2) * -1.3602976930126354E+00 +               &
+             & (tli**(-1)) * -1.1212637938360332E+02 + (tli**(3)) * 2.8515597265933207E-03) *                                 &
+             & LOG(satratli)**(-2) * LOG(rhoali)**(-2) +                                                                      &
+             & (2.6216455217763342E+02 +  tli * -2.3687553252750821E+00 +  (tli**2) * 7.4074554767517521E-03 +                &
+             & (tli**(-1)) * -1.9213956820114927E+03 + (tli**(3)) * -9.3839114856129453E-06) * LOG(satratli)**(-2) +          &
+             & (3.9652478944137344E+00 +  tli * 1.2469375098256536E-02 +  (tli**2) * -9.9837754694045633E-05 + (tli**(-1)) *  &
+             & -5.1919499210175138E+02 + (tli**(3)) * 1.6489001324583862E-07) * LOG(satratli)**(-2) * LOG(rhoali) +           &
+             & (2.4975714429096206E+02 +  tli * 1.7107594562445172E+02 +  (tli**2) * -7.8988711365135289E-01 + (tli**(-1)) *  &
+             & -2.2243599782483177E+01 + (tli**(3)) * -1.6291523004095427E-04) * LOG(satratli)**(-1) * LOG(rhoali)**(-2) +    &
+             & (-8.9270715592533611E+02 +  tli * 1.2053538883338946E+02 +  (tli**2) * -1.5490408828541018E+00 + (tli**(-1)) * &
+             & -1.1243275579419826E+01 + (tli**(3)) * 4.8053105606904655E-03) * LOG(satratli)**(-1) * LOG(rhoali)**(-1) +     &
+             & (7.6426441642091631E+03 +  tli * -7.1785462414656578E+01 +  (tli**2) * 2.3851864923199523E-01 + (tli**(-1)) *  &
+             & 8.5591775688708395E+01 + (tli**(3)) * -3.7000473243342858E-04) * LOG(satratli)**(-1) +                         &
+             & (-5.1516826398607911E+01 +  tli * 9.1385720811460558E-01 +  (tli**2) * -3.5477100262158974E-03 +               &
+             & (tli**(-1)) * 2.7545544507625586E+03 + (tli**(3)) * 5.4708262093640928E-06) * LOG(satratli)**(-1) * LOG(rhoali) + &
+             & (-3.0386767129196176E+02 +  tli * -1.1033438883583569E+04 +  (tli**2) * 8.1296859732896067E+01 + (tli**(-1)) * &
+             & 1.2625883141097162E+01 + (tli**(3)) * -1.2728497822219101E-01) * LOG(rhoali)**(-2) +                           &
+             & (-3.3763494256461472E+03 +  tli * 3.1916579136391006E+03 +  (tli**2) * -2.7234339474441143E+01 + (tli**(-1)) * &
+             & -2.1897653262707397E+01 + (tli**(3)) * 5.1788505812259071E-02) * LOG(rhoali)**(-1) +                           &
+             & (-1.8817843873687068E+03 +  tli * 4.3038072285882070E+00 +  (tli**2) * 6.6244087689671860E-03 + (tli**(-1)) *  &
+             & -2.7133073605696295E+03 + (tli**(3)) * -1.7951557394285043E-05) * LOG(rhoali) +                                &
+             & (-1.7668827539244447E+02 +  tli * 4.8160932330629913E-01 +  (tli**2) * -6.3133007671100293E-04 + (tli**(-1)) * &
+             & 2.5631774669873157E+04 + (tli**(3)) * 4.1534484127873519E-07) * LOG(rhoali)**(2) +                             &
+             & (-1.6661835889222382E+03 +  tli * 1.3708900504682877E+03 +  (tli**2) * -1.7919060052198969E+01 + (tli**(-1)) * &
+             & -3.5145029804436405E+01 + (tli**(3)) * 5.1047240947371224E-02) * LOG(satratli)* LOG(rhoali)**(-2) +            &
+             & (1.0843549363030939E+04 +  tli * -7.3557073636139577E+01 +  (tli**2) * 1.2054625131778862E+00 + (tli**(-1)) *  &
+             & 1.9358737917864391E+02 + (tli**(3)) * -4.2871620775911338E-03) * LOG(satratli)* LOG(rhoali)**(-1) +            &
+             & (-2.4269802549752835E+03 +  tli * 1.1348265061941714E+01 +  (tli**2) * -5.0430423939495157E-02 + (tli**(-1)) * &
+             & 2.3709874548950634E+03 + (tli**(3)) * 1.4091851828620244E-04) * LOG(satratli) +                                &
+             & (5.2745372575251588E+02 +  tli * -2.6080675912627314E+00 +  (tli**2) * 5.6902218056670145E-03 + (tli**(-1)) *  &
+             & -3.2149319482897838E+04 + (tli**(3)) * -5.4121996056745853E-06) * LOG(satratli)* LOG(rhoali) +                 &
+             & (-1.6401959518360403E+01 +  tli * 2.4322962162439640E-01 +  (tli**2) * 1.1744366627725344E-03 + (tli**(-1)) *  &
+             & -8.2694427518413195E+03 + (tli**(3)) * -5.0028379203873102E-06)* LOG(satratli)**(2) +                          &
+             & (-2.7556572017167782E+03 +  tli * 4.9293344495058264E+01 +  (tli**2) * -2.6503456520676050E-01 + (tli**(-1)) * &
+             & 1.2130698030982167E+03 + (tli**(3)) * 4.3530610668042957E-04)* LOG(satratli)**2 * LOG(rhoali)**(-1) +          &
+             & (-6.3419182228959192E+00 +  tli * 4.0636212834605827E-02 +  (tli**2) * -1.0450112687842742E-04 + (tli**(-1)) * &
+             & 3.1035882189759656E+02 + (tli**(3)) * 9.4328418657873500E-08)* LOG(satratli)**(-3) +                           &
+             & (3.0189213304689042E+03 +  tli * -2.3804654203861684E+01 +  (tli**2) * 6.8113013411972942E-02 + (tli**(-1)) *  &
+             & 6.3112071081188913E+02 + (tli**(3)) * -9.4460854261685723E-05)* (satratli) * LOG(rhoali) +                     &
+             & (1.1924791930673702E+04 +  tli * -1.1973824959206000E+02 +  (tli**2) * 1.6888713097971020E-01 + (tli**(-1)) *  &
+             & 1.8735938211539585E+02 + (tli**(3)) * 5.0974564680442852E-04)* (satratli) +                                    &
+             & (3.6409071302482083E+01 +  tli * 1.7919859306449623E-01 +  (tli**2) * -1.0020116255895206E-03 + (tli**(-1)) *  &
+             & -8.3521083354432303E+03 + (tli**(3)) * 1.5879900546795635E-06)* satratli * LOG(rhoali)**(2))
+          
+        rc_i = (-3.6318550637865524E-08 +  tli * 2.1740704135789128E-09   +  (tli**2) *                          &
+             & -8.5521429066506161E-12 + (tli**3) * -9.3538647454573390E-15) +                                   &
+             & (2.1366936839394922E-08 +  tli * -2.4087168827395623E-10 +  (tli**2) * 8.7969869277074319E-13 +   &
+             & (tli**3) * -1.0294466881303291E-15)* LOG(satratli)**(-2) * LOG(rhoali)**(-1) +                    &
+             & (-7.7804007761164303E-10 +  tli * 1.0327058173517932E-11 +  (tli**2) * -4.2557697639692428E-14 +  &
+             & (tli**3) * 5.4082507061618662E-17)* LOG(satratli)**(-2) +                                         &
+             & (3.2628927397420860E-12 +  tli * -7.6475692919751066E-14 +  (tli**2) * 4.1985816845259788E-16 +   &
+             & (tli**3) * -6.2281395889592719E-19)* LOG(satratli)**(-2) * LOG(rhoali) +                          &
+             & (2.0442205540818555E-09 +  tli * 4.0441858911249830E-08 +  (tli**2) * -3.3423487629482825E-10 +   &
+             & (tli**3) * 6.8000404742985678E-13)* LOG(satratli)**(-1) * LOG(rhoali)**(-2) +                     &
+             & (1.8381489183824627E-08 +  tli * -8.9853322951518919E-09 +  (tli**2) * 7.5888799566036185E-11 +   &
+             & (tli**3) * -1.5823457864755549E-13)* LOG(satratli)**(-1) * LOG(rhoali)**(-1) +                    &
+             & (1.1795760639695057E-07 +  tli * -8.1046722896375875E-10 +  (tli**2) * 9.1868604369041857E-14 +   &
+             & (tli**3) * 4.7882428237444610E-15)* LOG(satratli)**(-1) +                                         &
+             & (-4.4028846582545952E-09 +  tli * 4.6541269232626618E-11 +  (tli**2) * -1.1939929984285194E-13 +  &
+             & (tli**3) * 2.3602037016614437E-17)* LOG(satratli)**(-1) * LOG(rhoali) +                           &
+             & (2.7885056884209128E-11 +  tli * -4.5167129624119121E-13 +  (tli**2) * 1.6558404997394422E-15 +   &
+             & (tli**3) * -1.2037336621218054E-18)* LOG(satratli)**(-1) * LOG(rhoali)**2 +                       &
+             & (-2.3719627171699983E-09 +  tli * -1.5260127909292053E-07 +  (tli**2) * 1.7177017944754134E-09 +  &
+             & (tli**3) * -4.7031737537526395E-12)* LOG(rhoali)**(-2) +                                          &
+             & (-5.6946433724699646E-09 +  tli * 8.4629788237081735E-09 +  (tli**2) * -1.7674135187061521E-10 +  &
+             & (tli**3) * 6.6236547903091862E-13)* LOG(rhoali)**(-1) +                                           &
+             & (-2.2808617930606012E-08 +  tli * 1.4773376696847775E-10 +  (tli**2) * -1.3076953119957355E-13 +  &
+             & (tli**3) * 2.3625301497914000E-16)* LOG(rhoali) +                                                 &
+             & (1.4014269939947841E-10 +  tli * -2.3675117757377632E-12 +  (tli**2) * 5.1514033966707879E-15 +   &
+             & (tli**3) * -4.8864233454747856E-18)* LOG(rhoali)**2 +                                             &
+             & (6.5464943868885886E-11 +  tli * 1.6494354816942769E-08 +  (tli**2) * -1.7480097393483653E-10 +   &
+             & (tli**3) * 4.7460075628523984E-13)* LOG(satratli)* LOG(rhoali)**(-2) +                            &
+             & (8.4737893183927871E-09 +  tli * -6.0243327445597118E-09 +  (tli**2) * 5.8766070529814883E-11 +   &
+             & (tli**3) * -1.4926748560042018E-13)* LOG(satratli)* LOG(rhoali)**(-1) +                           &
+             & (1.0761964135701397E-07 +  tli * -1.0142496009071148E-09 +  (tli**2) * 2.1337312466519190E-12 +   &
+             & (tli**3) * 1.6376014957685404E-15)* LOG(satratli) +                                               &
+             & (-3.5621571395968670E-09 +  tli * 4.1175339587760905E-11 +  (tli**2) * -1.3535372357998504E-13 +  &
+             & (tli**3) * 8.9334219536920720E-17)* LOG(satratli)* LOG(rhoali) +                                  &
+             & (2.0700482083136289E-11 +  tli * -3.9238944562717421E-13 +  (tli**2) * 1.5850961422040196E-15 +   &
+             & (tli**3) * -1.5336775610911665E-18)* LOG(satratli)* LOG(rhoali)**2 +                              &
+             & (1.8524255464416206E-09 +  tli * -2.1959816152743264E-11 +  (tli**2) * -6.4478119501677012E-14 +  &
+             & (tli**3) * 5.5135243833766056E-16)* LOG(satratli)**2 * LOG(rhoali)**(-1) +                        &
+             & (1.9349488650922679E-09 +  tli * -2.2647295919976428E-11 +  (tli**2) * 9.2917479748268751E-14 +   &
+             & (tli**3) * -1.2741959892173170E-16)* LOG(satratli)**2 +                                           &
+             & (2.1484978031650972E-11 +  tli * -9.3976642475838013E-14 +  (tli**2) * -4.8892738002751923E-16 +  &
+             & (tli**3) * 1.4676120441783832E-18)* LOG(satratli)**2 * LOG(rhoali) +                              &
+             & (6.7565715216420310E-13 +  tli * -3.5421162549480807E-15 +  (tli**2) * -3.4201196868693569E-18 +  &
+             & (tli**3) * 2.2260187650412392E-20)* LOG(satratli)**3 * LOG(rhoali)
+                    
+        na_i=x_i*ntot_i
+        IF (na_i .LT. 1.) THEN
+!           print *, 'Warning: number of acid molecules < 1 in nucleation regime, setting na_n=1'
+           na_n=1.0
+        ENDIF
+     ENDIF
+    
+     jnuc_i=jnuc_i1 
+     ! Ion loss rate (1/s)
+     xloss=csi+jnuc_i
+     
+     ! Recombination (here following Brasseur and Chatel, 1983)   
+     recomb=6.0E-8*SQRT(300./tli)+6.0E-26*airn*(300./tli)**4
+     
+     ! Small ion concentration in air (1/cm3) (following Dunne et al., 2016)
+     ! max function is to avoid n_i to go practically zero at very high J_ion 
+     n_i=MAX(0.01,(SQRT(xloss**2.0+4.0*recomb*ipr)-xloss)/(2.0*recomb))
+     
+     ! Ion-induced nucleation rate
+     ! Min function is to ensure that max function above does not cause J_ion to overshoot 
+     jnuc_i=MIN(ipr,n_i*jnuc_i1)
+     ! Set the ion-induced nucleation rate to 0.0 if less than 1.0E-7      
+     IF (jnuc_i.LT.1.E-7) THEN
+        jnuc_i=0.0
+     ENDIF
+
+  ENDIF
+
+!--conversion from double precision to float in case the model is run in single precision
+  jnuc_n_real   = jnuc_n
+  ntot_n_real   = ntot_n
+  jnuc_i_real   = jnuc_i
+  ntot_i_real   = ntot_i
+  x_n_real      = x_n
+  x_i_real      = x_i
+  na_n_real     = na_n
+  na_i_real     = na_i
+  rc_n_real     = rc_n
+  rc_i_real     = rc_i
+  n_i_real      = n_i
+  rhoatres_real = rhoatres
+  
+END SUBROUTINE newbinapara
+
 END MODULE nucleation_tstep_mod
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/ocs_to_so2.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/ocs_to_so2.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/ocs_to_so2.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 SUBROUTINE ocs_to_so2(pdtphys,tr_seri,t_seri,pplay,paprs,is_strato)
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/so2_to_h2so4.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/so2_to_h2so4.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/so2_to_h2so4.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 SUBROUTINE SO2_TO_H2SO4(pdtphys,tr_seri,t_seri,pplay,paprs,is_strato)
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/strataer_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/strataer_mod.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/strataer_mod.F90	(revision 3605)
@@ -0,0 +1,231 @@
+! $Id$
+MODULE strataer_mod
+! This module contains information about strato microphysic model parameters
+  
+  IMPLICIT NONE
+
+  ! flag to constraint nucleation rate in a lat/pres box
+  LOGICAL,SAVE :: flag_nuc_rate_box      ! Nucleation rate limit or not to a lat/pres
+  !$OMP THREADPRIVATE(flag_nuc_rate_box)
+  REAL,SAVE    :: nuclat_min             ! min lat to activate nuc rate
+  REAL,SAVE    :: nuclat_max             ! max lat to activate nuc rate
+  REAL,SAVE    :: nucpres_min            ! min pres to activate nuc rate
+  REAL,SAVE    :: nucpres_max            ! max pres to activate nuc rate
+  !$OMP THREADPRIVATE(nuclat_min, nuclat_max, nucpres_min, nucpres_max)
+  
+  ! flag for sulfur emission scenario: (0) background aer ; (1) volcanic eruption ; (2) strato aer injections (SAI)
+  INTEGER,SAVE :: flag_sulf_emit
+  !$OMP THREADPRIVATE(flag_sulf_emit)
+
+  ! flag for sulfur emission altitude distribution: (0) gaussian; (1) uniform
+  INTEGER,SAVE :: flag_sulf_emit_distrib
+  !$OMP THREADPRIVATE(flag_sulf_emit_distrib)
+  
+  !--flag_sulf_emit=1 -- Volcanic eruption(s)
+  INTEGER,SAVE             :: nErupt                    ! number of eruptions specs
+  REAL,SAVE                :: injdur                    ! volcanic injection duration
+  !$OMP THREADPRIVATE(nErupt, injdur)
+  INTEGER,ALLOCATABLE,SAVE :: year_emit_vol(:)          ! year of emission date
+  INTEGER,ALLOCATABLE,SAVE :: mth_emit_vol(:)           ! month of emission date
+  INTEGER,ALLOCATABLE,SAVE :: day_emit_vol(:)           ! day of emission date
+  !$OMP THREADPRIVATE(year_emit_vol, mth_emit_vol, day_emit_vol)
+  REAL,ALLOCATABLE,SAVE    :: m_aer_emiss_vol(:)        ! emitted sulfur mass in kgS, e.g. 7Tg(S)=14Tg(SO2)
+  REAL,ALLOCATABLE,SAVE    :: altemiss_vol(:)           ! emission altitude in m
+  REAL,ALLOCATABLE,SAVE    :: sigma_alt_vol(:)          ! standard deviation of emission altitude in m
+  !$OMP THREADPRIVATE(m_aer_emiss_vol, altemiss_vol, sigma_alt_vol)
+  INTEGER,ALLOCATABLE,SAVE :: ponde_lonlat_vol(:)       ! lon/lat ponderation factor
+  REAL,ALLOCATABLE,SAVE    :: xlat_min_vol(:)           ! min latitude of volcano in degree
+  REAL,ALLOCATABLE,SAVE    :: xlat_max_vol(:)           ! max latitude of volcano in degree
+  REAL,ALLOCATABLE,SAVE    :: xlon_min_vol(:)           ! min longitude of volcano in degree
+  REAL,ALLOCATABLE,SAVE    :: xlon_max_vol(:)           ! max longitude of volcano in degree
+  !$OMP THREADPRIVATE(ponde_lonlat_vol, xlat_min_vol, xlat_max_vol, xlon_min_vol, xlon_max_vol)
+  
+  !--flag_sulf_emit=2 --SAI
+  REAL,SAVE    :: m_aer_emiss_sai        ! emitted sulfur mass in kgS, eg 1e9=1TgS, 1e10=10TgS
+  REAL,SAVE    :: altemiss_sai           ! emission altitude in m
+  REAL,SAVE    :: sigma_alt_sai          ! standard deviation of emission altitude in m
+  !$OMP THREADPRIVATE(m_aer_emiss_sai, altemiss_sai, sigma_alt_sai)
+  REAL,SAVE    :: xlat_sai               ! latitude of SAI in degree
+  REAL,SAVE    :: xlon_sai               ! longitude of SAI in degree
+  REAL,SAVE    :: dlat, dlon             ! delta latitude and d longitude of grid in degree
+  !$OMP THREADPRIVATE(xlat_sai, xlon_sai, dlat, dlon)
+  
+  !--flag_sulf_emit=3 -- SAI
+  REAL,SAVE    :: xlat_max_sai           ! maximum latitude of SAI in degrees
+  REAL,SAVE    :: xlat_min_sai           ! minimum latitude of SAI in degrees
+  !$OMP THREADPRIVATE(xlat_min_sai,xlat_max_sai)
+  
+CONTAINS
+    
+  SUBROUTINE strataer_init()
+    USE ioipsl_getin_p_mod, ONLY : getin_p
+    USE print_control_mod, ONLY : lunout
+    USE mod_phys_lmdz_para, ONLY : is_master
+
+    ! Local var
+    INTEGER       :: ieru
+ 
+    INTEGER :: i
+    
+    WRITE(lunout,*) 'IN STRATAER INIT WELCOME!'
+   
+    !Config Key  = flag_sulf_emit
+    !Config Desc = aerosol emission mode
+    ! - 0 = background aerosol
+    ! - 1 = volcanic eruption
+    ! - 2 = geo-ingeneering design
+    ! - 3 = geo-engineering between two latitudes
+    !Config Def  = 0
+    !Config Help = Used in physiq.F
+    !
+    flag_sulf_emit = 0
+    nErupt = 0 ! eruption number
+    injdur = 0 ! init injection duration
+    CALL getin_p('flag_sulf_emit',flag_sulf_emit)
+
+    IF (flag_sulf_emit==1) THEN ! Volcano
+       CALL getin_p('nErupt',nErupt)
+       CALL getin_p('injdur',injdur)
+    ELSEIF (flag_sulf_emit == 2) THEN ! SAI
+       CALL getin_p('m_aer_emiss_sai',m_aer_emiss_sai)
+       CALL getin_p('altemiss_sai',altemiss_sai)
+       CALL getin_p('sigma_alt_sai',sigma_alt_sai)
+       CALL getin_p('xlat_sai',xlat_sai)
+       CALL getin_p('xlon_sai',xlon_sai)
+       CALL getin_p('flag_sulf_emit_distrib',flag_sulf_emit_distrib)
+    ELSEIF (flag_sulf_emit == 3) THEN ! SAI between latitudes
+       CALL getin_p('m_aer_emiss_sai',m_aer_emiss_sai)
+       CALL getin_p('altemiss_sai',altemiss_sai)
+       CALL getin_p('sigma_alt_sai',sigma_alt_sai)
+       CALL getin_p('xlon_sai',xlon_sai)
+       CALL getin_p('xlat_max_sai',xlat_max_sai)
+       CALL getin_p('xlat_min_sai',xlat_min_sai)
+       CALL getin_p('flag_sulf_emit_distrib',flag_sulf_emit_distrib)
+    ENDIF
+
+    ALLOCATE(year_emit_vol(nErupt),mth_emit_vol(nErupt),day_emit_vol(nErupt))
+    ALLOCATE(m_aer_emiss_vol(nErupt),altemiss_vol(nErupt),sigma_alt_vol(nErupt))
+    ALLOCATE(xlat_min_vol(nErupt),xlon_min_vol(nErupt))
+    ALLOCATE(xlat_max_vol(nErupt),xlon_max_vol(nErupt))
+    
+    IF (nErupt.GT.0) THEN 
+      year_emit_vol=0 ; mth_emit_vol=0 ; day_emit_vol=0
+      m_aer_emiss_vol=0. ; altemiss_vol=0. ; sigma_alt_vol=0.
+      xlon_min_vol=0. ; xlon_max_vol=0.
+      xlat_min_vol=0. ; xlat_max_vol=0.
+    ENDIF
+    
+    CALL getin_p('year_emit_vol',year_emit_vol)
+    CALL getin_p('mth_emit_vol',mth_emit_vol)
+    CALL getin_p('day_emit_vol',day_emit_vol)
+    CALL getin_p('m_aer_emiss_vol',m_aer_emiss_vol)
+    CALL getin_p('altemiss_vol',altemiss_vol)
+    CALL getin_p('sigma_alt_vol',sigma_alt_vol)
+    CALL getin_p('xlon_min_vol',xlon_min_vol)
+    CALL getin_p('xlon_max_vol',xlon_max_vol)
+    CALL getin_p('xlat_min_vol',xlat_min_vol)
+    CALL getin_p('xlat_max_vol',xlat_max_vol)
+    !Config Key  = flag_nuc_rate_box
+    !Config Desc = define or not a box for nucleation rate
+    ! - F = global nucleation
+    ! - T = 2D-box for nucleation need nuclat_min, nuclat_max, nucpres_min and
+    ! nucpres_max
+    !       to define its bounds.
+    !Config Def  = F
+    !Config Help = Used in physiq.F
+    !
+    flag_nuc_rate_box = .FALSE.
+    CALL getin_p('flag_nuc_rate_box',flag_nuc_rate_box)
+    CALL getin_p('nuclat_min',nuclat_min)
+    CALL getin_p('nuclat_max',nuclat_max)
+    CALL getin_p('nucpres_min',nucpres_min)
+    CALL getin_p('nucpres_max',nucpres_max)
+
+    !IF (is_master) THEN
+    WRITE(lunout,*) 'flag_sulf_emit = ',flag_sulf_emit
+    IF (flag_sulf_emit == 1) THEN
+       WRITE(lunout,*) 'IN STRATAER nErupt: ',nErupt
+       WRITE(lunout,*) 'IN STRATAER injdur: ',injdur
+       WRITE(lunout,*) 'IN STRATAER : year_emit_vol',year_emit_vol
+       WRITE(lunout,*) 'IN STRATAER : mth_emit_vol',mth_emit_vol
+       WRITE(lunout,*) 'IN STRATAER : day_emit_vol',day_emit_vol
+       WRITE(lunout,*) 'IN STRATAER : m_aer_emiss_vol',m_aer_emiss_vol
+       WRITE(lunout,*) 'IN STRATAER : altemiss_vol',altemiss_vol
+       WRITE(lunout,*) 'IN STRATAER : sigma_alt_vol',sigma_alt_vol
+       WRITE(lunout,*) 'IN STRATAER : ponde_lonlat_vol',ponde_lonlat_vol
+       WRITE(lunout,*) 'IN STRATAER : xlat_min_vol',xlat_min_vol
+       WRITE(lunout,*) 'IN STRATAER : xlat_max_vol',xlat_max_vol
+       WRITE(lunout,*) 'IN STRATAER : xlon_min_vol',xlon_min_vol
+       WRITE(lunout,*) 'IN STRATAER : xlon_max_vol',xlon_max_vol
+    ELSEIF (flag_sulf_emit == 2) THEN
+       WRITE(lunout,*) 'IN STRATAER : m_aer_emiss_sai',m_aer_emiss_sai
+       WRITE(lunout,*) 'IN STRATAER : altemiss_sai',altemiss_sai
+       WRITE(lunout,*) 'IN STRATAER : sigma_alt_sai',sigma_alt_sai
+       WRITE(lunout,*) 'IN STRATAER : xlat_sai',xlat_sai
+       WRITE(lunout,*) 'IN STRATAER : xlon_sai',xlon_sai
+       WRITE(lunout,*) 'flag_sulf_emit_distrib = ',flag_sulf_emit_distrib
+    ELSEIF (flag_sulf_emit == 3) THEN
+       WRITE(lunout,*) 'IN STRATAER : m_aer_emiss_sai',m_aer_emiss_sai
+       WRITE(lunout,*) 'IN STRATAER : altemiss_sai',altemiss_sai
+       WRITE(lunout,*) 'IN STRATAER : sigma_alt_sai',sigma_alt_sai
+       WRITE(lunout,*) 'IN STRATAER : xlat_min_sai',xlat_min_sai
+       WRITE(lunout,*) 'IN STRATAER : xlat_max_sai',xlat_max_sai
+       WRITE(lunout,*) 'IN STRATAER : xlon_sai',xlon_sai
+       WRITE(lunout,*) 'flag_sulf_emit_distrib = ',flag_sulf_emit_distrib
+    ENDIF
+    WRITE(lunout,*) 'IN STRATAER : flag_nuc_rate_box = ',flag_nuc_rate_box
+    IF (flag_nuc_rate_box) THEN
+       WRITE(lunout,*) 'IN STRATAER : nuclat_min = ',nuclat_min,', nuclat_max = ',nuclat_max
+       WRITE(lunout,*) 'IN STRATAER : nucpres_min = ',nucpres_min,', nucpres_max = ',nucpres_max
+    ENDIF
+    !ENDIF
+
+    CALL strataer_ponde_init
+    WRITE(lunout,*) 'IN STRATAER INT2 END'
+
+  END SUBROUTINE strataer_init
+  
+  ! Compute the ponderation to applicate in each grid point for all eruptions and init
+  ! dlat & dlon variables
+  SUBROUTINE strataer_ponde_init()
+    
+    USE regular_lonlat_mod, ONLY: lon_reg, lat_reg
+    USE dimphy, ONLY: klon
+    USE mod_grid_phy_lmdz, ONLY: nbp_lat, nbp_lon
+    USE print_control_mod, ONLY : lunout
+    USE YOMCST, ONLY : RPI
+
+    ! local var
+    REAL                :: pi,lat_reg_deg,lon_reg_deg! latitude and d longitude of grid in degree
+    INTEGER             :: ieru, i, j
+    
+    ALLOCATE(ponde_lonlat_vol(nErupt))
+    
+    !Compute lon/lat ponderation for injection
+    dlat=180./2./FLOAT(nbp_lat)   ! d latitude in degree
+    dlon=360./2./FLOAT(nbp_lon)   ! d longitude in degree
+    WRITE(lunout,*) 'IN STRATAER_INIT dlat=',dlat,'dlon=',dlon
+    WRITE(lunout,*) 'IN STRATAER_INIT nErupt=',nErupt
+    WRITE(lunout,*) 'IN STRATAER_INIT xlat_min=',xlat_min_vol,'xlat_max=',xlat_max_vol
+    WRITE(lunout,*) 'IN STRATAER_INIT xlon_min=',xlon_min_vol,'xlon_max=',xlon_max_vol
+    DO ieru=1, nErupt
+       ponde_lonlat_vol(ieru) = 0
+       DO i=1,nbp_lon
+          lon_reg_deg = lon_reg(i)*180./RPI
+          DO j=1,nbp_lat
+             lat_reg_deg = lat_reg(j)*180./RPI
+             IF  ( lat_reg_deg.GE.xlat_min_vol(ieru)-dlat .AND. lat_reg_deg.LT.xlat_max_vol(ieru)+dlat .AND. &
+                  lon_reg_deg.GE.xlon_min_vol(ieru)-dlon .AND. lon_reg_deg.LT.xlon_max_vol(ieru)+dlon ) THEN
+                ponde_lonlat_vol(ieru) = ponde_lonlat_vol(ieru) + 1
+             ENDIF
+          ENDDO
+       ENDDO
+       IF(ponde_lonlat_vol(ieru) == 0) THEN
+          WRITE(lunout,*) 'STRATAER_INIT ERROR: no grid point found for eruption ieru=',ieru
+       ENDIF
+    ENDDO !ieru
+    WRITE(lunout,*) 'IN STRATAER_INIT ponde_lonlat: ',ponde_lonlat_vol
+    
+  END SUBROUTINE strataer_ponde_init
+  
+END MODULE strataer_mod
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/sulfate_aer_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/sulfate_aer_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/sulfate_aer_mod.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 MODULE sulfate_aer_mod
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/traccoag_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/traccoag_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/StratAer/traccoag_mod.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 MODULE traccoag_mod
 !
@@ -16,5 +19,5 @@
     USE infotrac
     USE aerophys
-    USE geometry_mod, ONLY : cell_area
+    USE geometry_mod, ONLY : cell_area, boundslat
     USE mod_grid_phy_lmdz
     USE mod_phys_lmdz_mpi_data, ONLY :  is_mpi_root
@@ -24,4 +27,7 @@
     USE phys_local_var_mod, ONLY: stratomask
     USE YOMCST
+    USE print_control_mod, ONLY: lunout
+    USE strataer_mod
+    USE phys_cal_mod, ONLY : year_len
 
     IMPLICIT NONE
@@ -52,26 +58,6 @@
 ! Local variables
 !----------------
-! flag for sulfur emission scenario: (0) background aerosol ; (1) volcanic eruption ; (2) stratospheric aerosol injections (SAI)
-    INTEGER,PARAMETER  :: flag_sulf_emit=2 
-!
-!--flag_sulf_emit=1 --example Pinatubo
-    INTEGER,PARAMETER :: year_emit_vol=1991          ! year of emission date
-    INTEGER,PARAMETER :: mth_emit_vol=6              ! month of emission date
-    INTEGER,PARAMETER :: day_emit_vol=15             ! day of emission date 
-    REAL,PARAMETER    :: m_aer_emiss_vol=7.e9   ! emitted sulfur mass in kgS, e.g. 7Tg(S)=14Tg(SO2)
-    REAL,PARAMETER    :: altemiss_vol=17.e3     ! emission altitude in m
-    REAL,PARAMETER    :: sigma_alt_vol=1.e3     ! standard deviation of emission altitude in m
-    REAL,PARAMETER    :: xlat_vol=15.14         ! latitude of volcano in degree
-    REAL,PARAMETER    :: xlon_vol=120.35        ! longitude of volcano in degree
-
-!--flag_sulf_emit=2 --SAI
-    REAL,PARAMETER    :: m_aer_emiss_sai=1.e10  ! emitted sulfur mass in kgS, eg 1e9=1TgS, 1e10=10TgS
-    REAL,PARAMETER    :: altemiss_sai=17.e3     ! emission altitude in m
-    REAL,PARAMETER    :: sigma_alt_sai=1.e3     ! standard deviation of emission altitude in m
-    REAL,PARAMETER    :: xlat_sai=0.01          ! latitude of SAI in degree
-    REAL,PARAMETER    :: xlon_sai=120.35        ! longitude of SAI in degree
-
-!--other local variables
-    INTEGER                                :: it, k, i, ilon, ilev, itime, i_int
+    REAL                                   :: m_aer_emiss_vol_daily ! daily injection mass emission
+    INTEGER                                :: it, k, i, ilon, ilev, itime, i_int, ieru
     LOGICAL,DIMENSION(klon,klev)           :: is_strato           ! true = above tropopause, false = below
     REAL,DIMENSION(klon,klev)              :: m_air_gridbox       ! mass of air in every grid box [kg]
@@ -90,14 +76,13 @@
     REAL,DIMENSION(klev)                   :: zdm                 ! mass of atm. model layer in kg
     REAL,DIMENSION(klon,klev)              :: dens_aer            ! density of aerosol particles [kg/m3 aerosol] with default H2SO4 mass fraction
-    REAL                                   :: dlat, dlon          ! d latitude and d longitude of grid in degree
     REAL                                   :: emission            ! emission
+    REAL                                   :: theta_min, theta_max ! for SAI computation between two latitudes
+    REAL                                   :: dlat_loc
 
     IF (is_mpi_root) THEN
-      PRINT *,'in traccoag: date from phys_cal_mod =',year_cur,'-',mth_cur,'-',day_cur,'-',hour
+       WRITE(lunout,*) 'in traccoag: date from phys_cal_mod =',year_cur,'-',mth_cur,'-',day_cur,'-',hour
+       WRITE(lunout,*) 'IN traccoag flag_sulf_emit: ',flag_sulf_emit
     ENDIF
-
-    dlat=180./2./FLOAT(nbp_lat)   ! d latitude in degree
-    dlon=360./2./FLOAT(nbp_lon)   ! d longitude in degree
-
+    
     DO it=1, nbtr_bin
       r_bin(it)=mdw(it)/2.
@@ -120,5 +105,5 @@
     IF (debutphy .and. is_mpi_root) THEN
       DO it=1, nbtr_bin
-        PRINT *,'radius bin', it, ':', r_bin(it), '(from',  r_lower(it), 'to', r_upper(it), ')'
+        WRITE(lunout,*) 'radius bin', it, ':', r_bin(it), '(from',  r_lower(it), 'to', r_upper(it), ')'
       ENDDO
     ENDIF
@@ -170,46 +155,77 @@
       !--only emit on day of eruption
       ! stretch emission over one day of Pinatubo eruption
-      IF (year_cur==year_emit_vol.AND.mth_cur==mth_emit_vol.AND.day_cur==day_emit_vol) THEN 
-!
-        DO i=1,klon
-          !Pinatubo eruption at 15.14N, 120.35E
-          IF  ( xlat(i).GE.xlat_vol-dlat .AND. xlat(i).LT.xlat_vol+dlat .AND. &
-                xlon(i).GE.xlon_vol-dlon .AND. xlon(i).LT.xlon_vol+dlon ) THEN
-! 
-          PRINT *,'coordinates of volcanic injection point=',xlat(i), xlon(i), day_cur, mth_cur, year_cur
-!         compute altLMDz
-            altLMDz(:)=0.0
-            DO k=1, klev
-              zrho=pplay(i,k)/t_seri(i,k)/RD       !air density in kg/m3
-              zdm(k)=(paprs(i,k)-paprs(i,k+1))/RG  !mass of layer in kg
-              zdz=zdm(k)/zrho                      !thickness of layer in m
-              altLMDz(k+1)=altLMDz(k)+zdz          !altitude of interface
-            ENDDO
-            !compute distribution of emission to vertical model layers (based on Gaussian peak in altitude)
-            f_lay_sum=0.0
-            DO k=1, klev
-              f_lay_emiss(k)=0.0
-              DO i_int=1, n_int_alt
-                alt=altLMDz(k)+float(i_int)*(altLMDz(k+1)-altLMDz(k))/float(n_int_alt)
-                f_lay_emiss(k)=f_lay_emiss(k)+1./(sqrt(2.*RPI)*sigma_alt_vol)* &
-                &              exp(-0.5*((alt-altemiss_vol)/sigma_alt_vol)**2.)*   & 
-                &              (altLMDz(k+1)-altLMDz(k))/float(n_int_alt) 
-              ENDDO
-              f_lay_sum=f_lay_sum+f_lay_emiss(k)
-            ENDDO
-            !correct for step integration error
-            f_lay_emiss(:)=f_lay_emiss(:)/f_lay_sum
-            !emission as SO2 gas (with m(SO2)=64/32*m_aer_emiss)
-            !vertically distributed emission
-            DO k=1, klev
-              ! stretch emission over one day (minus one timestep) of Pinatubo eruption
-              emission=m_aer_emiss_vol*(mSO2mol/mSatom)/m_air_gridbox(i,k)*f_lay_emiss(k)/1./(86400.-pdtphys)
-              tr_seri(i,k,id_SO2_strat)=tr_seri(i,k,id_SO2_strat)+emission*pdtphys 
-              budg_emi_so2(i)=budg_emi_so2(i)+emission*zdm(k)*mSatom/mSO2mol
-            ENDDO
-          ENDIF ! emission grid cell
-        ENDDO ! klon loop
-      ENDIF ! emission period
-
+       DO ieru=1, nErupt
+          IF (year_cur==year_emit_vol(ieru).AND.mth_cur==mth_emit_vol(ieru).AND.&
+               day_cur>=day_emit_vol(ieru).AND.day_cur<(day_emit_vol(ieru)+injdur)) THEN
+             !
+             ! daily injection mass emission - NL
+             m_aer_emiss_vol_daily = m_aer_emiss_vol(ieru)/(REAL(injdur)*REAL(ponde_lonlat_vol(ieru)))
+             WRITE(lunout,*) 'IN traccoag DD m_aer_emiss_vol(ieru)=',m_aer_emiss_vol(ieru), &
+                  'ponde_lonlat_vol(ieru)=',ponde_lonlat_vol(ieru),'(injdur*ponde_lonlat_vol(ieru))', &
+                  (injdur*ponde_lonlat_vol(ieru)),'m_aer_emiss_vol_daily=',m_aer_emiss_vol_daily,'ieru=',ieru
+             WRITE(lunout,*) 'IN traccoag, dlon=',dlon
+             DO i=1,klon
+                !Pinatubo eruption at 15.14N, 120.35E
+                dlat_loc=180./RPI/2.*(boundslat(i,1)-boundslat(i,3)) ! dlat = half difference of boundary latitudes
+                WRITE(lunout,*) 'IN traccoag, dlat=',dlat_loc
+                IF ( xlat(i).GE.xlat_min_vol(ieru)-dlat_loc .AND. xlat(i).LT.xlat_max_vol(ieru)+dlat_loc .AND. &
+                     xlon(i).GE.xlon_min_vol(ieru)-dlon .AND. xlon(i).LT.xlon_max_vol(ieru)+dlon ) THEN
+                   !
+                   WRITE(lunout,*) 'coordinates of volcanic injection point=',xlat(i),xlon(i),day_cur,mth_cur,year_cur
+                   WRITE(lunout,*) 'DD m_aer_emiss_vol_daily=',m_aer_emiss_vol_daily
+                   !         compute altLMDz
+                   altLMDz(:)=0.0
+                   DO k=1, klev
+                      zrho=pplay(i,k)/t_seri(i,k)/RD       !air density in kg/m3
+                      zdm(k)=(paprs(i,k)-paprs(i,k+1))/RG  !mass of layer in kg
+                      zdz=zdm(k)/zrho                      !thickness of layer in m
+                      altLMDz(k+1)=altLMDz(k)+zdz          !altitude of interface
+                   ENDDO
+
+                   SELECT CASE(flag_sulf_emit_distrib)
+                   
+                   CASE(0) ! Gaussian distribution
+                   !compute distribution of emission to vertical model layers (based on Gaussian peak in altitude)
+                   f_lay_sum=0.0
+                   DO k=1, klev
+                      f_lay_emiss(k)=0.0
+                      DO i_int=1, n_int_alt
+                         alt=altLMDz(k)+float(i_int)*(altLMDz(k+1)-altLMDz(k))/float(n_int_alt)
+                         f_lay_emiss(k)=f_lay_emiss(k)+1./(sqrt(2.*RPI)*sigma_alt_vol(ieru))* &
+                              &              exp(-0.5*((alt-altemiss_vol(ieru))/sigma_alt_vol(ieru))**2.)*   &
+                              &              (altLMDz(k+1)-altLMDz(k))/float(n_int_alt)
+                      ENDDO
+                      f_lay_sum=f_lay_sum+f_lay_emiss(k)
+                   ENDDO
+                   
+                   CASE(1) ! Uniform distribution
+                   ! In this case, parameter sigma_alt_vol(ieru) is considered to be half the
+                   ! height of the injection, centered around altemiss_vol(ieru)
+                   DO k=1, klev
+                      f_lay_emiss(k)=max(min(altemiss_vol(ieru)+sigma_alt_vol(ieru),altLMDz(k+1))- &
+                      & max(altemiss_vol(ieru)-sigma_alt_vol(ieru),altLMDz(k)),0.)/(2.*sigma_alt_vol(ieru))
+                      f_lay_sum=f_lay_sum+f_lay_emiss(k)
+                   ENDDO
+
+                   END SELECT        ! End CASE over flag_sulf_emit_distrib)
+
+                   WRITE(lunout,*) "IN traccoag m_aer_emiss_vol=",m_aer_emiss_vol(ieru)
+                   WRITE(lunout,*) "IN traccoag f_lay_emiss=",f_lay_emiss
+                   !correct for step integration error
+                   f_lay_emiss(:)=f_lay_emiss(:)/f_lay_sum
+                   !emission as SO2 gas (with m(SO2)=64/32*m_aer_emiss)
+                   !vertically distributed emission
+                   DO k=1, klev
+                      ! stretch emission over one day of Pinatubo eruption
+                      emission=m_aer_emiss_vol_daily*(mSO2mol/mSatom)/m_air_gridbox(i,k)*f_lay_emiss(k)/1./(86400.-pdtphys)
+                      tr_seri(i,k,id_SO2_strat)=tr_seri(i,k,id_SO2_strat)+emission*pdtphys
+                      budg_emi_so2(i)=budg_emi_so2(i)+emission*zdm(k)*mSatom/mSO2mol
+                   ENDDO
+                ENDIF ! emission grid cell
+             ENDDO ! klon loop
+             WRITE(lunout,*) "IN traccoag (ieru=",ieru,") m_aer_emiss_vol_daily=",m_aer_emiss_vol_daily
+          ENDIF ! emission period
+       ENDDO ! eruption number
+       
     CASE(2) ! stratospheric aerosol injections (SAI)
 !
@@ -217,10 +233,9 @@
 !       SAI standard scenario with continuous emission from 1 grid point at the equator
 !       SAI emission on single month
-!       IF  ((mth_cur==4 .AND. &
 !       SAI continuous emission o
-        IF  ( xlat(i).GE.xlat_sai-dlat .AND. xlat(i).LT.xlat_sai+dlat .AND. &
+        dlat_loc=180./RPI/2.*(boundslat(i,1)-boundslat(i,3)) ! dlat = half difference of boundary latitudes
+        IF  ( xlat(i).GE.xlat_sai-dlat_loc .AND. xlat(i).LT.xlat_sai+dlat_loc .AND. &
           &   xlon(i).GE.xlon_sai-dlon .AND. xlon(i).LT.xlon_sai+dlon ) THEN
 !
-          PRINT *,'coordinates of SAI point=',xlat(i), xlon(i), day_cur, mth_cur, year_cur
 !         compute altLMDz
           altLMDz(:)=0.0
@@ -231,16 +246,33 @@
             altLMDz(k+1)=altLMDz(k)+zdz          !altitude of interface
           ENDDO
+
+          SELECT CASE(flag_sulf_emit_distrib)
+
+          CASE(0) ! Gaussian distribution
           !compute distribution of emission to vertical model layers (based on Gaussian peak in altitude)
           f_lay_sum=0.0
-          DO k=1, klev
-            f_lay_emiss(k)=0.0
-            DO i_int=1, n_int_alt
-              alt=altLMDz(k)+float(i_int)*(altLMDz(k+1)-altLMDz(k))/float(n_int_alt)
-              f_lay_emiss(k)=f_lay_emiss(k)+1./(sqrt(2.*RPI)*sigma_alt_sai)* &
-              &              exp(-0.5*((alt-altemiss_sai)/sigma_alt_sai)**2.)*   & 
-              &              (altLMDz(k+1)-altLMDz(k))/float(n_int_alt) 
-            ENDDO
-            f_lay_sum=f_lay_sum+f_lay_emiss(k)
-          ENDDO
+               DO k=1, klev
+                     f_lay_emiss(k)=0.0
+                     DO i_int=1, n_int_alt
+                         alt=altLMDz(k)+float(i_int)*(altLMDz(k+1)-altLMDz(k))/float(n_int_alt)
+                         f_lay_emiss(k)=f_lay_emiss(k)+1./(sqrt(2.*RPI)*sigma_alt_sai)* &
+                         &              exp(-0.5*((alt-altemiss_sai)/sigma_alt_sai)**2.)*   & 
+                         &              (altLMDz(k+1)-altLMDz(k))/float(n_int_alt) 
+                     ENDDO
+                     f_lay_sum=f_lay_sum+f_lay_emiss(k)
+               ENDDO
+
+          CASE(1) ! Uniform distribution
+          f_lay_sum=0.0
+          ! In this case, parameter sigma_alt_vol(ieru) is considered to be half
+          ! the height of the injection, centered around altemiss_sai
+               DO k=1, klev
+                    f_lay_emiss(k)=max(min(altemiss_sai+sigma_alt_sai,altLMDz(k+1))- &
+                    & max(altemiss_sai-sigma_alt_sai,altLMDz(k)),0.)/(2.*sigma_alt_sai)
+                    f_lay_sum=f_lay_sum+f_lay_emiss(k)
+               ENDDO
+
+          END SELECT ! Gaussian or uniform distribution
+
           !correct for step integration error
           f_lay_emiss(:)=f_lay_emiss(:)/f_lay_sum
@@ -249,13 +281,87 @@
           DO k=1, klev
             ! stretch emission over whole year (360d)
-            emission=m_aer_emiss_sai*(mSO2mol/mSatom)/m_air_gridbox(i,k)*f_lay_emiss(k)/360./86400.  
+            emission=m_aer_emiss_sai*(mSO2mol/mSatom)/m_air_gridbox(i,k)*f_lay_emiss(k)/FLOAT(year_len)/86400.  
             tr_seri(i,k,id_SO2_strat)=tr_seri(i,k,id_SO2_strat)+emission*pdtphys
             budg_emi_so2(i)=budg_emi_so2(i)+emission*zdm(k)*mSatom/mSO2mol
           ENDDO
+
 !          !emission as monodisperse particles with 0.1um dry radius (BIN21)
 !          !vertically distributed emission
 !          DO k=1, klev
 !            ! stretch emission over whole year (360d)
-!            emission=m_aer_emiss*(mH2SO4mol/mSatom)/m_part_dry(21)/m_air_gridbox(i,k)*f_lay_emiss(k)/360./86400 
+!            emission=m_aer_emiss*(mH2SO4mol/mSatom)/m_part_dry(21)/m_air_gridbox(i,k)*f_lay_emiss(k)/FLOAT(year_len)/86400.
+!            tr_seri(i,k,id_BIN01_strat+20)=tr_seri(i,k,id_BIN01_strat+20)+emission*pdtphys 
+!            budg_emi_part(i)=budg_emi_part(i)+emission*zdm(k)*mSatom/mH2SO4mol
+!          ENDDO
+        ENDIF ! emission grid cell
+      ENDDO ! klon loop
+
+    CASE(3) ! --- SAI injection over a single band of longitude and between
+            !     lat_min and lat_max
+
+    DO i=1,klon
+!       SAI scenario with continuous emission
+        dlat_loc=180./RPI/2.*(boundslat(i,1)-boundslat(i,3)) ! dlat = half difference of boundary latitudes
+        theta_min = max(xlat(i)-dlat_loc,xlat_min_sai)
+        theta_max = min(xlat(i)+dlat_loc,xlat_max_sai)
+        IF  ( xlat(i).GE.xlat_min_sai-dlat_loc .AND. xlat(i).LT.xlat_max_sai+dlat_loc .AND. &
+          &   xlon(i).GE.xlon_sai-dlon .AND. xlon(i).LT.xlon_sai+dlon ) THEN
+!
+!         compute altLMDz
+          altLMDz(:)=0.0
+          DO k=1, klev
+            zrho=pplay(i,k)/t_seri(i,k)/RD       !air density in kg/m3
+            zdm(k)=(paprs(i,k)-paprs(i,k+1))/RG  !mass of layer in kg
+            zdz=zdm(k)/zrho                      !thickness of layer in m
+            altLMDz(k+1)=altLMDz(k)+zdz          !altitude of interface
+          ENDDO
+
+          SELECT CASE(flag_sulf_emit_distrib)
+
+          CASE(0) ! Gaussian distribution
+          !compute distribution of emission to vertical model layers (based on
+          !Gaussian peak in altitude)
+          f_lay_sum=0.0
+               DO k=1, klev
+                     f_lay_emiss(k)=0.0
+                     DO i_int=1, n_int_alt
+                         alt=altLMDz(k)+float(i_int)*(altLMDz(k+1)-altLMDz(k))/float(n_int_alt)
+                         f_lay_emiss(k)=f_lay_emiss(k)+1./(sqrt(2.*RPI)*sigma_alt_sai)* &
+                         & exp(-0.5*((alt-altemiss_sai)/sigma_alt_sai)**2.)*   &
+                         & (altLMDz(k+1)-altLMDz(k))/float(n_int_alt)
+                     ENDDO
+                     f_lay_sum=f_lay_sum+f_lay_emiss(k)
+               ENDDO
+
+          CASE(1) ! Uniform distribution
+          f_lay_sum=0.0
+          ! In this case, parameter sigma_alt_vol(ieru) is considered to be half
+          ! the height of the injection, centered around altemiss_sai
+               DO k=1, klev
+                    f_lay_emiss(k)=max(min(altemiss_sai+sigma_alt_sai,altLMDz(k+1))- &
+                    & max(altemiss_sai-sigma_alt_sai,altLMDz(k)),0.)/(2.*sigma_alt_sai)
+                    f_lay_sum=f_lay_sum+f_lay_emiss(k)
+               ENDDO
+
+          END SELECT ! Gaussian or uniform distribution
+
+          !correct for step integration error
+          f_lay_emiss(:)=f_lay_emiss(:)/f_lay_sum
+          !emission as SO2 gas (with m(SO2)=64/32*m_aer_emiss)
+          !vertically distributed emission
+          DO k=1, klev
+            ! stretch emission over whole year (360d)
+            emission=m_aer_emiss_sai*(mSO2mol/mSatom)/m_air_gridbox(i,k)*f_lay_emiss(k)/ &
+                      & FLOAT(year_len)/86400.*(sin(theta_max/180.*RPI)-sin(theta_min/180.*RPI))/ & 
+                      & (sin(xlat_max_sai/180.*RPI)-sin(xlat_min_sai/180.*RPI))
+            tr_seri(i,k,id_SO2_strat)=tr_seri(i,k,id_SO2_strat)+emission*pdtphys
+            budg_emi_so2(i)=budg_emi_so2(i)+emission*zdm(k)*mSatom/mSO2mol
+          ENDDO
+
+!          !emission as monodisperse particles with 0.1um dry radius (BIN21)
+!          !vertically distributed emission
+!          DO k=1, klev
+!            ! stretch emission over whole year (360d)
+!            emission=m_aer_emiss*(mH2SO4mol/mSatom)/m_part_dry(21)/m_air_gridbox(i,k)*f_lay_emiss(k)/year_len/86400 
 !            tr_seri(i,k,id_BIN01_strat+20)=tr_seri(i,k,id_BIN01_strat+20)+emission*pdtphys 
 !            budg_emi_part(i)=budg_emi_part(i)+emission*zdm(k)*mSatom/mH2SO4mol
@@ -291,5 +397,6 @@
         IF (mdw(it) .LT. 2.5e-6) THEN
           !surf_PM25_sulf(i)=surf_PM25_sulf(i)+tr_seri(i,1,it+nbtr_sulgas)*m_part(i,1,it) &
-          !assume that particles consist of ammonium sulfate at the surface (132g/mol) and are dry at T = 20 deg. C and 50 perc. humidity
+          !assume that particles consist of ammonium sulfate at the surface (132g/mol) 
+          !and are dry at T = 20 deg. C and 50 perc. humidity
           surf_PM25_sulf(i)=surf_PM25_sulf(i)+tr_seri(i,1,it+nbtr_sulgas) &
                            & *132./98.*dens_aer_dry*4./3.*RPI*(mdw(it)/2.)**3 &
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/YOMCST.h
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/YOMCST.h	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/YOMCST.h	(revision 3605)
@@ -20,5 +20,6 @@
       REAL RSIGMA
 ! A1.4 Thermodynamic gas phase
-      REAL R,RMD,RMO3,RMCO2,RMC,RMV,RD,RV,RCPD,RCPV,RCVD,RCVV
+      REAL RMO3,RMCO2,RMC,RMCH4,RMN2O,RMCFC11,RMCFC12
+      REAL R,RMD,RMV,RD,RV,RCPD,RCPV,RCVD,RCVV
       REAL RKAPPA,RETV, eps_w
 ! A1.5,6 Thermodynamic liquid,solid phases
@@ -35,5 +36,6 @@
      &      ,RA    ,RG    ,R1SA                                         &
      &      ,RSIGMA                                                     &
-     &      ,R     ,RMD   ,RMO3  ,RMCO2, RMC, RMV   ,RD    ,RV    ,RCPD &
+     &      ,R     ,RMD   ,RMV   ,RD    ,RV    ,RCPD                    &
+     &      ,RMO3  ,RMCO2 ,RMC   ,RMCH4 ,RMN2O ,RMCFC11 ,RMCFC12        &
      &      ,RCPV  ,RCVD  ,RCVV  ,RKAPPA,RETV, eps_w                    &
      &      ,RCW   ,RCS                                                 &
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/acama_gwd_rando_m.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/acama_gwd_rando_m.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/acama_gwd_rando_m.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 module ACAMA_GWD_rando_m
 
@@ -120,5 +123,5 @@
   !$OMP THREADPRIVATE(firstcall,gwd_reproductibilite_mpiomp)
 
-    CHARACTER (LEN=20) :: modname='flott_gwd_rando'
+    CHARACTER (LEN=20) :: modname='acama_gwd_rando_m'
     CHARACTER (LEN=80) :: abort_message
 
@@ -208,11 +211,15 @@
 
     IF(DELTAT < DTIME)THEN
-       PRINT *, 'flott_gwd_rando: deltat < dtime!'
-       STOP 1
+!       PRINT *, 'flott_gwd_rando: deltat < dtime!'
+!       STOP 1
+       abort_message=' deltat < dtime! '
+       CALL abort_physic(modname,abort_message,1)
     ENDIF
 
     IF (KLEV < NW) THEN
-       PRINT *, 'flott_gwd_rando: you will have problem with random numbers'
-       STOP 1
+!       PRINT *, 'flott_gwd_rando: you will have problem with random numbers'
+!       STOP 1
+       abort_message=' you will have problem with random numbers'
+       CALL abort_physic(modname,abort_message,1)
     ENDIF
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/add_phys_tend_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/add_phys_tend_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/add_phys_tend_mod.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 !
 MODULE add_phys_tend_mod
@@ -98,5 +101,5 @@
 
 USE dimphy, ONLY: klon, klev
-USE phys_state_var_mod, ONLY : dtime
+USE phys_state_var_mod, ONLY : phys_tstep
 USE phys_local_var_mod, ONLY: u_seri, v_seri, ql_seri, qs_seri, q_seri, t_seri
 USE phys_state_var_mod, ONLY: ftsol
@@ -451,17 +454,17 @@
     ! ------------------------------------------------
 
-    d_qw_col(:) = (zqw_col(:,2)-zqw_col(:,1))/dtime
-    d_ql_col(:) = (zql_col(:,2)-zql_col(:,1))/dtime
-    d_qs_col(:) = (zqs_col(:,2)-zqs_col(:,1))/dtime
+    d_qw_col(:) = (zqw_col(:,2)-zqw_col(:,1))/phys_tstep
+    d_ql_col(:) = (zql_col(:,2)-zql_col(:,1))/phys_tstep
+    d_qs_col(:) = (zqs_col(:,2)-zqs_col(:,1))/phys_tstep
     d_qt_col(:) = d_qw_col(:) + d_ql_col(:) + d_qs_col(:)
 
-    d_ek_col(:) = (zek_col(:,2)-zek_col(:,1))/dtime
-
-    d_h_dair_col(:) = (zh_dair_col(:,2)-zh_dair_col(:,1))/dtime
-    d_h_qw_col(:) = (zh_qw_col(:,2)-zh_qw_col(:,1))/dtime
-    d_h_ql_col(:) = (zh_ql_col(:,2)-zh_ql_col(:,1))/dtime
-    d_h_qs_col(:) = (zh_qs_col(:,2)-zh_qs_col(:,1))/dtime
-
-    d_h_col = (zh_col(:,2)-zh_col(:,1))/dtime 
+    d_ek_col(:) = (zek_col(:,2)-zek_col(:,1))/phys_tstep
+
+    d_h_dair_col(:) = (zh_dair_col(:,2)-zh_dair_col(:,1))/phys_tstep
+    d_h_qw_col(:) = (zh_qw_col(:,2)-zh_qw_col(:,1))/phys_tstep
+    d_h_ql_col(:) = (zh_ql_col(:,2)-zh_ql_col(:,1))/phys_tstep
+    d_h_qs_col(:) = (zh_qs_col(:,2)-zh_qs_col(:,1))/phys_tstep
+
+    d_h_col = (zh_col(:,2)-zh_col(:,1))/phys_tstep 
 
   end if ! end if (fl_ebil .GT. 0)
@@ -494,5 +497,5 @@
 !======================================================================
 
-USE phys_state_var_mod, ONLY : dtime, ftsol
+USE phys_state_var_mod, ONLY : phys_tstep, ftsol
 USE geometry_mod, ONLY: longitude_deg, latitude_deg
 USE print_control_mod, ONLY: prt_level
@@ -621,10 +624,10 @@
     ! ------------------------------------------------
 
-    d_qw_col(:) = (zqw_col(:,2)-zqw_col(:,1))/dtime
-    d_ql_col(:) = (zql_col(:,2)-zql_col(:,1))/dtime
-    d_qs_col(:) = (zqs_col(:,2)-zqs_col(:,1))/dtime
+    d_qw_col(:) = (zqw_col(:,2)-zqw_col(:,1))/phys_tstep
+    d_ql_col(:) = (zql_col(:,2)-zql_col(:,1))/phys_tstep
+    d_qs_col(:) = (zqs_col(:,2)-zqs_col(:,1))/phys_tstep
     d_qt_col(:) = d_qw_col(:) + d_ql_col(:) + d_qs_col(:)
 
-    d_ek_col(:) = (zek_col(:,2)-zek_col(:,1))/dtime
+    d_ek_col(:) = (zek_col(:,2)-zek_col(:,1))/phys_tstep
 
    print *,'zdu ', zdu
@@ -632,10 +635,10 @@
    print *,'d_ek_col, zek_col(2), zek_col(1) ',d_ek_col(1), zek_col(1,2), zek_col(1,1)
 
-    d_h_dair_col(:) = (zh_dair_col(:,2)-zh_dair_col(:,1))/dtime
-    d_h_qw_col(:) = (zh_qw_col(:,2)-zh_qw_col(:,1))/dtime
-    d_h_ql_col(:) = (zh_ql_col(:,2)-zh_ql_col(:,1))/dtime
-    d_h_qs_col(:) = (zh_qs_col(:,2)-zh_qs_col(:,1))/dtime
-
-    d_h_col = (zh_col(:,2)-zh_col(:,1))/dtime 
+    d_h_dair_col(:) = (zh_dair_col(:,2)-zh_dair_col(:,1))/phys_tstep
+    d_h_qw_col(:) = (zh_qw_col(:,2)-zh_qw_col(:,1))/phys_tstep
+    d_h_ql_col(:) = (zh_ql_col(:,2)-zh_ql_col(:,1))/phys_tstep
+    d_h_qs_col(:) = (zh_qs_col(:,2)-zh_qs_col(:,1))/phys_tstep
+
+    d_h_col = (zh_col(:,2)-zh_col(:,1))/phys_tstep 
 
   end if ! end if (fl_ebil .GT. 0)
@@ -716,5 +719,5 @@
 
 USE dimphy, ONLY: klon, klev
-USE phys_state_var_mod, ONLY : dtime
+USE phys_state_var_mod, ONLY : phys_tstep
 USE phys_state_var_mod, ONLY : topsw, toplw, solsw, sollw, rain_con, snow_con
 USE geometry_mod, ONLY: longitude_deg, latitude_deg
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/alpale_th.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/alpale_th.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/alpale_th.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 SUBROUTINE alpale_th ( dtime, lmax_th, t_seri, cell_area,  &
                        cin, s2, n2,  &
@@ -62,4 +65,7 @@
  REAL umexp  ! expression of (1.-exp(-x))/x valid for all x, especially when x->0
  REAL x
+     CHARACTER (LEN=20) :: modname='alpale_th'
+     CHARACTER (LEN=80) :: abort_message
+     
  umexp(x) = max(sign(1.,x-1.e-3),0.)*(1.-exp(-x))/max(x,1.e-3) + &
             (1.-max(sign(1.,x-1.e-3),0.))*(1.-0.5*x*(1.-x/3.*(1.-0.25*x)))  !!! correct formula            (jyg)
@@ -104,5 +110,5 @@
              !
              IF (prt_level .GE. 10) THEN
-                print *,'cin, ale_bl_stat, alp_bl, alp_bl_stat ', &
+                WRITE(lunout,*)'cin, ale_bl_stat, alp_bl, alp_bl_stat ', &
                      cin, ale_bl_stat, alp_bl, alp_bl_stat
              ENDIF
@@ -122,7 +128,7 @@
              !
              IF (prt_level .GE. 10) THEN
-                print *,'random_notrig, tau_trig ', &
+                WRITE(lunout,*)'random_notrig, tau_trig ', &
                      random_notrig, tau_trig
-                print *,'s_trig,s2,n2 ', &
+                WRITE(lunout,*)'s_trig,s2,n2 ', &
                      s_trig,s2,n2
              ENDIF
@@ -178,5 +184,5 @@
              !
              IF (prt_level .GE. 10) THEN
-                print *,'proba_notrig, ale_bl_trig ', &
+                WRITE(lunout,*)'proba_notrig, ale_bl_trig ', &
                      proba_notrig, ale_bl_trig
              ENDIF
@@ -224,5 +230,5 @@
         !
         IF (prt_level .GE. 10) THEN
-           print *,'cin, ale_bl_stat, alp_bl_stat ', &
+           WRITE(lunout,*)'cin, ale_bl_stat, alp_bl_stat ', &
                 cin, ale_bl_stat, alp_bl_stat
         ENDIF
@@ -253,7 +259,7 @@
         !
         IF (prt_level .GE. 10) THEN
-           print *,'random_notrig, tau_trig ', &
+           WRITE(lunout,*)'random_notrig, tau_trig ', &
                 random_notrig, tau_trig
-           print *,'s_trig,s2,n2 ', &
+           WRITE(lunout,*)'s_trig,s2,n2 ', &
                 s_trig,s2,n2
         ENDIF
@@ -289,5 +295,5 @@
         !
         IF (prt_level .GE. 10) THEN
-           print *,'proba_notrig, ale_bl_trig ', &
+           WRITE(lunout,*)'proba_notrig, ale_bl_trig ', &
                 proba_notrig, ale_bl_trig
         ENDIF
@@ -300,5 +306,5 @@
 
           IF (prt_level .GE. 10) THEN
-             print *,'alpale_th: ale_bl_trig, alp_bl_stat, birth_rate ', &
+             WRITE(lunout,*)'alpale_th: ale_bl_trig, alp_bl_stat, birth_rate ', &
                       ale_bl_trig(1), alp_bl_stat(1), birth_rate(1)
           ENDIF
@@ -310,5 +316,5 @@
           if (iflag_coupl==2) then
              IF (prt_level .GE. 10) THEN
-                print*,'Couplage Thermiques/Emanuel seulement si T<0'
+                WRITE(lunout,*)'Couplage Thermiques/Emanuel seulement si T<0'
              ENDIF
              do i=1,klon
@@ -317,6 +323,8 @@
                 endif
              enddo
-    print *,'In order to run with iflag_coupl=2, you have to comment out the following stop'
-             STOP
+!    print *,'In order to run with iflag_coupl=2, you have to comment out the following stop'
+!             STOP
+             abort_message='In order to run with iflag_coupl=2, you have to comment out the following abort'
+             CALL abort_physic(modname,abort_message,1)
           endif
    RETURN
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/atm2geo.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/atm2geo.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/atm2geo.F90	(revision 3605)
@@ -5,18 +5,28 @@
   USE dimphy
   USE mod_phys_lmdz_para
+  USE mod_grid_phy_lmdz, only: grid_type, unstructured, regular_lonlat
   IMPLICIT NONE
   INCLUDE 'YOMCST.h'
+
+  CHARACTER (len = 6)                :: clmodnam
+  CHARACTER (len = 20)               :: modname = 'atm2geo'
+  CHARACTER (len = 80)               :: abort_message
+
 !
 ! Change wind local atmospheric coordinates to geocentric
 !
+! Geocentric :
+! axe x is eastward : crosses (0 N, 0 E) point.
+! axe y crosses (0 N, 90 E) point.
+! axe z is 'up' : crosses north pole
   INTEGER, INTENT (in)                 :: im, jm
-  REAL, DIMENSION (im,jm), INTENT (in) :: pte, ptn
+  REAL, DIMENSION (im,jm), INTENT (in) :: pte  ! Eastward vector component
+  REAL, DIMENSION (im,jm), INTENT (in) :: ptn  ! Northward vector component
   REAL, DIMENSION (im,jm), INTENT (in) :: plon, plat
-  REAL, DIMENSION (im,jm), INTENT(out) :: pxx, pyy, pzz
-  
-  REAL :: rad
-
+  REAL, DIMENSION (im,jm), INTENT(out) :: pxx, pyy, pzz  ! Component in the geocentric referential 
+  REAL :: rad, reps
 
   rad = rpi / 180.0E0
+  reps = 1.0e-5
   
   pxx(:,:) = & 
@@ -31,17 +41,32 @@
        + ptn(:,:) * COS(rad * plat (:,:))
   
-! Value at North Pole  
-  IF (is_north_pole_dyn) THEN
-     pxx(:, 1) = - pte (1, 1)
-     pyy(:, 1) = - ptn (1, 1) 
-     pzz(:, 1) = pzz(1,1)
-  ENDIF
+  IF (grid_type==regular_lonlat) THEN
+  ! Value at North Pole  
+    IF (is_north_pole_dyn) THEN
+       pxx(:, 1) = - pte (1, 1)
+       pyy(:, 1) = - ptn (1, 1) 
+       pzz(:, 1) = pzz(1,1) ! => 0
+    ENDIF
 
-! Value at South Pole
-  IF (is_south_pole_dyn) THEN
-     pxx(:,jm) = pxx(1,jm)
-     pyy(:,jm) = pyy(1,jm)
-     pzz(:,jm) = pzz(1,jm)
-  ENDIF
+  ! Value at South Pole
+    IF (is_south_pole_dyn) THEN
+      pxx(:,jm) = pxx(1,jm)
+       pyy(:,jm) = pyy(1,jm)
+       pzz(:,jm) = pzz(1,jm) ! => 0
+    ENDIF
+ 
+  ELSE IF (grid_type==unstructured) THEN
+     ! Pole nord pour Dynamico
+     WHERE ( plat(:,:) >= 90.0d+0-reps )
+        pxx (:,:) = -ptn (:,:)
+        pyy (:,:) =  pte (:,:)
+        pzz (:,:) =  0.0e0
+     END WHERE
+
+  ELSE
+     abort_message='Problem: unknown grid type'
+     CALL abort_physic(modname,abort_message,1)
+  END IF
+
   
 END SUBROUTINE atm2geo
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/borne_var_surf.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/borne_var_surf.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/borne_var_surf.F90	(revision 3605)
@@ -0,0 +1,111 @@
+SUBROUTINE borne_var_surf(klon,klev,nbsrf,                   &
+         iflag_bug_t2m_stab_ipslcm61,                        &
+         t1,q1,u1,v1,                                        &
+         ftsol, qsurf, pctsrf, paprs,                        &
+         t2m, q2m, u10m, v10m,                               &
+         zt2m_cor, zq2m_cor, zu10m_cor, zv10m_cor,           &
+         zrh2m_cor, zqsat2m_cor)
+
+IMPLICIT NONE
+
+!==================================================================
+! Declarations
+!==================================================================
+
+! arguments
+INTEGER klon,klev,nbsrf,iflag_bug_t2m_stab_ipslcm61
+REAL,DIMENSION(klon),INTENT(IN) :: t1, q1, u1, v1
+REAL,DIMENSION(klon,nbsrf),INTENT(IN) :: t2m, q2m, u10m, v10m
+REAL,DIMENSION(klon,nbsrf),INTENT(IN) :: ftsol, pctsrf
+REAL,DIMENSION(klon,klev+1),INTENT(IN) :: paprs 
+REAL,DIMENSION(klon),INTENT(IN) :: qsurf
+REAL,DIMENSION (klon),INTENT(OUT) :: zt2m_cor, zq2m_cor, zu10m_cor, zv10m_cor
+REAL,DIMENSION (klon),INTENT(OUT)  :: zrh2m_cor, zqsat2m_cor
+
+
+! local
+INTEGER i,nsrf
+REAL,DIMENSION (klon,nbsrf) :: t2m_cor, q2m_cor, u10m_cor, v10m_cor
+REAL                               :: zx_qs1, zcor1, zdelta1
+include "YOMCST.h"
+include "YOETHF.h"
+include "FCTTRE.h"
+!==================================================================
+! Correction of sub surface variables
+!==================================================================
+
+zrh2m_cor=0.
+zqsat2m_cor=0.
+
+DO nsrf=1,nbsrf
+   DO i=1,klon
+    t2m_cor(i,nsrf)=t2m(i,nsrf)
+    q2m_cor(i,nsrf)=q2m(i,nsrf)
+    u10m_cor(i,nsrf)=u10m(i,nsrf)
+    v10m_cor(i,nsrf)=v10m(i,nsrf)
+     IF(iflag_bug_t2m_stab_ipslcm61.EQ.-2.AND.q2m(i,nsrf).LT.0.) THEN
+      t2m_cor(i,nsrf)=MIN(t2m(i,nsrf),MAX(t1(i),ftsol(i,nsrf)))
+      t2m_cor(i,nsrf)=MAX(t2m_cor(i,nsrf),MIN(t1(i),ftsol(i,nsrf)))
+      q2m_cor(i,nsrf)=MIN(q2m(i,nsrf),MAX(q1(i),qsurf(i)))
+      q2m_cor(i,nsrf)=MAX(q2m_cor(i,nsrf),MIN(q1(i),qsurf(i)))
+      q2m_cor(i,nsrf)=MAX(q2m_cor(i,nsrf),0.)
+      u10m_cor(i,nsrf)=SIGN(MIN(ABS(u1(i)),ABS(u10m(i,nsrf))),u1(i))
+      v10m_cor(i,nsrf)=SIGN(MIN(ABS(v1(i)),ABS(v10m(i,nsrf))),v1(i))
+     ELSEIF(iflag_bug_t2m_stab_ipslcm61.EQ.-1.AND.(ftsol(i,nsrf).LE.t1(i).OR.q2m(i,nsrf).LT.0.)) THEN
+      t2m_cor(i,nsrf)=MIN(t2m(i,nsrf),MAX(t1(i),ftsol(i,nsrf)))
+      t2m_cor(i,nsrf)=MAX(t2m_cor(i,nsrf),MIN(t1(i),ftsol(i,nsrf)))
+      q2m_cor(i,nsrf)=MIN(q2m(i,nsrf),MAX(q1(i),qsurf(i)))
+      q2m_cor(i,nsrf)=MAX(q2m_cor(i,nsrf),MIN(q1(i),qsurf(i)))
+      q2m_cor(i,nsrf)=MAX(q2m_cor(i,nsrf),0.)
+      u10m_cor(i,nsrf)=SIGN(MIN(ABS(u1(i)),ABS(u10m(i,nsrf))),u1(i))
+      v10m_cor(i,nsrf)=SIGN(MIN(ABS(v1(i)),ABS(v10m(i,nsrf))),v1(i))
+     ELSEIF(iflag_bug_t2m_stab_ipslcm61.EQ.1.AND.ftsol(i,nsrf).LE.t1(i)) THEN
+      t2m_cor(i,nsrf)=MIN(t2m(i,nsrf),MAX(t1(i),ftsol(i,nsrf)))
+      t2m_cor(i,nsrf)=MAX(t2m_cor(i,nsrf),MIN(t1(i),ftsol(i,nsrf)))
+      q2m_cor(i,nsrf)=MIN(q2m(i,nsrf),MAX(q1(i),qsurf(i)))
+      q2m_cor(i,nsrf)=MAX(q2m_cor(i,nsrf),MIN(q1(i),qsurf(i)))
+      q2m_cor(i,nsrf)=MAX(q2m_cor(i,nsrf),0.)
+      u10m_cor(i,nsrf)=SIGN(MIN(ABS(u1(i)),ABS(u10m(i,nsrf))),u1(i))
+      v10m_cor(i,nsrf)=SIGN(MIN(ABS(v1(i)),ABS(v10m(i,nsrf))),v1(i))
+     ELSEIF(iflag_bug_t2m_stab_ipslcm61.EQ.0) THEN
+      t2m_cor(i,nsrf)=MIN(t2m(i,nsrf),MAX(t1(i),ftsol(i,nsrf)))
+      t2m_cor(i,nsrf)=MAX(t2m_cor(i,nsrf),MIN(t1(i),ftsol(i,nsrf)))
+      q2m_cor(i,nsrf)=MIN(q2m(i,nsrf),MAX(q1(i),qsurf(i)))
+      q2m_cor(i,nsrf)=MAX(q2m_cor(i,nsrf),MIN(q1(i),qsurf(i)))
+      q2m_cor(i,nsrf)=MAX(q2m_cor(i,nsrf),0.)
+      u10m_cor(i,nsrf)=SIGN(MIN(ABS(u1(i)),ABS(u10m(i,nsrf))),u1(i))
+      v10m_cor(i,nsrf)=SIGN(MIN(ABS(v1(i)),ABS(v10m(i,nsrf))),v1(i))
+     ENDIF
+!!!
+     zdelta1 = MAX(0.,SIGN(1., rtt-t2m_cor(i,nsrf) ))
+     zx_qs1  = r2es * FOEEW(t2m_cor(i,nsrf),zdelta1)/paprs(i,1)
+     zx_qs1  = MIN(0.5,zx_qs1)
+     zcor1   = 1./(1.-RETV*zx_qs1)
+     zx_qs1  = zx_qs1*zcor1
+     zrh2m_cor(i) = zrh2m_cor(i) + q2m_cor(i,nsrf)/zx_qs1 * pctsrf(i,nsrf)
+     zqsat2m_cor(i) = zqsat2m_cor(i) + zx_qs1  * pctsrf(i,nsrf)
+!!!
+   ENDDO
+ENDDO
+
+!==================================================================
+! Agregation of sub surfaces
+!==================================================================
+
+zt2m_cor=0.
+zq2m_cor=0.
+zu10m_cor=0.
+zv10m_cor=0.
+DO nsrf = 1, nbsrf
+   DO i = 1, klon
+      zt2m_cor(i)  = zt2m_cor(i)  + t2m_cor(i,nsrf)  * pctsrf(i,nsrf)
+      zq2m_cor(i)  = zq2m_cor(i)  + q2m_cor(i,nsrf)  * pctsrf(i,nsrf)
+      zu10m_cor(i) = zu10m_cor(i) + u10m_cor(i,nsrf) * pctsrf(i,nsrf)
+      zv10m_cor(i) = zv10m_cor(i) + v10m_cor(i,nsrf) * pctsrf(i,nsrf)
+   ENDDO
+ENDDO
+
+RETURN
+END
+
+
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/calcul_divers.h
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/calcul_divers.h	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/calcul_divers.h	(revision 3605)
@@ -1,4 +1,5 @@
 !
-! $Header$
+! $Id$
+!
 !
 ! Initialisations diverses au tout debut
@@ -14,5 +15,5 @@
 
 ! Calcul fin de journee : total_rain, nday_rain
-      IF(MOD(itap,NINT(un_jour/dtime)).EQ.0) THEN
+      IF(MOD(itap,NINT(un_jour/phys_tstep)).EQ.0) THEN
 !        print*,'calcul nday_rain itap ',itap
          DO i = 1, klon
@@ -23,6 +24,6 @@
 
 ! Initialisation fin de mois
-      IF(MOD(itap-itapm1,NINT(mth_len*un_jour/dtime)).EQ.0) THEN
-        itapm1=itapm1+NINT(mth_len*un_jour/dtime)
+      IF(MOD(itap-itapm1,NINT(mth_len*un_jour/phys_tstep)).EQ.0) THEN
+        itapm1=itapm1+NINT(mth_len*un_jour/phys_tstep)
 !       print*,'initialisation itapm1 ',itapm1
       ENDIF
@@ -35,5 +36,5 @@
      t2m_max_mon=0.
   ENDIF
-  IF(MOD(itap,NINT(un_jour/dtime)).EQ.1) THEN
+  IF(MOD(itap,NINT(un_jour/phys_tstep)).EQ.1) THEN
      zt2m_min_mon=zt2m
      zt2m_max_mon=zt2m
@@ -45,5 +46,5 @@
      ENDDO
 !fin de journee
-  IF(MOD(itap,NINT(un_jour/dtime)).EQ.0) THEN
+  IF(MOD(itap,NINT(un_jour/phys_tstep)).EQ.0) THEN
    t2m_min_mon=t2m_min_mon+zt2m_min_mon 
    t2m_max_mon=t2m_max_mon+zt2m_max_mon 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/carbon_cycle_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/carbon_cycle_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/carbon_cycle_mod.F90	(revision 3605)
@@ -7,11 +7,8 @@
 !  -----------------------
 ! Control module for the carbon CO2 tracers :
-!   - Identification
-!   - Get concentrations comming from coupled model or read from file to tracers
-!   - Calculate new RCO2 for radiation scheme
-!   - Calculate new carbon flux for sending to coupled models (PISCES and ORCHIDEE)
-!
-! Module permettant de mettre a jour les champs (puits et sources) pour le
-! transport de CO2 en online (IPSL-CM et LMDZOR) et offline (lecture de carte)
+!   - Initialisation of carbon cycle fields
+!   - Definition of fluxes to be exchanged
+!
+! Rest of code is in tracco2i.F90
 !
 ! Le cas online/offline est defini par le flag carbon_cycle_cpl (y/n)
@@ -35,13 +32,19 @@
   SAVE
   PRIVATE
-  PUBLIC :: carbon_cycle_init, carbon_cycle, infocfields_init
+  PUBLIC :: carbon_cycle_init, infocfields_init
 
 ! Variables read from parmeter file physiq.def
+  LOGICAL, PUBLIC :: carbon_cycle_cpl       ! Coupling of CO2 fluxes between LMDZ/ORCHIDEE and LMDZ/OCEAN(PISCES) 
+!$OMP THREADPRIVATE(carbon_cycle_cpl)
   LOGICAL, PUBLIC :: carbon_cycle_tr        ! 3D transport of CO2 in the atmosphere, parameter read in conf_phys
 !$OMP THREADPRIVATE(carbon_cycle_tr)
-  LOGICAL, PUBLIC :: carbon_cycle_cpl       ! Coupling of CO2 fluxes between LMDZ/ORCHIDEE and LMDZ/OCEAN(PISCES) 
-!$OMP THREADPRIVATE(carbon_cycle_cpl)
+  LOGICAL, PUBLIC :: carbon_cycle_rad       ! CO2 interactive radiatively 
+!$OMP THREADPRIVATE(carbon_cycle_rad)
   INTEGER, PUBLIC :: level_coupling_esm ! Level of coupling for the ESM - 0, 1, 2, 3
 !$OMP THREADPRIVATE(level_coupling_esm)
+  REAL, PUBLIC :: RCO2_glo
+!$OMP THREADPRIVATE(RCO2_glo)
+  REAL, PUBLIC :: RCO2_tot
+!$OMP THREADPRIVATE(RCO2_tot)
 
   LOGICAL :: carbon_cycle_emis_comp_omp=.FALSE.
@@ -78,4 +81,18 @@
   REAL, DIMENSION(:), ALLOCATABLE, PUBLIC :: fco2_bb ! Emission from biomass burning [kgCO2/m2/s]
 !$OMP THREADPRIVATE(fco2_bb)
+  REAL, DIMENSION(:), ALLOCATABLE, PUBLIC :: fco2_land  ! Net flux from terrestrial ecocsystems [kgCO2/m2/s]
+!$OMP THREADPRIVATE(fco2_land)
+  REAL, DIMENSION(:), ALLOCATABLE, PUBLIC :: fco2_land_nbp  ! Net flux from terrestrial ecocsystems [kgCO2/m2/s]
+!$OMP THREADPRIVATE(fco2_land_nbp)
+  REAL, DIMENSION(:), ALLOCATABLE, PUBLIC :: fco2_land_nep  ! Net flux from terrestrial ecocsystems [kgCO2/m2/s]
+!$OMP THREADPRIVATE(fco2_land_nep)
+  REAL, DIMENSION(:), ALLOCATABLE, PUBLIC :: fco2_land_fLuc  ! Net flux from terrestrial ecocsystems [kgCO2/m2/s]
+!$OMP THREADPRIVATE(fco2_land_fLuc)
+  REAL, DIMENSION(:), ALLOCATABLE, PUBLIC :: fco2_land_fwoodharvest  ! Net flux from terrestrial ecocsystems [kgCO2/m2/s]
+!$OMP THREADPRIVATE(fco2_land_fwoodharvest)
+  REAL, DIMENSION(:), ALLOCATABLE, PUBLIC :: fco2_land_fHarvest  ! Net flux from terrestrial ecocsystems [kgCO2/m2/s]
+!$OMP THREADPRIVATE(fco2_land_fHarvest)
+  REAL, DIMENSION(:), ALLOCATABLE, PUBLIC :: fco2_ocean ! Net flux from ocean [kgCO2/m2/s]
+!$OMP THREADPRIVATE(fco2_ocean)
 
   REAL, DIMENSION(:,:), ALLOCATABLE :: dtr_add       ! Tracer concentration to be injected 
@@ -91,4 +108,6 @@
   REAL, DIMENSION(:), ALLOCATABLE, PUBLIC :: co2_send ! Field allocated in phyetat0
 !$OMP THREADPRIVATE(co2_send)
+
+  INTEGER, PARAMETER, PUBLIC :: id_CO2=1              !--temporaire OB -- to be changed
 
 ! nbfields : total number of fields 
@@ -181,5 +200,5 @@
 CONTAINS
   
-  SUBROUTINE carbon_cycle_init(tr_seri, pdtphys, aerosol, radio)
+  SUBROUTINE carbon_cycle_init()
 ! This subroutine is called from traclmdz_init, only at first timestep.
 ! - Read controle parameters from .def input file
@@ -189,10 +208,5 @@
 
     USE dimphy
-    USE geometry_mod, ONLY : cell_area 
-    USE mod_phys_lmdz_transfert_para
-    USE infotrac_phy, ONLY: nbtr, nqo, niadv, tname
     USE IOIPSL
-    USE surface_data, ONLY : ok_veget, type_ocean
-    USE phys_cal_mod, ONLY : mth_len
     USE print_control_mod, ONLY: lunout
 
@@ -200,387 +214,53 @@
     INCLUDE "clesphys.h"
  
-! Input argument
-    REAL,DIMENSION(klon,klev,nbtr),INTENT(IN) :: tr_seri ! Concentration Traceur [U/KgA]  
-    REAL,INTENT(IN)                           :: pdtphys ! length of time step in physiq (sec)
-
-! InOutput arguments
-    LOGICAL,DIMENSION(nbtr), INTENT(INOUT) :: aerosol
-    LOGICAL,DIMENSION(nbtr), INTENT(INOUT) :: radio
-
 ! Local variables
-    INTEGER               :: ierr, it, iiq, itc
-    INTEGER               :: teststop
-
-! 1) Read controle parameters from .def input file
-! ------------------------------------------------
-    ! Read fosil fuel value if no transport
-    IF (.NOT. carbon_cycle_tr) THEN
-!$OMP MASTER
-       fos_fuel_s_omp = 0.
-       CALL getin ('carbon_cycle_fos_fuel',fos_fuel_s_omp)
-!$OMP END MASTER
-!$OMP BARRIER
-       fos_fuel_s=fos_fuel_s_omp
-       WRITE(lunout,*) 'carbon_cycle_fos_fuel = ', fos_fuel_s 
-    END IF
-
-    ! Read parmeter for calculation compatible emission
-    IF (.NOT. carbon_cycle_tr) THEN
-!$OMP MASTER
-       carbon_cycle_emis_comp_omp=.FALSE.
-       CALL getin('carbon_cycle_emis_comp',carbon_cycle_emis_comp_omp)
-!$OMP END MASTER
-!$OMP BARRIER
-       carbon_cycle_emis_comp=carbon_cycle_emis_comp_omp
-       WRITE(lunout,*) 'carbon_cycle_emis_comp = ',carbon_cycle_emis_comp
-       IF (carbon_cycle_emis_comp) THEN
-          CALL abort_physic('carbon_cycle_init', 'carbon_cycle_emis_comp option not yet implemented!!',1)
-       END IF
-    END IF
-
-    ! Read parameter for interactive calculation of the CO2 value for the radiation scheme
-!$OMP MASTER
-    RCO2_inter_omp=.FALSE.
-    CALL getin('RCO2_inter',RCO2_inter_omp)
-!$OMP END MASTER
-!$OMP BARRIER
-    RCO2_inter=RCO2_inter_omp
-    WRITE(lunout,*) 'RCO2_inter = ', RCO2_inter
-    IF (RCO2_inter) THEN
-       WRITE(lunout,*) 'RCO2 will be recalculated once a day'
-       WRITE(lunout,*) 'RCO2 initial = ', RCO2
-    END IF
-
-
-! 2) Search for carbon tracers and set default values
-! ---------------------------------------------------
-    itc=0
-    DO it=1,nbtr
-!!       iiq=niadv(it+2)                                                            ! jyg
-       iiq=niadv(it+nqo)                                                            ! jyg
-       
-       SELECT CASE(tname(iiq))
-       CASE("fCO2_ocn")
-          itc = itc + 1
-          co2trac(itc)%name='fCO2_ocn'
-          co2trac(itc)%id=it
-          co2trac(itc)%file='fl_co2_ocean.nc'
-          IF (carbon_cycle_cpl .AND. type_ocean=='couple') THEN 
-             co2trac(itc)%cpl=.TRUE.
-             co2trac(itc)%updatefreq = 86400 ! Once a day as the coupling with OASIS/PISCES
-          ELSE
-             co2trac(itc)%cpl=.FALSE.
-             co2trac(itc)%updatefreq = 86400*mth_len ! Once a month
-          END IF
-       CASE("fCO2_land")
-          itc = itc + 1
-          co2trac(itc)%name='fCO2_land'
-          co2trac(itc)%id=it
-          co2trac(itc)%file='fl_co2_land.nc'
-          IF (carbon_cycle_cpl .AND. ok_veget) THEN 
-             co2trac(itc)%cpl=.TRUE.
-             co2trac(itc)%updatefreq = INT(pdtphys) ! Each timestep as the coupling with ORCHIDEE
-          ELSE
-             co2trac(itc)%cpl=.FALSE.
-!             co2trac(itc)%updatefreq = 10800   ! 10800sec = 3H
-             co2trac(itc)%updatefreq = 86400*mth_len ! Once a month
-          END IF
-       CASE("fCO2_land_use")
-          itc = itc + 1
-          co2trac(itc)%name='fCO2_land_use'
-          co2trac(itc)%id=it
-          co2trac(itc)%file='fl_co2_land_use.nc'
-          IF (carbon_cycle_cpl .AND. ok_veget) THEN 
-             co2trac(it)%cpl=.TRUE.
-             co2trac(itc)%updatefreq = INT(pdtphys) ! Each timestep as the coupling with ORCHIDEE
-          ELSE
-             co2trac(itc)%cpl=.FALSE.
-             co2trac(itc)%updatefreq = 10800   ! 10800sec = 3H
-          END IF
-       CASE("fCO2_fos_fuel")
-          itc = itc + 1
-          co2trac(itc)%name='fCO2_fos_fuel'
-          co2trac(itc)%id=it
-          co2trac(itc)%file='fossil_fuel.nc'
-          co2trac(itc)%cpl=.FALSE.       ! This tracer always read from file
-!         co2trac(itc)%updatefreq = 86400  ! 86400sec = 24H Cadule case
-          co2trac(itc)%updatefreq = 86400*mth_len ! Once a month
-       CASE("fCO2_bbg")
-          itc = itc + 1
-          co2trac(itc)%name='fCO2_bbg'
-          co2trac(itc)%id=it
-          co2trac(itc)%file='fl_co2_bbg.nc'
-          co2trac(itc)%cpl=.FALSE.       ! This tracer always read from file
-          co2trac(itc)%updatefreq = 86400*mth_len ! Once a month
-       CASE("fCO2")
-          ! fCO2 : One tracer transporting the total CO2 flux
-          itc = itc + 1
-          co2trac(itc)%name='fCO2'
-          co2trac(itc)%id=it
-          co2trac(itc)%file='fl_co2.nc'
-          IF (carbon_cycle_cpl) THEN 
-             co2trac(itc)%cpl=.TRUE.
-          ELSE
-             co2trac(itc)%cpl=.FALSE.
-          END IF
-          co2trac(itc)%updatefreq = 86400
-          ! DOES THIS WORK ???? Problematic due to implementation of the coupled fluxes...
-          CALL abort_physic('carbon_cycle_init','transport of total CO2 has to be implemented and tested',1)
-       END SELECT
-    END DO
-
-    ! Total number of carbon CO2 tracers
-    ntr_co2 = itc 
-    
-    ! Definition of control varaiables for the tracers
-    DO it=1,ntr_co2
-       aerosol(co2trac(it)%id) = .FALSE.
-       radio(co2trac(it)%id)   = .FALSE.
-    END DO
-    
-    ! Vector indicating which timestep to read for each tracer
-    ! Always start read in the beginning of the file
-    co2trac(:)%readstep = 0
-   
-
-! 3) Allocate variables
-! ---------------------
-    ! Allocate vector for storing fluxes to inject
-    ALLOCATE(dtr_add(klon,maxco2trac), stat=ierr)
-    IF (ierr /= 0) CALL abort_physic('carbon_cycle_init', 'pb in allocation 11',1)       
-    
-    ! Allocate variables for cumulating fluxes from ORCHIDEE
-    IF (RCO2_inter) THEN
-       IF (.NOT. carbon_cycle_tr .AND. carbon_cycle_cpl) THEN
-          ALLOCATE(fco2_land_day(klon), stat=ierr)
-          IF (ierr /= 0) CALL abort_physic('carbon_cycle_init', 'pb in allocation 2',1)
-          fco2_land_day(1:klon) = 0.
-          
-          ALLOCATE(fco2_lu_day(klon), stat=ierr)
-          IF (ierr /= 0) CALL abort_physic('carbon_cycle_init', 'pb in allocation 3',1)
-          fco2_lu_day(1:klon)   = 0.
-       END IF
-    END IF
-
-
-! 4) Test for compatibility
-! -------------------------
-!    IF (carbon_cycle_cpl .AND. type_ocean/='couple') THEN
-!       WRITE(lunout,*) 'Coupling with ocean model is needed for carbon_cycle_cpl'
-!       CALL abort_physic('carbon_cycle_init', 'coupled ocean is needed for carbon_cycle_cpl',1)
-!    END IF
-!
-!    IF (carbon_cycle_cpl .AND..NOT. ok_veget) THEN
-!       WRITE(lunout,*) 'Coupling with surface land model ORCHDIEE is needed for carbon_cycle_cpl'
-!       CALL abort_physic('carbon_cycle_init', 'ok_veget is needed for carbon_cycle_cpl',1)
-!    END IF
-
-    ! Compiler test : following should never happen
-    teststop=0
-    DO it=1,teststop
-       CALL abort_physic('carbon_cycle_init', 'Entering loop from 1 to 0',1)
-    END DO
-
-    IF (ntr_co2==0) THEN
-       ! No carbon tracers found in tracer.def. It is not possible to do carbon cycle 
-       WRITE(lunout,*) 'No carbon tracers found in tracer.def. Not ok with carbon_cycle_tr and/or carbon_cycle_cp'
-       CALL abort_physic('carbon_cycle_init', 'No carbon tracers found in tracer.def',1)
-    END IF
-    
-! 5) Calculate total area of the earth surface
-! --------------------------------------------
-    CALL reduce_sum(SUM(cell_area),airetot)
-    CALL bcast(airetot)
+    INTEGER               :: ierr
+
+    IF (carbon_cycle_cpl) THEN
+
+       ierr=0
+
+       IF (.NOT.ALLOCATED(fco2_land)) ALLOCATE(fco2_land(klon), stat=ierr)
+       IF (ierr /= 0) CALL abort_physic('carbon_cycle_init', 'pb in allocation fco2_land',1)
+       fco2_land(1:klon) = 0.
+
+       IF (.NOT.ALLOCATED(fco2_land_nbp)) ALLOCATE(fco2_land_nbp(klon), stat=ierr)
+       IF (ierr /= 0) CALL abort_physic('carbon_cycle_init', 'pb in allocation fco2_land_nbp',1)
+       fco2_land_nbp(1:klon) = 0.
+
+       IF (.NOT.ALLOCATED(fco2_land_nep)) ALLOCATE(fco2_land_nep(klon), stat=ierr)
+       IF (ierr /= 0) CALL abort_physic('carbon_cycle_init', 'pb in allocation fco2_land_nep',1)
+       fco2_land_nep(1:klon) = 0.
+
+       IF (.NOT.ALLOCATED(fco2_land_fLuc)) ALLOCATE(fco2_land_fLuc(klon), stat=ierr)
+       IF (ierr /= 0) CALL abort_physic('carbon_cycle_init', 'pb in allocation fco2_land_fLuc',1)
+       fco2_land_fLuc(1:klon) = 0.
+
+       IF (.NOT.ALLOCATED(fco2_land_fwoodharvest)) ALLOCATE(fco2_land_fwoodharvest(klon), stat=ierr)
+       IF (ierr /= 0) CALL abort_physic('carbon_cycle_init', 'pb in allocation fco2_land_fwoodharvest',1)
+       fco2_land_fwoodharvest(1:klon) = 0.
+
+       IF (.NOT.ALLOCATED(fco2_land_fHarvest)) ALLOCATE(fco2_land_fHarvest(klon), stat=ierr)
+       IF (ierr /= 0) CALL abort_physic('carbon_cycle_init', 'pb in allocation fco2_land_fHarvest',1)
+       fco2_land_fHarvest(1:klon) = 0.
+
+       IF (.NOT.ALLOCATED(fco2_ff)) ALLOCATE(fco2_ff(klon), stat=ierr)
+       IF (ierr /= 0) CALL abort_physic('carbon_cycle_init', 'pb in allocation fco2_ff',1)
+       fco2_ff(1:klon) = 0.
+
+       IF (.NOT.ALLOCATED(fco2_bb)) ALLOCATE(fco2_bb(klon), stat=ierr)
+       IF (ierr /= 0) CALL abort_physic('carbon_cycle_init', 'pb in allocation fco2_bb',1)
+       fco2_bb(1:klon) = 0.
+
+       IF (.NOT.ALLOCATED(fco2_ocean)) ALLOCATE(fco2_ocean(klon), stat=ierr)
+       IF (ierr /= 0) CALL abort_physic('carbon_cycle_init', 'pb in allocation fco2_ocean',1)
+       fco2_bb(1:klon) = 0.
+    ENDIF
 
   END SUBROUTINE carbon_cycle_init
 
-  SUBROUTINE carbon_cycle(nstep, pdtphys, pctsrf, tr_seri, source)
-! Subroutine for injection of co2 in the tracers
-!
-! - Find out if it is time to update
-! - Get tracer from coupled model or from file
-! - Calculate new RCO2 value for the radiation scheme
-! - Calculate CO2 flux to send to ocean and land models (PISCES and ORCHIDEE)
-
-    USE infotrac_phy, ONLY: nbtr
-    USE dimphy
-    USE mod_phys_lmdz_transfert_para
-    USE phys_cal_mod, ONLY : mth_cur, mth_len
-    USE phys_cal_mod, ONLY : day_cur
-    USE indice_sol_mod
-    USE print_control_mod, ONLY: lunout
-    USE geometry_mod, ONLY : cell_area
-
-    IMPLICIT NONE
-
-    INCLUDE "clesphys.h"
-    INCLUDE "YOMCST.h"
-
-! In/Output arguments
-    INTEGER,INTENT(IN) :: nstep      ! time step in physiq
-    REAL,INTENT(IN)    :: pdtphys    ! length of time step in physiq (sec)
-    REAL,DIMENSION(klon,nbsrf),INTENT(IN) :: pctsrf            ! Surface fraction
-    REAL, DIMENSION(klon,klev,nbtr), INTENT(INOUT)  :: tr_seri ! All tracers
-    REAL, DIMENSION(klon,nbtr), INTENT(INOUT)       :: source  ! Source for all tracers
-
-! Local variables
-    INTEGER :: it
-    LOGICAL :: newmonth ! indicates if a new month just started
-    LOGICAL :: newday   ! indicates if a new day just started
-    LOGICAL :: endday   ! indicated if last time step in a day
-
-    REAL, PARAMETER :: fact=1.E-15/2.12  ! transformation factor from gC/m2/day => ppm/m2/day
-    REAL, DIMENSION(klon) :: fco2_tmp
-    REAL :: sumtmp
-    REAL :: delta_co2_ppm
-    
-
-! 1) Calculate logicals indicating if it is a new month, new day or the last time step in a day (end day)
-! -------------------------------------------------------------------------------------------------------
-
-    newday = .FALSE.; endday = .FALSE.; newmonth = .FALSE.
-
-    IF (MOD(nstep,INT(86400./pdtphys))==1) newday=.TRUE.
-    IF (MOD(nstep,INT(86400./pdtphys))==0) endday=.TRUE.
-    IF (newday .AND. day_cur==1) newmonth=.TRUE.
-
-! 2)  For each carbon tracer find out if it is time to inject (update)
-! --------------------------------------------------------------------
-    DO it = 1, ntr_co2
-       IF ( MOD(nstep,INT(co2trac(it)%updatefreq/pdtphys)) == 1 ) THEN
-          co2trac(it)%updatenow = .TRUE.
-       ELSE
-          co2trac(it)%updatenow = .FALSE.
-       END IF
-    END DO
-
-! 3) Get tracer update
-! --------------------------------------
-    DO it = 1, ntr_co2
-       IF ( co2trac(it)%updatenow ) THEN
-          IF ( co2trac(it)%cpl ) THEN
-             ! Get tracer from coupled model
-             SELECT CASE(co2trac(it)%name)
-             CASE('fCO2_land')     ! from ORCHIDEE
-                dtr_add(:,it) = fco2_land_inst(:)*pctsrf(:,is_ter)*fact ! [ppm/m2/day]
-             CASE('fCO2_land_use') ! from ORCHIDEE
-                dtr_add(:,it) = fco2_lu_inst(:)  *pctsrf(:,is_ter)*fact ! [ppm/m2/day]
-             CASE('fCO2_ocn')      ! from PISCES
-                dtr_add(:,it) = fco2_ocn_day(:)  *pctsrf(:,is_oce)*fact ! [ppm/m2/day]
-             CASE DEFAULT
-                WRITE(lunout,*) 'Error with tracer ',co2trac(it)%name
-                CALL abort_physic('carbon_cycle', 'No coupling implemented for this tracer',1)
-             END SELECT
-          ELSE
-             ! Read tracer from file
-             co2trac(it)%readstep = co2trac(it)%readstep + 1 ! increment time step in file
-! Patricia   CALL read_map2D(co2trac(it)%file,'fco2',co2trac(it)%readstep,.FALSE.,dtr_add(:,it))
-             CALL read_map2D(co2trac(it)%file,'fco2',co2trac(it)%readstep,.TRUE.,dtr_add(:,it))
-
-             ! Converte from kgC/m2/h to kgC/m2/s
-             dtr_add(:,it) = dtr_add(:,it)/3600
-             ! Add individual treatment of values read from file
-             SELECT CASE(co2trac(it)%name)
-             CASE('fCO2_land')
-                dtr_add(:,it) = dtr_add(:,it) *pctsrf(:,is_ter)
-             CASE('fCO2_land_use')
-                dtr_add(:,it) = dtr_add(:,it) *pctsrf(:,is_ter)
-             CASE('fCO2_ocn')
-                dtr_add(:,it) = dtr_add(:,it) *pctsrf(:,is_oce)
-! Patricia :
-!             CASE('fCO2_fos_fuel')
-!                dtr_add(:,it) = dtr_add(:,it)/mth_len
-!                co2trac(it)%readstep = 0 ! Always read same value for fossil fuel(Cadule case)
-             END SELECT
-          END IF
-       END IF
-    END DO
-
-! 4) Update co2 tracers : 
-!    Loop over all carbon tracers and add source
-! ------------------------------------------------------------------
-    IF (carbon_cycle_tr) THEN
-       DO it = 1, ntr_co2
-          IF (.FALSE.) THEN
-             tr_seri(1:klon,1,co2trac(it)%id) = tr_seri(1:klon,1,co2trac(it)%id) + dtr_add(1:klon,it)
-             source(1:klon,co2trac(it)%id) = 0.
-          ELSE
-             source(1:klon,co2trac(it)%id) = dtr_add(1:klon,it)
-          END IF
-       END DO
-    END IF
-
-
-! 5) Calculations for new CO2 value for the radiation scheme(instead of reading value from .def)
-! ----------------------------------------------------------------------------------------------
-    IF (RCO2_inter) THEN
-       ! Cumulate fluxes from ORCHIDEE at each timestep
-       IF (.NOT. carbon_cycle_tr .AND. carbon_cycle_cpl) THEN
-          IF (newday) THEN ! Reset cumulative variables once a day 
-             fco2_land_day(1:klon) = 0.
-             fco2_lu_day(1:klon)   = 0.
-          END IF
-          fco2_land_day(1:klon) = fco2_land_day(1:klon) + fco2_land_inst(1:klon) ![gC/m2/day]
-          fco2_lu_day(1:klon)   = fco2_lu_day(1:klon)   + fco2_lu_inst(1:klon)   ![gC/m2/day]
-       END IF
-
-       ! At the end of a new day, calculate a mean scalare value of CO2
-       ! JG : Ici on utilise uniquement le traceur du premier couche du modele. Est-ce que c'est correcte ? 
-       IF (endday) THEN
-
-          IF (carbon_cycle_tr) THEN
-             ! Sum all co2 tracers to get the total delta CO2 flux
-             fco2_tmp(:) = 0.
-             DO it = 1, ntr_co2
-                fco2_tmp(1:klon) = fco2_tmp(1:klon) + tr_seri(1:klon,1,co2trac(it)%id)
-             END DO
-             
-          ELSE IF (carbon_cycle_cpl) THEN ! no carbon_cycle_tr
-             ! Sum co2 fluxes comming from coupled models and parameter for fossil fuel
-             fco2_tmp(1:klon) = fos_fuel_s + ((fco2_lu_day(1:klon) + fco2_land_day(1:klon))*pctsrf(1:klon,is_ter) &
-                  + fco2_ocn_day(:)*pctsrf(:,is_oce)) * fact
-          END IF
-
-          ! Calculate a global mean value of delta CO2 flux
-          fco2_tmp(1:klon) = fco2_tmp(1:klon) * cell_area(1:klon)
-          CALL reduce_sum(SUM(fco2_tmp),sumtmp)
-          CALL bcast(sumtmp)
-          delta_co2_ppm = sumtmp/airetot
-          
-          ! Add initial value for co2_ppm and delta value
-          co2_ppm = co2_ppm0 + delta_co2_ppm
-          
-          ! Transformation of atmospheric CO2 concentration for the radiation code
-          RCO2 = co2_ppm * 1.0e-06  * 44.011/28.97 
-          
-          WRITE(lunout,*) 'RCO2 is now updated! RCO2 = ', RCO2
-       END IF ! endday
-
-    END IF ! RCO2_inter
-
-
-! 6) Calculate CO2 flux to send to ocean and land models : PISCES and ORCHIDEE         
-! ----------------------------------------------------------------------------
-    IF (carbon_cycle_cpl) THEN
-
-       IF (carbon_cycle_tr) THEN
-          ! Sum all co2 tracers to get the total delta CO2 flux at first model layer
-          fco2_tmp(:) = 0.
-          DO it = 1, ntr_co2
-             fco2_tmp(1:klon) = fco2_tmp(1:klon) + tr_seri(1:klon,1,co2trac(it)%id)
-          END DO
-          co2_send(1:klon) = fco2_tmp(1:klon) + co2_ppm0
-       ELSE
-          ! Send a scalare value in 2D variable to ocean and land model (PISCES and ORCHIDEE)
-          co2_send(1:klon) = co2_ppm
-       END IF
-
-    END IF
-
-  END SUBROUTINE carbon_cycle
-  
   SUBROUTINE infocfields_init
 
-    USE control_mod, ONLY: planet_type
+!    USE control_mod, ONLY: planet_type
     USE phys_cal_mod, ONLY : mth_cur
     USE mod_synchro_omp
@@ -656,4 +336,6 @@
 
   CHARACTER(len=*),parameter :: modname="infocfields"
+
+  CHARACTER(len=10),SAVE :: planet_type="earth"
 
 !-----------------------------------------------------------------------
@@ -718,5 +400,5 @@
                   WRITE(lunout,*) 'abort_gcm --- nbcf_in : ',nbcf_in
                   WRITE(lunout,*) 'abort_gcm --- nbcf_out: ',nbcf_out
-                  CALL abort_gcm('infocfields_init','Problem in the definition of the coupling fields',1)
+                  CALL abort_physic('infocfields_init','Problem in the definition of the coupling fields',1)
                ENDIF
              ENDDO !DO iq=1,nbcf
@@ -836,11 +518,11 @@
 
  ALLOCATE(fields_in(klon,nbcf_in),stat=error)
- IF (error /= 0)  CALL abort_gcm(modname,'Pb in allocation fields_in',1)
+ IF (error /= 0)  CALL abort_physic(modname,'Pb in allocation fields_in',1)
  ALLOCATE(yfields_in(klon,nbcf_in),stat=error)
- IF (error /= 0)  CALL abort_gcm(modname,'Pb in allocation yfields_in',1)
+ IF (error /= 0)  CALL abort_physic(modname,'Pb in allocation yfields_in',1)
  ALLOCATE(fields_out(klon,nbcf_out),stat=error)
- IF (error /= 0)  CALL abort_gcm(modname,'Pb in allocation fields_out',1)
+ IF (error /= 0)  CALL abort_physic(modname,'Pb in allocation fields_out',1)
  ALLOCATE(yfields_out(klon,nbcf_out),stat=error)
- IF (error /= 0)  CALL abort_gcm(modname,'Pb in allocation yfields_out',1)
+ IF (error /= 0)  CALL abort_physic(modname,'Pb in allocation yfields_out',1)
 
 END SUBROUTINE infocfields_init
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/clesphys.h
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/clesphys.h	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/clesphys.h	(revision 3605)
@@ -70,6 +70,4 @@
 !IM freq_outNMC : frequences de sortie fichiers niveaux de pression (histmthNMC, histdayNMC, histhfNMC)
 !IM freq_calNMC : frequences de calcul fis. hist*NMC.nc
-!IM pasphys : pas de temps de physique (secondes)
-       REAL pasphys
        LOGICAL ok_histNMC(3)
        INTEGER levout_histNMC(3)
@@ -111,5 +109,5 @@
      &     , min_wind_speed,f_gust_wk,f_gust_bl,f_qsat_oce,f_z0qh_oce   &
      &     , z0m_seaice,z0h_seaice                                      &
-     &     , pasphys            , freq_outNMC, freq_calNMC              &
+     &     , freq_outNMC, freq_calNMC                                   &
      &     , lonmin_ins, lonmax_ins, latmin_ins, latmax_ins             &
      &     , freq_ISCCP, ecrit_ISCCP, freq_COSP, freq_AIRS              &
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cloudth_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cloudth_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cloudth_mod.F90	(revision 3605)
@@ -7,5 +7,5 @@
        SUBROUTINE cloudth(ngrid,klev,ind2,  &
      &           ztv,po,zqta,fraca, & 
-     &           qcloud,ctot,zpspsk,paprs,ztla,zthl, &
+     &           qcloud,ctot,zpspsk,paprs,pplay,ztla,zthl, &
      &           ratqs,zqs,t)
 
@@ -38,4 +38,5 @@
       REAL zpspsk(ngrid,klev)
       REAL paprs(ngrid,klev+1)
+      REAL pplay(ngrid,klev)
       REAL ztla(ngrid,klev)
       REAL zthl(ngrid,klev)
@@ -78,5 +79,5 @@
       CALL cloudth_vert(ngrid,klev,ind2,  &
      &           ztv,po,zqta,fraca, & 
-     &           qcloud,ctot,zpspsk,paprs,ztla,zthl, &
+     &           qcloud,ctot,zpspsk,paprs,pplay,ztla,zthl, &
      &           ratqs,zqs,t)
       RETURN
@@ -251,5 +252,5 @@
      SUBROUTINE cloudth_vert(ngrid,klev,ind2,  &
      &           ztv,po,zqta,fraca, & 
-     &           qcloud,ctot,zpspsk,paprs,ztla,zthl, &
+     &           qcloud,ctot,zpspsk,paprs,pplay,ztla,zthl, &
      &           ratqs,zqs,t)
 
@@ -282,4 +283,5 @@
       REAL zpspsk(ngrid,klev)
       REAL paprs(ngrid,klev+1)
+      REAL pplay(ngrid,klev)
       REAL ztla(ngrid,klev)
       REAL zthl(ngrid,klev)
@@ -585,7 +587,10 @@
 END SUBROUTINE cloudth_vert
 
+
+
+
        SUBROUTINE cloudth_v3(ngrid,klev,ind2,  &
      &           ztv,po,zqta,fraca, & 
-     &           qcloud,ctot,ctot_vol,zpspsk,paprs,ztla,zthl, &
+     &           qcloud,ctot,ctot_vol,zpspsk,paprs,pplay,ztla,zthl, &
      &           ratqs,zqs,t)
 
@@ -618,4 +623,5 @@
       REAL zpspsk(ngrid,klev)
       REAL paprs(ngrid,klev+1)
+      REAL pplay(ngrid,klev)
       REAL ztla(ngrid,klev)
       REAL zthl(ngrid,klev)
@@ -641,4 +647,5 @@
       REAL alth,alenv,ath,aenv
       REAL sth,senv,sigma1s,sigma2s,xth,xenv, exp_xenv1, exp_xenv2,exp_xth1,exp_xth2
+      REAL inverse_rho,beta,a_Brooks,b_Brooks,A_Maj_Brooks,Dx_Brooks,f_Brooks
       REAL Tbef,zdelta,qsatbef,zcor
       REAL qlbef  
@@ -654,5 +661,5 @@
       CALL cloudth_vert_v3(ngrid,klev,ind2,  &
      &           ztv,po,zqta,fraca, & 
-     &           qcloud,ctot,ctot_vol,zpspsk,paprs,ztla,zthl, &
+     &           qcloud,ctot,ctot_vol,zpspsk,paprs,pplay,ztla,zthl, &
      &           ratqs,zqs,t)
       RETURN
@@ -808,5 +815,5 @@
      SUBROUTINE cloudth_vert_v3(ngrid,klev,ind2,  &
      &           ztv,po,zqta,fraca, & 
-     &           qcloud,ctot,ctot_vol,zpspsk,paprs,ztla,zthl, &
+     &           qcloud,ctot,ctot_vol,zpspsk,paprs,pplay,ztla,zthl, &
      &           ratqs,zqs,t)
 
@@ -841,4 +848,5 @@
       REAL zpspsk(ngrid,klev)
       REAL paprs(ngrid,klev+1)
+      REAL pplay(ngrid,klev)
       REAL ztla(ngrid,klev)
       REAL zthl(ngrid,klev)
@@ -864,4 +872,5 @@
       REAL alth,alenv,ath,aenv
       REAL sth,senv,sigma1s,sigma2s,sigma1s_fraca,sigma1s_ratqs
+      REAL inverse_rho,beta,a_Brooks,b_Brooks,A_Maj_Brooks,Dx_Brooks,f_Brooks
       REAL xth,xenv,exp_xenv1,exp_xenv2,exp_xth1,exp_xth2
       REAL xth1,xth2,xenv1,xenv2,deltasth, deltasenv
@@ -876,6 +885,8 @@
       REAL,SAVE :: sigma1s_factor=1.1
       REAL,SAVE :: sigma1s_power=0.6
+      REAL,SAVE :: sigma2s_factor=0.09
+      REAL,SAVE :: sigma2s_power=0.5
       REAL,SAVE :: cloudth_ratqsmin=-1.
-      !$OMP THREADPRIVATE(sigma1s_factor,sigma1s_power,cloudth_ratqsmin)
+      !$OMP THREADPRIVATE(sigma1s_factor,sigma1s_power,sigma2s_factor,sigma2s_power,cloudth_ratqsmin)
       INTEGER, SAVE :: iflag_cloudth_vert_noratqs=0
       !$OMP THREADPRIVATE(iflag_cloudth_vert_noratqs)
@@ -888,4 +899,16 @@
       REAL zqs(ngrid), qcloud(ngrid)
       REAL erf
+
+      REAL rhodz(ngrid,klev)
+      REAL zrho(ngrid,klev)
+      REAL dz(ngrid,klev)
+
+      DO ind1 = 1, ngrid
+        !Layer calculation
+        rhodz(ind1,ind2) = (paprs(ind1,ind2)-paprs(ind1,ind2+1))/rg !kg/m2
+        zrho(ind1,ind2) = pplay(ind1,ind2)/t(ind1,ind2)/rd !kg/m3
+        dz(ind1,ind2) = rhodz(ind1,ind2)/zrho(ind1,ind2) !m : epaisseur de la couche en metre
+      END DO
+
 
 !------------------------------------------------------------------------------
@@ -930,4 +953,10 @@
         CALL getin_p('cloudth_sigma1s_power',sigma1s_power)
         WRITE(*,*) 'cloudth_sigma1s_power = ', sigma1s_power
+        ! Factor used in the calculation of sigma2s
+        CALL getin_p('cloudth_sigma2s_factor',sigma2s_factor)
+        WRITE(*,*) 'cloudth_sigma2s_factor = ', sigma2s_factor
+        ! Power used in the calculation of sigma2s
+        CALL getin_p('cloudth_sigma2s_power',sigma2s_power)
+        WRITE(*,*) 'cloudth_sigma2s_power = ', sigma2s_power
         ! Minimum value for the environmental air subgrid water distrib
         CALL getin_p('cloudth_ratqsmin',cloudth_ratqsmin)
@@ -998,5 +1027,5 @@
       ENDIF
       sigma1s = sigma1s_fraca + sigma1s_ratqs
-      sigma2s=(0.09*(((sth-senv)**2)**0.5)/((fraca(ind1,ind2)+0.02)**0.5))+0.002*zqta(ind1,ind2)
+      sigma2s=(sigma2s_factor*(((sth-senv)**2)**0.5)/((fraca(ind1,ind2)+0.02)**sigma2s_power))+0.002*zqta(ind1,ind2)
 !      tests
 !      sigma1s=(0.92**0.5)*(fraca(ind1,ind2)**0.5)/(1-fraca(ind1,ind2))*((sth-senv)**2)**0.5+ratqs(ind1,ind2)*po(ind1)
@@ -1050,5 +1079,5 @@
 
       ELSE IF (iflag_cloudth_vert >= 3) THEN
-
+      IF (iflag_cloudth_vert < 5) THEN
 !-------------------------------------------------------------------------------
 !  Version 3: Changes by J. Jouhaud; condensation for q > -delta s
@@ -1119,17 +1148,64 @@
       endif
 
-
       qltot(ind1,ind2)=fraca(ind1,ind2)*qlth(ind1,ind2)+(1.-1.*fraca(ind1,ind2))*qlenv(ind1,ind2)
       ctot_vol(ind1,ind2)=fraca(ind1,ind2)*cth_vol(ind1,ind2)+(1.-1.*fraca(ind1,ind2))*cenv_vol(ind1,ind2)
 
+      ELSE IF (iflag_cloudth_vert == 5) THEN
+      sigma1s=(0.71794+0.000498239*dz(ind1,ind2))*(fraca(ind1,ind2)**0.5)/(1-fraca(ind1,ind2))*(((sth-senv)**2)**0.5)+ratqs(ind1,ind2)*po(ind1) !Environment
+      sigma2s=(0.03218+0.000092655*dz(ind1,ind2))/((fraca(ind1,ind2)+0.02)**0.5)*(((sth-senv)**2)**0.5)+0.002*zqta(ind1,ind2)                   !Thermals
+      !sigma1s=(1.1**0.5)*(fraca(ind1,ind2)**0.6)/(1-fraca(ind1,ind2))*((sth-senv)**2)**0.5+0.002*po(ind1)
+      !sigma2s=0.11*((sth-senv)**2)**0.5/(fraca(ind1,ind2)+0.01)**0.4+0.002*zqta(ind1,ind2) 
+      xth=sth/(sqrt(2.)*sigma2s)
+      xenv=senv/(sqrt(2.)*sigma1s)
+
+      !Volumique
+      cth_vol(ind1,ind2)=0.5*(1.+1.*erf(xth))
+      cenv_vol(ind1,ind2)=0.5*(1.+1.*erf(xenv))
+      ctot_vol(ind1,ind2)=fraca(ind1,ind2)*cth_vol(ind1,ind2)+(1.-1.*fraca(ind1,ind2))*cenv_vol(ind1,ind2)
+      !print *,'jeanjean_CV=',ctot_vol(ind1,ind2)
+
+      qlth(ind1,ind2)=sigma2s*((exp(-1.*xth**2)/sqrt2pi)+xth*sqrt(2.)*cth_vol(ind1,ind2))
+      qlenv(ind1,ind2)=sigma1s*((exp(-1.*xenv**2)/sqrt2pi)+xenv*sqrt(2.)*cenv_vol(ind1,ind2))  
+      qltot(ind1,ind2)=fraca(ind1,ind2)*qlth(ind1,ind2)+(1.-1.*fraca(ind1,ind2))*qlenv(ind1,ind2)
+
+      !Surfacique
+      !Neggers
+      !beta=0.0044
+      !inverse_rho=1.+beta*dz(ind1,ind2)
+      !print *,'jeanjean : beta=',beta
+      !cth(ind1,ind2)=cth_vol(ind1,ind2)*inverse_rho
+      !cenv(ind1,ind2)=cenv_vol(ind1,ind2)*inverse_rho
+      !ctot(ind1,ind2)=fraca(ind1,ind2)*cth(ind1,ind2)+(1.-1.*fraca(ind1,ind2))*cenv(ind1,ind2)
+
+      !Brooks
+      a_Brooks=0.6694
+      b_Brooks=0.1882
+      A_Maj_Brooks=0.1635 !-- sans shear
+      !A_Maj_Brooks=0.17   !-- ARM LES
+      !A_Maj_Brooks=0.18   !-- RICO LES
+      !A_Maj_Brooks=0.19   !-- BOMEX LES
+      Dx_Brooks=200000.
+      f_Brooks=A_Maj_Brooks*(dz(ind1,ind2)**(a_Brooks))*(Dx_Brooks**(-b_Brooks))
+      !print *,'jeanjean_f=',f_Brooks
+
+      cth(ind1,ind2)=1./(1.+exp(-1.*f_Brooks)*((1./max(1.e-15,min(cth_vol(ind1,ind2),1.)))- 1.))
+      cenv(ind1,ind2)=1./(1.+exp(-1.*f_Brooks)*((1./max(1.e-15,min(cenv_vol(ind1,ind2),1.)))- 1.))
+      ctot(ind1,ind2)=1./(1.+exp(-1.*f_Brooks)*((1./max(1.e-15,min(ctot_vol(ind1,ind2),1.)))- 1.))
+      !print *,'JJ_ctot_1',ctot(ind1,ind2)
+
+
+
+
+
+      ENDIF ! of if (iflag_cloudth_vert<5)
       ENDIF ! of if (iflag_cloudth_vert==1 or 3 or 4)
 
-
+!      if (ctot(ind1,ind2).lt.1.e-10) then
       if (cenv(ind1,ind2).lt.1.e-10.or.cth(ind1,ind2).lt.1.e-10) then
       ctot(ind1,ind2)=0.
       ctot_vol(ind1,ind2)=0.
-      qcloud(ind1)=zqsatenv(ind1,ind2) 
-
-      else 
+      qcloud(ind1)=zqsatenv(ind1,ind2)
+
+      else
                 
       qcloud(ind1)=qltot(ind1,ind2)/ctot(ind1,ind2)+zqs(ind1)
@@ -1139,5 +1215,5 @@
       endif  
 
-      else  ! Environment only
+      else  ! gaussienne environnement seule
       
       zqenv(ind1)=po(ind1)
@@ -1151,29 +1227,35 @@
       
 
-!     qlbef=Max(po(ind1)-zqsatenv(ind1,ind2),0.)
+!      qlbef=Max(po(ind1)-zqsatenv(ind1,ind2),0.)
       zthl(ind1,ind2)=t(ind1,ind2)*(101325/paprs(ind1,ind2))**(rdd/cppd)
-      alenv=(0.622*Lv*zqsatenv(ind1,ind2))/(rdd*zthl(ind1,ind2)**2)  
+      alenv=(0.622*Lv*zqsatenv(ind1,ind2))/(rdd*zthl(ind1,ind2)**2)
       aenv=1./(1.+(alenv*Lv/cppd))
       senv=aenv*(po(ind1)-zqsatenv(ind1,ind2))
       sth=0.
+      
 
       sigma1s=ratqs(ind1,ind2)*zqenv(ind1)
       sigma2s=0.
 
-      xenv=senv/(sqrt2*sigma1s)
+      sqrt2pi=sqrt(2.*pi)
+      xenv=senv/(sqrt(2.)*sigma1s)
       ctot(ind1,ind2)=0.5*(1.+1.*erf(xenv))
       ctot_vol(ind1,ind2)=ctot(ind1,ind2)
-      qltot(ind1,ind2)=sigma1s*((exp(-1.*xenv**2)/sqrt2pi)+xenv*sqrt2*cenv(ind1,ind2))
+      qltot(ind1,ind2)=sigma1s*((exp(-1.*xenv**2)/sqrt2pi)+xenv*sqrt(2.)*cenv(ind1,ind2))
       
       if (ctot(ind1,ind2).lt.1.e-3) then
       ctot(ind1,ind2)=0.
-      qcloud(ind1)=zqsatenv(ind1,ind2) 
+      qcloud(ind1)=zqsatenv(ind1,ind2)
 
       else   
                 
+!      ctot(ind1,ind2)=ctot(ind1,ind2) 
       qcloud(ind1)=qltot(ind1,ind2)/ctot(ind1,ind2)+zqsatenv(ind1,ind2)
 
-      endif    
- 
+      endif  
+ 
+
+
+
       endif       ! From the separation (thermal/envrionnement) et (environnement) only, l.335 et l.492
       ! Outputs used to check the PDFs
@@ -1184,8 +1266,275 @@
 
       enddo       ! from the loop on ngrid l.333
-     
       return
 !     end
 END SUBROUTINE cloudth_vert_v3
 !
+
+
+
+
+
+
+
+
+
+
+
+       SUBROUTINE cloudth_v6(ngrid,klev,ind2,  &
+     &           ztv,po,zqta,fraca, & 
+     &           qcloud,ctot_surf,ctot_vol,zpspsk,paprs,pplay,ztla,zthl, &
+     &           ratqs,zqs,T)
+
+
+      USE ioipsl_getin_p_mod, ONLY : getin_p
+      USE phys_output_var_mod, ONLY : cloudth_sth,cloudth_senv, &
+     &                                cloudth_sigmath,cloudth_sigmaenv
+
+      IMPLICIT NONE
+
+#include "YOMCST.h"
+#include "YOETHF.h"
+#include "FCTTRE.h"
+#include "thermcell.h"
+#include "nuage.h"
+
+
+        !Domain variables
+      INTEGER ngrid !indice Max lat-lon
+      INTEGER klev  !indice Max alt
+      INTEGER ind1  !indice in [1:ngrid]
+      INTEGER ind2  !indice in [1:klev]
+        !thermal plume fraction
+      REAL fraca(ngrid,klev+1)   !thermal plumes fraction in the gridbox
+        !temperatures
+      REAL T(ngrid,klev)       !temperature
+      REAL zpspsk(ngrid,klev)  !factor (p/p0)**kappa (used for potential variables)
+      REAL ztv(ngrid,klev)     !potential temperature (voir thermcell_env.F90)
+      REAL ztla(ngrid,klev)    !liquid temperature in the thermals (Tl_th)
+      REAL zthl(ngrid,klev)    !liquid temperature in the environment (Tl_env)
+        !pressure
+      REAL paprs(ngrid,klev+1)   !pressure at the interface of levels
+      REAL pplay(ngrid,klev)     !pressure at the middle of the level
+        !humidity
+      REAL ratqs(ngrid,klev)   !width of the total water subgrid-scale distribution
+      REAL po(ngrid)           !total water (qt)
+      REAL zqenv(ngrid)        !total water in the environment (qt_env)
+      REAL zqta(ngrid,klev)    !total water in the thermals (qt_th)
+      REAL zqsatth(ngrid,klev)   !water saturation level in the thermals (q_sat_th)
+      REAL zqsatenv(ngrid,klev)  !water saturation level in the environment (q_sat_env)
+      REAL qlth(ngrid,klev)    !condensed water in the thermals
+      REAL qlenv(ngrid,klev)   !condensed water in the environment
+      REAL qltot(ngrid,klev)   !condensed water in the gridbox
+        !cloud fractions
+      REAL cth_vol(ngrid,klev)   !cloud fraction by volume in the thermals
+      REAL cenv_vol(ngrid,klev)  !cloud fraction by volume in the environment
+      REAL ctot_vol(ngrid,klev)  !cloud fraction by volume in the gridbox
+      REAL cth_surf(ngrid,klev)  !cloud fraction by surface in the thermals
+      REAL cenv_surf(ngrid,klev) !cloud fraction by surface in the environment  
+      REAL ctot_surf(ngrid,klev) !cloud fraction by surface in the gridbox
+        !PDF of saturation deficit variables
+      REAL rdd,cppd,Lv
+      REAL Tbef,zdelta,qsatbef,zcor
+      REAL alth,alenv,ath,aenv
+      REAL sth,senv              !saturation deficits in the thermals and environment
+      REAL sigma_env,sigma_th    !standard deviations of the biGaussian PDF
+        !cloud fraction variables
+      REAL xth,xenv
+      REAL inverse_rho,beta                                  !Neggers et al. (2011) method
+      REAL a_Brooks,b_Brooks,A_Maj_Brooks,Dx_Brooks,f_Brooks !Brooks et al. (2005) method
+        !Incloud total water variables
+      REAL zqs(ngrid)    !q_sat
+      REAL qcloud(ngrid) !eau totale dans le nuage
+        !Some arithmetic variables
+      REAL erf,pi,sqrt2,sqrt2pi
+        !Depth of the layer
+      REAL dz(ngrid,klev)    !epaisseur de la couche en metre
+      REAL rhodz(ngrid,klev)
+      REAL zrho(ngrid,klev)
+      DO ind1 = 1, ngrid
+        rhodz(ind1,ind2) = (paprs(ind1,ind2)-paprs(ind1,ind2+1))/rg ![kg/m2]
+        zrho(ind1,ind2) = pplay(ind1,ind2)/T(ind1,ind2)/rd          ![kg/m3]
+        dz(ind1,ind2) = rhodz(ind1,ind2)/zrho(ind1,ind2)            ![m]
+      END DO
+
+!------------------------------------------------------------------------------
+! Initialization
+!------------------------------------------------------------------------------
+      qlth(:,:)=0.
+      qlenv(:,:)=0.  
+      qltot(:,:)=0.
+      cth_vol(:,:)=0.
+      cenv_vol(:,:)=0.
+      ctot_vol(:,:)=0.
+      cth_surf(:,:)=0.
+      cenv_surf(:,:)=0.
+      ctot_surf(:,:)=0.
+      qcloud(:)=0.
+      rdd=287.04
+      cppd=1005.7
+      pi=3.14159 
+      Lv=2.5e6
+      sqrt2=sqrt(2.)
+      sqrt2pi=sqrt(2.*pi)
+
+
+      DO ind1=1,ngrid
+!-------------------------------------------------------------------------------
+!Both thermal and environment in the gridbox
+!-------------------------------------------------------------------------------
+      IF ((ztv(ind1,1).gt.ztv(ind1,2)).and.(fraca(ind1,ind2).gt.1.e-10)) THEN
+        !--------------------------------------------
+        !calcul de qsat_env
+        !--------------------------------------------
+      Tbef=zthl(ind1,ind2)*zpspsk(ind1,ind2)
+      zdelta=MAX(0.,SIGN(1.,RTT-Tbef))
+      qsatbef= R2ES*FOEEW(Tbef,zdelta)/paprs(ind1,ind2)
+      qsatbef=MIN(0.5,qsatbef)
+      zcor=1./(1.-retv*qsatbef)
+      qsatbef=qsatbef*zcor
+      zqsatenv(ind1,ind2)=qsatbef
+        !--------------------------------------------
+        !calcul de s_env
+        !--------------------------------------------
+      alenv=(0.622*Lv*zqsatenv(ind1,ind2))/(rdd*zthl(ind1,ind2)**2)     !qsl, p84 these Arnaud Jam
+      aenv=1./(1.+(alenv*Lv/cppd))                                      !al, p84 these Arnaud Jam
+      senv=aenv*(po(ind1)-zqsatenv(ind1,ind2))                          !s, p84 these Arnaud Jam
+        !--------------------------------------------
+        !calcul de qsat_th
+        !--------------------------------------------
+      Tbef=ztla(ind1,ind2)*zpspsk(ind1,ind2)
+      zdelta=MAX(0.,SIGN(1.,RTT-Tbef))
+      qsatbef= R2ES * FOEEW(Tbef,zdelta)/paprs(ind1,ind2)
+      qsatbef=MIN(0.5,qsatbef)
+      zcor=1./(1.-retv*qsatbef)
+      qsatbef=qsatbef*zcor
+      zqsatth(ind1,ind2)=qsatbef
+        !--------------------------------------------
+        !calcul de s_th  
+        !--------------------------------------------
+      alth=(0.622*Lv*zqsatth(ind1,ind2))/(rdd*ztla(ind1,ind2)**2)       !qsl, p84 these Arnaud Jam
+      ath=1./(1.+(alth*Lv/cppd))                                        !al, p84 these Arnaud Jam
+      sth=ath*(zqta(ind1,ind2)-zqsatth(ind1,ind2))                      !s, p84 these Arnaud Jam
+        !--------------------------------------------
+        !calcul standard deviations bi-Gaussian PDF
+        !--------------------------------------------
+      sigma_th=(0.03218+0.000092655*dz(ind1,ind2))/((fraca(ind1,ind2)+0.01)**0.5)*(((sth-senv)**2)**0.5)+0.002*zqta(ind1,ind2)
+      sigma_env=(0.71794+0.000498239*dz(ind1,ind2))*(fraca(ind1,ind2)**0.5)/(1-fraca(ind1,ind2))*(((sth-senv)**2)**0.5)+ratqs(ind1,ind2)*po(ind1)
+      xth=sth/(sqrt2*sigma_th)
+      xenv=senv/(sqrt2*sigma_env)
+        !--------------------------------------------
+        !Cloud fraction by volume CF_vol
+        !--------------------------------------------
+      cth_vol(ind1,ind2)=0.5*(1.+1.*erf(xth))
+      cenv_vol(ind1,ind2)=0.5*(1.+1.*erf(xenv))
+      ctot_vol(ind1,ind2)=fraca(ind1,ind2)*cth_vol(ind1,ind2)+(1.-1.*fraca(ind1,ind2))*cenv_vol(ind1,ind2)
+        !-------------------------------------------- 
+        !Condensed water qc
+        !--------------------------------------------
+      qlth(ind1,ind2)=sigma_th*((exp(-1.*xth**2)/sqrt2pi)+xth*sqrt2*cth_vol(ind1,ind2))
+      qlenv(ind1,ind2)=sigma_env*((exp(-1.*xenv**2)/sqrt2pi)+xenv*sqrt2*cenv_vol(ind1,ind2))  
+      qltot(ind1,ind2)=fraca(ind1,ind2)*qlth(ind1,ind2)+(1.-1.*fraca(ind1,ind2))*qlenv(ind1,ind2)
+        !--------------------------------------------
+        !Cloud fraction by surface CF_surf
+        !--------------------------------------------
+        !Method Neggers et al. (2011) : ok for cumulus clouds only
+      !beta=0.0044 (Jouhaud et al.2018)
+      !inverse_rho=1.+beta*dz(ind1,ind2)
+      !ctot_surf(ind1,ind2)=ctot_vol(ind1,ind2)*inverse_rho
+        !Method Brooks et al. (2005) : ok for all types of clouds
+      a_Brooks=0.6694
+      b_Brooks=0.1882
+      A_Maj_Brooks=0.1635 !-- sans dependence au cisaillement de vent
+      Dx_Brooks=200000.   !-- si l'on considere des mailles de 200km de cote
+      f_Brooks=A_Maj_Brooks*(dz(ind1,ind2)**(a_Brooks))*(Dx_Brooks**(-b_Brooks))
+      ctot_surf(ind1,ind2)=1./(1.+exp(-1.*f_Brooks)*((1./max(1.e-15,min(ctot_vol(ind1,ind2),1.)))- 1.))
+        !--------------------------------------------
+        !Incloud Condensed water qcloud
+        !--------------------------------------------
+      if (ctot_surf(ind1,ind2) .lt. 1.e-10) then
+      ctot_vol(ind1,ind2)=0.
+      ctot_surf(ind1,ind2)=0.
+      qcloud(ind1)=zqsatenv(ind1,ind2)
+      else
+      qcloud(ind1)=qltot(ind1,ind2)/ctot_vol(ind1,ind2)+zqs(ind1)
+      endif
+
+
+
+!-------------------------------------------------------------------------------
+!Environment only in the gridbox
+!-------------------------------------------------------------------------------
+      ELSE
+        !--------------------------------------------
+        !calcul de qsat_env
+        !--------------------------------------------
+      Tbef=zthl(ind1,ind2)*zpspsk(ind1,ind2)
+      zdelta=MAX(0.,SIGN(1.,RTT-Tbef))
+      qsatbef= R2ES * FOEEW(Tbef,zdelta)/paprs(ind1,ind2)
+      qsatbef=MIN(0.5,qsatbef)
+      zcor=1./(1.-retv*qsatbef)
+      qsatbef=qsatbef*zcor
+      zqsatenv(ind1,ind2)=qsatbef
+        !--------------------------------------------
+        !calcul de s_env
+        !--------------------------------------------
+      alenv=(0.622*Lv*zqsatenv(ind1,ind2))/(rdd*zthl(ind1,ind2)**2)     !qsl, p84 these Arnaud Jam
+      aenv=1./(1.+(alenv*Lv/cppd))                                      !al, p84 these Arnaud Jam
+      senv=aenv*(po(ind1)-zqsatenv(ind1,ind2))                          !s, p84 these Arnaud Jam 
+        !--------------------------------------------
+        !calcul standard deviations Gaussian PDF
+        !--------------------------------------------
+      zqenv(ind1)=po(ind1)
+      sigma_env=ratqs(ind1,ind2)*zqenv(ind1)
+      xenv=senv/(sqrt2*sigma_env)
+        !--------------------------------------------
+        !Cloud fraction by volume CF_vol
+        !--------------------------------------------
+      ctot_vol(ind1,ind2)=0.5*(1.+1.*erf(xenv))
+        !--------------------------------------------
+        !Condensed water qc
+        !--------------------------------------------
+      qltot(ind1,ind2)=sigma_env*((exp(-1.*xenv**2)/sqrt2pi)+xenv*sqrt2*ctot_vol(ind1,ind2))
+        !--------------------------------------------
+        !Cloud fraction by surface CF_surf
+        !--------------------------------------------
+        !Method Neggers et al. (2011) : ok for cumulus clouds only
+      !beta=0.0044 (Jouhaud et al.2018)
+      !inverse_rho=1.+beta*dz(ind1,ind2)
+      !ctot_surf(ind1,ind2)=ctot_vol(ind1,ind2)*inverse_rho
+        !Method Brooks et al. (2005) : ok for all types of clouds
+      a_Brooks=0.6694
+      b_Brooks=0.1882
+      A_Maj_Brooks=0.1635 !-- sans dependence au shear
+      Dx_Brooks=200000.
+      f_Brooks=A_Maj_Brooks*(dz(ind1,ind2)**(a_Brooks))*(Dx_Brooks**(-b_Brooks))
+      ctot_surf(ind1,ind2)=1./(1.+exp(-1.*f_Brooks)*((1./max(1.e-15,min(ctot_vol(ind1,ind2),1.)))- 1.))
+        !--------------------------------------------
+        !Incloud Condensed water qcloud
+        !--------------------------------------------
+      if (ctot_surf(ind1,ind2) .lt. 1.e-8) then
+      ctot_vol(ind1,ind2)=0.
+      ctot_surf(ind1,ind2)=0.
+      qcloud(ind1)=zqsatenv(ind1,ind2)
+      else
+      qcloud(ind1)=qltot(ind1,ind2)/ctot_vol(ind1,ind2)+zqsatenv(ind1,ind2)
+      endif
+
+
+      END IF  ! From the separation (thermal/envrionnement) et (environnement only)
+
+      ! Outputs used to check the PDFs
+      cloudth_senv(ind1,ind2) = senv
+      cloudth_sth(ind1,ind2) = sth
+      cloudth_sigmaenv(ind1,ind2) = sigma_env
+      cloudth_sigmath(ind1,ind2) = sigma_th
+
+      END DO  ! From the loop on ngrid
+      return
+
+END SUBROUTINE cloudth_v6
 END MODULE cloudth_mod
+
+
+
+
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/coef_diff_turb_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/coef_diff_turb_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/coef_diff_turb_mod.F90	(revision 3605)
@@ -65,4 +65,9 @@
 
 
+    ykmm = 0 !ym missing init
+    ykmn = 0 !ym missing init
+    ykmq = 0 !ym missing init
+    
+    
 !****************************************************************************************    
 ! Calcul de coefficients de diffusion turbulent de l'atmosphere : 
@@ -177,4 +182,7 @@
        ycoefh(1:knon,2:klev)=ykmn(1:knon,2:klev)
                 
+    ELSE
+       ! No TKE for Standard Physics
+       yq2=0.
     ENDIF !(iflag_pbl.ge.3)
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/concvl.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/concvl.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/concvl.F90	(revision 3605)
@@ -13,8 +13,8 @@
 !RomP >>>
 !!     .             da,phi,mp,dd_t,dd_q,lalim_conv,wght_th)
-                  da, phi, mp, phii, d1a, dam, sij, clw, elij, &     ! RomP
+                  da, phi, mp, phii, d1a, dam, sij, qta, clw, elij, &! RomP
                   dd_t, dd_q, lalim_conv, wght_th, &                 ! RomP
                   evap, ep, epmlmMm, eplaMm, &                       ! RomP
-                  wdtrainA, wdtrainM, wght, qtc, sigt, &
+                  wdtrainA, wdtrainS, wdtrainM, wght, qtc, sigt, &
                   tau_cld_cv, coefw_cld_cv, &                           ! RomP+RL, AJ
 !RomP <<<
@@ -80,4 +80,5 @@
 ! eplaMm-----output-R
 ! wdtrainA---output-R
+! wdtrainS---output-R
 ! wdtrainM---output-R
 ! wght-------output-R
@@ -134,4 +135,5 @@
   REAL, DIMENSION(klon,klev),   INTENT(OUT)     :: d1a, dam
   REAL, DIMENSION(klon,klev,klev),INTENT(OUT)   :: sij, elij
+  REAL, DIMENSION(klon,klev),   INTENT(OUT)     :: qta
   REAL, DIMENSION(klon,klev),   INTENT(OUT)     :: clw
   REAL, DIMENSION(klon,klev),   INTENT(OUT)     :: dd_t, dd_q
@@ -139,5 +141,5 @@
   REAL, DIMENSION(klon,klev),   INTENT(OUT)     :: eplaMm
   REAL, DIMENSION(klon,klev,klev), INTENT(OUT)  :: epmlmMm
-  REAL, DIMENSION(klon,klev),   INTENT(OUT)     :: wdtrainA, wdtrainM
+  REAL, DIMENSION(klon,klev),   INTENT(OUT)     :: wdtrainA, wdtrainS, wdtrainM
 ! RomP <<<
   REAL, DIMENSION(klon,klev),   INTENT(OUT)     :: wght                       !RL
@@ -437,6 +439,6 @@
 !!                   evap,ep,epmlmMm,eplaMm,                              ! RomP
                     da, phi, mp, phii, d1a, dam, sij, wght, &           ! RomP+RL
-                    clw, elij, evap, ep, epmlmMm, eplaMm, &             ! RomP+RL
-                    wdtrainA, wdtrainM, qtc, sigt, &
+                    qta, clw, elij, evap, ep, epmlmMm, eplaMm, &        ! RomP+RL
+                    wdtrainA, wdtrainS, wdtrainM, qtc, sigt, &
                     tau_cld_cv, coefw_cld_cv, &                         ! RomP,AJ
 !AC!+!RomP+jyg
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/conf_phys_m.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/conf_phys_m.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/conf_phys_m.F90	(revision 3605)
@@ -17,5 +17,5 @@
        iflag_cld_th, &
        iflag_ratqs,ratqsbas,ratqshaut,tau_ratqs, &
-       ok_ade, ok_aie, ok_alw, ok_cdnc, aerosol_couple, chemistry_couple, &
+       ok_ade, ok_aie, ok_alw, ok_cdnc, ok_volcan, aerosol_couple, chemistry_couple, &
        flag_aerosol, flag_aerosol_strat, flag_aer_feedback, new_aod, &
        flag_bc_internal_mixture, bl95_b0, bl95_b1,&
@@ -26,8 +26,9 @@
     USE surface_data
     USE phys_cal_mod
-    USE carbon_cycle_mod,  ONLY: carbon_cycle_tr, carbon_cycle_cpl, level_coupling_esm
+    USE carbon_cycle_mod,  ONLY: carbon_cycle_tr, carbon_cycle_cpl, carbon_cycle_rad, level_coupling_esm
     USE mod_grid_phy_lmdz, ONLY: klon_glo
     USE print_control_mod, ONLY: lunout
     use config_ocean_skin_m, only: config_ocean_skin
+    USE phys_state_var_mod, ONLY: phys_tstep
 
     INCLUDE "conema3.h"
@@ -63,4 +64,5 @@
     ! flag_bc_internal_mixture : use BC internal mixture if true
     ! bl95_b*: parameters in the formula to link CDNC to aerosol mass conc 
+    ! ok_volcan: activate volcanic diags (SW heat & LW cool rate, SW & LW flux)
     !
 
@@ -71,5 +73,5 @@
     LOGICAL              :: ok_LES
     LOGICAL              :: callstats
-    LOGICAL              :: ok_ade, ok_aie, ok_alw, ok_cdnc
+    LOGICAL              :: ok_ade, ok_aie, ok_alw, ok_cdnc, ok_volcan
     LOGICAL              :: aerosol_couple, chemistry_couple
     INTEGER              :: flag_aerosol
@@ -93,5 +95,5 @@
     LOGICAL, SAVE       :: ok_LES_omp   
     LOGICAL, SAVE       :: callstats_omp
-    LOGICAL, SAVE       :: ok_ade_omp, ok_aie_omp, ok_alw_omp, ok_cdnc_omp
+    LOGICAL, SAVE       :: ok_ade_omp, ok_aie_omp, ok_alw_omp, ok_cdnc_omp, ok_volcan_omp
     LOGICAL, SAVE       :: aerosol_couple_omp, chemistry_couple_omp
     INTEGER, SAVE       :: flag_aerosol_omp
@@ -151,5 +153,5 @@
 
     REAL,SAVE :: R_ecc_omp,R_peri_omp,R_incl_omp,solaire_omp
-    REAL      :: solaire_omp_init
+    REAL,SAVE      :: solaire_omp_init
     LOGICAL,SAVE :: ok_suntime_rrtm_omp
     REAL,SAVE :: co2_ppm_omp, RCO2_omp, co2_ppm_per_omp, RCO2_per_omp
@@ -231,4 +233,5 @@
     LOGICAL, SAVE :: carbon_cycle_tr_omp
     LOGICAL, SAVE :: carbon_cycle_cpl_omp
+    LOGICAL, SAVE :: carbon_cycle_rad_omp
     INTEGER, SAVE :: level_coupling_esm_omp
     LOGICAL, SAVE :: adjust_tropopause_omp
@@ -395,4 +398,14 @@
     ok_cdnc_omp = .FALSE.
     CALL getin('ok_cdnc', ok_cdnc_omp)
+
+    !
+    !Config Key  = ok_volcan
+    !Config Desc = ok to generate volcanic diags
+    !Config Def  = .FALSE.
+    !Config Help = Used in radlwsw_m.F
+    !
+    ok_volcan_omp = .FALSE.
+    CALL getin('ok_volcan', ok_volcan_omp)
+
     !
     !Config Key  = aerosol_couple
@@ -595,5 +608,5 @@
     ! RCO2 = 5.286789092164308E-04
     !ancienne valeur
-    RCO2_omp = co2_ppm_omp * 1.0e-06  * 44.011/28.97 ! pour co2_ppm=348.
+    RCO2_omp = co2_ppm_omp * 1.0e-06 * RMCO2 / RMD ! pour co2_ppm=348.
 
     !  CALL getin('RCO2', RCO2)
@@ -615,5 +628,5 @@
     CALL getin('CH4_ppb', zzz)
     CH4_ppb_omp = zzz
-    RCH4_omp = CH4_ppb_omp * 1.0E-09 * 16.043/28.97
+    RCH4_omp = CH4_ppb_omp * 1.0E-09 * RMCH4 / RMD
     !
     !Config Key  = RN2O
@@ -633,5 +646,5 @@
     CALL getin('N2O_ppb', zzz)
     N2O_ppb_omp = zzz
-    RN2O_omp = N2O_ppb_omp * 1.0E-09 * 44.013/28.97
+    RN2O_omp = N2O_ppb_omp * 1.0E-09 * RMN2O / RMD
     !
     !Config Key  = RCFC11
@@ -645,5 +658,5 @@
     CALL getin('CFC11_ppt',zzz)
     CFC11_ppt_omp = zzz
-    RCFC11_omp=CFC11_ppt_omp* 1.0E-12 * 137.3686/28.97
+    RCFC11_omp=CFC11_ppt_omp* 1.0E-12 * RMCFC11 / RMD
     ! RCFC11 = 1.327690990680013E-09
     !OK CALL getin('RCFC11', RCFC11)
@@ -659,5 +672,5 @@
     CALL getin('CFC12_ppt',zzz)
     CFC12_ppt_omp = zzz
-    RCFC12_omp = CFC12_ppt_omp * 1.0E-12 * 120.9140/28.97
+    RCFC12_omp = CFC12_ppt_omp * 1.0E-12 * RMCFC12 / RMD
     ! RCFC12 = 2.020102726958923E-09
     !OK CALL getin('RCFC12', RCFC12)
@@ -679,5 +692,5 @@
     !Config Help = 
     !               
-    RCO2_per_omp = co2_ppm_per_omp * 1.0e-06  * 44.011/28.97
+    RCO2_per_omp = co2_ppm_per_omp * 1.0e-06 * RMCO2 / RMD
 
     !Config Key  = ok_4xCO2atm
@@ -694,5 +707,5 @@
     CALL getin('CH4_ppb_per', zzz)
     CH4_ppb_per_omp = zzz
-    RCH4_per_omp = CH4_ppb_per_omp * 1.0E-09 * 16.043/28.97
+    RCH4_per_omp = CH4_ppb_per_omp * 1.0E-09 * RMCH4 / RMD
     !
     !Config Key  = RN2O_per
@@ -704,5 +717,5 @@
     CALL getin('N2O_ppb_per', zzz)
     N2O_ppb_per_omp = zzz
-    RN2O_per_omp = N2O_ppb_per_omp * 1.0E-09 * 44.013/28.97
+    RN2O_per_omp = N2O_ppb_per_omp * 1.0E-09 * RMN2O / RMD
     !
     !Config Key  = RCFC11_per
@@ -714,5 +727,5 @@
     CALL getin('CFC11_ppt_per',zzz)
     CFC11_ppt_per_omp = zzz
-    RCFC11_per_omp=CFC11_ppt_per_omp* 1.0E-12 * 137.3686/28.97
+    RCFC11_per_omp=CFC11_ppt_per_omp* 1.0E-12 * RMCFC11 / RMD
     !
     !Config Key  = RCFC12_per
@@ -724,5 +737,5 @@
     CALL getin('CFC12_ppt_per',zzz)
     CFC12_ppt_per_omp = zzz
-    RCFC12_per_omp = CFC12_ppt_per_omp * 1.0E-12 * 120.9140/28.97
+    RCFC12_per_omp = CFC12_ppt_per_omp * 1.0E-12 * RMCFC12 / RMD
     !ajout CFMIP end
 
@@ -1031,5 +1044,5 @@
     ! - 1 = stratospheric aerosols scaled from 550 nm AOD 
     ! - 2 = stratospheric aerosol properties from CMIP6
-    !Option 2 is only available with RRTM, this is tested later on
+    !Option 2 is only available with RRTM, this is tested later on 
     !Config Def  = 0
     !Config Help = Used in physiq.F
@@ -1724,10 +1737,10 @@
     !Config Desc = freq_calNMC(2) = frequence de calcul fichiers histdayNMC
     !Config Desc = freq_calNMC(3) = frequence de calcul fichiers histhfNMC
-    !Config Def  = pasphys
-    !Config Help =
-    !
-    freq_calNMC_omp(1) = pasphys
-    freq_calNMC_omp(2) = pasphys
-    freq_calNMC_omp(3) = pasphys
+    !Config Def  = phys_tstep
+    !Config Help =
+    !
+    freq_calNMC_omp(1) = phys_tstep
+    freq_calNMC_omp(2) = phys_tstep
+    freq_calNMC_omp(3) = phys_tstep
     CALL getin('freq_calNMC',freq_calNMC_omp)
     !
@@ -2156,4 +2169,7 @@
     carbon_cycle_cpl_omp=.FALSE.
     CALL getin('carbon_cycle_cpl',carbon_cycle_cpl_omp)
+
+    carbon_cycle_rad_omp=.FALSE.
+    CALL getin('carbon_cycle_rad',carbon_cycle_rad_omp)
 
     ! >> PC
@@ -2306,4 +2322,5 @@
     ok_alw = ok_alw_omp
     ok_cdnc = ok_cdnc_omp
+    ok_volcan = ok_volcan_omp
     aerosol_couple = aerosol_couple_omp
     chemistry_couple = chemistry_couple_omp
@@ -2428,4 +2445,5 @@
     carbon_cycle_tr = carbon_cycle_tr_omp
     carbon_cycle_cpl = carbon_cycle_cpl_omp
+    carbon_cycle_rad = carbon_cycle_rad_omp
     level_coupling_esm = level_coupling_esm_omp
 
@@ -2529,4 +2547,12 @@
     IF (flag_bc_internal_mixture .AND. flag_aerosol.NE.6) THEN 
        CALL abort_physic('conf_phys', 'flag_bc_internal_mixture can only be activated with flag_aerosol=6',1)
+    ENDIF
+
+    ! Test on carbon cycle
+    IF (carbon_cycle_tr .AND. .NOT. carbon_cycle_cpl) THEN
+       CALL abort_physic('conf_phys', 'carbon_cycle_cpl has to be TRUE if carbon_cycle_tr is on',1)
+    ENDIF
+    IF (carbon_cycle_rad .AND. .NOT. carbon_cycle_cpl) THEN
+       CALL abort_physic('conf_phys', 'carbon_cycle_cpl has to be TRUE if carbon_cycle_rad is on',1)
     ENDIF
 
@@ -2643,4 +2669,5 @@
     WRITE(lunout,*) ' pmagic = ',pmagic
     WRITE(lunout,*) ' ok_ade = ',ok_ade
+    WRITE(lunout,*) ' ok_volcan = ',ok_volcan
     WRITE(lunout,*) ' ok_aie = ',ok_aie
     WRITE(lunout,*) ' ok_alw = ',ok_alw
@@ -2742,4 +2769,5 @@
     WRITE(lunout,*) ' carbon_cycle_tr = ', carbon_cycle_tr
     WRITE(lunout,*) ' carbon_cycle_cpl = ', carbon_cycle_cpl
+    WRITE(lunout,*) ' carbon_cycle_rad = ', carbon_cycle_rad
     WRITE(lunout,*) ' level_coupling_esm = ', level_coupling_esm
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cosp/phys_cosp.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cosp/phys_cosp.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cosp/phys_cosp.F90	(revision 3605)
@@ -354,5 +354,4 @@
       !$OMP END MASTER
       !$OMP BARRIER
-        debut_cosp=.false.
       endif ! debut_cosp
 !    else
@@ -366,5 +365,5 @@
 !        call cosp(overlap,Ncolumns,cfg,vgrid,gbx,sgx,sgradar,sglidar,isccp,misr,modis,rttov,stradar,stlidar)
 !#else
-        call cosp(overlap,Ncolumns,cfg,vgrid,gbx,sgx,sgradar,sglidar,isccp,misr,modis,stradar,stlidar)
+     if (.NOT. debut_cosp) call cosp(overlap,Ncolumns,cfg,vgrid,gbx,sgx,sgradar,sglidar,isccp,misr,modis,stradar,stlidar)
 !#endif
 !!
@@ -374,5 +373,5 @@
 
 !       print *, 'Calling write output'
-        call cosp_output_write(Nlevlmdz, Npoints, Ncolumns, itap, dtime, freq_COSP, missing_val, &
+     if (.NOT. debut_cosp) call cosp_output_write(Nlevlmdz, Npoints, Ncolumns, itap, dtime, freq_COSP, missing_val, &
                                cfg, gbx, vgrid, sglidar, sgradar, stlidar, stradar, & 
                                isccp, misr, modis)
@@ -400,4 +399,7 @@
 !  call system_clock(t1,count_rate,count_max)
 !  print *,(t1-t0)*1.0/count_rate
+    if (debut_cosp) then 
+      debut_cosp=.false.
+    endif
  
   CONTAINS 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cosp2/cosp_output_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cosp2/cosp_output_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cosp2/cosp_output_mod.F90	(revision 3605)
@@ -359,5 +359,5 @@
    WRITE(lunout,*) 'wxios_add_vaxis cth16 numMISRHgtBins, misr_histHgtCenters ', & 
                     numMISRHgtBins, misr_histHgtCenters 
-   CALL wxios_add_vaxis("cth", numMISRHgtBins, misr_histHgtCenters)
+   CALL wxios_add_vaxis("cth16", numMISRHgtBins, misr_histHgtCenters)
 
    WRITE(lunout,*) 'wxios_add_vaxis dbze DBZE_BINS, dbze_ax ', &
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/MISR_simulator.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/MISR_simulator.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/MISR_simulator.F90	(revision 3605)
@@ -0,0 +1,292 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2009, Roger Marchand, version 1.2
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History
+! May 2015 - D. Swales - Modified for COSPv2.0
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MODULE MOD_MISR_SIMULATOR
+  use cosp_kinds,      only: wp
+  use MOD_COSP_STATS,  ONLY: hist2D
+  use mod_cosp_config, ONLY: R_UNDEF,numMISRHgtBins,numMISRTauBins,misr_histHgt,  &
+                             misr_histTau
+  implicit none 
+
+  ! Parameters
+  real(wp),parameter :: &
+       misr_taumin = 0.3_wp,            & ! Minimum optical depth for joint-histogram
+       tauchk      = -1.*log(0.9999999)   ! Lower limit on optical depth
+
+contains
+
+  ! ######################################################################################
+  ! SUBROUTINE misr_subcolumn
+  ! ######################################################################################
+  SUBROUTINE MISR_SUBCOLUMN(npoints,ncol,nlev,dtau,zfull,at,sunlit,tauOUT,               &
+                        dist_model_layertops,box_MISR_ztop)
+    ! INPUTS
+    INTEGER, intent(in) :: &
+         npoints,    & ! Number of horizontal gridpoints
+         ncol,       & ! Number of subcolumns
+         nlev          ! Number of vertical layers
+    INTEGER, intent(in),dimension(npoints) :: &
+         sunlit        ! 1 for day points, 0 for night time
+    REAL(WP),intent(in),dimension(npoints,ncol,nlev) :: &
+         dtau          ! Optical thickness
+    REAL(WP),intent(in),dimension(npoints,nlev) :: &
+         zfull,      & ! Height of full model levels (i.e. midpoints), [nlev] is bottom
+         at            ! Temperature (K)
+
+    ! OUTPUTS
+    REAL(WP),intent(out),dimension(npoints,ncol) :: &
+         box_MISR_ztop,     & ! Cloud-top height in each column
+         tauOUT               ! Optical depth in each column
+    REAL(WP),intent(out),dimension(npoints,numMISRHgtBins) :: &
+         dist_model_layertops ! 
+
+    ! INTERNAL VARIABLES
+    INTEGER :: ilev,j,loop,ibox,thres_crossed_MISR
+    INTEGER :: iMISR_ztop
+    REAL(WP) :: cloud_dtau,MISR_penetration_height,ztest
+
+    ! ############################################################################
+    ! Initialize
+    box_MISR_ztop(1:npoints,1:ncol) = 0._wp  
+
+    do j=1,npoints
+
+       ! Estimate distribution of Model layer tops
+       dist_model_layertops(j,:)=0
+       do ilev=1,nlev
+          ! Define location of "layer top"
+          if(ilev.eq.1 .or. ilev.eq.nlev) then
+             ztest=zfull(j,ilev)
+          else
+             ztest=0.5_wp*(zfull(j,ilev)+zfull(j,ilev-1))
+          endif
+
+          ! Find MISR layer that contains this level
+          ! *NOTE* the first MISR level is "no height" level
+          iMISR_ztop=2
+          do loop=2,numMISRHgtBins
+             if ( ztest .gt. 1000*misr_histHgt(loop+1) ) then
+                iMISR_ztop=loop+1
+             endif
+          enddo
+          
+          dist_model_layertops(j,iMISR_ztop) = dist_model_layertops(j,iMISR_ztop)+1
+       enddo
+
+       ! For each GCM cell or horizontal model grid point   
+       do ibox=1,ncol
+          ! Compute optical depth as a cummulative distribution in the vertical (nlev).
+          tauOUT(j,ibox)=sum(dtau(j,ibox,1:nlev))
+
+          thres_crossed_MISR=0
+          do ilev=1,nlev
+             ! If there a cloud, start the counter and store this height
+             if(thres_crossed_MISR .eq. 0 .and. dtau(j,ibox,ilev) .gt. 0.) then
+                ! First encountered a "cloud"
+                thres_crossed_MISR = 1  
+                cloud_dtau         = 0            
+             endif
+
+             if( thres_crossed_MISR .lt. 99 .and. thres_crossed_MISR .gt. 0 ) then
+                if( dtau(j,ibox,ilev) .eq. 0.) then
+                   ! We have come to the end of the current cloud layer without yet 
+                   ! selecting a CTH boundary. Restart cloud tau counter 
+                   cloud_dtau=0
+                else
+                   ! Add current optical depth to count for the current cloud layer
+                   cloud_dtau=cloud_dtau+dtau(j,ibox,ilev)
+                endif
+                
+                ! If the cloud is continuous but optically thin (< 1) from above the 
+                ! current layer cloud top to the current level then MISR will like 
+                ! see a top below the top of the current layer.
+                if( dtau(j,ibox,ilev).gt.0 .and. (cloud_dtau-dtau(j,ibox,ilev)) .lt. 1) then
+                   if(dtau(j,ibox,ilev) .lt. 1 .or. ilev.eq.1 .or. ilev.eq.nlev) then
+                      ! MISR will likely penetrate to some point within this layer ... the middle
+                      MISR_penetration_height=zfull(j,ilev)
+                   else
+                      ! Take the OD = 1.0 level into this layer
+                      MISR_penetration_height=0.5_wp*(zfull(j,ilev)+zfull(j,ilev-1)) - &
+                           0.5_wp*(zfull(j,ilev-1)-zfull(j,ilev+1))/dtau(j,ibox,ilev) 
+                   endif
+                   box_MISR_ztop(j,ibox)=MISR_penetration_height
+                endif
+                
+                ! Check for a distinctive water layer
+                if(dtau(j,ibox,ilev) .gt. 1 .and. at(j,ilev) .gt. 273 ) then
+                   ! Must be a water cloud, take this as CTH level
+                   thres_crossed_MISR=99
+                endif
+                
+                ! If the total column optical depth is "large" than MISR can't see
+                ! anything else. Set current point as CTH level
+                if(sum(dtau(j,ibox,1:ilev)) .gt. 5) then
+                   thres_crossed_MISR=99           
+                endif
+             endif
+          enddo  
+          
+          ! Check to see if there was a cloud for which we didn't 
+          ! set a MISR cloud top boundary
+          if( thres_crossed_MISR .eq. 1) then
+             ! If the cloud has a total optical depth of greater
+             ! than ~ 0.5 MISR will still likely pick up this cloud
+             ! with a height near the true cloud top
+             ! otherwise there should be no CTH
+             if(sum(dtau(j,ibox,1:nlev)) .gt. 0.5) then
+                ! keep MISR detected CTH
+             elseif(sum(dtau(j,ibox,1:nlev)) .gt. 0.2) then
+                ! MISR may detect but wont likley have a good height
+                box_MISR_ztop(j,ibox)=-1
+             else
+                ! MISR not likely to even detect.
+                ! so set as not cloudy
+                box_MISR_ztop(j,ibox)=0
+             endif
+          endif
+       enddo  ! loop of subcolumns
+       
+    enddo    ! loop of gridpoints
+    
+    ! Modify MISR CTH for satellite spatial / pattern matcher effects
+    ! Code in this region added by roj 5/2006 to account
+    ! for spatial effect of the MISR pattern matcher.
+    ! Basically, if a column is found between two neighbors
+    ! at the same CTH, and that column has no hieght or
+    ! a lower CTH, THEN misr will tend to but place the
+    ! odd column at the same height as it neighbors.
+    
+    ! This setup assumes the columns represent a about a 1 to 4 km scale
+    ! it will need to be modified significantly, otherwise
+!	! DS2015: Add loop over gridpoints and index accordingly.
+!    if(ncol.eq.1) then
+!       ! Adjust based on neightboring points.
+!       do j=2,npoints-1   
+!          if(box_MISR_ztop(j-1,1) .gt. 0                             .and. &
+!             box_MISR_ztop(j+1,1) .gt. 0                             .and. &
+!             abs(box_MISR_ztop(j-1,1)-box_MISR_ztop(j+1,1)) .lt. 500 .and. &
+!             box_MISR_ztop(j,1) .lt. box_MISR_ztop(j+1,1)) then
+!             box_MISR_ztop(j,1) = box_MISR_ztop(j+1,1)    
+!          endif
+!       enddo
+!    else
+!       ! Adjust based on neighboring subcolumns.
+!       do j=1,npoints
+!          do ibox=2,ncol-1  
+!                 if(box_MISR_ztop(j,ibox-1) .gt. 0                                .and. &
+!                 box_MISR_ztop(j,ibox+1) .gt. 0                                .and. &
+!                 abs(box_MISR_ztop(j,ibox-1)-box_MISR_ztop(j,ibox+1)) .lt. 500 .and. &
+!                 box_MISR_ztop(j,ibox) .lt. box_MISR_ztop(j,ibox+1)) then
+!                 box_MISR_ztop(j,ibox) = box_MISR_ztop(j,ibox+1)    
+!               endif
+!          enddo
+!       enddo
+!    endif
+!    ! DS2015 END
+     
+    ! Fill dark scenes 
+    do j=1,numMISRHgtBins
+       where(sunlit .ne. 1) dist_model_layertops(1:npoints,j) = R_UNDEF
+    enddo
+
+  end SUBROUTINE MISR_SUBCOLUMN
+
+  ! ######################################################################################
+  ! SUBROUTINE misr_column
+  ! ######################################################################################
+  SUBROUTINE MISR_COLUMN(npoints,ncol,box_MISR_ztop,sunlit,tau,MISR_cldarea,MISR_mean_ztop,fq_MISR_TAU_v_CTH)
+
+    ! INPUTS
+    INTEGER, intent(in) :: &
+         npoints,        & ! Number of horizontal gridpoints
+         ncol              ! Number of subcolumns
+    INTEGER, intent(in),dimension(npoints) :: &
+         sunlit            ! 1 for day points, 0 for night time
+    REAL(WP),intent(in),dimension(npoints,ncol) :: &
+         box_MISR_ztop,  & ! Cloud-top height in each column
+         tau               ! Column optical thickness
+
+    ! OUTPUTS
+    REAL(WP),intent(inout),dimension(npoints) :: &
+         MISR_cldarea,   & ! Fraction area covered by clouds
+         MISR_mean_ztop    ! Mean cloud top height MISR would observe
+    REAL(WP),intent(inout),dimension(npoints,7,numMISRHgtBins) :: &
+         fq_MISR_TAU_v_CTH ! Joint histogram of cloud-cover and tau
+
+    ! INTERNAL VARIABLES
+    INTEGER :: j
+    LOGICAL,dimension(ncol) :: box_cloudy 
+    real(wp),dimension(npoints,ncol) :: tauWRK,box_MISR_ztopWRK
+    ! ############################################################################
+
+    ! Compute column quantities and joint-histogram
+    MISR_cldarea(1:npoints)                       = 0._wp
+    MISR_mean_ztop(1:npoints)                     = 0._wp
+    fq_MISR_TAU_v_CTH(1:npoints,1:7,1:numMISRHgtBins) = 0._wp
+    tauWRK(1:npoints,1:ncol)                      = tau(1:npoints,1:ncol)
+    box_MISR_ztopWRK(1:npoints,1:ncol)            = box_MISR_ztop(1:npoints,1:ncol)
+    do j=1,npoints
+
+       ! Subcolumns that are cloudy(true) and not(false)
+       box_cloudy(1:ncol) = merge(.true.,.false.,tau(j,1:ncol) .gt. tauchk)
+
+       ! Fill optically thin clouds with fill value
+       where(.not. box_cloudy(1:ncol)) tauWRK(j,1:ncol)  = -999._wp
+       where(box_MISR_ztopWRK(j,1:ncol) .eq. 0) box_MISR_ztopWRK(j,1:ncol)=-999._wp
+
+       ! Compute joint histogram and column quantities for points that are sunlit and cloudy
+       if (sunlit(j) .eq. 1) then 
+          ! Joint histogram
+          call hist2D(tauWRK(j,1:ncol),box_MISR_ztopWRK(j,1:ncol),ncol,misr_histTau,numMISRTauBins,&
+               1000*misr_histHgt,numMISRHgtBins,fq_MISR_TAU_v_CTH(j,1:numMISRTauBins,1:numMISRHgtBins))
+          fq_MISR_TAU_v_CTH(j,1:numMISRTauBins,1:numMISRHgtBins) =                       &
+             100._wp*fq_MISR_TAU_v_CTH(j,1:numMISRTauBins,1:numMISRHgtBins)/ncol
+
+          ! Column cloud area
+          MISR_cldarea(j)=real(count(box_MISR_ztopWRK(j,1:ncol) .ne. -999.))/ncol
+
+          ! Column cloud-top height
+          if ( count(box_MISR_ztopWRK(j,1:ncol) .ne. -999.) .ne. 0 ) then
+             MISR_mean_ztop(j) = sum(box_MISR_ztopWRK(j,1:ncol),box_MISR_ztopWRK(j,1:ncol) .ne. -999.)/ &
+                  count(box_MISR_ztopWRK(j,1:ncol) .ne. -999.)
+          else
+             MISR_mean_ztop(j) = R_UNDEF
+          endif
+
+       else
+          MISR_cldarea(j)         = R_UNDEF
+          MISR_mean_ztop(npoints) = R_UNDEF
+       endif
+    enddo
+
+  end SUBROUTINE MISR_COLUMN
+
+end MODULE MOD_MISR_SIMULATOR
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/array_lib.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/array_lib.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/array_lib.F90	(revision 3605)
@@ -0,0 +1,103 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History:
+! 10/16/03  John Haynes   - Original version (haynes@atmos.colostate.edu)
+! 01/31/06  John Haynes   - IDL to Fortran 90
+! 01/01/15  Dustin Swales - Modified for COSPv2.0
+! 
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+module array_lib
+  USE COSP_KINDS, ONLY: wp
+  implicit none
+contains
+
+  ! ############################################################################
+  !                               function INFIND
+  ! ############################################################################
+  function infind(list,val)
+    implicit none
+    ! ##########################################################################
+    ! Purpose:
+    !   Finds the index of an array that is closest to a value, plus the
+    !   difference between the value found and the value specified
+    !
+    ! Inputs:
+    !   [list]   an array of sequential values
+    !   [val]    a value to locate
+    ! Optional input:
+    !   [sort]   set to 1 if [list] is in unknown/non-sequential order
+    !
+    ! Returns:
+    !   index of [list] that is closest to [val]
+    !
+    ! Optional output:
+    !   [dist]   set to variable containing [list([result])] - [val]
+    !
+    ! Requires:
+    !   mrgrnk library
+    !
+    ! ##########################################################################
+
+    ! INPUTS
+    real(wp), dimension(:), intent(in) :: &
+         list   ! An array of sequential values
+    real(wp), intent(in) :: &
+         val    ! A value to locate
+    ! OUTPUTS
+    integer :: &
+         infind ! Index of [list] that is closest to [val]
+
+    ! Internal Variables
+    real(wp), dimension(size(list)) :: lists
+    integer :: nlist, result, tmp(1), sort_list
+    integer, dimension(size(list)) :: mask
+    
+    sort_list = 0
+    
+    nlist = size(list)
+    lists = list
+    
+    if (val >= lists(nlist)) then
+       result = nlist
+    else if (val <= lists(1)) then
+       result = 1
+    else
+       mask(:) = 0
+       where (lists < val) mask = 1
+       tmp = minloc(mask,1)
+       if (abs(lists(tmp(1)-1)-val) < abs(lists(tmp(1))-val)) then
+          result = tmp(1) - 1
+      else
+         result = tmp(1)
+      endif
+   endif
+   infind = result
+ end function infind
+
+end module array_lib
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp.F90	(revision 3605)
@@ -0,0 +1,3665 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History:
+! May 2015- D. Swales - Original version
+! Mar 2018- R. Guzman - Added OPAQ diagnostics and GLID simulator
+! Apr 2018- R. Guzman - Added ATLID simulator
+!
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
+MODULE MOD_COSP
+  USE COSP_KINDS,                  ONLY: wp
+  USE MOD_COSP_CONFIG,             ONLY: R_UNDEF,PARASOL_NREFL,LIDAR_NCAT,LIDAR_NTYPE, SR_BINS,&
+                                         N_HYDRO,RTTOV_MAX_CHANNELS,numMISRHgtBins,      &
+                                         cloudsat_DBZE_BINS,LIDAR_NTEMP,calipso_histBsct,&
+                                         use_vgrid,Nlvgrid,vgrid_zu,vgrid_zl,vgrid_z,    &
+                                         numMODISTauBins,numMODISPresBins,               &
+                                         numMODISReffIceBins,numMODISReffLiqBins,        &
+                                         numISCCPTauBins,numISCCPPresBins,numMISRTauBins,&
+                                         ntau,modis_histTau,tau_binBounds,               &
+                                         modis_histTauEdges,tau_binEdges,nCloudsatPrecipClass,&
+                                         modis_histTauCenters,tau_binCenters,            &
+!                                         cloudsat_preclvl,grLidar532_histBsct,atlid_histBsct !PREC_BUG
+                                         grLidar532_histBsct,atlid_histBsct                                
+  USE MOD_COSP_MODIS_INTERFACE,      ONLY: cosp_modis_init,       modis_IN
+!  USE MOD_COSP_RTTOV_INTERFACE,      ONLY: cosp_rttov_init,       rttov_IN
+  USE MOD_COSP_MISR_INTERFACE,       ONLY: cosp_misr_init,        misr_IN
+  USE MOD_COSP_ISCCP_INTERFACE,      ONLY: cosp_isccp_init,       isccp_IN
+  USE MOD_COSP_CALIPSO_INTERFACE,    ONLY: cosp_calipso_init,     calipso_IN
+  USE MOD_COSP_ATLID_INTERFACE,      ONLY: cosp_atlid_init,       atlid_IN 
+  USE MOD_COSP_GRLIDAR532_INTERFACE, ONLY: cosp_grLidar532_init, grLidar532_IN
+  USE MOD_COSP_PARASOL_INTERFACE,    ONLY: cosp_parasol_init,     parasol_in
+  USE MOD_COSP_CLOUDSAT_INTERFACE,   ONLY: cosp_cloudsat_init,    cloudsat_IN
+  USE quickbeam,                     ONLY: quickbeam_subcolumn,   quickbeam_column, radar_cfg
+  USE MOD_ICARUS,                    ONLY: icarus_subcolumn,      icarus_column
+  USE MOD_MISR_SIMULATOR,            ONLY: misr_subcolumn,        misr_column
+  USE MOD_LIDAR_SIMULATOR,           ONLY: lidar_subcolumn,       lidar_column
+  USE MOD_MODIS_SIM,                 ONLY: modis_subcolumn,       modis_column
+  USE MOD_PARASOL,                   ONLY: parasol_subcolumn,     parasol_column
+!  use mod_cosp_rttov,                ONLY: rttov_column
+  USE MOD_COSP_STATS,                ONLY: COSP_LIDAR_ONLY_CLOUD,COSP_CHANGE_VERTICAL_GRID
+
+  IMPLICIT NONE
+
+  logical :: linitialization ! Initialization flag
+
+  ! ######################################################################################
+  ! TYPE cosp_column_inputs
+  ! ######################################################################################
+  type cosp_column_inputs
+     integer :: &
+          Npoints,             & ! Number of gridpoints.
+          Ncolumns,            & ! Number of columns.
+          Nlevels                ! Number of levels.
+
+     integer,allocatable,dimension(:) :: &
+          sunlit                 ! Sunlit flag                            (0-1)
+
+     real(wp),allocatable,dimension(:,:) :: &
+          at,                  & ! Temperature                            (K)
+          pfull,               & ! Pressure                               (Pa)
+          phalf,               & ! Pressure at half-levels                (Pa)
+          qv,                  & ! Specific humidity                      (kg/kg)
+          hgt_matrix,          & ! Height of hydrometeors                 (km)
+          hgt_matrix_half        ! Height of hydrometeors at half levels  (km)
+
+     real(wp),allocatable,dimension(:) :: &
+          land,                & ! Land/Sea mask                          (0-1)
+          skt,                 & ! Surface temperature                    (K)
+          surfelev               ! Surface Elevation                      (m)
+     ! Fields used ONLY by RTTOV
+     integer :: &
+          month                  ! Month for surface emissivty atlas      (1-12)
+     real(wp) :: &
+          zenang,              & ! Satellite zenith angle for RTTOV       (deg)
+          co2,                 & ! CO2                                    (kg/kg)
+          ch4,                 & ! Methane                                (kg/kg)
+          n2o,                 & ! N2O                                    (kg/kg)
+          co                     ! CO                                     (kg/kg)
+     real(wp),allocatable,dimension(:) :: &
+          emis_sfc,            & ! Surface emissivity                     (1)
+          u_sfc,               & ! Surface u-wind                         (m/s)
+          v_sfc,               & ! Surface v-wind                         (m/s)
+          seaice,              & ! Sea-ice fraction                       (0-1)
+          lat,                 & ! Latitude                              (deg)
+          lon                    ! Longitude                              (deg)
+     real(wp),allocatable,dimension(:,:) :: &
+          o3,                  & ! Ozone                                  (kg/kg)
+          tca,                 & ! Total column cloud fraction            (0-1)
+          cloudIce,            & ! Cloud ice water mixing ratio           (kg/kg)
+          cloudLiq,            & ! Cloud liquid water mixing ratio        (kg/kg)
+          fl_rain,             & ! Precipitation (rain) flux              (kg/m2/s)
+          fl_snow                ! Precipitation (snow) flux              (kg/m2/s)
+  end type cosp_column_inputs
+
+  ! ######################################################################################
+  ! TYPE cosp_optical_inputs
+  ! ######################################################################################
+  type cosp_optical_inputs
+     integer :: &
+          Npoints,             & ! Number of gridpoints.
+          Ncolumns,            & ! Number of columns.
+          Nlevels,             & ! Number of levels.
+          Npart,               & ! Number of cloud meteors for LIDAR simulators.
+          Nrefl                  ! Number of reflectances for PARASOL simulator
+     real(wp) :: &
+          emsfc_lw               ! Surface emissivity @ 11micron
+     real(wp),allocatable,dimension(:,:,:) :: &
+          frac_out,            & ! Cloud fraction
+          tau_067,             & ! Optical depth @ 0.67micron
+          emiss_11,            & ! Emissivity @ 11 micron
+          fracLiq,             & ! Fraction of optical-depth due to liquid (MODIS)
+          asym,                & ! Assymetry parameter @ 3.7micron (MODIS)
+          ss_alb,              & ! Single-scattering albedo @ 3.7micron (MODIS)
+          betatot_calipso,     & ! Lidar backscatter coefficient (calipso @ 532nm)
+          betatot_grLidar532,  & ! Lidar backscatter coefficient (ground-lidar @ 532nm)
+          betatot_atlid,       & ! Lidar backscatter coefficient (atlid @ 355nm)
+          betatot_ice_calipso, & ! Lidar backscatter coefficient ICE (calipso @ 532nm)
+          betatot_liq_calipso, & ! Lidar backscatter coefficient LIQUID (calipso @ 532nm)
+          tautot_calipso,      & ! Lidar Optical thickness (calipso @ 532nm)
+          tautot_grLidar532,   & ! Lidar Optical thickness (ground-lidar @ 532nm)  
+          tautot_atlid,        & ! Lidar Optical thickness (atlid @ 355nm)
+          tautot_ice_calipso,  & ! Lidar Ice Optical thickness (calipso @ 532nm)
+          tautot_liq_calipso,  & ! Lidar Liquid Optical thickness (calipso @ 532nm)
+          z_vol_cloudsat,      & ! Effective reflectivity factor (mm^6/m^3)
+          kr_vol_cloudsat,     & ! Attenuation coefficient hydro (dB/km) 
+          g_vol_cloudsat         ! Attenuation coefficient gases (dB/km)
+     real(wp),allocatable,dimension(:,:) :: &
+          beta_mol_calipso,    & ! Lidar molecular backscatter coefficient (calipso @ 532nm)
+          beta_mol_grLidar532, & ! Lidar molecular backscatter coefficient (ground-lidar @ 532nm) 
+          beta_mol_atlid,      & ! Lidar molecular backscatter coefficient (atlid @ 355nm)
+          tau_mol_calipso,     & ! Lidar molecular optical depth (calipso @ 532nm)
+          tau_mol_grLidar532,  & ! Lidar molecular optical depth (ground-lidar @ 532nm) 
+          tau_mol_atlid,       & ! Lidar molecular optical depth (atlid @ 355nm)
+          tautot_S_liq,        & ! Parasol Liquid water optical thickness, from TOA to SFC
+          tautot_S_ice,        & ! Parasol Ice water optical thickness, from TOA to SFC
+          fracPrecipIce          ! Fraction of precipitation which is frozen (1).
+     type(radar_cfg) :: &
+          rcfg_cloudsat          ! Radar configuration information (CLOUDSAT)
+  end type cosp_optical_inputs
+
+  ! ######################################################################################
+  ! TYPE cosp_outputs
+  ! ######################################################################################
+  type cosp_outputs
+
+     ! CALIPSO outputs
+     real(wp),dimension(:,:,:),pointer :: &
+          calipso_betaperp_tot => null(),  & ! Total backscattered signal
+          calipso_beta_tot => null(),      & ! Total backscattered signal
+          calipso_tau_tot => null(),       & ! Optical thickness integrated from top to level z
+          calipso_lidarcldphase => null(), & ! 3D "lidar" phase cloud fraction
+          calipso_lidarcldtype => null(),  & ! 3D "lidar" OPAQ type fraction
+          calipso_cldlayerphase => null(), & ! low, mid, high-level lidar phase cloud cover
+          calipso_lidarcldtmp => null(),   & ! 3D "lidar" phase cloud temperature
+          calipso_cfad_sr => null()          ! CFAD of scattering ratio
+     real(wp), dimension(:,:),pointer :: &
+          calipso_lidarcld => null(),      & ! 3D "lidar" cloud fraction 
+          calipso_cldlayer => null(),      & ! low, mid, high-level, total lidar cloud cover
+          calipso_cldtype => null(),       & ! opaque and thin lidar cloud cover + z_opaque altitude
+          calipso_cldtypetemp => null(),   & ! opaque and thin cloud temperature  
+          calipso_cldtypemeanz => null(),  & ! opaque and thin cloud altitude 
+          calipso_cldtypemeanzse => null(),& ! same as just above with respect to SE
+          calipso_beta_mol => null(),      & ! Molecular backscatter
+          calipso_temp_tot => null()
+     real(wp), dimension(:),pointer :: &
+          calipso_cldthinemis => null(),   & ! thin cloud emissivity 
+          calipso_srbval => null()           ! SR bins in cfad_sr
+
+     ! GROUND LIDAR outputs
+     real(wp),dimension(:,:,:),pointer :: &  
+          grLidar532_beta_tot => null(),   & ! Total GROUND LIDAR backscattered signal 
+          grLidar532_cfad_sr => null()       ! CFAD of GROUND LIDAR scattering ratio 
+     real(wp), dimension(:,:),pointer :: &  
+          grLidar532_lidarcld => null(),   & ! 3D GROUND "lidar" cloud fraction  
+          grLidar532_cldlayer => null(),   & ! low, mid, high-level, total GROUND lidar cloud cover
+          grLidar532_beta_mol => null()      ! GROUND LIDAR Molecular backscatter 
+     real(wp), dimension(:),pointer :: &  
+          grLidar532_srbval => null()        ! SR bins in cfad_sr
+
+     ! ATLID outputs
+     real(wp),dimension(:,:,:),pointer :: & 
+          atlid_beta_tot => null(),   & ! Total ATLID backscattered signal 
+          atlid_cfad_sr => null()       ! CFAD of ATLID scattering ratio 
+     real(wp), dimension(:,:),pointer :: & 
+          atlid_lidarcld => null(),   & ! 3D ATLID cloud fraction
+          atlid_cldlayer => null(),   & ! low, mid, high-level, total ATLID cloud cover 
+          atlid_beta_mol => null()      ! ATLID Molecular backscatter 
+     real(wp), dimension(:),pointer :: & 
+          atlid_srbval => null()        ! SR bins in cfad_sr
+
+
+     ! PARASOL outputs
+     real(wp),dimension(:,:,:),pointer :: &
+          parasolPix_refl => null()            ! PARASOL reflectances (subcolumn)
+     real(wp),dimension(:,:),pointer :: &
+          parasolGrid_refl => null()           ! PARASOOL reflectances (column)
+
+     ! CLOUDSAT outputs
+     real(wp),dimension(:,:,:),pointer :: &
+          cloudsat_Ze_tot => null(),         & ! Effective reflectivity factor (Npoints,Ncolumns,Nlevels)
+          cloudsat_cfad_ze => null()           ! Ze CFAD(Npoints,dBZe_bins,Nlevels)
+     real(wp), dimension(:,:),pointer :: &
+          lidar_only_freq_cloud => null(),   & ! (Npoints,Nlevels)
+          cloudsat_precip_cover => null()      ! Radar total cloud amount by CloudSat precip flag (Npoints,dBZe_bins)
+     real(wp),dimension(:),pointer :: &
+          cloudsat_tcc => null(),             &
+          cloudsat_tcc2 => null(),            &          
+          radar_lidar_tcc => null(),         & ! Radar&lidar total cloud amount, grid-box scale (Npoints)
+          cloudsat_pia => null()               ! Radar path integrated attenuation (Npoints)
+          
+     ! ISCCP outputs       
+     real(wp),dimension(:),pointer :: &
+          isccp_totalcldarea => null(), & ! The fraction of model grid box columns with cloud
+           		                  ! somewhere in them. (%)
+          isccp_meantb => null(),       & ! Mean all-sky 10.5 micron brightness temperature. (K)
+          isccp_meantbclr => null(),    & ! Mean clear-sky 10.5 micron brightness temperature. (K)
+          isccp_meanptop => null(),     & ! Mean cloud top pressure (mb).
+          isccp_meantaucld => null(),   & ! Mean optical thickness. (1)
+          isccp_meanalbedocld => null()   ! Mean cloud albedo. (1)
+     real(wp),dimension(:,:),pointer ::&
+          isccp_boxtau => null(),       & ! Optical thickness in each column. (1)
+          isccp_boxptop => null()         ! Cloud top pressure in each column. (mb)
+     real(wp),dimension(:,:,:),pointer :: &
+          isccp_fq  => null()             ! The fraction of the model grid box covered by each of
+                                          ! the 49 ISCCP D level cloud types. (%)
+
+     ! MISR outptus
+     real(wp),dimension(:,:,:),pointer ::   & !
+          misr_fq => null()          ! Fraction of the model grid box covered by each of the MISR
+                           ! cloud types
+     real(wp),dimension(:,:),pointer ::   & !
+          misr_dist_model_layertops => null() !
+     real(wp),dimension(:),pointer ::   & !
+          misr_meanztop => null(), & ! Mean MISR cloud top height
+          misr_cldarea => null()     ! Mean MISR cloud cover area
+
+     ! MODIS outptus
+     real(wp),pointer,dimension(:) ::      & !
+          modis_Cloud_Fraction_Total_Mean => null(),       & ! L3 MODIS retrieved cloud fraction (total)
+          modis_Cloud_Fraction_Water_Mean => null(),       & ! L3 MODIS retrieved cloud fraction (liq)
+          modis_Cloud_Fraction_Ice_Mean => null(),         & ! L3 MODIS retrieved cloud fraction (ice)
+          modis_Cloud_Fraction_High_Mean => null(),        & ! L3 MODIS retrieved cloud fraction (high)
+          modis_Cloud_Fraction_Mid_Mean => null(),         & ! L3 MODIS retrieved cloud fraction (middle)
+          modis_Cloud_Fraction_Low_Mean => null(),         & ! L3 MODIS retrieved cloud fraction (low )
+          modis_Optical_Thickness_Total_Mean => null(),    & ! L3 MODIS retrieved optical thickness (tot)
+          modis_Optical_Thickness_Water_Mean => null(),    & ! L3 MODIS retrieved optical thickness (liq)
+          modis_Optical_Thickness_Ice_Mean => null(),      & ! L3 MODIS retrieved optical thickness (ice)
+          modis_Optical_Thickness_Total_LogMean => null(), & ! L3 MODIS retrieved log10 optical thickness
+          modis_Optical_Thickness_Water_LogMean => null(), & ! L3 MODIS retrieved log10 optical thickness
+          modis_Optical_Thickness_Ice_LogMean => null(),   & ! L3 MODIS retrieved log10 optical thickness
+          modis_Cloud_Particle_Size_Water_Mean => null(),  & ! L3 MODIS retrieved particle size (liquid)
+          modis_Cloud_Particle_Size_Ice_Mean => null(),    & ! L3 MODIS retrieved particle size (ice)
+          modis_Cloud_Top_Pressure_Total_Mean => null(),   & ! L3 MODIS retrieved cloud top pressure
+          modis_Liquid_Water_Path_Mean => null(),          & ! L3 MODIS retrieved liquid water path
+          modis_Ice_Water_Path_Mean => null()                ! L3 MODIS retrieved ice water path
+     real(wp),pointer,dimension(:,:,:) ::  &
+          modis_Optical_Thickness_vs_Cloud_Top_Pressure => null(), & ! Tau/Pressure joint histogram
+          modis_Optical_Thickness_vs_ReffICE => null(),            & ! Tau/ReffICE joint histogram
+          modis_Optical_Thickness_vs_ReffLIQ => null()               ! Tau/ReffLIQ joint histogram
+
+     ! RTTOV outputs
+     real(wp),pointer :: &
+          rttov_tbs(:,:) => null() ! Brightness Temperature
+
+  end type cosp_outputs
+
+CONTAINS
+  ! ######################################################################################
+  ! FUNCTION cosp_simulator
+  ! ######################################################################################
+  function COSP_SIMULATOR(cospIN,cospgridIN,cospOUT,start_idx,stop_idx,debug)
+    type(cosp_optical_inputs),intent(in),target :: cospIN     ! Optical inputs to COSP simulator
+    type(cosp_column_inputs), intent(in),target :: cospgridIN ! Host model inputs to COSP
+
+    ! Inputs into the simulators
+    type(isccp_IN)    :: isccpIN    ! Input to the ISCCP simulator
+    type(misr_IN)     :: misrIN     ! Input to the LIDAR simulator
+    type(calipso_IN)  :: calipsoIN  ! Input to the LIDAR simulator
+    type(grLidar532_IN) :: grLidar532IN ! Input to the GROUND LIDAR simulator
+    type(atlid_IN)    :: atlidIN    ! Input to the ATLID simulator 
+    type(parasol_IN)  :: parasolIN  ! Input to the PARASOL simulator
+    type(cloudsat_IN) :: cloudsatIN ! Input to the CLOUDSAT radar simulator
+    type(modis_IN)    :: modisIN    ! Input to the MODIS simulator
+!    type(rttov_IN)    :: rttovIN    ! Input to the RTTOV simulator
+    integer,optional  :: start_idx,stop_idx
+    logical,optional  :: debug
+
+    ! Outputs from the simulators (nested simulator output structure)
+    type(cosp_outputs), intent(inout) :: cospOUT
+    character(len=256),dimension(100) :: cosp_simulator
+
+    ! Local variables
+    integer :: &
+         i,icol,ij,ik,nError
+    integer,target :: &
+         Npoints
+    logical :: &
+         Lisccp_subcolumn,     & ! On/Off switch for subcolumn ISCCP simulator
+         Lmisr_subcolumn,      & ! On/Off switch for subcolumn MISR simulator
+         Lcalipso_subcolumn,   & ! On/Off switch for subcolumn CALIPSO simulator
+         LgrLidar532_subcolumn,& ! On/Off switch for subcolumn GROUND LIDAR simulator
+         Latlid_subcolumn,     & ! On/Off switch for subcolumn ATLID simulator
+         Lparasol_subcolumn,   & ! On/Off switch for subcolumn PARASOL simulator
+         Lcloudsat_subcolumn,  & ! On/Off switch for subcolumn CLOUDSAT simulator
+         Lmodis_subcolumn,     & ! On/Off switch for subcolumn MODIS simulator
+         Lrttov_subcolumn,     & ! On/Off switch for subcolumn RTTOV simulator
+         Lisccp_column,        & ! On/Off switch for column ISCCP simulator
+         Lmisr_column,         & ! On/Off switch for column MISR simulator
+         Lcalipso_column,      & ! On/Off switch for column CALIPSO simulator
+         LgrLidar532_column,   & ! On/Off switch for column GROUND LIDAR simulator
+         Latlid_column,        & ! On/Off switch for column ATLID simulator
+         Lparasol_column,      & ! On/Off switch for column PARASOL simulator
+         Lcloudsat_column,     & ! On/Off switch for column CLOUDSAT simulator
+         Lmodis_column,        & ! On/Off switch for column MODIS simulator
+         Lrttov_column,        & ! On/Off switch for column RTTOV simulator (not used)
+         Lradar_lidar_tcc,     & ! On/Off switch from joint Calipso/Cloudsat product
+         Lcloudsat_tcc,       & !
+         Lcloudsat_tcc2,      & !         
+         Llidar_only_freq_cloud  ! On/Off switch from joint Calipso/Cloudsat product
+    logical :: &
+         ok_lidar_cfad    = .false., &
+         ok_lidar_cfad_grLidar532 = .false., & 
+         ok_lidar_cfad_atlid = .false., &
+         lrttov_cleanUp   = .false.
+    
+    integer, dimension(:,:),allocatable  :: &
+         modisRetrievedPhase,isccpLEVMATCH
+    real(wp), dimension(:),  allocatable  :: &
+         modisCfTotal,modisCfLiquid,modisMeanIceWaterPath, isccp_meantbclr,     &
+         modisCfIce, modisCfHigh, modisCfMid, modisCfLow,modisMeanTauTotal,     &
+         modisMeanTauLiquid, modisMeanTauIce, modisMeanLogTauTotal,             &
+         modisMeanLogTauLiquid, modisMeanLogTauIce, modisMeanSizeLiquid,        &
+         modisMeanSizeIce, modisMeanCloudTopPressure, modisMeanLiquidWaterPath, &
+         radar_lidar_tcc, cloudsat_tcc, cloudsat_tcc2
+    REAL(WP), dimension(:,:),allocatable  :: &
+         modisRetrievedCloudTopPressure,modisRetrievedTau,modisRetrievedSize,   &
+         misr_boxtau,misr_boxztop,misr_dist_model_layertops,isccp_boxtau,       &
+         isccp_boxttop,isccp_boxptop,calipso_beta_mol,lidar_only_freq_cloud,    &
+         grLidar532_beta_mol,atlid_beta_mol 
+    REAL(WP), dimension(:,:,:),allocatable :: &
+         modisJointHistogram,modisJointHistogramIce,modisJointHistogramLiq,     &
+         calipso_beta_tot,calipso_betaperp_tot, cloudsatDBZe,parasolPix_refl,   &
+         grLidar532_beta_tot,atlid_beta_tot,cloudsatZe_non
+    real(wp),dimension(:),allocatable,target :: &
+         out1D_1,out1D_2,out1D_3,out1D_4,out1D_5,out1D_6,out1D_7,out1D_8,       &
+         out1D_9,out1D_10,out1D_11,out1D_12 
+    real(wp),dimension(:,:,:),allocatable :: &
+       betamol_in,betamoli,pnormi,ze_toti,ze_noni
+
+    ! Initialize error reporting for output
+    cosp_simulator(:)=''
+
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! 1) Determine if using full inputs or subset
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if (present(start_idx) .and. present(stop_idx)) then
+       ij=start_idx
+       ik=stop_idx
+    else
+       ij=1
+       ik=cospIN%Npoints
+    endif
+    Npoints = ik-ij+1
+
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! 2a) Determine which simulators to run and which statistics to compute
+    !    - If any of the subcolumn fields are allocated, then run the subcolumn simulators.
+    !    - If any of the column fields are allocated, then compute the statistics for that
+    !      simulator, but only save the requested fields.
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! Start with all simulators and joint-diagnostics off
+    Lisccp_subcolumn    = .false.
+    Lmisr_subcolumn     = .false.
+    Lcalipso_subcolumn  = .false.
+    LgrLidar532_subcolumn = .false.
+    Latlid_subcolumn    = .false. 
+    Lparasol_subcolumn  = .false.
+    Lcloudsat_subcolumn = .false.
+    Lmodis_subcolumn    = .false.
+    Lrttov_subcolumn    = .false.
+    Lisccp_column       = .false.
+    Lmisr_column        = .false.
+    Lcalipso_column     = .false.
+    LgrLidar532_column = .false.
+    Latlid_column       = .false.
+    Lparasol_column     = .false.
+    Lcloudsat_column    = .false.
+    Lmodis_column       = .false.
+    Lrttov_column       = .false.
+    Lradar_lidar_tcc    = .false.
+    Llidar_only_freq_cloud = .false.
+    Lcloudsat_tcc       = .false.
+    Lcloudsat_tcc2      = .false.
+
+    ! CLOUDSAT subcolumn
+    if (associated(cospOUT%cloudsat_Ze_tot)) Lcloudsat_subcolumn = .true.
+
+    ! MODIS subcolumn
+    if (associated(cospOUT%modis_Cloud_Fraction_Water_Mean)                .or.          &
+        associated(cospOUT%modis_Cloud_Fraction_Total_Mean)                .or.          &
+        associated(cospOUT%modis_Cloud_Fraction_Ice_Mean)                  .or.          &
+        associated(cospOUT%modis_Cloud_Fraction_High_Mean)                 .or.          &
+        associated(cospOUT%modis_Cloud_Fraction_Mid_Mean)                  .or.          &
+        associated(cospOUT%modis_Cloud_Fraction_Low_Mean)                  .or.          &
+        associated(cospOUT%modis_Optical_Thickness_Total_Mean)             .or.          &
+        associated(cospOUT%modis_Optical_Thickness_Water_Mean)             .or.          &
+        associated(cospOUT%modis_Optical_Thickness_Ice_Mean)               .or.          &
+        associated(cospOUT%modis_Optical_Thickness_Total_LogMean)          .or.          &
+        associated(cospOUT%modis_Optical_Thickness_Water_LogMean)          .or.          &
+        associated(cospOUT%modis_Optical_Thickness_Ice_LogMean)            .or.          &
+        associated(cospOUT%modis_Cloud_Particle_Size_Water_Mean)           .or.          &
+        associated(cospOUT%modis_Cloud_Particle_Size_Ice_Mean)             .or.          &
+        associated(cospOUT%modis_Cloud_Top_Pressure_Total_Mean)            .or.          &
+        associated(cospOUT%modis_Liquid_Water_Path_Mean)                   .or.          &
+        associated(cospOUT%modis_Ice_Water_Path_Mean)                      .or.          &
+        associated(cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure))               &
+       Lmodis_subcolumn    = .true.
+
+    ! ISCCP subcolumn
+    if (associated(cospOUT%isccp_boxtau)                                   .or.          &
+        associated(cospOUT%isccp_boxptop))                                               &
+       Lisccp_subcolumn    = .true.
+
+    ! MISR subcolumn
+    if (associated(cospOUT%misr_dist_model_layertops))                                   &
+       Lmisr_subcolumn     = .true.
+
+    ! CALIPOSO subcolumn
+    if (associated(cospOUT%calipso_tau_tot)                                .or.          &
+        associated(cospOUT%calipso_beta_mol)                               .or.          &
+        associated(cospOUT%calipso_temp_tot)                               .or.          &
+        associated(cospOUT%calipso_betaperp_tot)                           .or.          &
+        associated(cospOUT%calipso_beta_tot))                                            &
+       Lcalipso_subcolumn  = .true.
+
+    ! GROUND LIDAR subcolumn 
+    if (associated(cospOUT%grLidar532_beta_mol)                           .or.          &
+        associated(cospOUT%grLidar532_beta_tot))                                        &
+       LgrLidar532_subcolumn  = .true. 
+
+    ! ATLID subcolumn
+    if (associated(cospOUT%atlid_beta_mol)                                 .or.          & 
+        associated(cospOUT%atlid_beta_tot))                                              &
+       Latlid_subcolumn  = .true.  
+
+    ! PARASOL subcolumn
+    if (associated(cospOUT%parasolPix_refl))                                             &
+       Lparasol_subcolumn  = .true.
+
+    ! RTTOV column
+    if (associated(cospOUT%rttov_tbs))                                                   &
+       Lrttov_column    = .true.
+
+    ! Set flag to deallocate rttov types (only done on final call to simulator)
+    if (size(cospOUT%isccp_meantb) .eq. stop_idx) lrttov_cleanUp = .true.
+
+    ! ISCCP column
+    if (associated(cospOUT%isccp_fq)                                       .or.          &
+        associated(cospOUT%isccp_meanalbedocld)                            .or.          &
+        associated(cospOUT%isccp_meanptop)                                 .or.          &
+        associated(cospOUT%isccp_meantaucld)                               .or.          &
+        associated(cospOUT%isccp_totalcldarea)                             .or.          &
+        associated(cospOUT%isccp_meantb)) then
+       Lisccp_column    = .true.
+       Lisccp_subcolumn = .true.
+    endif
+
+    ! MISR column
+    if (associated(cospOUT%misr_cldarea)                                   .or.          &
+        associated(cospOUT%misr_meanztop)                                  .or.          &
+        associated(cospOUT%misr_fq)) then
+       Lmisr_column    = .true.
+       Lmisr_subcolumn = .true.
+    endif
+
+    ! CALIPSO column
+    if (associated(cospOUT%calipso_cfad_sr)                                .or.          &
+        associated(cospOUT%calipso_lidarcld)                               .or.          &
+        associated(cospOUT%calipso_lidarcldphase)                          .or.          &
+        associated(cospOUT%calipso_lidarcldtype)                           .or.          &
+        associated(cospOUT%calipso_cldlayer)                               .or.          &
+        associated(cospOUT%calipso_cldtype)                                .or.          & 
+        associated(cospOUT%calipso_cldtypetemp)                            .or.          & 
+        associated(cospOUT%calipso_cldtypemeanz)                           .or.          & 
+        associated(cospOUT%calipso_cldtypemeanzse)                         .or.          & 
+        associated(cospOUT%calipso_cldthinemis)                            .or.          &
+        associated(cospOUT%calipso_cldlayerphase)                          .or.          &
+        associated(cospOUT%calipso_lidarcldtmp)) then
+       Lcalipso_column    = .true.
+       Lcalipso_subcolumn = .true.
+    endif
+
+    ! GROUND LIDAR column 
+    if (associated(cospOUT%grLidar532_cfad_sr)                            .or.          & 
+        associated(cospOUT%grLidar532_lidarcld)                           .or.          & 
+        associated(cospOUT%grLidar532_cldlayer)) then 
+       LgrLidar532_column    = .true. 
+       LgrLidar532_subcolumn = .true. 
+    endif
+
+    ! ATLID column 
+    if (associated(cospOUT%atlid_cfad_sr)                                  .or.          & 
+        associated(cospOUT%atlid_lidarcld)                                 .or.          & 
+        associated(cospOUT%atlid_cldlayer)) then  
+       Latlid_column    = .true. 
+       Latlid_subcolumn = .true.
+    endif
+
+    ! PARASOL column
+    if (associated(cospOUT%parasolGrid_refl)) then
+       Lparasol_column    = .true.
+       Lparasol_subcolumn = .true.
+    endif
+
+    ! CLOUDSAT column
+    if (associated(cospOUT%cloudsat_cfad_ze)) then
+       Lcloudsat_column    = .true.
+       Lcloudsat_subcolumn = .true.
+    endif
+
+    ! MODIS column
+    if (associated(cospOUT%modis_Cloud_Fraction_Total_Mean)                .or.          &
+        associated(cospOUT%modis_Cloud_Fraction_Water_Mean)                .or.          &
+        associated(cospOUT%modis_Cloud_Fraction_Ice_Mean)                  .or.          &
+        associated(cospOUT%modis_Cloud_Fraction_High_Mean)                 .or.          &
+        associated(cospOUT%modis_Cloud_Fraction_Mid_Mean)                  .or.          &
+        associated(cospOUT%modis_Cloud_Fraction_Low_Mean)                  .or.          &
+        associated(cospOUT%modis_Optical_Thickness_Total_Mean)             .or.          &
+        associated(cospOUT%modis_Optical_Thickness_Water_Mean)             .or.          &
+        associated(cospOUT%modis_Optical_Thickness_Ice_Mean)               .or.          &
+        associated(cospOUT%modis_Optical_Thickness_Total_LogMean)          .or.          &
+        associated(cospOUT%modis_Optical_Thickness_Water_LogMean)          .or.          &
+        associated(cospOUT%modis_Optical_Thickness_Ice_LogMean)            .or.          &
+        associated(cospOUT%modis_Cloud_Particle_Size_Water_Mean)           .or.          &
+        associated(cospOUT%modis_Cloud_Particle_Size_Ice_Mean)             .or.          &
+        associated(cospOUT%modis_Cloud_Top_Pressure_Total_Mean)            .or.          &
+        associated(cospOUT%modis_Liquid_Water_Path_Mean)                   .or.          &
+        associated(cospOUT%modis_Ice_Water_Path_Mean)                      .or.          &
+        associated(cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure)) then
+       Lmodis_column    = .true.
+       Lmodis_subcolumn = .true.
+    endif
+
+    ! Joint simulator products
+    if (associated(cospOUT%lidar_only_freq_cloud) .or. associated(cospOUT%radar_lidar_tcc) .or. &
+        associated(cospOUT%cloudsat_tcc) .or. associated(cospOUT%cloudsat_tcc2)) then
+       Lcalipso_column     = .true.
+       Lcalipso_subcolumn  = .true.
+       Lcloudsat_column    = .true.
+       Lcloudsat_subcolumn = .true.
+       Lradar_lidar_tcc    = .true.
+       Llidar_only_freq_cloud = .true.
+       Lcloudsat_tcc       = .true.
+       Lcloudsat_tcc2      = .true.
+    endif
+
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! 2b) Error Checking
+    !     Enforce bounds on input fields. If input field is out-of-bounds, report error
+    !     and turn off simulator
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    call cosp_errorCheck(cospgridIN, cospIN, Lisccp_subcolumn, Lisccp_column,            &
+         Lmisr_subcolumn, Lmisr_column, Lmodis_subcolumn, Lmodis_column,                 &
+         Lcloudsat_subcolumn, Lcloudsat_column, Lcalipso_subcolumn, Lcalipso_column,     &
+         Latlid_subcolumn, Latlid_column, LgrLidar532_subcolumn, LgrLidar532_column,     &
+         Lrttov_subcolumn, Lrttov_column, Lparasol_subcolumn, Lparasol_column,           &
+         Lradar_lidar_tcc, Llidar_only_freq_cloud, Lcloudsat_tcc,Lcloudsat_tcc2, cospOUT,&
+         cosp_simulator, nError)
+
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! 3) Populate instrument simulator inputs
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if (Lisccp_subcolumn .or. Lmodis_subcolumn) then
+       isccpIN%Npoints  => Npoints
+       isccpIN%Ncolumns => cospIN%Ncolumns
+       isccpIN%Nlevels  => cospIN%Nlevels
+       isccpIN%emsfc_lw => cospIN%emsfc_lw
+       isccpIN%skt      => cospgridIN%skt
+       isccpIN%qv       => cospgridIN%qv
+       isccpIN%at       => cospgridIN%at
+       isccpIN%frac_out => cospIN%frac_out
+       isccpIN%dtau     => cospIN%tau_067
+       isccpIN%dem      => cospIN%emiss_11
+       isccpIN%phalf    => cospgridIN%phalf
+       isccpIN%sunlit   => cospgridIN%sunlit
+       isccpIN%pfull    => cospgridIN%pfull
+    endif
+
+    if (Lmisr_subcolumn) then
+       misrIN%Npoints  => Npoints
+       misrIN%Ncolumns => cospIN%Ncolumns
+       misrIN%Nlevels  => cospIN%Nlevels
+       misrIN%dtau     => cospIN%tau_067
+       misrIN%sunlit   => cospgridIN%sunlit
+       misrIN%zfull    => cospgridIN%hgt_matrix
+       misrIN%at       => cospgridIN%at
+    endif
+
+    if (Lcalipso_subcolumn) then
+       calipsoIN%Npoints     => Npoints
+       calipsoIN%Ncolumns    => cospIN%Ncolumns
+       calipsoIN%Nlevels     => cospIN%Nlevels
+       calipsoIN%beta_mol    => cospIN%beta_mol_calipso
+       calipsoIN%betatot     => cospIN%betatot_calipso
+       calipsoIN%betatot_liq => cospIN%betatot_liq_calipso
+       calipsoIN%betatot_ice => cospIN%betatot_ice_calipso
+       calipsoIN%tau_mol     => cospIN%tau_mol_calipso
+       calipsoIN%tautot      => cospIN%tautot_calipso
+       calipsoIN%tautot_liq  => cospIN%tautot_liq_calipso
+       calipsoIN%tautot_ice  => cospIN%tautot_ice_calipso
+    endif
+
+    if (LgrLidar532_subcolumn) then 
+       grLidar532IN%Npoints  => Npoints
+       grLidar532IN%Ncolumns => cospIN%Ncolumns 
+       grLidar532IN%Nlevels  => cospIN%Nlevels
+       grLidar532IN%beta_mol => cospIN%beta_mol_grLidar532 
+       grLidar532IN%betatot  => cospIN%betatot_grLidar532 
+       grLidar532IN%tau_mol  => cospIN%tau_mol_grLidar532 
+       grLidar532IN%tautot   => cospIN%tautot_grLidar532  
+    endif
+    
+    if (Latlid_subcolumn) then 
+       atlidIN%Npoints        => Npoints 
+       atlidIN%Ncolumns       => cospIN%Ncolumns 
+       atlidIN%Nlevels        => cospIN%Nlevels 
+       atlidIN%beta_mol_atlid => cospIN%beta_mol_atlid
+       atlidIN%betatot_atlid  => cospIN%betatot_atlid 
+       atlidIN%tau_mol_atlid  => cospIN%tau_mol_atlid 
+       atlidIN%tautot_atlid   => cospIN%tautot_atlid 
+    endif 
+    
+    if (Lparasol_subcolumn) then
+       parasolIN%Npoints      => Npoints
+       parasolIN%Nlevels      => cospIN%Nlevels
+       parasolIN%Ncolumns     => cospIN%Ncolumns
+       parasolIN%Nrefl        => cospIN%Nrefl
+       parasolIN%tautot_S_liq => cospIN%tautot_S_liq
+       parasolIN%tautot_S_ice => cospIN%tautot_S_ice
+    endif
+
+    if (Lcloudsat_subcolumn) then
+       cloudsatIN%Npoints    => Npoints
+       cloudsatIN%Nlevels    => cospIN%Nlevels
+       cloudsatIN%Ncolumns   => cospIN%Ncolumns
+       cloudsatIN%z_vol      => cospIN%z_vol_cloudsat
+       cloudsatIN%kr_vol     => cospIN%kr_vol_cloudsat
+       cloudsatIN%g_vol      => cospIN%g_vol_cloudsat
+       cloudsatIN%rcfg       => cospIN%rcfg_cloudsat
+       cloudsatIN%hgt_matrix => cospgridIN%hgt_matrix
+    endif
+
+    if (Lmodis_subcolumn) then
+       modisIN%Ncolumns  => cospIN%Ncolumns
+       modisIN%Nlevels   => cospIN%Nlevels
+       modisIN%Npoints   => Npoints
+       modisIN%liqFrac   => cospIN%fracLiq
+       modisIN%tau       => cospIN%tau_067
+       modisIN%g         => cospIN%asym
+       modisIN%w0        => cospIN%ss_alb
+       modisIN%Nsunlit   = count(cospgridIN%sunlit > 0)
+       if (modisIN%Nsunlit .gt. 0) then
+          allocate(modisIN%sunlit(modisIN%Nsunlit),modisIN%pres(modisIN%Nsunlit,cospIN%Nlevels+1))
+          modisIN%sunlit    = pack((/ (i, i = 1, Npoints ) /),mask = cospgridIN%sunlit > 0)
+          modisIN%pres      = cospgridIN%phalf(int(modisIN%sunlit(:)),:)
+       endif
+       if (count(cospgridIN%sunlit <= 0) .gt. 0) then
+          allocate(modisIN%notSunlit(count(cospgridIN%sunlit <= 0)))
+          modisIN%notSunlit = pack((/ (i, i = 1, Npoints ) /),mask = .not. cospgridIN%sunlit > 0)
+       endif
+    endif
+
+!    if (Lrttov_column) then
+!       rttovIN%nPoints    => Npoints
+!       rttovIN%nLevels    => cospIN%nLevels
+!       rttovIN%nSubCols   => cospIN%nColumns
+!       rttovIN%zenang     => cospgridIN%zenang
+!       rttovIN%co2        => cospgridIN%co2
+!       rttovIN%ch4        => cospgridIN%ch4
+!       rttovIN%n2o        => cospgridIN%n2o
+!       rttovIN%co         => cospgridIN%co
+!       rttovIN%surfem     => cospgridIN%emis_sfc
+!       rttovIN%h_surf     => cospgridIN%hgt_matrix_half(:,cospIN%Nlevels+1)
+!       rttovIN%u_surf     => cospgridIN%u_sfc
+!       rttovIN%v_surf     => cospgridIN%v_sfc
+!       rttovIN%t_skin     => cospgridIN%skt
+!       rttovIN%p_surf     => cospgridIN%phalf(:,cospIN%Nlevels+1)
+!       rttovIN%q2m        => cospgridIN%qv(:,cospIN%Nlevels)
+!       rttovIN%t2m        => cospgridIN%at(:,cospIN%Nlevels)
+!       rttovIN%lsmask     => cospgridIN%land
+!       rttovIN%latitude   => cospgridIN%lat
+!       rttovIN%longitude  => cospgridIN%lon
+!       rttovIN%seaice     => cospgridIN%seaice
+!       rttovIN%p          => cospgridIN%pfull
+!       rttovIN%ph         => cospgridIN%phalf
+!       rttovIN%t          => cospgridIN%at
+!       rttovIN%q          => cospgridIN%qv
+!       rttovIN%o3         => cospgridIN%o3
+       ! Below only needed for all-sky RTTOV calculation
+!       rttovIN%month      => cospgridIN%month
+!       rttovIN%tca        => cospgridIN%tca
+!       rttovIN%cldIce     => cospgridIN%cloudIce
+!       rttovIN%cldLiq     => cospgridIN%cloudLiq
+!       rttovIN%fl_rain    => cospgridIN%fl_rain
+!       rttovIN%fl_snow    => cospgridIN%fl_snow
+!    endif
+
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! 4) Call subcolumn simulators
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+    ! ISCCP (icarus) subcolumn simulator
+    if (Lisccp_subcolumn .or. Lmodis_subcolumn) then
+       ! Allocate space for local variables
+       allocate(isccpLEVMATCH(Npoints,isccpIN%Ncolumns),                                 &
+                isccp_boxttop(Npoints,isccpIN%Ncolumns),                                 &
+                isccp_boxptop(Npoints,isccpIN%Ncolumns),                                 &
+                isccp_boxtau(Npoints,isccpIN%Ncolumns), isccp_meantbclr(Npoints))
+       ! Call simulator
+       call icarus_subcolumn(isccpIN%npoints,isccpIN%ncolumns,isccpIN%nlevels,           &
+                             isccpIN%sunlit,isccpIN%dtau,isccpIN%dem,isccpIN%skt,        &
+                             isccpIN%emsfc_lw,isccpIN%qv,isccpIN%at,isccpIN%pfull,       &
+                             isccpIN%phalf,isccpIN%frac_out,isccpLEVMATCH,               &
+                             isccp_boxtau(:,:),isccp_boxptop(:,:),                       &
+                             isccp_boxttop(:,:),isccp_meantbclr(:))
+       ! Store output (if requested)
+       if (associated(cospOUT%isccp_boxtau)) then
+          cospOUT%isccp_boxtau(ij:ik,:)  = isccp_boxtau
+       endif
+       if (associated(cospOUT%isccp_boxptop)) then
+          cospOUT%isccp_boxptop(ij:ik,:) = isccp_boxptop
+       endif
+       if (associated(cospOUT%isccp_meantbclr)) then
+          cospOUT%isccp_meantbclr(ij:ik) = isccp_meantbclr
+       endif
+   endif
+
+   ! MISR subcolumn simulator
+    if (Lmisr_subcolumn) then
+       ! Allocate space for local variables
+       allocate(misr_boxztop(Npoints,misrIN%Ncolumns),                                   &
+                misr_boxtau(Npoints,misrIN%Ncolumns),                                    &
+                misr_dist_model_layertops(Npoints,numMISRHgtBins))
+       ! Call simulator
+       call misr_subcolumn(misrIN%Npoints,misrIN%Ncolumns,misrIN%Nlevels,misrIN%dtau,    &
+                           misrIN%zfull,misrIN%at,misrIN%sunlit,misr_boxtau,             &
+                           misr_dist_model_layertops,misr_boxztop)
+       ! Store output (if requested)
+       if (associated(cospOUT%misr_dist_model_layertops)) then
+          cospOUT%misr_dist_model_layertops(ij:ik,:) = misr_dist_model_layertops
+       endif
+    endif
+
+    ! Calipso subcolumn simulator
+    if (Lcalipso_subcolumn) then
+       ! Allocate space for local variables
+       allocate(calipso_beta_mol(calipsoIN%Npoints,calipsoIN%Nlevels),                   &
+                calipso_beta_tot(calipsoIN%Npoints,calipsoIN%Ncolumns,calipsoIN%Nlevels),&
+                calipso_betaperp_tot(calipsoIN%Npoints,calipsoIN%Ncolumns,calipsoIN%Nlevels))
+       ! Call simulator
+       call lidar_subcolumn(calipsoIN%npoints, calipsoIN%ncolumns, calipsoIN%nlevels, .false., &
+            calipsoIN%beta_mol, calipsoIN%tau_mol, calipsoIN%betatot, calipsoIN%tautot,  &
+            calipso_beta_mol(:,:), calipso_beta_tot(:,:,:), calipsoIN%betatot_ice,       &
+            calipsoIN%tautot_ice, calipsoIN%betatot_liq, calipsoIN%tautot_liq,           &
+            calipso_betaperp_tot(:,:,:))
+       ! Store output (if requested)
+       if (associated(cospOUT%calipso_beta_mol))                                         &
+            cospOUT%calipso_beta_mol(ij:ik,calipsoIN%Nlevels:1:-1) = calipso_beta_mol
+       if (associated(cospOUT%calipso_beta_tot))                                         &
+            cospOUT%calipso_beta_tot(ij:ik,:,calipsoIN%Nlevels:1:-1) = calipso_beta_tot
+       if (associated(cospOUT%calipso_betaperp_tot))                                     &
+            cospOUT%calipso_betaperp_tot(ij:ik,:,:) = calipso_betaperp_tot
+    endif
+
+    ! GROUND LIDAR subcolumn simulator 
+    if (LgrLidar532_subcolumn) then  
+       ! Allocate space for local variables  
+       allocate(grLidar532_beta_mol(grLidar532IN%Npoints,grLidar532IN%Nlevels),       &  
+                grLidar532_beta_tot(grLidar532IN%Npoints,grLidar532IN%Ncolumns,grLidar532IN%Nlevels))
+       ! Call simulator  
+       call lidar_subcolumn(grLidar532IN%npoints, grLidar532IN%ncolumns, grLidar532IN%nlevels,&
+            .true., grLidar532IN%beta_mol, grLidar532IN%tau_mol, grLidar532IN%betatot,&
+            grLidar532IN%tautot, grLidar532_beta_mol(:,:), grLidar532_beta_tot(:,:,:))
+       ! Store output (if requested) 
+       if (associated(cospOUT%grLidar532_beta_mol))                                      & 
+            cospOUT%grLidar532_beta_mol(ij:ik,grLidar532IN%Nlevels:1:-1) = grLidar532_beta_mol 
+       if (associated(cospOUT%grLidar532_beta_tot))                                         & 
+            cospOUT%grLidar532_beta_tot(ij:ik,:,grLidar532IN%Nlevels:1:-1) = grLidar532_beta_tot 
+    endif 
+
+    ! ATLID subcolumn simulator
+    if (Latlid_subcolumn) then
+       ! Allocate space for local variables
+       allocate(atlid_beta_mol(atlidIN%Npoints,atlidIN%Nlevels),                      & 
+                atlid_beta_tot(atlidIN%Npoints,atlidIN%Ncolumns,atlidIN%Nlevels)) 
+       ! Call simulator 
+       call lidar_subcolumn(atlidIN%npoints, atlidIN%ncolumns, atlidIN%nlevels,&
+            .false., atlidIN%beta_mol_atlid, atlidIN%tau_mol_atlid, atlidIN%betatot_atlid,&
+            atlidIN%tautot_atlid, atlid_beta_mol(:,:), atlid_beta_tot(:,:,:))
+       ! Store output (if requested)
+       if (associated(cospOUT%atlid_beta_mol))                                        & 
+            cospOUT%atlid_beta_mol(ij:ik,atlidIN%Nlevels:1:-1) = atlid_beta_mol 
+       if (associated(cospOUT%atlid_beta_tot))                                        &
+            cospOUT%atlid_beta_tot(ij:ik,:,atlidIN%Nlevels:1:-1) = atlid_beta_tot   
+    endif
+
+    ! PARASOL subcolumn simulator
+    if (Lparasol_subcolumn) then
+       ! Allocate space for local variables
+       allocate(parasolPix_refl(parasolIN%Npoints,parasolIN%Ncolumns,PARASOL_NREFL))
+       ! Call simulator
+       do icol=1,parasolIN%Ncolumns
+          call parasol_subcolumn(parasolIN%npoints, PARASOL_NREFL,                       &
+                                 parasolIN%tautot_S_liq(1:parasolIN%Npoints,icol),       &
+                                 parasolIN%tautot_S_ice(1:parasolIN%Npoints,icol),       &
+                                 parasolPix_refl(:,icol,1:PARASOL_NREFL))
+          ! Store output (if requested)
+          if (associated(cospOUT%parasolPix_refl)) then
+             cospOUT%parasolPix_refl(ij:ik,icol,1:PARASOL_NREFL) =                          &
+                  parasolPix_refl(:,icol,1:PARASOL_NREFL)
+          endif
+       enddo
+    endif
+
+    ! Cloudsat (quickbeam) subcolumn simulator
+    if (Lcloudsat_subcolumn) then
+       ! Allocate space for local variables
+       allocate(cloudsatDBZe(cloudsatIN%Npoints,cloudsatIN%Ncolumns,cloudsatIN%Nlevels), &
+                cloudsatZe_non(cloudsatIN%Npoints,cloudsatIN%Ncolumns,cloudsatIN%Nlevels))
+       do icol=1,cloudsatIN%ncolumns
+          call quickbeam_subcolumn(cloudsatIN%rcfg,cloudsatIN%Npoints,cloudsatIN%Nlevels,&
+                                   cloudsatIN%hgt_matrix/1000._wp,                       &
+                                   cloudsatIN%z_vol(:,icol,:),                           &
+                                   cloudsatIN%kr_vol(:,icol,:),                          &
+                                   cloudsatIN%g_vol(:,1,:),cloudsatDBze(:,icol,:),cloudsatZe_non(:,icol,:))
+       enddo
+       ! Store output (if requested)
+       if (associated(cospOUT%cloudsat_Ze_tot)) then
+          cospOUT%cloudsat_Ze_tot(ij:ik,:,:) = cloudsatDBZe(:,:,1:cloudsatIN%Nlevels)
+       endif
+    endif
+
+    if (Lmodis_subcolumn) then
+       if(modisiN%nSunlit > 0) then
+          ! Allocate space for local variables
+          allocate(modisRetrievedTau(modisIN%nSunlit,modisIN%nColumns),                  &
+                   modisRetrievedSize(modisIN%nSunlit,modisIN%nColumns),                 &
+                   modisRetrievedPhase(modisIN%nSunlit,modisIN%nColumns),                &
+                   modisRetrievedCloudTopPressure(modisIN%nSunlit,modisIN%nColumns))
+          ! Call simulator
+          do i = 1, modisIN%nSunlit
+             call modis_subcolumn(modisIN%Ncolumns,modisIN%Nlevels,modisIN%pres(i,:),    &
+                                  modisIN%tau(int(modisIN%sunlit(i)),:,:),               &
+                                  modisIN%liqFrac(int(modisIN%sunlit(i)),:,:),           &
+                                  modisIN%g(int(modisIN%sunlit(i)),:,:),                 &
+                                  modisIN%w0(int(modisIN%sunlit(i)),:,:),                &
+                                  isccp_boxptop(int(modisIN%sunlit(i)),:),               &
+                                  modisRetrievedPhase(i,:),                              &
+                                  modisRetrievedCloudTopPressure(i,:),                   &
+                                  modisRetrievedTau(i,:),modisRetrievedSize(i,:))
+          end do
+       endif
+    endif
+
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! 5) Call column simulators
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+    ! ISCCP
+    if (Lisccp_column) then
+       ! Check to see which outputs are requested. If not requested, use a local dummy array
+       if(.not. associated(cospOUT%isccp_meanalbedocld)) then
+          allocate(out1D_1(Npoints))
+          cospOUT%isccp_meanalbedocld(ij:ik) => out1D_1
+       endif
+       if(.not. associated(cospOUT%isccp_meanptop)) then
+          allocate(out1D_2(Npoints))
+          cospOUT%isccp_meanptop(ij:ik) => out1D_2
+       endif
+       if(.not. associated(cospOUT%isccp_meantaucld)) then
+          allocate(out1D_3(Npoints))
+          cospOUT%isccp_meantaucld(ij:ik) => out1D_3
+       endif
+       if(.not. associated(cospOUT%isccp_totalcldarea)) then
+          allocate(out1D_4(Npoints))
+          cospOUT%isccp_totalcldarea(ij:ik) => out1D_4
+       endif
+       if(.not. associated(cospOUT%isccp_meantb)) then
+          allocate(out1D_5(Npoints))
+          cospOUT%isccp_meantb(ij:ik) => out1D_5
+       endif
+       if(.not. associated(cospOUT%isccp_fq)) then
+          allocate(out1D_6(Npoints*numISCCPTauBins*numISCCPPresBins))
+          cospOUT%isccp_fq(ij:ik,1:numISCCPTauBins,1:numISCCPPresBins) => out1D_6
+       endif
+
+       ! Call simulator
+       call icarus_column(isccpIN%npoints, isccpIN%ncolumns,isccp_boxtau(:,:),           &
+                          isccp_boxptop(:,:)/100._wp, isccpIN%sunlit,isccp_boxttop,      &
+                          cospOUT%isccp_fq(ij:ik,:,:),                                   &
+                          cospOUT%isccp_meanalbedocld(ij:ik),                            &
+                          cospOUT%isccp_meanptop(ij:ik),cospOUT%isccp_meantaucld(ij:ik), &
+                          cospOUT%isccp_totalcldarea(ij:ik),cospOUT%isccp_meantb(ij:ik))
+       cospOUT%isccp_fq(ij:ik,:,:) = cospOUT%isccp_fq(ij:ik,:,7:1:-1)
+
+       ! Check if there is any value slightly greater than 1
+       where ((cospOUT%isccp_totalcldarea > 1.0-1.e-5) .and.                             &
+              (cospOUT%isccp_totalcldarea < 1.0+1.e-5))
+              cospOUT%isccp_totalcldarea = 1.0
+       endwhere
+
+       ! Clear up memory (if necessary)
+       if (allocated(isccp_boxttop))   deallocate(isccp_boxttop)
+       if (allocated(isccp_boxptop))   deallocate(isccp_boxptop)
+       if (allocated(isccp_boxtau))    deallocate(isccp_boxtau)
+       if (allocated(isccp_meantbclr)) deallocate(isccp_meantbclr)
+       if (allocated(isccpLEVMATCH))   deallocate(isccpLEVMATCH)
+       if (allocated(out1D_1)) then
+          deallocate(out1D_1)
+          nullify(cospOUT%isccp_meanalbedocld)
+       endif
+       if (allocated(out1D_2)) then
+          deallocate(out1D_2)
+          nullify(cospOUT%isccp_meanptop)
+       endif
+       if (allocated(out1D_3)) then
+          deallocate(out1D_3)
+          nullify(cospOUT%isccp_meantaucld)
+       endif
+       if (allocated(out1D_4)) then
+          deallocate(out1D_4)
+          nullify(cospOUT%isccp_totalcldarea)
+       endif
+       if (allocated(out1D_5)) then
+          deallocate(out1D_5)
+          nullify(cospOUT%isccp_meantb)
+       endif
+       if (allocated(out1D_6)) then
+          deallocate(out1D_6)
+          nullify(cospOUT%isccp_fq)
+       endif
+    endif
+
+    ! MISR
+    if (Lmisr_column) then
+       ! Check to see which outputs are requested. If not requested, use a local dummy array
+       if (.not. associated(cospOUT%misr_cldarea)) then
+          allocate(out1D_1(Npoints))
+          cospOUT%misr_cldarea(ij:ik) => out1D_1
+       endif
+       if (.not. associated(cospOUT%misr_meanztop)) then
+          allocate(out1D_2(Npoints))
+          cospOUT%misr_meanztop(ij:ik) => out1D_2
+       endif
+       if (.not. associated(cospOUT%misr_fq)) then
+          allocate(out1D_3(Npoints*numMISRTauBins*numMISRHgtBins))
+          cospOUT%misr_fq(ij:ik,1:numMISRTauBins,1:numMISRHgtBins) => out1D_3
+        endif
+
+       ! Call simulator
+        call misr_column(misrIN%Npoints,misrIN%Ncolumns,misr_boxztop,misrIN%sunlit,&
+                         misr_boxtau,cospOUT%misr_cldarea(ij:ik),                  &
+                         cospOUT%misr_meanztop(ij:ik),cospOUT%misr_fq(ij:ik,:,:))
+
+       ! Clear up memory
+       if (allocated(misr_boxtau))               deallocate(misr_boxtau)
+       if (allocated(misr_boxztop))              deallocate(misr_boxztop)
+       if (allocated(misr_dist_model_layertops)) deallocate(misr_dist_model_layertops)
+       if (allocated(out1D_1)) then
+          deallocate(out1D_1)
+          nullify(cospOUT%misr_cldarea)
+       endif
+       if (allocated(out1D_2)) then
+          deallocate(out1D_2)
+          nullify(cospOUT%misr_meanztop)
+       endif
+       if (allocated(out1D_3)) then
+          deallocate(out1D_3)
+          nullify(cospOUT%misr_fq)
+       endif
+    endif
+
+    ! CALIPSO LIDAR Simulator
+    if (Lcalipso_column) then
+       ! Check to see which outputs are requested. If not requested, use a local dummy array
+       if (.not. associated(cospOUT%calipso_cfad_sr)) then
+          allocate(out1D_1(Npoints*SR_BINS*Nlvgrid))
+          cospOUT%calipso_cfad_sr(ij:ik,1:SR_BINS,1:Nlvgrid) => out1D_1
+       endif
+       if (.not. associated(cospOUT%calipso_lidarcld)) then
+          allocate(out1D_2(Npoints*Nlvgrid))
+          cospOUT%calipso_lidarcld(ij:ik,1:Nlvgrid) => out1D_2
+       endif
+       if (.not. associated(cospOUT%calipso_lidarcldphase)) then
+          allocate(out1D_3(Npoints*Nlvgrid*6))
+          cospOUT%calipso_lidarcldphase(ij:ik,1:Nlvgrid,1:6) => out1D_3
+       endif
+       if (.not. associated(cospOUT%calipso_cldlayer)) then
+          allocate(out1D_4(Npoints*LIDAR_NCAT))
+          cospOUT%calipso_cldlayer(ij:ik,1:LIDAR_NCAT) => out1D_4
+       endif
+       if (.not. associated(cospOUT%calipso_cldlayerphase)) then
+          allocate(out1D_5(Npoints*LIDAR_NCAT*6))
+          cospOUT%calipso_cldlayerphase(ij:ik,1:LIDAR_NCAT,1:6) => out1D_5
+       endif
+       if (.not. associated(cospOUT%calipso_lidarcldtmp)) then
+          allocate(out1D_6(Npoints*40*5))
+          cospOUT%calipso_lidarcldtmp(ij:ik,1:40,1:5) => out1D_6
+       endif   
+       if (.not. associated(cospOUT%calipso_lidarcldtype)) then
+          allocate(out1D_7(Npoints*Nlvgrid*4))
+          cospOUT%calipso_lidarcldtype(ij:ik,1:Nlvgrid,1:4) => out1D_7
+       endif
+       if (.not. associated(cospOUT%calipso_cldtype)) then 
+          allocate(out1D_8(Npoints*LIDAR_NTYPE)) 
+          cospOUT%calipso_cldtype(ij:ik,1:LIDAR_NTYPE) => out1D_8  
+       endif 
+       if (.not. associated(cospOUT%calipso_cldtypetemp)) then 
+          allocate(out1D_9(Npoints*LIDAR_NTYPE))  
+          cospOUT%calipso_cldtypetemp(ij:ik,1:LIDAR_NTYPE) => out1D_9 
+       endif 
+       if (.not. associated(cospOUT%calipso_cldtypemeanz)) then 
+          allocate(out1D_10(Npoints*2))
+          cospOUT%calipso_cldtypemeanz(ij:ik,1:2) => out1D_10 
+       endif 
+       if (.not. associated(cospOUT%calipso_cldtypemeanzse)) then
+          allocate(out1D_12(Npoints*3)) 
+          cospOUT%calipso_cldtypemeanzse(ij:ik,1:3) => out1D_12
+       endif
+       if (.not. associated(cospOUT%calipso_cldthinemis)) then
+          allocate(out1D_11(Npoints)) 
+          cospOUT%calipso_cldthinemis(ij:ik) => out1D_11 
+       endif
+       
+       ! Call simulator
+       ok_lidar_cfad=.true.
+       call lidar_column(calipsoIN%Npoints, calipsoIN%Ncolumns, calipsoIN%Nlevels,       &
+            Nlvgrid, SR_BINS, LIDAR_NTYPE, 'calipso',calipso_beta_tot(:,:,:), calipso_beta_mol(:,:),&
+            cospgridIN%phalf(:,2:calipsoIN%Nlevels),cospgridIN%hgt_matrix,               &
+            cospgridIN%hgt_matrix_half, vgrid_z(:), ok_lidar_cfad, LIDAR_NCAT,           &
+            cospOUT%calipso_cfad_sr(ij:ik,:,:), cospOUT%calipso_lidarcld(ij:ik,:),       &
+            cospOUT%calipso_cldlayer(ij:ik,:),                                           &
+            cospgridIN%at(:,:), calipso_betaperp_tot(:,:,:), cospgridIN%surfelev,        & 
+            cospOUT%calipso_lidarcldphase(ij:ik,:,:),                       &
+            cospOUT%calipso_lidarcldtype(ij:ik,:,:),  cospOUT%calipso_cldtype(ij:ik,:),  &
+            cospOUT%calipso_cldtypetemp(ij:ik,:), cospOUT%calipso_cldtypemeanz(ij:ik,:), & 
+            cospOUT%calipso_cldtypemeanzse(ij:ik,:), cospOUT%calipso_cldthinemis(ij:ik), &
+            cospOUT%calipso_cldlayerphase(ij:ik,:,:), cospOUT%calipso_lidarcldtmp(ij:ik,:,:))
+
+         if (associated(cospOUT%calipso_srbval)) cospOUT%calipso_srbval = calipso_histBsct
+
+       ! Free up memory (if necessary)
+       if (allocated(out1D_1)) then
+          deallocate(out1D_1)
+          nullify(cospOUT%calipso_cfad_sr)
+       endif
+       if (allocated(out1D_2)) then
+          deallocate(out1D_2)
+          nullify(cospOUT%calipso_lidarcld)
+       endif
+       if (allocated(out1D_3)) then
+          deallocate(out1D_3)
+          nullify(cospOUT%calipso_lidarcldphase)
+       endif
+       if (allocated(out1D_4)) then
+          deallocate(out1D_4)
+          nullify(cospOUT%calipso_cldlayer)
+       endif
+       if (allocated(out1D_5)) then
+          deallocate(out1D_5)
+          nullify(cospOUT%calipso_cldlayerphase)
+       endif
+       if (allocated(out1D_6)) then
+          deallocate(out1D_6)
+          nullify(cospOUT%calipso_lidarcldtmp)
+       endif
+       if (allocated(out1D_7)) then
+          deallocate(out1D_7)  
+          nullify(cospOUT%calipso_lidarcldtype)
+       endif  
+       if (allocated(out1D_8)) then
+          deallocate(out1D_8)
+          nullify(cospOUT%calipso_cldtype)
+       endif 
+       if (allocated(out1D_9)) then 
+          deallocate(out1D_9) 
+          nullify(cospOUT%calipso_cldtypetemp)
+       endif 
+       if (allocated(out1D_10)) then 
+          deallocate(out1D_10)
+          nullify(cospOUT%calipso_cldtypemeanz)
+       endif 
+       if (allocated(out1D_12)) then 
+          deallocate(out1D_12) 
+          nullify(cospOUT%calipso_cldtypemeanzse)
+       endif 
+       if (allocated(out1D_11)) then 
+          deallocate(out1D_11) 
+          nullify(cospOUT%calipso_cldthinemis)
+       endif
+
+    endif
+
+    ! GROUND LIDAR Simulator
+    if (LgrLidar532_column) then
+       ! Check to see which outputs are requested. If not requested, use a local dummy array
+       if (.not. associated(cospOUT%grLidar532_cfad_sr)) then
+          allocate(out1D_1(Npoints*SR_BINS*Nlvgrid)) 
+          cospOUT%grLidar532_cfad_sr(ij:ik,1:SR_BINS,1:Nlvgrid) => out1D_1
+       endif 
+       if (.not. associated(cospOUT%grLidar532_lidarcld)) then
+          allocate(out1D_2(Npoints*Nlvgrid)) 
+          cospOUT%grLidar532_lidarcld(ij:ik,1:Nlvgrid) => out1D_2
+       endif
+       if (.not. associated(cospOUT%grLidar532_cldlayer)) then
+          allocate(out1D_3(Npoints*LIDAR_NCAT))
+          cospOUT%grLidar532_cldlayer(ij:ik,1:LIDAR_NCAT) => out1D_3
+       endif
+       
+       ! Call simulator 
+       ok_lidar_cfad_grLidar532=.true.
+       call lidar_column(grLidar532IN%Npoints, grLidar532IN%Ncolumns, grLidar532IN%Nlevels,       &
+            Nlvgrid, SR_BINS, LIDAR_NTYPE, 'grlidar532',grLidar532_beta_tot(:,:,:), grLidar532_beta_mol(:,:),&
+            cospgridIN%phalf(:,2:grLidar532IN%Nlevels),cospgridIN%hgt_matrix,               &
+            cospgridIN%hgt_matrix_half, vgrid_z(:), ok_lidar_cfad_grLidar532, LIDAR_NCAT,      &
+            cospOUT%grLidar532_cfad_sr(ij:ik,:,:), cospOUT%grLidar532_lidarcld(ij:ik,:),       &
+            cospOUT%grLidar532_cldlayer(ij:ik,:))
+
+       if (associated(cospOUT%grLidar532_srbval)) cospOUT%grLidar532_srbval = grLidar532_histBsct
+
+       ! Free up memory (if necessary) 
+       if (allocated(out1D_1)) then
+          deallocate(out1D_1)
+          nullify(cospOUT%grLidar532_cfad_sr)
+       endif 
+       if (allocated(out1D_2)) then
+          deallocate(out1D_2)
+          nullify(cospOUT%grLidar532_lidarcld)
+       endif 
+       if (allocated(out1D_3)) then
+          deallocate(out1D_3)
+          nullify(cospOUT%grLidar532_cldlayer)
+       endif
+
+    endif
+
+    ! ATLID Simulator
+    if (Latlid_column) then
+       ! Check to see which outputs are requested. If not requested, use a local dummy array
+       if (.not. associated(cospOUT%atlid_cfad_sr)) then
+          allocate(out1D_1(Npoints*SR_BINS*Nlvgrid))
+          cospOUT%atlid_cfad_sr(ij:ik,1:SR_BINS,1:Nlvgrid) => out1D_1
+       endif                                    
+       if (.not. associated(cospOUT%atlid_lidarcld)) then 
+          allocate(out1D_2(Npoints*Nlvgrid))                 
+          cospOUT%atlid_lidarcld(ij:ik,1:Nlvgrid) => out1D_2 
+       endif                                                   
+       if (.not. associated(cospOUT%atlid_cldlayer)) then   
+          allocate(out1D_3(Npoints*LIDAR_NCAT))                 
+          cospOUT%atlid_cldlayer(ij:ik,1:LIDAR_NCAT) => out1D_3 
+       endif                                                      
+       
+       ! Call simulator                                                             
+       ok_lidar_cfad_atlid=.true.
+       call lidar_column(atlidIN%Npoints, atlidIN%Ncolumns, atlidIN%Nlevels,       &
+            Nlvgrid, SR_BINS, LIDAR_NTYPE, 'atlid',atlid_beta_tot(:,:,:),     &
+            atlid_beta_mol(:,:), cospgridIN%phalf(:,2:atlidIN%Nlevels),            &
+            cospgridIN%hgt_matrix, cospgridIN%hgt_matrix_half, vgrid_z(:),         &
+            ok_lidar_cfad_atlid, LIDAR_NCAT, cospOUT%atlid_cfad_sr(ij:ik,:,:),     &
+            cospOUT%atlid_lidarcld(ij:ik,:), cospOUT%atlid_cldlayer(ij:ik,:))
+       
+       if (associated(cospOUT%atlid_srbval)) cospOUT%atlid_srbval = atlid_histBsct 
+
+       ! Free up memory (if necessary)        
+       if (allocated(out1D_1)) then           
+          deallocate(out1D_1)                 
+          nullify(cospOUT%atlid_cfad_sr)
+       endif                                  
+       if (allocated(out1D_2)) then          
+          deallocate(out1D_2)                
+          nullify(cospOUT%atlid_lidarcld)
+       endif                                  
+       if (allocated(out1D_3)) then          
+          deallocate(out1D_3)
+          nullify(cospOUT%atlid_cldlayer)
+       endif          
+
+    endif
+
+    ! PARASOL
+    if (Lparasol_column) then
+       call parasol_column(parasolIN%Npoints,PARASOL_NREFL,parasolIN%Ncolumns,           &
+                            cospgridIN%land(:),parasolPix_refl(:,:,:),                   &
+                            cospOUT%parasolGrid_refl(ij:ik,:))
+       if (allocated(parasolPix_refl)) deallocate(parasolPix_refl)
+    endif
+
+    ! CLOUDSAT
+    if (Lcloudsat_column) then
+       ! Check to see which outputs are requested. If not requested, use a local dummy array
+       if (.not. associated(cospOUT%cloudsat_cfad_ze)) then
+          allocate(out1D_1(Npoints*cloudsat_DBZE_BINS*Nlvgrid))
+          cospOUT%cloudsat_cfad_ze(ij:ik,1:cloudsat_DBZE_BINS,1:Nlvgrid) => out1D_1
+       endif
+
+       if (.not. associated(cospOUT%cloudsat_pia)) then
+          allocate(out1D_2(Npoints))
+          cospOUT%cloudsat_pia(ij:ik) => out1D_2
+       endif
+       if (.not. associated(cospOUT%cloudsat_precip_cover)) then
+          allocate(out1D_3(Npoints*nCloudsatPrecipClass))
+          cospOUT%cloudsat_precip_cover(ij:ik,1:nCloudsatPrecipClass) => out1D_3
+       endif
+          
+       ! Call simulator
+       call quickbeam_column(cloudsatIN%Npoints, cloudsatIN%Ncolumns, cloudsatIN%Nlevels,&
+            Nlvgrid, cloudsat_DBZE_BINS, 'cloudsat', cloudsatDBZe, cloudsatZe_non,       &
+!            cospgridIN%land(:), cospgridIN%at(:,cospIN%Nlevels), cospIN%fracPrecipIce,   & !PREC_BUG
+!            cospgridIN%hgt_matrix, cospgridIN%hgt_matrix_half,                           & !PREC_BUG
+            cospgridIN%land(:), cospgridIN%surfelev(:), cospgridIN%at(:,cospIN%Nlevels), & !PREC_BUG
+	    cospIN%fracPrecipIce, cospgridIN%hgt_matrix, cospgridIN%hgt_matrix_half,     & !PREC_BUG
+            cospOUT%cloudsat_cfad_ze(ij:ik,:,:), cospOUT%cloudsat_precip_cover,          &
+            cospOUT%cloudsat_pia)
+       ! Free up memory  (if necessary)
+       if (allocated(out1D_1)) then
+          deallocate(out1D_1)
+          nullify(cospOUT%cloudsat_cfad_ze)
+       endif
+       if (allocated(out1D_2)) then
+          deallocate(out1D_2)
+          nullify(cospOUT%cloudsat_pia)
+       endif
+       if (allocated(out1D_3)) then
+          deallocate(out1D_3)
+          nullify(cospOUT%cloudsat_precip_cover)
+       endif
+    endif
+
+    ! MODIS
+    if (Lmodis_column) then
+       if(modisiN%nSunlit > 0) then
+          ! Allocate space for local variables
+          allocate(modisCftotal(modisIN%nSunlit), modisCfLiquid(modisIN%nSunlit),        &
+                   modisCfIce(modisIN%nSunlit),modisCfHigh(modisIN%nSunlit),             &
+                   modisCfMid(modisIN%nSunlit),modisCfLow(modisIN%nSunlit),              &
+                   modisMeanTauTotal(modisIN%nSunlit),                                   &
+                   modisMeanTauLiquid(modisIN%nSunlit),modisMeanTauIce(modisIN%nSunlit), &
+                   modisMeanLogTauTotal(modisIN%nSunlit),                                &
+                   modisMeanLogTauLiquid(modisIN%nSunlit),                               &
+                   modisMeanLogTauIce(modisIN%nSunlit),                                  &
+                   modisMeanSizeLiquid(modisIN%nSunlit),                                 &
+                   modisMeanSizeIce(modisIN%nSunlit),                                    &
+                   modisMeanCloudTopPressure(modisIN%nSunlit),                           &
+                   modisMeanLiquidWaterPath(modisIN%nSunlit),                            &
+                   modisMeanIceWaterPath(modisIN%nSunlit),                               &
+                   modisJointHistogram(modisIN%nSunlit,numMODISTauBins,numMODISPresBins),&
+                   modisJointHistogramIce(modisIN%nSunlit,numModisTauBins,numMODISReffIceBins),&
+                   modisJointHistogramLiq(modisIN%nSunlit,numModisTauBins,numMODISReffLiqBins))
+          ! Call simulator
+          call modis_column(modisIN%nSunlit, modisIN%Ncolumns,modisRetrievedPhase,       &
+                             modisRetrievedCloudTopPressure,modisRetrievedTau,           &
+                             modisRetrievedSize, modisCfTotal, modisCfLiquid, modisCfIce,&
+                             modisCfHigh, modisCfMid, modisCfLow, modisMeanTauTotal,     &
+                             modisMeanTauLiquid, modisMeanTauIce, modisMeanLogTauTotal,  &
+                             modisMeanLogTauLiquid, modisMeanLogTauIce,                  &
+                             modisMeanSizeLiquid, modisMeanSizeIce,                      &
+                             modisMeanCloudTopPressure, modisMeanLiquidWaterPath,        &
+                             modisMeanIceWaterPath, modisJointHistogram,                 &
+                             modisJointHistogramIce,modisJointHistogramLiq)
+          ! Store data (if requested)
+          if (associated(cospOUT%modis_Cloud_Fraction_Total_Mean)) then
+             cospOUT%modis_Cloud_Fraction_Total_Mean(ij+int(modisIN%sunlit(:))-1)   =    &
+                  modisCfTotal
+          endif
+          if (associated(cospOUT%modis_Cloud_Fraction_Water_Mean)) then
+             cospOUT%modis_Cloud_Fraction_Water_Mean(ij+int(modisIN%sunlit(:))-1)   =    &
+                  modisCfLiquid
+          endif
+          if (associated(cospOUT%modis_Cloud_Fraction_Ice_Mean)) then
+             cospOUT%modis_Cloud_Fraction_Ice_Mean(ij+int(modisIN%sunlit(:))-1)     =    &
+                  modisCfIce
+          endif
+          if (associated(cospOUT%modis_Cloud_Fraction_High_Mean)) then
+             cospOUT%modis_Cloud_Fraction_High_Mean(ij+int(modisIN%sunlit(:))-1)    =    &
+                  modisCfHigh
+          endif
+          if (associated(cospOUT%modis_Cloud_Fraction_Mid_Mean)) then
+             cospOUT%modis_Cloud_Fraction_Mid_Mean(ij+int(modisIN%sunlit(:))-1)     =    &
+                  modisCfMid
+          endif
+          if (associated(cospOUT%modis_Cloud_Fraction_Low_Mean)) then
+             cospOUT%modis_Cloud_Fraction_Low_Mean(ij+int(modisIN%sunlit(:))-1)     =    &
+                  modisCfLow
+          endif
+          if (associated(cospOUT%modis_Optical_Thickness_Total_Mean)) then
+             cospOUT%modis_Optical_Thickness_Total_Mean(ij+int(modisIN%sunlit(:))-1) =   &
+                  modisMeanTauTotal
+          endif
+          if (associated(cospOUT%modis_Optical_Thickness_Water_Mean)) then
+             cospOUT%modis_Optical_Thickness_Water_Mean(ij+int(modisIN%sunlit(:))-1) =   &
+                  modisMeanTauLiquid
+          endif
+          if (associated(cospOUT%modis_Optical_Thickness_Ice_Mean)) then
+             cospOUT%modis_Optical_Thickness_Ice_Mean(ij+int(modisIN%sunlit(:))-1)  =    &
+                  modisMeanTauIce
+          endif
+          if (associated(cospOUT%modis_Optical_Thickness_Total_LogMean)) then
+             cospOUT%modis_Optical_Thickness_Total_LogMean(ij+int(modisIN%sunlit(:))-1)= &
+                  modisMeanLogTauTotal
+          endif
+          if (associated(cospOUT%modis_Optical_Thickness_Water_LogMean)) then
+             cospOUT%modis_Optical_Thickness_Water_LogMean(ij+int(modisIN%sunlit(:))-1) = &
+                  modisMeanLogTauLiquid
+          endif
+          if (associated(cospOUT%modis_Optical_Thickness_Ice_LogMean)) then
+             cospOUT%modis_Optical_Thickness_Ice_LogMean(ij+int(modisIN%sunlit(:))-1) =  &
+                  modisMeanLogTauIce
+          endif
+          if (associated(cospOUT%modis_Cloud_Particle_Size_Water_Mean)) then
+             cospOUT%modis_Cloud_Particle_Size_Water_Mean(ij+int(modisIN%sunlit(:))-1) = &
+                  modisMeanSizeLiquid
+          endif
+          if (associated(cospOUT%modis_Cloud_Particle_Size_Ice_Mean)) then
+             cospOUT%modis_Cloud_Particle_Size_Ice_Mean(ij+int(modisIN%sunlit(:))-1) =   &
+                  modisMeanSizeIce
+          endif
+          if (associated(cospOUT%modis_Cloud_Top_Pressure_Total_Mean)) then
+             cospOUT%modis_Cloud_Top_Pressure_Total_Mean(ij+int(modisIN%sunlit(:))-1) =  &
+                  modisMeanCloudTopPressure
+          endif
+          if (associated(cospOUT%modis_Liquid_Water_Path_Mean)) then
+             cospOUT%modis_Liquid_Water_Path_Mean(ij+int(modisIN%sunlit(:))-1)      =    &
+                  modisMeanLiquidWaterPath
+          endif
+          if (associated(cospOUT%modis_Ice_Water_Path_Mean)) then
+              cospOUT%modis_Ice_Water_Path_Mean(ij+int(modisIN%sunlit(:))-1)         =   &
+                  modisMeanIceWaterPath
+          endif
+          if (associated(cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure)) then
+             cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure(ij+            &
+                  int(modisIN%sunlit(:))-1, 1:numModisTauBins, :) = modisJointHistogram(:, :, :)
+             ! Reorder pressure bins in joint histogram to go from surface to TOA
+             cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure(ij:ik,:,:) = &
+                  cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure(ij:ik,:,numMODISPresBins:1:-1)
+          endif
+          if (associated(cospOUT%modis_Optical_Thickness_vs_ReffIce)) then
+             cospOUT%modis_Optical_Thickness_vs_ReffIce(ij+int(modisIN%sunlit(:))-1, 1:numMODISTauBins,:) = &
+                modisJointHistogramIce(:,:,:)
+          endif
+          if (associated(cospOUT%modis_Optical_Thickness_vs_ReffLiq)) then
+             cospOUT%modis_Optical_Thickness_vs_ReffLiq(ij+int(modisIN%sunlit(:))-1, 1:numMODISTauBins,:) = &
+                modisJointHistogramLiq(:,:,:)
+          endif
+
+          if(modisIN%nSunlit < modisIN%Npoints) then
+             ! Where it's night and we haven't done the retrievals the values are undefined
+             if (associated(cospOUT%modis_Cloud_Fraction_Total_Mean))                    &
+                cospOUT%modis_Cloud_Fraction_Total_Mean(ij+int(modisIN%notSunlit(:))-1) = R_UNDEF
+             if (associated(cospOUT%modis_Cloud_Fraction_Water_Mean))                    &
+                cospOUT%modis_Cloud_Fraction_Water_Mean(ij+int(modisIN%notSunlit(:))-1) = R_UNDEF
+             if (associated(cospOUT%modis_Cloud_Fraction_Ice_Mean))                      &
+                cospOUT%modis_Cloud_Fraction_Ice_Mean(ij+int(modisIN%notSunlit(:))-1) = R_UNDEF
+             if (associated(cospOUT%modis_Cloud_Fraction_High_Mean))                     &
+                cospOUT%modis_Cloud_Fraction_High_Mean(ij+int(modisIN%notSunlit(:))-1) = R_UNDEF
+             if (associated(cospOUT%modis_Cloud_Fraction_Mid_Mean))                      &
+                cospOUT%modis_Cloud_Fraction_Mid_Mean(ij+int(modisIN%notSunlit(:))-1) = R_UNDEF
+             if (associated(cospOUT%modis_Cloud_Fraction_Low_Mean))                      &
+                cospOUT%modis_Cloud_Fraction_Low_Mean(ij+int(modisIN%notSunlit(:))-1) = R_UNDEF
+             if (associated(cospOUT%modis_Optical_Thickness_Total_Mean))                 &
+                cospOUT%modis_Optical_Thickness_Total_Mean(ij+int(modisIN%notSunlit(:))-1) = R_UNDEF
+             if (associated(cospOUT%modis_Optical_Thickness_Water_Mean))                 &
+                cospOUT%modis_Optical_Thickness_Water_Mean(ij+int(modisIN%notSunlit(:))-1) = R_UNDEF
+             if (associated(cospOUT%modis_Optical_Thickness_Ice_Mean))                   &
+                cospOUT%modis_Optical_Thickness_Ice_Mean(ij+int(modisIN%notSunlit(:))-1) = R_UNDEF
+             if (associated(cospOUT%modis_Optical_Thickness_Total_LogMean))              &
+                cospOUT%modis_Optical_Thickness_Total_LogMean(ij+int(modisIN%notSunlit(:))-1) = R_UNDEF
+             if (associated(cospOUT%modis_Optical_Thickness_Water_LogMean))              &
+                cospOUT%modis_Optical_Thickness_Water_LogMean(ij+int(modisIN%notSunlit(:))-1) = R_UNDEF
+             if (associated(cospOUT%modis_Optical_Thickness_Ice_LogMean))                &
+                cospOUT%modis_Optical_Thickness_Ice_LogMean(ij+int(modisIN%notSunlit(:))-1) = R_UNDEF
+             if (associated(cospOUT%modis_Cloud_Particle_Size_Water_Mean))               &
+                cospOUT%modis_Cloud_Particle_Size_Water_Mean(ij+int(modisIN%notSunlit(:))-1) = R_UNDEF
+             if (associated(cospOUT%modis_Cloud_Particle_Size_Ice_Mean))                 &
+                cospOUT%modis_Cloud_Particle_Size_Ice_Mean(ij+int(modisIN%notSunlit(:))-1) = R_UNDEF
+             if (associated(cospOUT%modis_Cloud_Top_Pressure_Total_Mean))                &
+                cospOUT%modis_Cloud_Top_Pressure_Total_Mean(ij+int(modisIN%notSunlit(:))-1) = R_UNDEF
+             if (associated(cospOUT%modis_Liquid_Water_Path_Mean))                       &
+                cospOUT%modis_Liquid_Water_Path_Mean(ij+int(modisIN%notSunlit(:))-1) = R_UNDEF
+             if (associated(cospOUT%modis_Ice_Water_Path_Mean))                          &
+                cospOUT%modis_Ice_Water_Path_Mean(ij+int(modisIN%notSunlit(:))-1) = R_UNDEF
+             if (associated(cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure))      &
+                cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure(ij+int(modisIN%notSunlit(:))-1, :, :) = R_UNDEF
+          end if
+       else
+          ! It's nightime everywhere - everything is undefined
+          if (associated(cospOUT%modis_Cloud_Fraction_Total_Mean))                       &
+             cospOUT%modis_Cloud_Fraction_Total_Mean(ij:ik) = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Water_Mean))                       &
+             cospOUT%modis_Cloud_Fraction_Water_Mean(ij:ik) = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Ice_Mean))                         &
+             cospOUT%modis_Cloud_Fraction_Ice_Mean(ij:ik) = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_High_Mean))                        &
+             cospOUT%modis_Cloud_Fraction_High_Mean(ij:ik) = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Mid_Mean))                         &
+             cospOUT%modis_Cloud_Fraction_Mid_Mean(ij:ik) = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Low_Mean))                         &
+             cospOUT%modis_Cloud_Fraction_Low_Mean(ij:ik) = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Total_Mean))                    &
+             cospOUT%modis_Optical_Thickness_Total_Mean(ij:ik) = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Water_Mean))                    &
+             cospOUT%modis_Optical_Thickness_Water_Mean(ij:ik) = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Ice_Mean))                      &
+             cospOUT%modis_Optical_Thickness_Ice_Mean(ij:ik) = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Total_LogMean))                 &
+             cospOUT%modis_Optical_Thickness_Total_LogMean(ij:ik) = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Water_LogMean))                 &
+             cospOUT%modis_Optical_Thickness_Water_LogMean(ij:ik) = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Ice_LogMean))                   &
+             cospOUT%modis_Optical_Thickness_Ice_LogMean(ij:ik) = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Particle_Size_Water_Mean))                  &
+             cospOUT%modis_Cloud_Particle_Size_Water_Mean(ij:ik) = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Particle_Size_Ice_Mean))                    &
+              cospOUT%modis_Cloud_Particle_Size_Ice_Mean(ij:ik) = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Top_Pressure_Total_Mean))                   &
+             cospOUT%modis_Cloud_Top_Pressure_Total_Mean(ij:ik) = R_UNDEF
+          if (associated(cospOUT%modis_Liquid_Water_Path_Mean))                          &
+             cospOUT%modis_Liquid_Water_Path_Mean(ij:ik) = R_UNDEF
+          if (associated(cospOUT%modis_Ice_Water_Path_Mean))                             &
+             cospOUT%modis_Ice_Water_Path_Mean(ij:ik) = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure))         &
+             cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure(ij:ik, :, :) = R_UNDEF
+       endif
+       ! Free up memory (if necessary)
+       if (allocated(modisRetrievedTau))               deallocate(modisRetrievedTau)
+       if (allocated(modisRetrievedSize))              deallocate(modisRetrievedSize)
+       if (allocated(modisRetrievedPhase))             deallocate(modisRetrievedPhase)
+       if (allocated(modisRetrievedCloudTopPressure))  deallocate(modisRetrievedCloudTopPressure)
+       if (allocated(modisCftotal))                    deallocate(modisCftotal)
+       if (allocated(modisCfLiquid))                   deallocate(modisCfLiquid)
+       if (allocated(modisCfIce))                      deallocate(modisCfIce)
+       if (allocated(modisCfHigh))                     deallocate(modisCfHigh)
+       if (allocated(modisCfMid))                      deallocate(modisCfMid)
+       if (allocated(modisCfLow))                      deallocate(modisCfLow)
+       if (allocated(modisMeanTauTotal))               deallocate(modisMeanTauTotal)
+       if (allocated(modisMeanTauLiquid))              deallocate(modisMeanTauLiquid)
+       if (allocated(modisMeanTauIce))                 deallocate(modisMeanTauIce)
+       if (allocated(modisMeanLogTauTotal))            deallocate(modisMeanLogTauTotal)
+       if (allocated(modisMeanLogTauLiquid))           deallocate(modisMeanLogTauLiquid)
+       if (allocated(modisMeanLogTauIce))              deallocate(modisMeanLogTauIce)
+       if (allocated(modisMeanSizeLiquid))             deallocate(modisMeanSizeLiquid)
+       if (allocated(modisMeanSizeIce))                deallocate(modisMeanSizeIce)
+       if (allocated(modisMeanCloudTopPressure))       deallocate(modisMeanCloudTopPressure)
+       if (allocated(modisMeanLiquidWaterPath))        deallocate(modisMeanLiquidWaterPath)
+       if (allocated(modisMeanIceWaterPath))           deallocate(modisMeanIceWaterPath)
+       if (allocated(modisJointHistogram))             deallocate(modisJointHistogram)
+       if (allocated(modisJointHistogramIce))          deallocate(modisJointHistogramIce)
+       if (allocated(modisJointHistogramLiq))          deallocate(modisJointHistogramLiq)
+       if (allocated(isccp_boxttop))                   deallocate(isccp_boxttop)
+       if (allocated(isccp_boxptop))                   deallocate(isccp_boxptop)
+       if (allocated(isccp_boxtau))                    deallocate(isccp_boxtau)
+       if (allocated(isccp_meantbclr))                 deallocate(isccp_meantbclr)
+       if (allocated(isccpLEVMATCH))                   deallocate(isccpLEVMATCH)
+    endif
+
+    ! RTTOV
+!    if (lrttov_column) then
+!       call rttov_column(rttovIN%nPoints,rttovIN%nLevels,rttovIN%nSubCols,rttovIN%q,    &
+!                         rttovIN%p,rttovIN%t,rttovIN%o3,rttovIN%ph,rttovIN%h_surf,      &
+!                         rttovIN%u_surf,rttovIN%v_surf,rttovIN%p_surf,rttovIN%t_skin,   &
+!                         rttovIN%t2m,rttovIN%q2m,rttovIN%lsmask,rttovIN%longitude,      &
+!                         rttovIN%latitude,rttovIN%seaice,rttovIN%co2,rttovIN%ch4,       &
+!                         rttovIN%n2o,rttovIN%co,rttovIN%zenang,lrttov_cleanUp,          &
+!                         cospOUT%rttov_tbs(ij:ik,:),cosp_simulator(nError+1),           &
+!                         ! Optional arguments for surface emissivity calculation
+!                         month=rttovIN%month)
+!                         ! Optional arguments to rttov for all-sky calculation
+!                         ! rttovIN%month, rttovIN%tca,rttovIN%cldIce,rttovIN%cldLiq,     &
+!                         ! rttovIN%fl_rain,rttovIN%fl_snow)
+!    endif
+
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! 6) Compute multi-instrument products
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+    ! CLOUDSAT/CALIPSO products
+    if (Lradar_lidar_tcc .or. Llidar_only_freq_cloud .or. Lcloudsat_tcc .or. Lcloudsat_tcc2) then
+
+       if (use_vgrid) then
+          allocate(lidar_only_freq_cloud(cloudsatIN%Npoints,Nlvgrid),                    &
+               radar_lidar_tcc(cloudsatIN%Npoints), cloudsat_tcc(cloudsatIN%Npoints),    &
+               cloudsat_tcc2(cloudsatIN%Npoints))
+          allocate(betamol_in(cloudsatIN%Npoints,1,cloudsatIN%Nlevels),                  &
+                   betamoli(cloudsatIN%Npoints,1,Nlvgrid),                               &
+                   pnormI(cloudsatIN%Npoints,cloudsatIN%Ncolumns,Nlvgrid),               &
+                   Ze_totI(cloudsatIN%Npoints,cloudsatIN%Ncolumns,Nlvgrid))
+
+          ! Regrid in the vertical (*NOTE* This routine requires SFC-2-TOA ordering, so flip
+          ! inputs and outputs to maintain TOA-2-SFC ordering convention in COSP2.)
+          betamol_in(:,1,:) = calipso_beta_mol(:,cloudsatIN%Nlevels:1:-1)
+          call cosp_change_vertical_grid(cloudsatIN%Npoints,1,cloudsatIN%Nlevels,        &
+               cospgridIN%hgt_matrix(:,cloudsatIN%Nlevels:1:-1),                         &
+               cospgridIN%hgt_matrix_half(:,cloudsatIN%Nlevels:1:-1),betamol_in,         &
+               Nlvgrid,vgrid_zl(Nlvgrid:1:-1),vgrid_zu(Nlvgrid:1:-1),                    &
+               betamolI(:,1,Nlvgrid:1:-1))
+
+          call cosp_change_vertical_grid(cloudsatIN%Npoints,cloudsatIN%Ncolumns,         &
+               cloudsatIN%Nlevels,cospgridIN%hgt_matrix(:,cloudsatIN%Nlevels:1:-1),      &
+               cospgridIN%hgt_matrix_half(:,cloudsatIN%Nlevels:1:-1),                    &
+               calipso_beta_tot(:,:,cloudsatIN%Nlevels:1:-1),Nlvgrid,                    &
+               vgrid_zl(Nlvgrid:1:-1),vgrid_zu(Nlvgrid:1:-1),pnormI(:,:,Nlvgrid:1:-1))
+
+          call cosp_change_vertical_grid(cloudsatIN%Npoints,cloudsatIN%Ncolumns,         &
+               cloudsatIN%Nlevels,cospgridIN%hgt_matrix(:,cloudsatIN%Nlevels:1:-1),      &
+               cospgridIN%hgt_matrix_half(:,cloudsatIN%Nlevels:1:-1),                    &
+               cloudsatDBZe(:,:,cloudsatIN%Nlevels:1:-1),Nlvgrid,vgrid_zl(Nlvgrid:1:-1), &
+               vgrid_zu(Nlvgrid:1:-1),Ze_totI(:,:,Nlvgrid:1:-1),log_units=.true.)
+
+          call cosp_lidar_only_cloud(cloudsatIN%Npoints, cloudsatIN%Ncolumns, Nlvgrid,   &
+             pnormI, betamolI, Ze_totI, lidar_only_freq_cloud, radar_lidar_tcc,          &
+             cloudsat_tcc, cloudsat_tcc2)
+
+          deallocate(betamol_in,betamolI,pnormI,ze_totI)
+       else
+          allocate(lidar_only_freq_cloud(cloudsatIN%Npoints,cloudsatIN%Nlevels),         &
+               radar_lidar_tcc(cloudsatIN%Npoints), cloudsat_tcc(cloudsatIN%Npoints),    &
+               cloudsat_tcc2(cloudsatIN%Npoints))
+          call cosp_lidar_only_cloud(cloudsatIN%Npoints,cloudsatIN%Ncolumns,             &
+               cospIN%Nlevels,calipso_beta_tot(:,:,cloudsatIN%Nlevels:1:-1),             &
+               calipso_beta_mol(:,cloudsatIN%Nlevels:1:-1),                              &
+               cloudsatDBZe(:,:,cloudsatIN%Nlevels:1:-1),lidar_only_freq_cloud,          &
+               radar_lidar_tcc, cloudsat_tcc, cloudsat_tcc2)
+       endif
+
+       ! Store, when necessary
+       if (associated(cospOUT%lidar_only_freq_cloud)) then
+          cospOUT%lidar_only_freq_cloud(ij:ik,:) = lidar_only_freq_cloud
+       endif
+       if (associated(cospOUT%radar_lidar_tcc)) then
+          cospOUT%radar_lidar_tcc(ij:ik) = radar_lidar_tcc
+       endif
+       if (associated(cospOUT%cloudsat_tcc)) then
+          cospOUT%cloudsat_tcc(ij:ik) = cloudsat_tcc
+       endif
+       if (associated(cospOUT%cloudsat_tcc2)) then
+          cospOUT%cloudsat_tcc2(ij:ik) = cloudsat_tcc2
+       endif
+    endif
+
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! 7) Cleanup
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if (Lisccp_subcolumn .or. Lmodis_subcolumn) then
+       nullify(isccpIN%Npoints,isccpIN%Ncolumns,isccpIN%Nlevels,isccpIN%emsfc_lw,        &
+               isccpIN%skt,isccpIN%qv,isccpIN%at,isccpIN%frac_out,isccpIN%dtau,          &
+               isccpIN%dem,isccpIN%phalf,isccpIN%sunlit,isccpIN%pfull)
+    endif
+
+    if (Lmisr_subcolumn) then
+       nullify(misrIN%Npoints,misrIN%Ncolumns,misrIN%Nlevels,misrIN%dtau,misrIN%sunlit,  &
+               misrIN%zfull,misrIN%at)
+    endif
+
+    if (Lcalipso_subcolumn) then
+       nullify(calipsoIN%Npoints,calipsoIN%Ncolumns,calipsoIN%Nlevels,calipsoIN%beta_mol,&
+               calipsoIN%betatot,calipsoIN%betatot_liq,calipsoIN%betatot_ice,            &
+               calipsoIN%tau_mol,calipsoIN%tautot,calipsoIN%tautot_liq,calipsoIN%tautot_ice)
+    endif
+
+    if (LgrLidar532_subcolumn) then 
+       nullify(grLidar532IN%Npoints,grLidar532IN%Ncolumns,grLidar532IN%Nlevels,grLidar532IN%beta_mol, &
+               grLidar532IN%betatot,grLidar532IN%tau_mol,grLidar532IN%tautot) 
+    endif 
+
+    if (Latlid_subcolumn) then
+       nullify(atlidIN%Npoints,atlidIN%Ncolumns,atlidIN%Nlevels,atlidIN%beta_mol_atlid, &
+               atlidIN%betatot_atlid,atlidIN%tau_mol_atlid,atlidIN%tautot_atlid)
+    endif 
+
+    if (Lparasol_subcolumn) then
+       nullify(parasolIN%Npoints,parasolIN%Nlevels,parasolIN%Ncolumns,parasolIN%Nrefl,   &
+            parasolIN%tautot_S_liq,parasolIN%tautot_S_ice)
+    endif
+
+
+    if (Lcloudsat_subcolumn) then
+       nullify(cloudsatIN%Npoints,cloudsatIN%Nlevels,cloudsatIN%Ncolumns,cloudsatIN%rcfg,&
+               cloudsatIN%kr_vol,cloudsatIN%g_vol,cloudsatIN%z_vol,cloudsatIN%hgt_matrix)
+    endif
+
+    if (Lmodis_subcolumn) then
+       nullify(modisIN%Npoints,modisIN%Ncolumns,modisIN%Nlevels,modisIN%tau,modisIN%g,   &
+               modisIN%liqFrac,modisIN%w0)
+       if (allocated(modisIN%sunlit))    deallocate(modisIN%sunlit)
+       if (allocated(modisIN%notSunlit)) deallocate(modisIN%notSunlit)
+       if (allocated(modisIN%pres))      deallocate(modisIN%pres)
+    endif
+
+    if (allocated(calipso_beta_tot))      deallocate(calipso_beta_tot)
+    if (allocated(grLidar532_beta_tot))  deallocate(grLidar532_beta_tot)
+    if (allocated(atlid_beta_tot))        deallocate(atlid_beta_tot) 
+    if (allocated(calipso_beta_mol))      deallocate(calipso_beta_mol)
+    if (allocated(grLidar532_beta_mol))  deallocate(grLidar532_beta_mol)
+    if (allocated(atlid_beta_mol))        deallocate(atlid_beta_mol)
+    if (allocated(calipso_betaperp_tot))  deallocate(calipso_betaperp_tot)
+    if (allocated(cloudsatDBZe))          deallocate(cloudsatDBZe)
+    if (allocated(lidar_only_freq_cloud)) deallocate(lidar_only_freq_cloud)
+    if (allocated(radar_lidar_tcc))       deallocate(radar_lidar_tcc)
+    if (allocated(cloudsat_tcc))          deallocate(cloudsat_tcc)
+    if (allocated(cloudsat_tcc2))         deallocate(cloudsat_tcc2)
+
+  end function COSP_SIMULATOR
+  ! ######################################################################################
+  ! SUBROUTINE cosp_init
+  ! ######################################################################################
+  SUBROUTINE COSP_INIT(Lisccp, Lmodis, Lmisr, Lcloudsat, Lcalipso, LgrLidar532, Latlid, Lparasol, Lrttov,     &
+       cloudsat_radar_freq, cloudsat_k2, cloudsat_use_gas_abs, cloudsat_do_ray,          &
+       isccp_top_height, isccp_top_height_direction, surface_radar, rcfg, lusevgrid,     &
+       luseCSATvgrid, Nvgrid, Nlevels, cloudsat_micro_scheme)
+
+    ! INPUTS
+    logical,intent(in) :: Lisccp,Lmodis,Lmisr,Lcloudsat,Lcalipso,LgrLidar532,Latlid,Lparasol,Lrttov
+    integer,intent(in)  :: &
+         cloudsat_use_gas_abs,       & !
+         cloudsat_do_ray,            & !
+         isccp_top_height,           & !
+         isccp_top_height_direction, & !
+         Nlevels,                    & !
+         Nvgrid,                     & ! Number of levels for new L3 grid
+         surface_radar                 !
+    real(wp),intent(in) :: &
+         cloudsat_radar_freq,        & !
+         cloudsat_k2                   !
+    logical,intent(in) :: &
+         lusevgrid,                  & ! Switch to use different vertical grid
+         luseCSATvgrid                 ! Switch to use CLOUDSAT grid spacing for new
+                                       ! vertical grid
+    character(len=64),intent(in) :: &
+       cloudsat_micro_scheme           ! Microphysical scheme used by CLOUDSAT
+
+    ! OUTPUTS
+    type(radar_cfg) :: rcfg
+
+    ! Local variables
+    integer  :: i
+    real(wp) :: zstep
+
+    ! Initialize MODIS optical-depth bin boundaries for joint-histogram. (defined in cosp_config.F90)
+    if (.not. allocated(modis_histTau)) then
+       allocate(modis_histTau(ntau+1),modis_histTauEdges(2,ntau),modis_histTauCenters(ntau))
+       numMODISTauBins      = ntau
+       modis_histTau        = tau_binBounds
+       modis_histTauEdges   = tau_binEdges
+       modis_histTauCenters = tau_binCenters
+    endif
+
+    ! Set up vertical grid used by CALIPSO and CLOUDSAT L3
+    use_vgrid = lusevgrid
+
+    if (use_vgrid) then
+      Nlvgrid  = Nvgrid
+       allocate(vgrid_zl(Nlvgrid),vgrid_zu(Nlvgrid),vgrid_z(Nlvgrid))
+       ! CloudSat grid requested
+       if (luseCSATvgrid)       zstep = 480._wp
+       ! Other grid requested. Constant vertical spacing with top at 20 km
+       if (.not. luseCSATvgrid) zstep = 20000._wp/Nvgrid
+       do i=1,Nvgrid
+          vgrid_zl(Nlvgrid-i+1) = (i-1)*zstep
+          vgrid_zu(Nlvgrid-i+1) = i*zstep
+       enddo
+       vgrid_z = (vgrid_zl+vgrid_zu)/2._wp
+    else
+       Nlvgrid = Nlevels
+       allocate(vgrid_zl(Nlvgrid),vgrid_zu(Nlvgrid),vgrid_z(Nlvgrid))
+    endif
+
+    ! Initialize simulators
+    if (Lisccp) call cosp_isccp_init(isccp_top_height,isccp_top_height_direction)
+    if (Lmodis) call cosp_modis_init()
+    if (Lmisr)  call cosp_misr_init()
+!    if (Lrttov) call cosp_rttov_init()
+    if (Lcloudsat) call cosp_cloudsat_init(cloudsat_radar_freq,cloudsat_k2,              &
+         cloudsat_use_gas_abs,cloudsat_do_ray,R_UNDEF,N_HYDRO, surface_radar,            &
+         rcfg,cloudsat_micro_scheme)
+    if (Lcalipso) call cosp_calipso_init()
+    if (LgrLidar532) call cosp_grLidar532_init()
+    if (Latlid) call cosp_atlid_init()
+    if (Lparasol) call cosp_parasol_init()
+
+    linitialization = .FALSE.
+  END SUBROUTINE COSP_INIT
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! SUBROUTINE cosp_cleanUp
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  subroutine cosp_cleanUp()
+    deallocate(vgrid_zl,vgrid_zu,vgrid_z)
+  end subroutine cosp_cleanUp
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! SUBROUTINE cosp_errorCheck
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  subroutine cosp_errorCheck(cospgridIN, cospIN, Lisccp_subcolumn, Lisccp_column,           &
+       Lmisr_subcolumn, Lmisr_column, Lmodis_subcolumn, Lmodis_column, Lcloudsat_subcolumn, &
+       Lcloudsat_column, Lcalipso_subcolumn, Lcalipso_column, Latlid_subcolumn,             &
+       Latlid_column, LgrLidar532_subcolumn, LgrLidar532_column, Lrttov_subcolumn,        &
+       Lrttov_column, Lparasol_subcolumn, Lparasol_column, Lradar_lidar_tcc,                &
+       Llidar_only_freq_cloud, Lcloudsat_tcc, Lcloudsat_tcc2, cospOUT, errorMessage, nError)
+    
+    ! Inputs
+    type(cosp_column_inputs),intent(in) :: &
+         cospgridIN       ! Model grid inputs to COSP
+    type(cosp_optical_inputs),intent(in) :: &
+         cospIN           ! Derived (optical) input to COSP
+    
+    ! Outputs
+    logical,intent(inout) :: &
+         Lisccp_subcolumn,    & ! ISCCP subcolumn simulator on/off switch
+         Lisccp_column,       & ! ISCCP column simulator on/off switch
+         Lmisr_subcolumn,     & ! MISR subcolumn simulator on/off switch
+         Lmisr_column,        & ! MISR column simulator on/off switch
+         Lmodis_subcolumn,    & ! MODIS subcolumn simulator on/off switch
+         Lmodis_column,       & ! MODIS column simulator on/off switch
+         Lcloudsat_subcolumn, & ! CLOUDSAT subcolumn simulator on/off switch
+         Lcloudsat_column,    & ! CLOUDSAT column simulator on/off switch
+         Lcalipso_subcolumn,  & ! CALIPSO subcolumn simulator on/off switch
+         Lcalipso_column,     & ! CALIPSO column simulator on/off switch
+         Latlid_subcolumn,    & ! EarthCare subcolumn simulator on/off switch
+         Latlid_column,       & ! EarthCare column simulator on/off switch
+         LgrLidar532_subcolumn, & ! Ground Lidar subcolumn simulator on/off switch
+         LgrLidar532_column, & ! Ground Lidar column simulator on/off switch
+         Lparasol_subcolumn,  & ! PARASOL subcolumn simulator on/off switch
+         Lparasol_column,     & ! PARASOL column simulator on/off switch
+         Lrttov_subcolumn,    & ! RTTOV subcolumn simulator on/off switch
+         Lrttov_column,       & ! RTTOV column simulator on/off switch
+         Lcloudsat_tcc,       & !
+         Lcloudsat_tcc2,      & !
+         Lradar_lidar_tcc,    & ! On/Off switch for joint Calipso/Cloudsat product
+         Llidar_only_freq_cloud ! On/Off switch for joint Calipso/Cloudsat product
+    type(cosp_outputs),intent(inout) :: &
+         cospOUT                ! COSP Outputs
+    character(len=256),dimension(100) :: errorMessage
+    integer,intent(out) :: nError
+    
+    ! Local variables
+    character(len=100) :: parasolErrorMessage
+    logical :: alloc_status
+    
+    nError = 0
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! PART 0: Ensure that the inputs needed by the requested simulators are allocated.
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! ISCCP simulator
+    if (Lisccp_subcolumn .or. Lisccp_column) then
+       alloc_status = .true.
+       if (.not. allocated(cospgridIN%skt)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (ISSCP simulator): cospgridIN%skt has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%qv)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (ISSCP simulator): cospgridIN%qv has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%at)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (ISSCP simulator): cospgridIN%at has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%frac_out)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (ISSCP simulator): cospIN%frac_out has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%tau_067)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (ISSCP simulator): cospIN%tau_067 has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%emiss_11)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (ISSCP simulator): cospIN%emiss_11 has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%phalf)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (ISSCP simulator): cospgridIN%phalf has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%sunlit)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (ISSCP simulator): cospgridIN%sunlit has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%pfull)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (ISSCP simulator): cospgridIN%pfull has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. alloc_status) then
+          Lisccp_subcolumn = .false.
+          Lisccp_column    = .false.
+          if (associated(cospOUT%isccp_totalcldarea))  cospOUT%isccp_totalcldarea(:)  = R_UNDEF
+          if (associated(cospOUT%isccp_meantb))        cospOUT%isccp_meantb(:)        = R_UNDEF
+          if (associated(cospOUT%isccp_meantbclr))     cospOUT%isccp_meantbclr(:)     = R_UNDEF
+          if (associated(cospOUT%isccp_meanptop))      cospOUT%isccp_meanptop(:)      = R_UNDEF
+          if (associated(cospOUT%isccp_meantaucld))    cospOUT%isccp_meantaucld(:)    = R_UNDEF
+          if (associated(cospOUT%isccp_meanalbedocld)) cospOUT%isccp_meanalbedocld(:) = R_UNDEF
+          if (associated(cospOUT%isccp_boxtau))        cospOUT%isccp_boxtau(:,:)      = R_UNDEF
+          if (associated(cospOUT%isccp_boxptop))       cospOUT%isccp_boxptop(:,:)     = R_UNDEF
+          if (associated(cospOUT%isccp_fq))            cospOUT%isccp_fq(:,:,:)        = R_UNDEF
+       endif
+    endif
+    
+    ! MISR simulator
+    if (Lmisr_subcolumn .or. Lmisr_column) then
+       alloc_status = .true.
+       if (.not. allocated(cospIN%tau_067)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (MISR simulator): cospIN%tau_067 has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%sunlit)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (MISR simulator): cospgridIN%sunlit has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%hgt_matrix)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (MISR simulator): cospgridIN%hgt_matrix has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%at)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (MISR simulator): cospgridIN%at has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. alloc_status) then
+          Lmisr_subcolumn = .false.
+          Lmisr_column    = .false.
+          if (associated(cospOUT%misr_fq))                   cospOUT%misr_fq(:,:,:)                 = R_UNDEF
+          if (associated(cospOUT%misr_dist_model_layertops)) cospOUT%misr_dist_model_layertops(:,:) = R_UNDEF
+          if (associated(cospOUT%misr_meanztop))             cospOUT%misr_meanztop(:)               = R_UNDEF
+          if (associated(cospOUT%misr_cldarea))              cospOUT%misr_cldarea(:)                = R_UNDEF          
+       endif
+    endif
+
+    ! EarthCare Lidar simulator.
+    if (Latlid_subcolumn .or. Latlid_column) then
+       alloc_status = .true.
+       if (.not. allocated(cospIN%beta_mol_atlid)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (EarthCare Lidar simulator): cospIN%beta_mol_atlid has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%betatot_atlid)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (EarthCare Lidar simulator): cospIN%betatot_atlid has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%tau_mol_atlid)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (EarthCare Lidar simulator): cospIN%tau_mol_atlid has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%tautot_atlid)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (EarthCare Lidar simulator): cospIN%tautot_atlid has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. alloc_status) then
+          Latlid_subcolumn = .false.
+          Latlid_column    = .false.
+          if (associated(cospOUT%atlid_cfad_sr))  cospOUT%atlid_cfad_sr(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%atlid_lidarcld)) cospOUT%atlid_lidarcld(:,:)   = R_UNDEF
+          if (associated(cospOUT%atlid_cldlayer)) cospOUT%atlid_cldlayer(:,:)   = R_UNDEF
+          if (associated(cospOUT%atlid_beta_mol)) cospOUT%atlid_beta_mol(:,:)   = R_UNDEF
+          if (associated(cospOUT%atlid_beta_tot)) cospOUT%atlid_beta_tot(:,:,:) = R_UNDEF
+       endif
+       
+       ! EarthCare column simulator requires additional inputs not required by the subcolumn simulator.
+       alloc_status = .true.
+       if (.not. allocated(cospgridIN%hgt_matrix)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (EarthCare Lidar simulator): cospgridIN%hgt_matrix has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%hgt_matrix_half)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (EarthCare Lidar simulator): cospgridIN%hgt_matrix_half has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%phalf)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (EarthCare Lidar simulator): cospgridIN%phalf has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. alloc_status) then
+          Latlid_column  = .false.
+          if (associated(cospOUT%atlid_cfad_sr)) cospOUT%atlid_cfad_sr(:,:,:) = R_UNDEF
+       endif
+    endif
+
+    ! Ground Lidar simulator.
+    if (LgrLidar532_subcolumn .or. LgrLidar532_column) then
+       alloc_status = .true.
+       if (.not. allocated(cospIN%beta_mol_grLidar532)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Ground Lidar simulator): cospIN%beta_mol_grLidar532 has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%betatot_grLidar532)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Ground Lidar simulator): cospIN%betatot_grLidar532 has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%tau_mol_grLidar532)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Ground Lidar simulator): cospIN%tau_mol_grLidar532 has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%tautot_grLidar532)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Ground Lidar simulator): cospIN%tautot_grLidar532 has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. alloc_status) then
+          LgrLidar532_subcolumn = .false.
+          LgrLidar532_column    = .false.
+          if (associated(cospOUT%grLidar532_cfad_sr))  cospOUT%grLidar532_cfad_sr(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%grLidar532_lidarcld)) cospOUT%grLidar532_lidarcld(:,:)   = R_UNDEF
+          if (associated(cospOUT%grLidar532_cldlayer)) cospOUT%grLidar532_cldlayer(:,:)   = R_UNDEF
+          if (associated(cospOUT%grLidar532_beta_mol)) cospOUT%grLidar532_beta_mol(:,:)   = R_UNDEF
+          if (associated(cospOUT%grLidar532_beta_tot)) cospOUT%grLidar532_beta_tot(:,:,:) = R_UNDEF
+       endif
+       
+       ! Ground Lidar column simulator requires additional inputs not required by the subcolumn simulator.
+       alloc_status = .true.
+       if (.not. allocated(cospgridIN%hgt_matrix)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Ground Lidar simulator): cospgridIN%hgt_matrix has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%hgt_matrix_half)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Ground Lidar simulator): cospgridIN%hgt_matrix_half has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%phalf)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Ground Lidar simulator): cospgridIN%phalf has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. alloc_status) then
+          LgrLidar532_column  = .false.
+          if (associated(cospOUT%grLidar532_cfad_sr)) cospOUT%grLidar532_cfad_sr(:,:,:) = R_UNDEF
+       endif
+    endif
+    
+    ! Calipso Lidar simulator
+    if (Lcalipso_subcolumn .or. Lcalipso_column) then
+       alloc_status = .true.
+       if (.not. allocated(cospIN%beta_mol_calipso)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Calipso Lidar simulator): cospIN%beta_mol_calipso has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%betatot_calipso)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Calipso Lidar simulator): cospIN%betatot_calipso has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%betatot_liq_calipso)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Calipso Lidar simulator):'//&
+               ' cospIN%betatot_liq_calipso has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%betatot_ice_calipso)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Calipso Lidar simulator):'//&
+               ' cospIN%betatot_ice_calipso has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%tau_mol_calipso)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Calipso Lidar simulator): cospIN%tau_mol_calipso has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%tautot_calipso)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Calipso Lidar simulator): cospIN%tautot_calipso has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%tautot_liq_calipso)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Calipso Lidar simulator):'//&
+               ' cospIN%tautot_liq has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%tautot_ice_calipso)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Calipso Lidar simulator):'//&
+               ' cospIN%tautot_ice has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. alloc_status) then
+          Lcalipso_subcolumn = .false.
+          Lcalipso_column    = .false.
+          if (associated(cospOUT%calipso_cfad_sr))       cospOUT%calipso_cfad_sr(:,:,:)       = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcld))      cospOUT%calipso_lidarcld(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldphase)) cospOUT%calipso_lidarcldphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayer))      cospOUT%calipso_cldlayer(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayerphase)) cospOUT%calipso_cldlayerphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtmp))   cospOUT%calipso_lidarcldtmp(:,:,:)   = R_UNDEF
+          if (associated(cospOUT%calipso_beta_mol))      cospOUT%calipso_beta_mol(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_beta_tot))      cospOUT%calipso_beta_tot(:,:,:)      = R_UNDEF
+          if (associated(cospOUT%calipso_betaperp_tot))  cospOUT%calipso_betaperp_tot(:,:,:)  = R_UNDEF
+          ! Also, turn-off joint-products 
+          if (Lradar_lidar_tcc) then
+             Lradar_lidar_tcc = .false.
+             if (associated(cospOUT%radar_lidar_tcc)) cospOUT%radar_lidar_tcc(:) = R_UNDEF
+          endif
+          if (Lcloudsat_tcc) then
+             Lcloudsat_tcc = .false.
+             if (associated(cospOUT%cloudsat_tcc)) cospOUT%cloudsat_tcc(:) = R_UNDEF
+          endif
+          if (Lcloudsat_tcc2) then
+             Lcloudsat_tcc2 = .false.
+             if (associated(cospOUT%cloudsat_tcc2)) cospOUT%cloudsat_tcc2(:) = R_UNDEF
+          endif
+          if (Llidar_only_freq_cloud) then
+             Llidar_only_freq_cloud = .false.
+             if (associated(cospOUT%lidar_only_freq_cloud)) cospOUT%lidar_only_freq_cloud(:,:) = R_UNDEF
+          endif
+       endif
+       
+       ! Calipso column simulator requires additional inputs not required by the subcolumn simulator.
+       alloc_status = .true.
+       if (.not. allocated(cospgridIN%hgt_matrix)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Calipso Lidar simulator):'//&
+               ' cospgridIN%hgt_matrix has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%hgt_matrix_half)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Calipso Lidar simulator):'//&
+               ' cospgridIN%hgt_matrix_half has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%at)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Calipso Lidar simulator): cospgridIN%at has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%phalf)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Calipso Lidar simulator): cospgridIN%phalf has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. alloc_status) then
+          Lcalipso_column  = .false.
+          if (associated(cospOUT%calipso_cfad_sr))       cospOUT%calipso_cfad_sr(:,:,:)       = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcld))      cospOUT%calipso_lidarcld(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldphase)) cospOUT%calipso_lidarcldphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayer))      cospOUT%calipso_cldlayer(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayerphase)) cospOUT%calipso_cldlayerphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtmp))   cospOUT%calipso_lidarcldtmp(:,:,:)   = R_UNDEF
+          if (Lcloudsat_tcc) then
+             Lcloudsat_tcc = .false.
+             if (associated(cospOUT%cloudsat_tcc)) cospOUT%cloudsat_tcc(:) = R_UNDEF
+          endif
+          if (Lcloudsat_tcc2) then
+             Lcloudsat_tcc2 = .false.
+             if (associated(cospOUT%cloudsat_tcc2)) cospOUT%cloudsat_tcc2(:) = R_UNDEF
+          endif
+          ! Also, turn-off joint-products 
+          if (Lradar_lidar_tcc) then
+             Lradar_lidar_tcc = .false.
+             if (associated(cospOUT%radar_lidar_tcc)) cospOUT%radar_lidar_tcc(:) = R_UNDEF
+          endif
+          if (Llidar_only_freq_cloud) then
+             Llidar_only_freq_cloud = .false.
+             if (associated(cospOUT%lidar_only_freq_cloud)) cospOUT%lidar_only_freq_cloud(:,:) = R_UNDEF
+          endif
+       endif
+    endif
+    
+    ! PARASOL simulator
+    if (Lparasol_subcolumn .or. Lparasol_column) then
+       alloc_status = .true.
+       if (.not. allocated(cospIN%tautot_S_liq)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (PARASOL simulator): cospIN%tautot_S_liq has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%tautot_S_ice)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (PARASOL simulator): cospIN%tautot_S_ice has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. alloc_status) then
+          Lparasol_subcolumn  = .false.
+          Lparasol_column     = .false.
+          if (associated(cospOUT%parasolPix_refl))  cospOUT%parasolPix_refl(:,:,:) = R_UNDEF
+          if (associated(cospOUT%parasolGrid_refl)) cospOUT%parasolGrid_refl(:,:)  = R_UNDEF
+       endif
+       
+       ! PARASOL column simulator requires additional inputs not required by the subcolumn simulator.
+       alloc_status = .true.
+       if (.not. allocated(cospgridIN%land)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (PARASOL simulator): cospgridIN%land has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. alloc_status) then
+          Lparasol_column  = .false.
+          if (associated(cospOUT%parasolGrid_refl)) cospOUT%parasolGrid_refl(:,:)  = R_UNDEF
+       endif
+    endif
+    
+    ! Cloudsat radar simulator
+    if (Lcloudsat_subcolumn .or. Lcloudsat_column) then
+       alloc_status = .true.
+       if (.not. allocated(cospIN%z_vol_cloudsat)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Cloudsat radar simulator):'//&
+               ' cospIN%z_vol_cloudsat has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%kr_vol_cloudsat)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Cloudsat radar simulator):'//&
+               ' cospIN%kr_vol_cloudsat has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%g_vol_cloudsat)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Cloudsat radar simulator):'//&
+               ' cospIN%g_vol_cloudsat has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%hgt_matrix)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Cloudsat radar simulator):'//&
+               ' cospgridIN%hgt_matrix has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. alloc_status) then
+          Lcloudsat_subcolumn  = .false.
+          Lcloudsat_column     = .false.
+          if (associated(cospOUT%cloudsat_cfad_ze)) cospOUT%cloudsat_cfad_ze(:,:,:) = R_UNDEF
+          if (associated(cospOUT%cloudsat_Ze_tot))  cospOUT%cloudsat_Ze_tot(:,:,:)  = R_UNDEF
+          if (Lcloudsat_tcc) then
+             Lcloudsat_tcc = .false.
+             if (associated(cospOUT%cloudsat_tcc)) cospOUT%cloudsat_tcc(:) = R_UNDEF
+          endif
+          if (Lcloudsat_tcc2) then
+             Lcloudsat_tcc2 = .false.
+             if (associated(cospOUT%cloudsat_tcc2)) cospOUT%cloudsat_tcc2(:) = R_UNDEF
+          endif
+          ! Also, turn-off joint-products 
+          if (Lradar_lidar_tcc) then
+             Lradar_lidar_tcc = .false.
+             if (associated(cospOUT%radar_lidar_tcc)) cospOUT%radar_lidar_tcc(:) = R_UNDEF
+          endif
+          if (Llidar_only_freq_cloud) then
+             Llidar_only_freq_cloud = .false.
+             if (associated(cospOUT%lidar_only_freq_cloud)) cospOUT%lidar_only_freq_cloud(:,:) = R_UNDEF
+          endif
+       endif
+       
+       ! Cloudsat column simulator requires additional inputs not required by the subcolumn simulator.
+       alloc_status = .true.
+       if (.not. allocated(cospgridIN%hgt_matrix_half)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (Cloudsat radar simulator):'//&
+               ' cospgridIN%hgt_matrix_half has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. alloc_status) then
+          Lcloudsat_column  = .false.
+          if (associated(cospOUT%cloudsat_cfad_ze))      cospOUT%cloudsat_cfad_ze(:,:,:)    = R_UNDEF
+          if (Lcloudsat_tcc) then
+             Lcloudsat_tcc = .false.
+             if (associated(cospOUT%cloudsat_tcc)) cospOUT%cloudsat_tcc(:) = R_UNDEF
+          endif
+          if (Lcloudsat_tcc2) then
+             Lcloudsat_tcc2 = .false.
+             if (associated(cospOUT%cloudsat_tcc2)) cospOUT%cloudsat_tcc2(:) = R_UNDEF
+          endif
+          ! Also, turn-off joint-products 
+          if (Lradar_lidar_tcc) then
+             Lradar_lidar_tcc = .false.
+             if (associated(cospOUT%radar_lidar_tcc)) cospOUT%radar_lidar_tcc(:) = R_UNDEF
+          endif
+          if (Llidar_only_freq_cloud) then
+             Llidar_only_freq_cloud = .false.
+             if (associated(cospOUT%lidar_only_freq_cloud)) cospOUT%lidar_only_freq_cloud(:,:) = R_UNDEF
+          endif
+       endif
+    endif
+    
+    ! MODIS simulator
+    if (Lmodis_subcolumn .or. Lmodis_column) then
+       alloc_status = .true.
+       if (.not. allocated(cospIN%fracLiq)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (MODIS simulator): cospIN%fracLiq has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%tau_067)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (MODIS simulator): cospIN%tau_067 has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%asym)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (MODIS simulator): cospIN%asym has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospIN%ss_alb)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (MODIS simulator): cospIN%ss_alb has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%sunlit)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (MODIS simulator): cospgridIN%sunlit has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. alloc_status) then
+          Lmodis_subcolumn  = .false.
+          Lmodis_column     = .false.
+          if (associated(cospOUT%modis_Cloud_Fraction_Total_Mean))                          &
+               cospOUT%modis_Cloud_Fraction_Total_Mean(:)                   = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Water_Mean))                          &
+               cospOUT%modis_Cloud_Fraction_Water_Mean(:)                   = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Ice_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Ice_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_High_Mean))                           &
+               cospOUT%modis_Cloud_Fraction_High_Mean(:)                    = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Mid_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Mid_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Low_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Low_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Total_Mean))                       &
+               cospOUT%modis_Optical_Thickness_Total_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Water_Mean))                       &
+               cospOUT%modis_Optical_Thickness_Water_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Ice_Mean))                         &
+               cospOUT%modis_Optical_Thickness_Ice_Mean(:)                  = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Total_LogMean))                    &
+               cospOUT%modis_Optical_Thickness_Total_LogMean(:)             = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Water_LogMean))                    &
+               cospOUT%modis_Optical_Thickness_Water_LogMean(:)             = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Ice_LogMean))                      &
+               cospOUT%modis_Optical_Thickness_Ice_LogMean(:)               = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Particle_Size_Water_Mean))                     &
+               cospOUT%modis_Cloud_Particle_Size_Water_Mean(:)              = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Particle_Size_Ice_Mean))                       &
+               cospOUT%modis_Cloud_Particle_Size_Ice_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Top_Pressure_Total_Mean))                      &
+               cospOUT%modis_Cloud_Top_Pressure_Total_Mean(:)               = R_UNDEF
+          if (associated(cospOUT%modis_Liquid_Water_Path_Mean))                             &
+               cospOUT%modis_Liquid_Water_Path_Mean(:)                      = R_UNDEF
+          if (associated(cospOUT%modis_Ice_Water_Path_Mean))                                &
+               cospOUT%modis_Ice_Water_Path_Mean(:)                         = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure))            &
+               cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure(:,:,:) = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_ReffICE))                       &
+               cospOUT%modis_Optical_Thickness_vs_ReffICE(:,:,:)            = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_ReffLIQ))                       &
+               cospOUT%modis_Optical_Thickness_vs_ReffLIQ(:,:,:)            = R_UNDEF          
+       endif
+    endif
+    
+    ! RTTOV
+    if (Lrttov_column) then
+       alloc_status = .true.
+       if (.not. allocated(cospgridIN%emis_sfc)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%emis_sfc has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%hgt_matrix_half)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%emis_sfc has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%u_sfc)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%u_sfc has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%v_sfc)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%v_sfc has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%skt)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%skt has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%phalf)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%phalf has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%qv)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%qv has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%at)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%at has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%land)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%land has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%lat)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%lat has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%lon)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%lon has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%seaice)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%seaice has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%pfull)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%pfull has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%phalf)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%phalf has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%at)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%at has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%qv)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%qv has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%o3)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%o3 has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%tca)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%tca has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%cloudIce)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%cloudIce has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%cloudLiq)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%cloudLiq has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%fl_rain)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%fl_rain has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. allocated(cospgridIN%fl_snow)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable (RTTOV): cospgridIN%fl_snow has not been allocated'
+          alloc_status = .false.
+       endif
+       if (.not. alloc_status) then
+          Lrttov_column     = .false.
+          if (associated(cospOUT%rttov_tbs)) cospOUT%rttov_tbs(:,:)         = R_UNDEF          
+       endif
+    endif
+    
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! PART 1: Check input array values for out-of-bounds values. When an out-of-bound value
+    !         is encountered, COSP outputs that are dependent on that input are filled with
+    !         an undefined value (set in cosp_config.f90) and if necessary, that simulator
+    !         is turned off.
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if (any([Lisccp_subcolumn, Lisccp_column, Lmisr_subcolumn, Lmisr_column, Lmodis_subcolumn, Lmodis_column])) then
+       if (any(cospgridIN%sunlit .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospgridIN%sunlit contains values out of range (0 or 1)'
+          Lisccp_subcolumn = .false.
+          Lisccp_column    = .false.
+          Lmisr_subcolumn  = .false.
+          Lmisr_column     = .false.
+          Lmodis_subcolumn = .false.
+          Lmodis_column    = .false.
+          if (associated(cospOUT%isccp_totalcldarea))  cospOUT%isccp_totalcldarea(:)  = R_UNDEF
+          if (associated(cospOUT%isccp_meantb))        cospOUT%isccp_meantb(:)        = R_UNDEF
+          if (associated(cospOUT%isccp_meantbclr))     cospOUT%isccp_meantbclr(:)     = R_UNDEF
+          if (associated(cospOUT%isccp_meanptop))      cospOUT%isccp_meanptop(:)      = R_UNDEF
+          if (associated(cospOUT%isccp_meantaucld))    cospOUT%isccp_meantaucld(:)    = R_UNDEF
+          if (associated(cospOUT%isccp_meanalbedocld)) cospOUT%isccp_meanalbedocld(:) = R_UNDEF
+          if (associated(cospOUT%isccp_boxtau))        cospOUT%isccp_boxtau(:,:)      = R_UNDEF
+          if (associated(cospOUT%isccp_boxptop))       cospOUT%isccp_boxptop(:,:)     = R_UNDEF
+          if (associated(cospOUT%isccp_fq))            cospOUT%isccp_fq(:,:,:)        = R_UNDEF
+          if (associated(cospOUT%misr_fq))                   cospOUT%misr_fq(:,:,:)                 = R_UNDEF
+          if (associated(cospOUT%misr_dist_model_layertops)) cospOUT%misr_dist_model_layertops(:,:) = R_UNDEF
+          if (associated(cospOUT%misr_meanztop))             cospOUT%misr_meanztop(:)               = R_UNDEF
+          if (associated(cospOUT%misr_cldarea))              cospOUT%misr_cldarea(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Total_Mean))                          &
+               cospOUT%modis_Cloud_Fraction_Total_Mean(:)                   = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Water_Mean))                          &
+               cospOUT%modis_Cloud_Fraction_Water_Mean(:)                   = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Ice_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Ice_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_High_Mean))                           &
+               cospOUT%modis_Cloud_Fraction_High_Mean(:)                    = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Mid_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Mid_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Low_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Low_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Total_Mean))                       &
+               cospOUT%modis_Optical_Thickness_Total_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Water_Mean))                       &
+               cospOUT%modis_Optical_Thickness_Water_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Ice_Mean))                         &
+               cospOUT%modis_Optical_Thickness_Ice_Mean(:)                  = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Total_LogMean))                    &
+               cospOUT%modis_Optical_Thickness_Total_LogMean(:)             = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Water_LogMean))                    &
+               cospOUT%modis_Optical_Thickness_Water_LogMean(:)             = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Ice_LogMean))                      &
+               cospOUT%modis_Optical_Thickness_Ice_LogMean(:)               = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Particle_Size_Water_Mean))                     &
+               cospOUT%modis_Cloud_Particle_Size_Water_Mean(:)              = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Particle_Size_Ice_Mean))                       &
+               cospOUT%modis_Cloud_Particle_Size_Ice_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Top_Pressure_Total_Mean))                      &
+               cospOUT%modis_Cloud_Top_Pressure_Total_Mean(:)               = R_UNDEF
+          if (associated(cospOUT%modis_Liquid_Water_Path_Mean))                             &
+               cospOUT%modis_Liquid_Water_Path_Mean(:)                      = R_UNDEF
+          if (associated(cospOUT%modis_Ice_Water_Path_Mean))                                &
+               cospOUT%modis_Ice_Water_Path_Mean(:)                         = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure))            &
+               cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure(:,:,:) = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_ReffICE))                       &
+               cospOUT%modis_Optical_Thickness_vs_ReffICE(:,:,:)            = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_ReffLIQ))                       &
+               cospOUT%modis_Optical_Thickness_vs_ReffLIQ(:,:,:)            = R_UNDEF
+       endif
+    endif
+
+    if (any([Lisccp_subcolumn, Lisccp_column, Lmisr_subcolumn, Lmisr_column, Lrttov_column,&
+         Lcalipso_column, Lcloudsat_column, Lradar_lidar_tcc,Llidar_only_freq_cloud, &
+         Lcloudsat_tcc, Lcloudsat_tcc2])) then
+       if (any(cospgridIN%at .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospgridIN%at contains values out of range (at<0), expected units (K)'
+          Lisccp_subcolumn = .false.
+          Lisccp_column    = .false.
+          Lmisr_subcolumn  = .false.
+          Lmisr_column     = .false.
+          Lrttov_column    = .false.
+          Lcalipso_column  = .false.
+          Lcloudsat_column = .false.
+          Lradar_lidar_tcc = .false.
+          Llidar_only_freq_cloud = .false.
+          Lcloudsat_tcc    = .false.
+          Lcloudsat_tcc2   = .false.
+          if (associated(cospOUT%rttov_tbs)) cospOUT%rttov_tbs(:,:)         = R_UNDEF
+          if (associated(cospOUT%isccp_totalcldarea))  cospOUT%isccp_totalcldarea(:)  = R_UNDEF
+          if (associated(cospOUT%isccp_meantb))        cospOUT%isccp_meantb(:)        = R_UNDEF
+          if (associated(cospOUT%isccp_meantbclr))     cospOUT%isccp_meantbclr(:)     = R_UNDEF
+          if (associated(cospOUT%isccp_meanptop))      cospOUT%isccp_meanptop(:)      = R_UNDEF
+          if (associated(cospOUT%isccp_meantaucld))    cospOUT%isccp_meantaucld(:)    = R_UNDEF
+          if (associated(cospOUT%isccp_meanalbedocld)) cospOUT%isccp_meanalbedocld(:) = R_UNDEF
+          if (associated(cospOUT%isccp_boxtau))        cospOUT%isccp_boxtau(:,:)      = R_UNDEF
+          if (associated(cospOUT%isccp_boxptop))       cospOUT%isccp_boxptop(:,:)     = R_UNDEF
+          if (associated(cospOUT%isccp_fq))            cospOUT%isccp_fq(:,:,:)        = R_UNDEF
+          if (associated(cospOUT%misr_fq))                   cospOUT%misr_fq(:,:,:)                 = R_UNDEF
+          if (associated(cospOUT%misr_dist_model_layertops)) cospOUT%misr_dist_model_layertops(:,:) = R_UNDEF
+          if (associated(cospOUT%misr_meanztop))             cospOUT%misr_meanztop(:)               = R_UNDEF
+          if (associated(cospOUT%misr_cldarea))              cospOUT%misr_cldarea(:)                = R_UNDEF
+          if (associated(cospOUT%calipso_cfad_sr))       cospOUT%calipso_cfad_sr(:,:,:)       = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcld))      cospOUT%calipso_lidarcld(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldphase)) cospOUT%calipso_lidarcldphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayer))      cospOUT%calipso_cldlayer(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayerphase)) cospOUT%calipso_cldlayerphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtmp))   cospOUT%calipso_lidarcldtmp(:,:,:)   = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtype))  cospOUT%calipso_lidarcldtype(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%calipso_cldtype))       cospOUT%calipso_cldtype(:,:)         = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypetemp))   cospOUT%calipso_cldtypetemp(:,:)     = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypemeanz))  cospOUT%calipso_cldtypemeanz(:,:)    = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypemeanzse)) cospOUT%calipso_cldtypemeanzse(:,:) = R_UNDEF 
+          if (associated(cospOUT%calipso_cldthinemis))   cospOUT%calipso_cldthinemis(:)       = R_UNDEF
+          if (associated(cospOUT%cloudsat_cfad_ze))      cospOUT%cloudsat_cfad_ze(:,:,:)      = R_UNDEF
+          if (associated(cospOUT%lidar_only_freq_cloud)) cospOUT%lidar_only_freq_cloud(:,:)   = R_UNDEF
+          if (associated(cospOUT%radar_lidar_tcc))       cospOUT%radar_lidar_tcc(:)           = R_UNDEF
+          if (associated(cospOUT%cloudsat_tcc)) cospOUT%cloudsat_tcc(:) = R_UNDEF
+          if (associated(cospOUT%cloudsat_tcc2)) cospOUT%cloudsat_tcc2(:) = R_UNDEF
+       endif
+    endif
+    if (any([Lisccp_subcolumn, Lisccp_column, Lrttov_column])) then
+       if (any(cospgridIN%pfull .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospgridIN%pfull contains values out of range'
+          Lisccp_subcolumn = .false.
+          Lisccp_column    = .false.
+          Lrttov_column    = .false.
+          if (associated(cospOUT%rttov_tbs))           cospOUT%rttov_tbs(:,:)         = R_UNDEF
+          if (associated(cospOUT%isccp_totalcldarea))  cospOUT%isccp_totalcldarea(:)  = R_UNDEF
+          if (associated(cospOUT%isccp_meantb))        cospOUT%isccp_meantb(:)        = R_UNDEF
+          if (associated(cospOUT%isccp_meantbclr))     cospOUT%isccp_meantbclr(:)     = R_UNDEF
+          if (associated(cospOUT%isccp_meanptop))      cospOUT%isccp_meanptop(:)      = R_UNDEF
+          if (associated(cospOUT%isccp_meantaucld))    cospOUT%isccp_meantaucld(:)    = R_UNDEF
+          if (associated(cospOUT%isccp_meanalbedocld)) cospOUT%isccp_meanalbedocld(:) = R_UNDEF
+          if (associated(cospOUT%isccp_boxtau))        cospOUT%isccp_boxtau(:,:)      = R_UNDEF
+          if (associated(cospOUT%isccp_boxptop))       cospOUT%isccp_boxptop(:,:)     = R_UNDEF
+          if (associated(cospOUT%isccp_fq))            cospOUT%isccp_fq(:,:,:)        = R_UNDEF
+       endif
+    endif
+    if (any([Lisccp_subcolumn,Lisccp_column,Lmodis_subcolumn,Lmodis_column,Lcalipso_column,Lrttov_column,&
+             LgrLidar532_column,Latlid_column])) then
+       if (any(cospgridIN%phalf .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospgridIN%phalf contains values out of range'
+          Lisccp_subcolumn = .false.
+          Lisccp_column    = .false.
+          Lmodis_subcolumn = .false.
+          Lmodis_column    = .false.
+          Lcalipso_column  = .false.
+          Lrttov_column    = .false.
+          Latlid_column    = .false.
+          LgrLidar532_column = .false.
+          if (associated(cospOUT%rttov_tbs))           cospOUT%rttov_tbs(:,:)         = R_UNDEF
+          if (associated(cospOUT%isccp_totalcldarea))  cospOUT%isccp_totalcldarea(:)  = R_UNDEF
+          if (associated(cospOUT%isccp_meantb))        cospOUT%isccp_meantb(:)        = R_UNDEF
+          if (associated(cospOUT%isccp_meantbclr))     cospOUT%isccp_meantbclr(:)     = R_UNDEF
+          if (associated(cospOUT%isccp_meanptop))      cospOUT%isccp_meanptop(:)      = R_UNDEF
+          if (associated(cospOUT%isccp_meantaucld))    cospOUT%isccp_meantaucld(:)    = R_UNDEF
+          if (associated(cospOUT%isccp_meanalbedocld)) cospOUT%isccp_meanalbedocld(:) = R_UNDEF
+          if (associated(cospOUT%isccp_boxtau))        cospOUT%isccp_boxtau(:,:)      = R_UNDEF
+          if (associated(cospOUT%isccp_boxptop))       cospOUT%isccp_boxptop(:,:)     = R_UNDEF
+          if (associated(cospOUT%isccp_fq))            cospOUT%isccp_fq(:,:,:)        = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Total_Mean))                          &
+               cospOUT%modis_Cloud_Fraction_Total_Mean(:)                   = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Water_Mean))                          &
+               cospOUT%modis_Cloud_Fraction_Water_Mean(:)                   = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Ice_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Ice_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_High_Mean))                           &
+               cospOUT%modis_Cloud_Fraction_High_Mean(:)                    = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Mid_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Mid_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Low_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Low_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Total_Mean))                       &
+               cospOUT%modis_Optical_Thickness_Total_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Water_Mean))                       &
+               cospOUT%modis_Optical_Thickness_Water_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Ice_Mean))                         &
+               cospOUT%modis_Optical_Thickness_Ice_Mean(:)                  = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Total_LogMean))                    &
+               cospOUT%modis_Optical_Thickness_Total_LogMean(:)             = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Water_LogMean))                    &
+               cospOUT%modis_Optical_Thickness_Water_LogMean(:)             = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Ice_LogMean))                      &
+               cospOUT%modis_Optical_Thickness_Ice_LogMean(:)               = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Particle_Size_Water_Mean))                     &
+               cospOUT%modis_Cloud_Particle_Size_Water_Mean(:)              = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Particle_Size_Ice_Mean))                       &
+               cospOUT%modis_Cloud_Particle_Size_Ice_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Top_Pressure_Total_Mean))                      &
+               cospOUT%modis_Cloud_Top_Pressure_Total_Mean(:)               = R_UNDEF
+          if (associated(cospOUT%modis_Liquid_Water_Path_Mean))                             &
+               cospOUT%modis_Liquid_Water_Path_Mean(:)                      = R_UNDEF
+          if (associated(cospOUT%modis_Ice_Water_Path_Mean))                                &
+               cospOUT%modis_Ice_Water_Path_Mean(:)                         = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure))            &
+               cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure(:,:,:) = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_ReffICE))                       &
+               cospOUT%modis_Optical_Thickness_vs_ReffICE(:,:,:)            = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_ReffLIQ))                       &
+               cospOUT%modis_Optical_Thickness_vs_ReffLIQ(:,:,:)            = R_UNDEF
+          if (associated(cospOUT%calipso_cfad_sr))       cospOUT%calipso_cfad_sr(:,:,:)       = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcld))      cospOUT%calipso_lidarcld(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldphase)) cospOUT%calipso_lidarcldphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayer))      cospOUT%calipso_cldlayer(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayerphase)) cospOUT%calipso_cldlayerphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtmp))   cospOUT%calipso_lidarcldtmp(:,:,:)   = R_UNDEF
+          if (associated(cospOUT%atlid_cfad_sr))         cospOUT%atlid_cfad_sr(:,:,:)         = R_UNDEF
+          if (associated(cospOUT%atlid_lidarcld))        cospOUT%atlid_lidarcld(:,:)          = R_UNDEF
+          if (associated(cospOUT%atlid_cldlayer))        cospOUT%atlid_cldlayer(:,:)          = R_UNDEF
+          if (associated(cospOUT%grLidar532_cfad_sr))   cospOUT%grLidar532_cfad_sr(:,:,:)   = R_UNDEF
+          if (associated(cospOUT%grLidar532_lidarcld))  cospOUT%grLidar532_lidarcld(:,:)    = R_UNDEF
+          if (associated(cospOUT%grLidar532_cldlayer))  cospOUT%grLidar532_cldlayer(:,:)    = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtype))  cospOUT%calipso_lidarcldtype(:,:,:)  = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtype))       cospOUT%calipso_cldtype(:,:)         = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypetemp))   cospOUT%calipso_cldtypetemp(:,:)     = R_UNDEF
+          if (associated(cospOUT%calipso_cldtypemeanz))  cospOUT%calipso_cldtypemeanz(:,:)    = R_UNDEF
+          if (associated(cospOUT%calipso_cldtypemeanzse)) cospOUT%calipso_cldtypemeanzse(:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldthinemis))   cospOUT%calipso_cldthinemis(:)       = R_UNDEF
+       endif
+    endif
+    if (any([Lisccp_subcolumn,Lisccp_column,Lrttov_column])) then
+       if (any(cospgridIN%qv .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospgridIN%qv contains values out of range'
+          Lisccp_subcolumn = .false.
+          Lisccp_column    = .false.
+          Lrttov_column    = .false.
+          if (associated(cospOUT%rttov_tbs))           cospOUT%rttov_tbs(:,:)         = R_UNDEF
+          if (associated(cospOUT%isccp_totalcldarea))  cospOUT%isccp_totalcldarea(:)  = R_UNDEF
+          if (associated(cospOUT%isccp_meantb))        cospOUT%isccp_meantb(:)        = R_UNDEF
+          if (associated(cospOUT%isccp_meantbclr))     cospOUT%isccp_meantbclr(:)     = R_UNDEF
+          if (associated(cospOUT%isccp_meanptop))      cospOUT%isccp_meanptop(:)      = R_UNDEF
+          if (associated(cospOUT%isccp_meantaucld))    cospOUT%isccp_meantaucld(:)    = R_UNDEF
+          if (associated(cospOUT%isccp_meanalbedocld)) cospOUT%isccp_meanalbedocld(:) = R_UNDEF
+          if (associated(cospOUT%isccp_boxtau))        cospOUT%isccp_boxtau(:,:)      = R_UNDEF
+          if (associated(cospOUT%isccp_boxptop))       cospOUT%isccp_boxptop(:,:)     = R_UNDEF
+          if (associated(cospOUT%isccp_fq))            cospOUT%isccp_fq(:,:,:)        = R_UNDEF
+       endif
+    endif
+    if (any([Lmisr_subcolumn,Lmisr_column,Lcloudsat_subcolumn,Lcloudsat_column,Lcalipso_column,Lradar_lidar_tcc,&
+         Llidar_only_freq_cloud,LgrLidar532_column,Latlid_column,Lcloudsat_tcc, Lcloudsat_tcc2])) then
+       if (any(cospgridIN%hgt_matrix .lt. -300)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospgridIN%hgt_matrix contains values out of range'
+          Lmisr_subcolumn     = .false.
+          Lmisr_column        = .false.
+          Lcloudsat_subcolumn = .false.
+          Lcloudsat_column    = .false.
+          Lcalipso_column     = .false.
+          Lradar_lidar_tcc    = .false.
+          Llidar_only_freq_cloud = .false.
+          Lcloudsat_tcc       = .false.
+          Lcloudsat_tcc2      = .false.
+          Latlid_column       = .false.
+          LgrLidar532_column  = .false.
+          if (associated(cospOUT%misr_fq))                   cospOUT%misr_fq(:,:,:)                 = R_UNDEF
+          if (associated(cospOUT%misr_dist_model_layertops)) cospOUT%misr_dist_model_layertops(:,:) = R_UNDEF
+          if (associated(cospOUT%misr_meanztop))             cospOUT%misr_meanztop(:)               = R_UNDEF
+          if (associated(cospOUT%misr_cldarea))              cospOUT%misr_cldarea(:)                = R_UNDEF
+          if (associated(cospOUT%calipso_cfad_sr))           cospOUT%calipso_cfad_sr(:,:,:)         = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcld))          cospOUT%calipso_lidarcld(:,:)          = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldphase))     cospOUT%calipso_lidarcldphase(:,:,:)   = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayer))          cospOUT%calipso_cldlayer(:,:)          = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayerphase))     cospOUT%calipso_cldlayerphase(:,:,:)   = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtmp))       cospOUT%calipso_lidarcldtmp(:,:,:)     = R_UNDEF
+          if (associated(cospOUT%cloudsat_cfad_ze))          cospOUT%cloudsat_cfad_ze(:,:,:)        = R_UNDEF
+          if (associated(cospOUT%cloudsat_Ze_tot))           cospOUT%cloudsat_Ze_tot(:,:,:)         = R_UNDEF
+          if (associated(cospOUT%lidar_only_freq_cloud))     cospOUT%lidar_only_freq_cloud(:,:)     = R_UNDEF
+          if (associated(cospOUT%radar_lidar_tcc))           cospOUT%radar_lidar_tcc(:)             = R_UNDEF
+          if (associated(cospOUT%cloudsat_tcc))              cospOUT%cloudsat_tcc(:)                = R_UNDEF
+          if (associated(cospOUT%cloudsat_tcc2))             cospOUT%cloudsat_tcc2(:)               = R_UNDEF
+          if (associated(cospOUT%atlid_cfad_sr))             cospOUT%atlid_cfad_sr(:,:,:)           = R_UNDEF
+          if (associated(cospOUT%atlid_lidarcld))            cospOUT%atlid_lidarcld(:,:)            = R_UNDEF
+          if (associated(cospOUT%atlid_cldlayer))            cospOUT%atlid_cldlayer(:,:)            = R_UNDEF
+          if (associated(cospOUT%grLidar532_cfad_sr))        cospOUT%grLidar532_cfad_sr(:,:,:)      = R_UNDEF
+          if (associated(cospOUT%grLidar532_lidarcld))       cospOUT%grLidar532_lidarcld(:,:)       = R_UNDEF
+          if (associated(cospOUT%grLidar532_cldlayer))       cospOUT%grLidar532_cldlayer(:,:)       = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtype))      cospOUT%calipso_lidarcldtype(:,:,:)    = R_UNDEF
+          if (associated(cospOUT%calipso_cldtype))           cospOUT%calipso_cldtype(:,:)           = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypetemp))       cospOUT%calipso_cldtypetemp(:,:)       = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypemeanz))      cospOUT%calipso_cldtypemeanz(:,:)      = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypemeanzse))    cospOUT%calipso_cldtypemeanzse(:,:)    = R_UNDEF
+          if (associated(cospOUT%calipso_cldthinemis))       cospOUT%calipso_cldthinemis(:)         = R_UNDEF
+       endif
+    endif
+    if (any([Lrttov_column,Lcloudsat_column,Lcalipso_column,Lradar_lidar_tcc,Llidar_only_freq_cloud, &
+             LgrLidar532_column, Latlid_column, Lcloudsat_tcc, Lcloudsat_tcc2])) then
+       if (any(cospgridIN%hgt_matrix_half .lt. -300)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospgridIN%hgt_matrix_half contains values out of range'
+          Lrttov_column    = .false.
+          Lcloudsat_column = .false.
+          Lcalipso_column  = .false.
+          Lradar_lidar_tcc = .false.
+          Llidar_only_freq_cloud = .false.
+          Lcloudsat_tcc    = .false.
+          Lcloudsat_tcc2   = .false.
+          Latlid_column       = .false.
+          LgrLidar532_column = .false.
+          if (associated(cospOUT%rttov_tbs))              cospOUT%rttov_tbs(:,:)               = R_UNDEF
+          if (associated(cospOUT%calipso_cfad_sr))        cospOUT%calipso_cfad_sr(:,:,:)       = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcld))       cospOUT%calipso_lidarcld(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldphase))  cospOUT%calipso_lidarcldphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayer))       cospOUT%calipso_cldlayer(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayerphase))  cospOUT%calipso_cldlayerphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtmp))    cospOUT%calipso_lidarcldtmp(:,:,:)   = R_UNDEF
+          if (associated(cospOUT%cloudsat_cfad_ze))       cospOUT%cloudsat_cfad_ze(:,:,:)      = R_UNDEF
+          if (associated(cospOUT%lidar_only_freq_cloud))  cospOUT%lidar_only_freq_cloud(:,:)   = R_UNDEF
+          if (associated(cospOUT%radar_lidar_tcc))        cospOUT%radar_lidar_tcc(:)           = R_UNDEF
+          if (associated(cospOUT%cloudsat_tcc))           cospOUT%cloudsat_tcc(:)              = R_UNDEF
+          if (associated(cospOUT%cloudsat_tcc2))          cospOUT%cloudsat_tcc2(:)             = R_UNDEF          
+          if (associated(cospOUT%atlid_cfad_sr))          cospOUT%atlid_cfad_sr(:,:,:)         = R_UNDEF
+          if (associated(cospOUT%atlid_lidarcld))         cospOUT%atlid_lidarcld(:,:)          = R_UNDEF
+          if (associated(cospOUT%atlid_cldlayer))         cospOUT%atlid_cldlayer(:,:)          = R_UNDEF
+          if (associated(cospOUT%grLidar532_cfad_sr))     cospOUT%grLidar532_cfad_sr(:,:,:)    = R_UNDEF
+          if (associated(cospOUT%grLidar532_lidarcld))    cospOUT%grLidar532_lidarcld(:,:)     = R_UNDEF
+          if (associated(cospOUT%grLidar532_cldlayer))    cospOUT%grLidar532_cldlayer(:,:)     = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtype))   cospOUT%calipso_lidarcldtype(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%calipso_cldtype))        cospOUT%calipso_cldtype(:,:)         = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypetemp))    cospOUT%calipso_cldtypetemp(:,:)     = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypemeanz))   cospOUT%calipso_cldtypemeanz(:,:)    = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypemeanzse)) cospOUT%calipso_cldtypemeanzse(:,:)  = R_UNDEF 
+          if (associated(cospOUT%calipso_cldthinemis))    cospOUT%calipso_cldthinemis(:)       = R_UNDEF
+       endif
+    endif
+    if (any([Lrttov_column,Lcalipso_column,Lparasol_column])) then
+       if (any(cospgridIN%land .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospgridIN%land contains values out of range'
+          Lrttov_column    = .false.
+          Lcalipso_column  = .false.
+          Lparasol_column  = .false.
+          if (associated(cospOUT%rttov_tbs))             cospOUT%rttov_tbs(:,:)               = R_UNDEF
+          if (associated(cospOUT%calipso_cfad_sr))       cospOUT%calipso_cfad_sr(:,:,:)       = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcld))      cospOUT%calipso_lidarcld(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldphase)) cospOUT%calipso_lidarcldphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayer))      cospOUT%calipso_cldlayer(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayerphase)) cospOUT%calipso_cldlayerphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtmp))   cospOUT%calipso_lidarcldtmp(:,:,:)   = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtype))  cospOUT%calipso_lidarcldtype(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%calipso_cldtype))       cospOUT%calipso_cldtype(:,:)         = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypetemp))   cospOUT%calipso_cldtypetemp(:,:)     = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypemeanz))  cospOUT%calipso_cldtypemeanz(:,:)    = R_UNDEF
+          if (associated(cospOUT%calipso_cldtypemeanzse)) cospOUT%calipso_cldtypemeanzse(:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldthinemis))   cospOUT%calipso_cldthinemis(:)       = R_UNDEF
+          if (associated(cospOUT%parasolGrid_refl))      cospOUT%parasolGrid_refl(:,:)        = R_UNDEF
+       endif
+    endif
+    if (any([Lisccp_subcolumn,Lisccp_column,Lrttov_column])) then
+       if (any(cospgridIN%skt .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospgridIN%skt contains values out of range'
+          Lisccp_subcolumn = .false.
+          Lisccp_column    = .false.
+          Lrttov_column    = .false.
+          if (associated(cospOUT%rttov_tbs))           cospOUT%rttov_tbs(:,:)         = R_UNDEF
+          if (associated(cospOUT%isccp_totalcldarea))  cospOUT%isccp_totalcldarea(:)  = R_UNDEF
+          if (associated(cospOUT%isccp_meantb))        cospOUT%isccp_meantb(:)        = R_UNDEF
+          if (associated(cospOUT%isccp_meantbclr))     cospOUT%isccp_meantbclr(:)     = R_UNDEF
+          if (associated(cospOUT%isccp_meanptop))      cospOUT%isccp_meanptop(:)      = R_UNDEF
+          if (associated(cospOUT%isccp_meantaucld))    cospOUT%isccp_meantaucld(:)    = R_UNDEF
+          if (associated(cospOUT%isccp_meanalbedocld)) cospOUT%isccp_meanalbedocld(:) = R_UNDEF
+          if (associated(cospOUT%isccp_boxtau))        cospOUT%isccp_boxtau(:,:)      = R_UNDEF
+          if (associated(cospOUT%isccp_boxptop))       cospOUT%isccp_boxptop(:,:)     = R_UNDEF
+          if (associated(cospOUT%isccp_fq))            cospOUT%isccp_fq(:,:,:)        = R_UNDEF
+       endif
+    endif
+    
+    ! RTTOV Inputs
+    if (Lrttov_column) then
+       if (cospgridIN%zenang .lt. -90. .OR. cospgridIN%zenang .gt. 90) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospgridIN%zenang contains values out of range'
+          Lrttov_column = .false.
+          if (associated(cospOUT%rttov_tbs)) cospOUT%rttov_tbs(:,:) = R_UNDEF
+       endif
+       if (cospgridIN%co2 .lt. 0) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospgridIN%co2 contains values out of range'
+          Lrttov_column = .false.
+          if (associated(cospOUT%rttov_tbs)) cospOUT%rttov_tbs(:,:) = R_UNDEF
+       endif
+       if (cospgridIN%ch4 .lt. 0) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospgridIN%ch4 contains values out of range'
+          Lrttov_column = .false.
+          if (associated(cospOUT%rttov_tbs)) cospOUT%rttov_tbs(:,:) = R_UNDEF
+       endif
+       if (cospgridIN%n2o .lt. 0) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospgridIN%n2o contains values out of range'
+          Lrttov_column = .false.
+          if (associated(cospOUT%rttov_tbs)) cospOUT%rttov_tbs(:,:) = R_UNDEF
+       endif
+       if (cospgridIN%co.lt. 0) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospgridIN%co contains values out of range'
+          Lrttov_column = .false.
+          if (associated(cospOUT%rttov_tbs)) cospOUT%rttov_tbs(:,:) = R_UNDEF
+       endif
+       if (any(cospgridIN%o3 .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospgridIN%o3 contains values out of range'
+          Lrttov_column = .false.
+          if (associated(cospOUT%rttov_tbs)) cospOUT%rttov_tbs(:,:) = R_UNDEF
+       endif
+       if (any(cospgridIN%emis_sfc .lt. 0. .OR. cospgridIN%emis_sfc .gt. 1)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospgridIN%emis_sfc contains values out of range'
+          Lrttov_column = .false.
+          if (associated(cospOUT%rttov_tbs)) cospOUT%rttov_tbs(:,:) = R_UNDEF
+       endif
+       if (any(cospgridIN%u_sfc .lt. -100. .OR. cospgridIN%u_sfc .gt. 100.)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%u_sfc contains values out of range'
+          if (associated(cospOUT%rttov_tbs)) cospOUT%rttov_tbs(:,:) = R_UNDEF
+          Lrttov_column = .false.
+       endif
+       if (any(cospgridIN%v_sfc .lt. -100. .OR. cospgridIN%v_sfc .gt. 100.)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%v_sfc contains values out of range'
+          Lrttov_column = .false.
+          if (associated(cospOUT%rttov_tbs)) cospOUT%rttov_tbs(:,:) = R_UNDEF
+       endif
+       if (any(cospgridIN%lat .lt. -90 .OR. cospgridIN%lat .gt. 90)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%lat contains values out of range'
+          Lrttov_column = .false.
+          if (associated(cospOUT%rttov_tbs)) cospOUT%rttov_tbs(:,:) = R_UNDEF
+       endif
+    endif
+    
+    ! COSP_INPUTS
+    if (any([Lisccp_subcolumn,Lisccp_column])) then
+       if (cospIN%emsfc_lw .lt. 0. .OR. cospIN%emsfc_lw .gt. 1.) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%emsfc_lw contains values out of range'
+          Lisccp_subcolumn = .false.
+          Lisccp_column    = .false.
+          if (associated(cospOUT%isccp_totalcldarea))  cospOUT%isccp_totalcldarea(:)  = R_UNDEF
+          if (associated(cospOUT%isccp_meantb))        cospOUT%isccp_meantb(:)        = R_UNDEF
+          if (associated(cospOUT%isccp_meantbclr))     cospOUT%isccp_meantbclr(:)     = R_UNDEF
+          if (associated(cospOUT%isccp_meanptop))      cospOUT%isccp_meanptop(:)      = R_UNDEF
+          if (associated(cospOUT%isccp_meantaucld))    cospOUT%isccp_meantaucld(:)    = R_UNDEF
+          if (associated(cospOUT%isccp_meanalbedocld)) cospOUT%isccp_meanalbedocld(:) = R_UNDEF
+          if (associated(cospOUT%isccp_boxtau))        cospOUT%isccp_boxtau(:,:)      = R_UNDEF
+          if (associated(cospOUT%isccp_boxptop))       cospOUT%isccp_boxptop(:,:)     = R_UNDEF
+          if (associated(cospOUT%isccp_fq))            cospOUT%isccp_fq(:,:,:)        = R_UNDEF
+       endif
+    endif
+    if (any([Lisccp_subcolumn,Lisccp_column,Lmisr_subcolumn,Lmisr_column,Lmodis_subcolumn,Lmodis_column])) then
+       if (any(cospIN%tau_067 .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%tau_067 contains values out of range'
+          Lisccp_subcolumn = .false.
+          Lisccp_column    = .false.
+          Lmisr_subcolumn  = .false.
+          Lmisr_column     = .false.
+          Lmodis_subcolumn = .false.
+          Lmodis_column    = .false.
+          if (associated(cospOUT%isccp_totalcldarea))  cospOUT%isccp_totalcldarea(:)  = R_UNDEF
+          if (associated(cospOUT%isccp_meantb))        cospOUT%isccp_meantb(:)        = R_UNDEF
+          if (associated(cospOUT%isccp_meantbclr))     cospOUT%isccp_meantbclr(:)     = R_UNDEF
+          if (associated(cospOUT%isccp_meanptop))      cospOUT%isccp_meanptop(:)      = R_UNDEF
+          if (associated(cospOUT%isccp_meantaucld))    cospOUT%isccp_meantaucld(:)    = R_UNDEF
+          if (associated(cospOUT%isccp_meanalbedocld)) cospOUT%isccp_meanalbedocld(:) = R_UNDEF
+          if (associated(cospOUT%isccp_boxtau))        cospOUT%isccp_boxtau(:,:)      = R_UNDEF
+          if (associated(cospOUT%isccp_boxptop))       cospOUT%isccp_boxptop(:,:)     = R_UNDEF
+          if (associated(cospOUT%isccp_fq))            cospOUT%isccp_fq(:,:,:)        = R_UNDEF
+          if (associated(cospOUT%misr_fq))                   cospOUT%misr_fq(:,:,:)                 = R_UNDEF
+          if (associated(cospOUT%misr_dist_model_layertops)) cospOUT%misr_dist_model_layertops(:,:) = R_UNDEF
+          if (associated(cospOUT%misr_meanztop))             cospOUT%misr_meanztop(:)               = R_UNDEF
+          if (associated(cospOUT%misr_cldarea))              cospOUT%misr_cldarea(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Total_Mean))                          &
+               cospOUT%modis_Cloud_Fraction_Total_Mean(:)                   = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Water_Mean))                          &
+               cospOUT%modis_Cloud_Fraction_Water_Mean(:)                   = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Ice_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Ice_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_High_Mean))                           &
+               cospOUT%modis_Cloud_Fraction_High_Mean(:)                    = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Mid_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Mid_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Low_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Low_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Total_Mean))                       &
+               cospOUT%modis_Optical_Thickness_Total_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Water_Mean))                       &
+               cospOUT%modis_Optical_Thickness_Water_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Ice_Mean))                         &
+               cospOUT%modis_Optical_Thickness_Ice_Mean(:)                  = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Total_LogMean))                    &
+               cospOUT%modis_Optical_Thickness_Total_LogMean(:)             = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Water_LogMean))                    &
+               cospOUT%modis_Optical_Thickness_Water_LogMean(:)             = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Ice_LogMean))                      &
+               cospOUT%modis_Optical_Thickness_Ice_LogMean(:)               = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Particle_Size_Water_Mean))                     &
+               cospOUT%modis_Cloud_Particle_Size_Water_Mean(:)              = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Particle_Size_Ice_Mean))                       &
+               cospOUT%modis_Cloud_Particle_Size_Ice_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Top_Pressure_Total_Mean))                      &
+               cospOUT%modis_Cloud_Top_Pressure_Total_Mean(:)               = R_UNDEF
+          if (associated(cospOUT%modis_Liquid_Water_Path_Mean))                             &
+               cospOUT%modis_Liquid_Water_Path_Mean(:)                      = R_UNDEF
+          if (associated(cospOUT%modis_Ice_Water_Path_Mean))                                &
+               cospOUT%modis_Ice_Water_Path_Mean(:)                         = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure))            &
+               cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure(:,:,:) = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_ReffICE))                       &
+               cospOUT%modis_Optical_Thickness_vs_ReffICE(:,:,:)            = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_ReffLIQ))                       &
+               cospOUT%modis_Optical_Thickness_vs_ReffLIQ(:,:,:)            = R_UNDEF
+       endif
+    endif
+    if (any([Lisccp_subcolumn,Lisccp_column])) then
+       if (any(cospIN%emiss_11 .lt. 0. .OR. cospIN%emiss_11 .gt. 1)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%emiss_11 contains values out of range'
+          Lisccp_subcolumn = .false.
+          Lisccp_column    = .false.
+          if (associated(cospOUT%isccp_totalcldarea))  cospOUT%isccp_totalcldarea(:)  = R_UNDEF
+          if (associated(cospOUT%isccp_meantb))        cospOUT%isccp_meantb(:)        = R_UNDEF
+          if (associated(cospOUT%isccp_meantbclr))     cospOUT%isccp_meantbclr(:)     = R_UNDEF
+          if (associated(cospOUT%isccp_meanptop))      cospOUT%isccp_meanptop(:)      = R_UNDEF
+          if (associated(cospOUT%isccp_meantaucld))    cospOUT%isccp_meantaucld(:)    = R_UNDEF
+          if (associated(cospOUT%isccp_meanalbedocld)) cospOUT%isccp_meanalbedocld(:) = R_UNDEF
+          if (associated(cospOUT%isccp_boxtau))        cospOUT%isccp_boxtau(:,:)      = R_UNDEF
+          if (associated(cospOUT%isccp_boxptop))       cospOUT%isccp_boxptop(:,:)     = R_UNDEF
+          if (associated(cospOUT%isccp_fq))            cospOUT%isccp_fq(:,:,:)        = R_UNDEF
+       endif
+    endif
+    if (any([Lmodis_subcolumn,Lmodis_column])) then
+       if (any(cospIN%asym .lt. -1. .OR. cospIN%asym .gt. 1)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%asym contains values out of range'
+          Lmodis_subcolumn = .false.
+          Lmodis_column    = .false.
+          if (associated(cospOUT%modis_Cloud_Fraction_Total_Mean))                          &
+               cospOUT%modis_Cloud_Fraction_Total_Mean(:)                   = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Water_Mean))                          &
+               cospOUT%modis_Cloud_Fraction_Water_Mean(:)                   = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Ice_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Ice_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_High_Mean))                           &
+               cospOUT%modis_Cloud_Fraction_High_Mean(:)                    = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Mid_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Mid_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Low_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Low_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Total_Mean))                       &
+               cospOUT%modis_Optical_Thickness_Total_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Water_Mean))                       &
+               cospOUT%modis_Optical_Thickness_Water_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Ice_Mean))                         &
+               cospOUT%modis_Optical_Thickness_Ice_Mean(:)                  = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Total_LogMean))                    &
+               cospOUT%modis_Optical_Thickness_Total_LogMean(:)             = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Water_LogMean))                    &
+               cospOUT%modis_Optical_Thickness_Water_LogMean(:)             = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Ice_LogMean))                      &
+               cospOUT%modis_Optical_Thickness_Ice_LogMean(:)               = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Particle_Size_Water_Mean))                     &
+               cospOUT%modis_Cloud_Particle_Size_Water_Mean(:)              = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Particle_Size_Ice_Mean))                       &
+               cospOUT%modis_Cloud_Particle_Size_Ice_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Top_Pressure_Total_Mean))                      &
+               cospOUT%modis_Cloud_Top_Pressure_Total_Mean(:)               = R_UNDEF
+          if (associated(cospOUT%modis_Liquid_Water_Path_Mean))                             &
+               cospOUT%modis_Liquid_Water_Path_Mean(:)                      = R_UNDEF
+          if (associated(cospOUT%modis_Ice_Water_Path_Mean))                                &
+               cospOUT%modis_Ice_Water_Path_Mean(:)                         = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure))            &
+               cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure(:,:,:) = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_ReffICE))                       &
+               cospOUT%modis_Optical_Thickness_vs_ReffICE(:,:,:)            = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_ReffLIQ))                       &
+               cospOUT%modis_Optical_Thickness_vs_ReffLIQ(:,:,:)            = R_UNDEF
+       endif
+       if (any(cospIN%ss_alb .lt. 0 .OR. cospIN%ss_alb .gt. 1)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%ss_alb contains values out of range'
+          Lmodis_subcolumn = .false.
+          Lmodis_column    = .false.
+          if (associated(cospOUT%modis_Cloud_Fraction_Total_Mean))                          &
+               cospOUT%modis_Cloud_Fraction_Total_Mean(:)                   = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Water_Mean))                          &
+               cospOUT%modis_Cloud_Fraction_Water_Mean(:)                   = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Ice_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Ice_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_High_Mean))                           &
+               cospOUT%modis_Cloud_Fraction_High_Mean(:)                    = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Mid_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Mid_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Fraction_Low_Mean))                            &
+               cospOUT%modis_Cloud_Fraction_Low_Mean(:)                     = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Total_Mean))                       &
+               cospOUT%modis_Optical_Thickness_Total_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Water_Mean))                       &
+               cospOUT%modis_Optical_Thickness_Water_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Ice_Mean))                         &
+               cospOUT%modis_Optical_Thickness_Ice_Mean(:)                  = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Total_LogMean))                    &
+               cospOUT%modis_Optical_Thickness_Total_LogMean(:)             = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Water_LogMean))                    &
+               cospOUT%modis_Optical_Thickness_Water_LogMean(:)             = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_Ice_LogMean))                      &
+               cospOUT%modis_Optical_Thickness_Ice_LogMean(:)               = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Particle_Size_Water_Mean))                     &
+               cospOUT%modis_Cloud_Particle_Size_Water_Mean(:)              = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Particle_Size_Ice_Mean))                       &
+               cospOUT%modis_Cloud_Particle_Size_Ice_Mean(:)                = R_UNDEF
+          if (associated(cospOUT%modis_Cloud_Top_Pressure_Total_Mean))                      &
+               cospOUT%modis_Cloud_Top_Pressure_Total_Mean(:)               = R_UNDEF
+          if (associated(cospOUT%modis_Liquid_Water_Path_Mean))                             &
+               cospOUT%modis_Liquid_Water_Path_Mean(:)                      = R_UNDEF
+          if (associated(cospOUT%modis_Ice_Water_Path_Mean))                                &
+               cospOUT%modis_Ice_Water_Path_Mean(:)                         = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure))            &
+               cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure(:,:,:) = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_ReffICE))                       &
+               cospOUT%modis_Optical_Thickness_vs_ReffICE(:,:,:)            = R_UNDEF
+          if (associated(cospOUT%modis_Optical_Thickness_vs_ReffLIQ))                       &
+               cospOUT%modis_Optical_Thickness_vs_ReffLIQ(:,:,:)            = R_UNDEF
+       endif
+    endif
+    if (any([Latlid_subcolumn,Latlid_column])) then
+       if (any(cospIN%betatot_atlid .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%betatot_atlid contains values out of range'
+          Latlid_subcolumn = .false.
+          Latlid_column    = .false.
+          if (associated(cospOUT%atlid_cfad_sr))       cospOUT%atlid_cfad_sr(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%atlid_lidarcld))      cospOUT%atlid_lidarcld(:,:)   = R_UNDEF
+          if (associated(cospOUT%atlid_cldlayer))      cospOUT%atlid_cldlayer(:,:)   = R_UNDEF
+          if (associated(cospOUT%atlid_beta_tot))      cospOUT%atlid_beta_tot(:,:,:) = R_UNDEF
+          if (associated(cospOUT%atlid_beta_mol))      cospOUT%atlid_beta_mol(:,:)   = R_UNDEF
+       endif
+       if (any(cospIN%beta_mol_atlid .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%beta_mol_atlid contains values out of range'
+          Latlid_subcolumn = .false.
+          Latlid_column    = .false.
+          if (associated(cospOUT%atlid_cfad_sr))       cospOUT%atlid_cfad_sr(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%atlid_lidarcld))      cospOUT%atlid_lidarcld(:,:)   = R_UNDEF
+          if (associated(cospOUT%atlid_cldlayer))      cospOUT%atlid_cldlayer(:,:)   = R_UNDEF
+          if (associated(cospOUT%atlid_beta_tot))      cospOUT%atlid_beta_tot(:,:,:) = R_UNDEF
+          if (associated(cospOUT%atlid_beta_mol))      cospOUT%atlid_beta_mol(:,:)   = R_UNDEF
+       endif
+       if (any(cospIN%tautot_atlid .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%tautot_atlid contains values out of range'
+          Latlid_subcolumn = .false.
+          Latlid_column    = .false.
+          if (associated(cospOUT%atlid_cfad_sr))       cospOUT%atlid_cfad_sr(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%atlid_lidarcld))      cospOUT%atlid_lidarcld(:,:)   = R_UNDEF
+          if (associated(cospOUT%atlid_cldlayer))      cospOUT%atlid_cldlayer(:,:)   = R_UNDEF
+          if (associated(cospOUT%atlid_beta_tot))      cospOUT%atlid_beta_tot(:,:,:) = R_UNDEF
+          if (associated(cospOUT%atlid_beta_mol))      cospOUT%atlid_beta_mol(:,:)   = R_UNDEF
+       endif
+       if (any(cospIN%tau_mol_atlid .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%tau_mol_atlid contains values out of range'
+          Latlid_subcolumn = .false.
+          Latlid_column    = .false.
+          if (associated(cospOUT%atlid_cfad_sr))       cospOUT%atlid_cfad_sr(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%atlid_lidarcld))      cospOUT%atlid_lidarcld(:,:)   = R_UNDEF
+          if (associated(cospOUT%atlid_cldlayer))      cospOUT%atlid_cldlayer(:,:)   = R_UNDEF
+          if (associated(cospOUT%atlid_beta_tot))      cospOUT%atlid_beta_tot(:,:,:) = R_UNDEF
+          if (associated(cospOUT%atlid_beta_mol))      cospOUT%atlid_beta_mol(:,:)   = R_UNDEF
+       endif
+    endif
+    
+    if (any([LgrLidar532_subcolumn,LgrLidar532_column])) then
+       if (any(cospIN%betatot_grLidar532 .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%betatot_grLidar532 contains values out of range'
+          LgrLidar532_subcolumn = .false.
+          LgrLidar532_column    = .false.
+          if (associated(cospOUT%grLidar532_cfad_sr))       cospOUT%grLidar532_cfad_sr(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%grLidar532_lidarcld))      cospOUT%grLidar532_lidarcld(:,:)   = R_UNDEF
+          if (associated(cospOUT%grLidar532_cldlayer))      cospOUT%grLidar532_cldlayer(:,:)   = R_UNDEF
+          if (associated(cospOUT%grLidar532_beta_tot))      cospOUT%grLidar532_beta_tot(:,:,:) = R_UNDEF
+          if (associated(cospOUT%grLidar532_beta_mol))      cospOUT%grLidar532_beta_mol(:,:)   = R_UNDEF
+       endif
+       if (any(cospIN%beta_mol_grLidar532 .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%beta_mol_grLidar532 contains values out of range'
+          LgrLidar532_subcolumn = .false.
+          LgrLidar532_column    = .false.
+          if (associated(cospOUT%grLidar532_cfad_sr))       cospOUT%grLidar532_cfad_sr(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%grLidar532_lidarcld))      cospOUT%grLidar532_lidarcld(:,:)   = R_UNDEF
+          if (associated(cospOUT%grLidar532_cldlayer))      cospOUT%grLidar532_cldlayer(:,:)   = R_UNDEF
+          if (associated(cospOUT%grLidar532_beta_tot))      cospOUT%grLidar532_beta_tot(:,:,:) = R_UNDEF
+          if (associated(cospOUT%grLidar532_beta_mol))      cospOUT%grLidar532_beta_mol(:,:)   = R_UNDEF
+       endif
+       if (any(cospIN%tautot_grLidar532 .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%tautot_grLidar532 contains values out of range'
+          LgrLidar532_subcolumn = .false.
+          LgrLidar532_column    = .false.
+          if (associated(cospOUT%grLidar532_cfad_sr))       cospOUT%grLidar532_cfad_sr(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%grLidar532_lidarcld))      cospOUT%grLidar532_lidarcld(:,:)   = R_UNDEF
+          if (associated(cospOUT%grLidar532_cldlayer))      cospOUT%grLidar532_cldlayer(:,:)   = R_UNDEF
+          if (associated(cospOUT%grLidar532_beta_tot))      cospOUT%grLidar532_beta_tot(:,:,:) = R_UNDEF
+          if (associated(cospOUT%grLidar532_beta_mol))      cospOUT%grLidar532_beta_mol(:,:)   = R_UNDEF
+       endif
+       if (any(cospIN%tau_mol_grLidar532 .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%tau_mol_grLidar532 contains values out of range'
+          LgrLidar532_subcolumn = .false.
+          LgrLidar532_column    = .false.
+          if (associated(cospOUT%grLidar532_cfad_sr))       cospOUT%grLidar532_cfad_sr(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%grLidar532_lidarcld))      cospOUT%grLidar532_lidarcld(:,:)   = R_UNDEF
+          if (associated(cospOUT%grLidar532_cldlayer))      cospOUT%grLidar532_cldlayer(:,:)   = R_UNDEF
+          if (associated(cospOUT%grLidar532_beta_tot))      cospOUT%grLidar532_beta_tot(:,:,:) = R_UNDEF
+          if (associated(cospOUT%grLidar532_beta_mol))      cospOUT%grLidar532_beta_mol(:,:)   = R_UNDEF
+       endif
+    endif
+
+    if (any([Lcalipso_subcolumn,Lcalipso_column])) then
+       if (any(cospIN%betatot_calipso .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%betatot_calipso contains values out of range'
+          Lcalipso_subcolumn = .false.
+          Lcalipso_column    = .false.
+          if (associated(cospOUT%calipso_cfad_sr))       cospOUT%calipso_cfad_sr(:,:,:)       = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcld))      cospOUT%calipso_lidarcld(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldphase)) cospOUT%calipso_lidarcldphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayer))      cospOUT%calipso_cldlayer(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayerphase)) cospOUT%calipso_cldlayerphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtmp))   cospOUT%calipso_lidarcldtmp(:,:,:)   = R_UNDEF
+          if (associated(cospOUT%calipso_srbval))        cospOUT%calipso_srbval(:)            = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtype))  cospOUT%calipso_lidarcldtype(:,:,:)  = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtype))       cospOUT%calipso_cldtype(:,:)         = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypetemp))   cospOUT%calipso_cldtypetemp(:,:)     = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypemeanz))  cospOUT%calipso_cldtypemeanz(:,:)    = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypemeanzse)) cospOUT%calipso_cldtypemeanzse(:,:) = R_UNDEF 
+          if (associated(cospOUT%calipso_cldthinemis))   cospOUT%calipso_cldthinemis(:)       = R_UNDEF
+       endif
+       if (any(cospIN%betatot_liq_calipso .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = ('ERROR: COSP input variable: cospIN%betatot_liq_calipso contains values out of range')
+          Lcalipso_subcolumn = .false.
+          Lcalipso_column    = .false.
+          if (associated(cospOUT%calipso_cfad_sr))       cospOUT%calipso_cfad_sr(:,:,:)       = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcld))      cospOUT%calipso_lidarcld(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldphase)) cospOUT%calipso_lidarcldphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayer))      cospOUT%calipso_cldlayer(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayerphase)) cospOUT%calipso_cldlayerphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtmp))   cospOUT%calipso_lidarcldtmp(:,:,:)   = R_UNDEF
+          if (associated(cospOUT%calipso_srbval))        cospOUT%calipso_srbval(:)            = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtype))  cospOUT%calipso_lidarcldtype(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%calipso_cldtype))       cospOUT%calipso_cldtype(:,:)         = R_UNDEF
+          if (associated(cospOUT%calipso_cldtypetemp))   cospOUT%calipso_cldtypetemp(:,:)     = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypemeanz))  cospOUT%calipso_cldtypemeanz(:,:)    = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypemeanzse)) cospOUT%calipso_cldtypemeanzse(:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldthinemis))   cospOUT%calipso_cldthinemis(:)       = R_UNDEF
+       endif
+       if (any(cospIN%betatot_ice_calipso .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%betatot_ice_calipso contains values out of range'
+          Lcalipso_subcolumn = .false.
+          Lcalipso_column    = .false.
+          if (associated(cospOUT%calipso_cfad_sr))       cospOUT%calipso_cfad_sr(:,:,:)       = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcld))      cospOUT%calipso_lidarcld(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldphase)) cospOUT%calipso_lidarcldphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayer))      cospOUT%calipso_cldlayer(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayerphase)) cospOUT%calipso_cldlayerphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtmp))   cospOUT%calipso_lidarcldtmp(:,:,:)   = R_UNDEF
+          if (associated(cospOUT%calipso_srbval))        cospOUT%calipso_srbval(:)            = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtype))  cospOUT%calipso_lidarcldtype(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%calipso_cldtype))       cospOUT%calipso_cldtype(:,:)         = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypetemp))   cospOUT%calipso_cldtypetemp(:,:)     = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypemeanz))  cospOUT%calipso_cldtypemeanz(:,:)    = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypemeanzse)) cospOUT%calipso_cldtypemeanzse(:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldthinemis))   cospOUT%calipso_cldthinemis(:)       = R_UNDEF
+       endif
+       if (any(cospIN%tautot_calipso .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%tautot_calipso contains values out of range'
+          Lcalipso_subcolumn = .false.
+          Lcalipso_column    = .false.
+          if (associated(cospOUT%calipso_cfad_sr))       cospOUT%calipso_cfad_sr(:,:,:)       = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcld))      cospOUT%calipso_lidarcld(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldphase)) cospOUT%calipso_lidarcldphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayer))      cospOUT%calipso_cldlayer(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayerphase)) cospOUT%calipso_cldlayerphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtmp))   cospOUT%calipso_lidarcldtmp(:,:,:)   = R_UNDEF
+          if (associated(cospOUT%calipso_srbval))        cospOUT%calipso_srbval(:)            = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtype))  cospOUT%calipso_lidarcldtype(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%calipso_cldtype))       cospOUT%calipso_cldtype(:,:)         = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypetemp))   cospOUT%calipso_cldtypetemp(:,:)     = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypemeanz))  cospOUT%calipso_cldtypemeanz(:,:)    = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypemeanzse)) cospOUT%calipso_cldtypemeanzse(:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldthinemis))   cospOUT%calipso_cldthinemis(:)       = R_UNDEF
+       endif
+       if (any(cospIN%tautot_liq_calipso .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = ('ERROR: COSP input variable: cospIN%tautot_liq_calipso contains values out of range')
+          Lcalipso_subcolumn = .false.
+          Lcalipso_column    = .false.
+          if (associated(cospOUT%calipso_cfad_sr))       cospOUT%calipso_cfad_sr(:,:,:)       = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcld))      cospOUT%calipso_lidarcld(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldphase)) cospOUT%calipso_lidarcldphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayer))      cospOUT%calipso_cldlayer(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayerphase)) cospOUT%calipso_cldlayerphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtmp))   cospOUT%calipso_lidarcldtmp(:,:,:)   = R_UNDEF
+          if (associated(cospOUT%calipso_srbval))        cospOUT%calipso_srbval(:)            = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtype))  cospOUT%calipso_lidarcldtype(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%calipso_cldtype))       cospOUT%calipso_cldtype(:,:)         = R_UNDEF
+          if (associated(cospOUT%calipso_cldtypetemp))   cospOUT%calipso_cldtypetemp(:,:)     = R_UNDEF
+          if (associated(cospOUT%calipso_cldtypemeanz))  cospOUT%calipso_cldtypemeanz(:,:)    = R_UNDEF
+          if (associated(cospOUT%calipso_cldtypemeanzse)) cospOUT%calipso_cldtypemeanzse(:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldthinemis))   cospOUT%calipso_cldthinemis(:)       = R_UNDEF
+       endif
+       if (any(cospIN%tautot_ice_calipso .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%tautot_ice_calipso contains values out of range'
+          Lcalipso_subcolumn = .false.
+          Lcalipso_column    = .false.
+          if (associated(cospOUT%calipso_cfad_sr))       cospOUT%calipso_cfad_sr(:,:,:)       = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcld))      cospOUT%calipso_lidarcld(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldphase)) cospOUT%calipso_lidarcldphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayer))      cospOUT%calipso_cldlayer(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayerphase)) cospOUT%calipso_cldlayerphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtmp))   cospOUT%calipso_lidarcldtmp(:,:,:)   = R_UNDEF
+          if (associated(cospOUT%calipso_srbval))        cospOUT%calipso_srbval(:)            = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtype))  cospOUT%calipso_lidarcldtype(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%calipso_cldtype))       cospOUT%calipso_cldtype(:,:)         = R_UNDEF
+          if (associated(cospOUT%calipso_cldtypetemp))   cospOUT%calipso_cldtypetemp(:,:)     = R_UNDEF
+          if (associated(cospOUT%calipso_cldtypemeanz))  cospOUT%calipso_cldtypemeanz(:,:)    = R_UNDEF
+          if (associated(cospOUT%calipso_cldtypemeanzse)) cospOUT%calipso_cldtypemeanzse(:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldthinemis))   cospOUT%calipso_cldthinemis(:)       = R_UNDEF
+       endif
+       if (any(cospIN%tau_mol_calipso .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%tau_mol_calipso contains values out of range'
+          Lcalipso_subcolumn = .false.
+          Lcalipso_column    = .false.
+          if (associated(cospOUT%calipso_cfad_sr))       cospOUT%calipso_cfad_sr(:,:,:)       = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcld))      cospOUT%calipso_lidarcld(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldphase)) cospOUT%calipso_lidarcldphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayer))      cospOUT%calipso_cldlayer(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayerphase)) cospOUT%calipso_cldlayerphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtmp))   cospOUT%calipso_lidarcldtmp(:,:,:)   = R_UNDEF
+          if (associated(cospOUT%calipso_srbval))        cospOUT%calipso_srbval(:)            = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtype))  cospOUT%calipso_lidarcldtype(:,:,:)  = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtype))       cospOUT%calipso_cldtype(:,:)         = R_UNDEF 
+          if (associated(cospOUT%calipso_cldtypetemp))   cospOUT%calipso_cldtypetemp(:,:)     = R_UNDEF
+          if (associated(cospOUT%calipso_cldtypemeanz))  cospOUT%calipso_cldtypemeanz(:,:)    = R_UNDEF
+          if (associated(cospOUT%calipso_cldtypemeanzse)) cospOUT%calipso_cldtypemeanzse(:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldthinemis))   cospOUT%calipso_cldthinemis(:)       = R_UNDEF
+       endif
+    endif
+    if (any([Lcalipso_subcolumn,Lcalipso_column,Lcloudsat_column,Lradar_lidar_tcc,       &
+        Llidar_only_freq_cloud, Lcloudsat_tcc, Lcloudsat_tcc2])) then
+       if (any(cospIN%beta_mol_calipso .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%beta_mol_calipso contains values out of range'
+          Lcalipso_subcolumn = .false.
+          Lcalipso_column    = .false.
+          Lcloudsat_column   = .false.
+          Lradar_lidar_tcc   = .false.
+          Llidar_only_freq_cloud = .false.
+          Lcloudsat_tcc      = .false.
+          Lcloudsat_tcc2     = .false.
+          if (associated(cospOUT%calipso_cfad_sr))        cospOUT%calipso_cfad_sr(:,:,:)       = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcld))       cospOUT%calipso_lidarcld(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldphase))  cospOUT%calipso_lidarcldphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayer))       cospOUT%calipso_cldlayer(:,:)        = R_UNDEF
+          if (associated(cospOUT%calipso_cldlayerphase))  cospOUT%calipso_cldlayerphase(:,:,:) = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtmp))    cospOUT%calipso_lidarcldtmp(:,:,:)   = R_UNDEF
+          if (associated(cospOUT%calipso_srbval))         cospOUT%calipso_srbval(:)            = R_UNDEF
+          if (associated(cospOUT%cloudsat_cfad_ze))       cospOUT%cloudsat_cfad_ze(:,:,:)      = R_UNDEF
+          if (associated(cospOUT%lidar_only_freq_cloud))  cospOUT%lidar_only_freq_cloud(:,:)   = R_UNDEF
+          if (associated(cospOUT%radar_lidar_tcc))        cospOUT%radar_lidar_tcc(:)           = R_UNDEF
+          if (associated(cospOUT%cloudsat_tcc))           cospOUT%cloudsat_tcc(:)              = R_UNDEF
+          if (associated(cospOUT%cloudsat_tcc2))          cospOUT%cloudsat_tcc2(:)             = R_UNDEF
+          if (associated(cospOUT%calipso_lidarcldtype))   cospOUT%calipso_lidarcldtype(:,:,:)  = R_UNDEF
+          if (associated(cospOUT%calipso_cldtype))        cospOUT%calipso_cldtype(:,:)         = R_UNDEF
+          if (associated(cospOUT%calipso_cldtypetemp))    cospOUT%calipso_cldtypetemp(:,:)     = R_UNDEF
+          if (associated(cospOUT%calipso_cldtypemeanz))   cospOUT%calipso_cldtypemeanz(:,:)    = R_UNDEF
+          if (associated(cospOUT%calipso_cldtypemeanzse)) cospOUT%calipso_cldtypemeanzse(:,:)  = R_UNDEF
+          if (associated(cospOUT%calipso_cldthinemis))    cospOUT%calipso_cldthinemis(:)       = R_UNDEF
+       endif
+    endif
+    if (any([Lparasol_subcolumn,Lparasol_column])) then
+       if (any(cospIN%tautot_S_liq .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%tautot_S_liq contains values out of range'
+          Lparasol_subcolumn = .false.
+          Lparasol_column    = .false.
+          if (associated(cospOUT%parasolPix_refl))  cospOUT%parasolPix_refl(:,:,:) = R_UNDEF
+          if (associated(cospOUT%parasolGrid_refl)) cospOUT%parasolGrid_refl(:,:)  = R_UNDEF
+       endif
+       if (any(cospIN%tautot_S_ice .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%tautot_S_ice contains values out of range'
+          Lparasol_subcolumn = .false.
+          Lparasol_column    = .false.
+          if (associated(cospOUT%parasolPix_refl))  cospOUT%parasolPix_refl(:,:,:) = R_UNDEF
+          if (associated(cospOUT%parasolGrid_refl)) cospOUT%parasolGrid_refl(:,:)  = R_UNDEF
+       endif
+    endif
+    if (any([Lcloudsat_subcolumn,Lcloudsat_column,Lradar_lidar_tcc,Llidar_only_freq_cloud, &
+        Lcloudsat_tcc, Lcloudsat_tcc2])) then
+       if (any(cospIN%z_vol_cloudsat .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%z_vol_cloudsat contains values out of range'
+          Lcloudsat_subcolumn = .false.
+          Lcloudsat_column    = .false.
+          Lradar_lidar_tcc    = .false.
+          Llidar_only_freq_cloud = .false.
+          Lcloudsat_tcc       = .false.
+          Lcloudsat_tcc2      = .false.
+          if (associated(cospOUT%cloudsat_cfad_ze))          cospOUT%cloudsat_cfad_ze(:,:,:)        = R_UNDEF
+          if (associated(cospOUT%cloudsat_Ze_tot))           cospOUT%cloudsat_Ze_tot(:,:,:)         = R_UNDEF
+          if (associated(cospOUT%lidar_only_freq_cloud))     cospOUT%lidar_only_freq_cloud(:,:)     = R_UNDEF
+          if (associated(cospOUT%radar_lidar_tcc))           cospOUT%radar_lidar_tcc(:)             = R_UNDEF
+          if (associated(cospOUT%cloudsat_tcc)) cospOUT%cloudsat_tcc(:) = R_UNDEF
+          if (associated(cospOUT%cloudsat_tcc2)) cospOUT%cloudsat_tcc2(:) = R_UNDEF
+       endif
+       if (any(cospIN%kr_vol_cloudsat .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%kr_vol_cloudsat contains values out of range'
+          Lcloudsat_subcolumn = .false.
+          Lcloudsat_column    = .false.
+          Lradar_lidar_tcc    = .false.
+          Llidar_only_freq_cloud = .false.
+          Lcloudsat_tcc       = .false.
+          Lcloudsat_tcc2      = .false.
+          if (associated(cospOUT%cloudsat_cfad_ze))          cospOUT%cloudsat_cfad_ze(:,:,:)        = R_UNDEF
+          if (associated(cospOUT%cloudsat_Ze_tot))           cospOUT%cloudsat_Ze_tot(:,:,:)         = R_UNDEF
+          if (associated(cospOUT%lidar_only_freq_cloud))     cospOUT%lidar_only_freq_cloud(:,:)     = R_UNDEF
+          if (associated(cospOUT%radar_lidar_tcc))           cospOUT%radar_lidar_tcc(:)             = R_UNDEF
+          if (associated(cospOUT%cloudsat_tcc)) cospOUT%cloudsat_tcc(:) = R_UNDEF
+          if (associated(cospOUT%cloudsat_tcc2)) cospOUT%cloudsat_tcc2(:) = R_UNDEF
+       endif
+       if (any(cospIN%g_vol_cloudsat .lt. 0)) then
+          nError=nError+1
+          errorMessage(nError) = 'ERROR: COSP input variable: cospIN%g_vol_cloudsat contains values out of range'
+          Lcloudsat_subcolumn = .false.
+          Lcloudsat_column    = .false.
+          Lradar_lidar_tcc    = .false.
+          Llidar_only_freq_cloud = .false.
+          Lcloudsat_tcc       = .false.
+          Lcloudsat_tcc2      = .false.          
+          if (associated(cospOUT%cloudsat_cfad_ze))          cospOUT%cloudsat_cfad_ze(:,:,:)        = R_UNDEF
+          if (associated(cospOUT%cloudsat_Ze_tot))           cospOUT%cloudsat_Ze_tot(:,:,:)         = R_UNDEF
+          if (associated(cospOUT%lidar_only_freq_cloud))     cospOUT%lidar_only_freq_cloud(:,:)     = R_UNDEF
+          if (associated(cospOUT%radar_lidar_tcc))           cospOUT%radar_lidar_tcc(:)             = R_UNDEF
+          if (associated(cospOUT%cloudsat_tcc)) cospOUT%cloudsat_tcc(:) = R_UNDEF
+          if (associated(cospOUT%cloudsat_tcc2)) cospOUT%cloudsat_tcc2(:) = R_UNDEF          
+       endif
+    endif
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! Part 2: Check input fields array size for consistency. This needs to be done for each
+    !         simulator
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! ISCCP
+    if (Lisccp_subcolumn .or. Lisccp_column) then
+       if (size(cospIN%frac_out,1)  .ne. cospIN%Npoints .OR. &
+           size(cospIN%tau_067,1)   .ne. cospIN%Npoints .OR. &
+           size(cospIN%emiss_11,1)  .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%skt)     .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%qv,1)    .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%at,1)    .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%phalf,1) .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%sunlit)  .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%pfull,1) .ne. cospIN%Npoints) then
+          Lisccp_subcolumn = .false.
+          Lisccp_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(isccp_simulator): The number of points in the input fields are inconsistent'
+       endif
+       if (size(cospIN%frac_out,2) .ne. cospIN%Ncolumns .OR. &
+           size(cospIN%tau_067,2)  .ne. cospIN%Ncolumns .OR. &
+           size(cospIN%emiss_11,2) .ne. cospIN%Ncolumns) then
+          Lisccp_subcolumn = .false.
+          Lisccp_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(isccp_simulator): The number of sub-columns in the input fields are inconsistent'
+       endif
+       if (size(cospIN%frac_out,3)  .ne. cospIN%Nlevels .OR. &
+           size(cospIN%tau_067,3)   .ne. cospIN%Nlevels .OR. &
+           size(cospIN%emiss_11,3)  .ne. cospIN%Nlevels .OR. &
+           size(cospgridIN%qv,2)    .ne. cospIN%Nlevels .OR. &
+           size(cospgridIN%at,2)    .ne. cospIN%Nlevels .OR. &
+           size(cospgridIN%pfull,2) .ne. cospIN%Nlevels .OR. &
+           size(cospgridIN%phalf,2) .ne. cospIN%Nlevels+1) then
+          Lisccp_subcolumn = .false.
+          Lisccp_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(isccp_simulator): The number of levels in the input fields are inconsistent'
+       endif
+    endif
+    
+    ! MISR
+    if (Lmisr_subcolumn .or. Lmisr_column) then
+       if (size(cospIN%tau_067,1)        .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%sunlit)       .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%hgt_matrix,1) .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%at,1)         .ne. cospIN%Npoints) then
+          Lmisr_subcolumn = .false.
+          Lmisr_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(misr_simulator): The number of points in the input fields are inconsistent'
+       endif
+       if (size(cospIN%tau_067,2) .ne. cospIN%Ncolumns) then
+          Lmisr_subcolumn = .false.
+          Lmisr_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(misr_simulator): The number of sub-columns in the input fields are inconsistent'
+       endif
+       if (size(cospIN%tau_067,3)        .ne. cospIN%Nlevels .OR. &
+           size(cospgridIN%hgt_matrix,2) .ne. cospIN%Nlevels .OR. &
+           size(cospgridIN%at,2)         .ne. cospIN%Nlevels) then
+          Lmisr_subcolumn = .false.
+          Lmisr_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(misr_simulator): The number of levels in the input fields are inconsistent'
+       endif
+    endif
+    
+    ! MODIS
+    if (Lmodis_subcolumn .or. Lmodis_column) then
+       if (size(cospIN%fracLiq,1) .ne. cospIN%Npoints .OR. &
+           size(cospIN%tau_067,1) .ne. cospIN%Npoints .OR. &
+           size(cospIN%asym,1)    .ne. cospIN%Npoints .OR. &
+           size(cospIN%ss_alb,1)  .ne. cospIN%Npoints) then
+          Lmodis_subcolumn = .false.
+          Lmodis_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(modis_simulator): The number of points in the input fields are inconsistent'
+       endif
+       if (size(cospIN%fracLiq,2) .ne. cospIN%Ncolumns .OR. &
+           size(cospIN%tau_067,2) .ne. cospIN%Ncolumns .OR. &
+           size(cospIN%asym,2)    .ne. cospIN%Ncolumns .OR. &
+           size(cospIN%ss_alb,2)  .ne. cospIN%Ncolumns) then
+          Lmodis_subcolumn = .false.
+          Lmodis_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(modis_simulator): The number of sub-columns in the input fields are inconsistent'
+       endif
+       if (size(cospIN%fracLiq,3) .ne. cospIN%Nlevels .OR. &
+           size(cospIN%tau_067,3) .ne. cospIN%Nlevels .OR. &
+           size(cospIN%asym,3)    .ne. cospIN%Nlevels .OR. &
+           size(cospIN%ss_alb,3)  .ne. cospIN%Nlevels) then
+          Lmodis_subcolumn = .false.
+          Lmodis_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(modis_simulator): The number of levels in the input fields are inconsistent'
+       endif
+    endif
+    
+    ! CLOUDSAT
+    if (Lcloudsat_subcolumn .or. Lcloudsat_column) then
+       if (size(cospIN%z_vol_cloudsat,1)   .ne. cospIN%Npoints .OR. &
+           size(cospIN%kr_vol_cloudsat,1)  .ne. cospIN%Npoints .OR. &
+           size(cospIN%g_vol_cloudsat,1)   .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%hgt_matrix,1)   .ne. cospIN%Npoints) then
+          Lcloudsat_subcolumn = .false.
+          Lcloudsat_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(cloudsat_simulator): The number of points in the input fields are inconsistent'
+       endif
+       if (size(cospIN%z_vol_cloudsat,2)  .ne. cospIN%Ncolumns .OR. &
+           size(cospIN%kr_vol_cloudsat,2) .ne. cospIN%Ncolumns .OR. &
+           size(cospIN%g_vol_cloudsat,2)  .ne. cospIN%Ncolumns) then
+          Lcloudsat_subcolumn = .false.
+          Lcloudsat_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(cloudsat_simulator): The number of sub-columns in the input fields are inconsistent'
+       endif
+       if (size(cospIN%z_vol_cloudsat,3)  .ne. cospIN%Nlevels .OR. &
+           size(cospIN%kr_vol_cloudsat,3) .ne. cospIN%Nlevels .OR. &
+           size(cospIN%g_vol_cloudsat,3)  .ne. cospIN%Nlevels .OR. &
+           size(cospgridIN%hgt_matrix,2)  .ne. cospIN%Nlevels) then
+          Lcloudsat_subcolumn = .false.
+          Lcloudsat_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(cloudsat_simulator): The number of levels in the input fields are inconsistent'
+       endif
+    endif
+
+    ! GROUND LIDAR @ 532nm
+    if (LgrLidar532_subcolumn .or. LgrLidar532_column) then
+       if (size(cospIN%beta_mol_grLidar532,1)    .ne. cospIN%Npoints .OR. & 
+           size(cospIN%betatot_grLidar532,1)     .ne. cospIN%Npoints .OR. &
+           size(cospIN%tau_mol_grLidar532,1)     .ne. cospIN%Npoints .OR. &
+           size(cospIN%tautot_grLidar532,1)      .ne. cospIN%Npoints) then
+          LgrLidar532_subcolumn = .false.
+          LgrLidar532_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(grLidar532_simulator): The number of points in the input fields are inconsistent'
+       endif
+       if (size(cospIN%betatot_grLidar532,2)    .ne. cospIN%Ncolumns .OR. & 
+           size(cospIN%tautot_grLidar532,2)     .ne. cospIN%Ncolumns) then 
+          LgrLidar532_subcolumn = .false. 
+          LgrLidar532_column    = .false. 
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(grLidar532_simulator): The number of sub-columns in the input fields are inconsistent'
+       endif
+       if (size(cospIN%beta_mol_grLidar532,2)    .ne. cospIN%Nlevels .OR. &
+           size(cospIN%betatot_grLidar532,3)     .ne. cospIN%Nlevels .OR. &
+           size(cospIN%tau_mol_grLidar532,2)     .ne. cospIN%Nlevels .OR. &
+           size(cospIN%tautot_grLidar532,3)      .ne. cospIN%Nlevels) then
+          LgrLidar532_subcolumn = .false. 
+          LgrLidar532_column    = .false. 
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(grLidar532_simulator): The number of levels in the input fields are inconsistent' 
+       endif
+    endif
+    
+    ! ATLID
+    if (Latlid_subcolumn .or. Latlid_column) then
+       if (size(cospIN%beta_mol_atlid,1)    .ne. cospIN%Npoints .OR. &
+           size(cospIN%betatot_atlid,1)     .ne. cospIN%Npoints .OR. &
+           size(cospIN%tau_mol_atlid,1)     .ne. cospIN%Npoints .OR. & 
+           size(cospIN%tautot_atlid,1)      .ne. cospIN%Npoints) then 
+          Latlid_subcolumn = .false. 
+          Latlid_column    = .false. 
+          nError=nError+1             
+          errorMessage(nError) = 'ERROR(atlid_simulator): The number of points in the input fields are inconsistent'
+       endif
+       if (size(cospIN%betatot_atlid,2)    .ne. cospIN%Ncolumns .OR. &
+           size(cospIN%tautot_atlid,2)     .ne. cospIN%Ncolumns) then 
+          Latlid_subcolumn = .false.
+          Latlid_column    = .false.
+          nError=nError+1              
+          errorMessage(nError) = 'ERROR(atlid_simulator): The number of sub-columns in the input fields are inconsistent'
+       endif
+       if (size(cospIN%beta_mol_atlid,2)    .ne. cospIN%Nlevels .OR. &
+           size(cospIN%betatot_atlid,3)     .ne. cospIN%Nlevels .OR. & 
+           size(cospIN%tau_mol_atlid,2)     .ne. cospIN%Nlevels .OR. &
+           size(cospIN%tautot_atlid,3)      .ne. cospIN%Nlevels) then 
+          Latlid_subcolumn = .false.
+          Latlid_column    = .false. 
+          nError=nError+1 
+          errorMessage(nError) = 'ERROR(atlid_simulator): The number of levels in the input fields are inconsistent'
+       endif
+    endif
+
+    ! CALIPSO
+    if (Lcalipso_subcolumn .or. Lcalipso_column) then
+       if (size(cospIN%beta_mol_calipso,1)    .ne. cospIN%Npoints .OR. &
+           size(cospIN%betatot_calipso,1)     .ne. cospIN%Npoints .OR. &
+           size(cospIN%betatot_liq_calipso,1) .ne. cospIN%Npoints .OR. &
+           size(cospIN%betatot_ice_calipso,1) .ne. cospIN%Npoints .OR. &
+           size(cospIN%tau_mol_calipso,1)     .ne. cospIN%Npoints .OR. &
+           size(cospIN%tautot_calipso,1)      .ne. cospIN%Npoints .OR. &
+           size(cospIN%tautot_liq_calipso,1)  .ne. cospIN%Npoints .OR. &
+           size(cospIN%tautot_ice_calipso,1)  .ne. cospIN%Npoints) then
+          Lcalipso_subcolumn = .false.
+          Lcalipso_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(calipso_simulator): The number of points in the input fields are inconsistent'
+       endif
+       if (size(cospIN%betatot_calipso,2)     .ne. cospIN%Ncolumns .OR. &
+           size(cospIN%betatot_liq_calipso,2) .ne. cospIN%Ncolumns .OR. &
+           size(cospIN%betatot_ice_calipso,2) .ne. cospIN%Ncolumns .OR. &
+           size(cospIN%tautot_calipso,2)      .ne. cospIN%Ncolumns .OR. &
+           size(cospIN%tautot_liq_calipso,2)  .ne. cospIN%Ncolumns .OR. &
+           size(cospIN%tautot_ice_calipso,2)  .ne. cospIN%Ncolumns) then
+          Lcalipso_subcolumn = .false.
+          Lcalipso_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(calipso_simulator): The number of sub-columns in the input fields are inconsistent'
+       endif
+       if (size(cospIN%beta_mol_calipso,2)    .ne. cospIN%Nlevels .OR. &
+           size(cospIN%betatot_calipso,3)     .ne. cospIN%Nlevels .OR. &
+           size(cospIN%betatot_liq_calipso,3) .ne. cospIN%Nlevels .OR. &
+           size(cospIN%betatot_ice_calipso,3) .ne. cospIN%Nlevels .OR. &
+           size(cospIN%tau_mol_calipso,2)     .ne. cospIN%Nlevels .OR. &
+           size(cospIN%tautot_calipso,3)      .ne. cospIN%Nlevels .OR. &
+           size(cospIN%tautot_liq_calipso,3)  .ne. cospIN%Nlevels .OR. &
+           size(cospIN%tautot_ice_calipso,3)  .ne. cospIN%Nlevels) then
+          Lcalipso_subcolumn = .false.
+          Lcalipso_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(calipso_simulator): The number of levels in the input fields are inconsistent'
+       endif
+    endif
+    
+    ! PARASOL
+    if (Lparasol_subcolumn .or. Lparasol_column) then
+       if (size(cospIN%tautot_S_liq,1) .ne. cospIN%Npoints .OR. &
+           size(cospIN%tautot_S_ice,1) .ne. cospIN%Npoints) then
+          Lparasol_subcolumn = .false.
+          Lparasol_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(parasol_simulator): The number of points in the input fields are inconsistent'
+       endif
+       if (size(cospIN%tautot_S_liq,2) .ne. cospIN%Ncolumns .OR. &
+           size(cospIN%tautot_S_ice,2) .ne. cospIN%Ncolumns) then
+          Lparasol_subcolumn = .false.
+          Lparasol_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(parasol_simulator): The number of levels in the input fields are inconsistent'
+       endif
+    endif
+
+    ! RTTOV
+    if (Lrttov_column) then
+       if (size(cospgridIN%pfull,1)           .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%at,1)              .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%qv,1)              .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%hgt_matrix_half,1) .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%u_sfc)             .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%v_sfc)             .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%skt)               .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%phalf,1)           .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%qv,1)              .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%land)              .ne. cospIN%Npoints .OR. &
+           size(cospgridIN%lat)               .ne. cospIN%Npoints) then
+          Lrttov_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(rttov_simulator): The number of points in the input fields are inconsistent'
+       endif
+       if (size(cospgridIN%pfull,2)           .ne. cospIN%Nlevels   .OR. &
+           size(cospgridIN%at,2)              .ne. cospIN%Nlevels   .OR. &
+           size(cospgridIN%qv,2)              .ne. cospIN%Nlevels   .OR. &
+           size(cospgridIN%hgt_matrix_half,2) .ne. cospIN%Nlevels+1 .OR. &
+           size(cospgridIN%phalf,2)           .ne. cospIN%Nlevels+1 .OR. &
+           size(cospgridIN%qv,2)              .ne. cospIN%Nlevels) then
+          Lrttov_column    = .false.
+          nError=nError+1
+          errorMessage(nError) = 'ERROR(rttov_simulator): The number of levels in the input fields are inconsistent'
+       endif
+    endif
+  end subroutine cosp_errorCheck
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! END MODULE
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+END MODULE MOD_COSP
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_atlid_interface.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_atlid_interface.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_atlid_interface.F90	(revision 3605)
@@ -0,0 +1,66 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History
+! Apr 2018 - R. Guzman - Original version
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MODULE MOD_COSP_ATLID_INTERFACE
+  USE COSP_KINDS,              ONLY: wp
+  IMPLICIT NONE
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! TYPE atlid_in
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+  type atlid_IN
+     integer,pointer ::       &
+          Npoints,      & ! Number of gridpoints.
+          Ncolumns,     & ! Number of columns.
+          Nlevels         ! Number of levels.
+
+     real(wp),dimension(:,:),pointer :: &
+          beta_mol_atlid,     & ! Molecular backscatter coefficient
+          tau_mol_atlid         ! Molecular optical depth
+     real(wp),dimension(:,:,:),pointer :: &
+          betatot_atlid,      & ! 
+          tautot_atlid          ! Optical thickess integrated from top
+     real(wp),dimension(:,:,:,:),pointer :: &
+          taupart_atlid
+  end type atlid_IN
+
+CONTAINS
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! SUBROUTINE cosp_atlid_init
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  subroutine cosp_atlid_init() 
+
+  end subroutine cosp_atlid_init
+
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  !	END MODULE
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+END MODULE MOD_COSP_ATLID_INTERFACE
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_calipso_interface.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_calipso_interface.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_calipso_interface.F90	(revision 3605)
@@ -0,0 +1,85 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History
+! May 2015 - D. Swales - Original version
+! Jul 2017 - R. Guzman - Added Ground LIDar variables (GLID)
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MODULE MOD_COSP_CALIPSO_INTERFACE
+  USE COSP_KINDS,              ONLY: wp
+  USE MOD_LIDAR_SIMULATOR,     ONLY: alpha,beta,gamma
+  IMPLICIT NONE
+  
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! TYPE calipso_in
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+  type calipso_IN
+     integer,pointer ::       &
+          Npoints,      & ! Number of gridpoints.
+          Ncolumns,     & ! Number of columns.
+          Nlevels         ! Number of levels.
+
+     real(wp),dimension(:,:),pointer :: &
+          beta_mol,     & ! Molecular backscatter coefficient
+          tau_mol         ! Molecular optical depth
+     real(wp),dimension(:,:,:),pointer :: &
+          betatot,      & ! 
+          tautot,       & ! Optical thickess integrated from top
+          betatot_ice,  & ! Backscatter coefficient for ice particles
+          betatot_liq,  & ! Backscatter coefficient for liquid particles
+          tautot_ice,   & ! Total optical thickness of ice
+          tautot_liq      ! Total optical thickness of liq
+     real(wp),dimension(:,:,:,:),pointer :: &
+          taupart
+  end type calipso_IN
+
+CONTAINS
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! SUBROUTINE cosp_calipso_init
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  subroutine cosp_calipso_init() 
+    
+    ! Polynomial coefficients (Alpha, Beta, Gamma) which allow to compute the 
+    ! ATBperpendicular as a function of the ATB for ice or liquid cloud particles 
+    ! derived from CALIPSO-GOCCP observations at 120m vertical grid 
+    ! (Cesana and Chepfer, JGR, 2013).
+    !
+    ! Relationship between ATBice and ATBperp,ice for ice particles:
+    !                ATBperp,ice = Alpha*ATBice 
+    ! Relationship between ATBice and ATBperp,ice for liquid particles:
+    !          ATBperp,ice = Beta*ATBice^2 + Gamma*ATBice
+    Alpha = 0.2904_wp
+    Beta  = 0.4099_wp
+    Gamma = 0.009_wp    
+    
+  end subroutine cosp_calipso_init
+
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  !	END MODULE
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+END MODULE MOD_COSP_CALIPSO_INTERFACE
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_cloudsat_interface.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_cloudsat_interface.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_cloudsat_interface.F90	(revision 3605)
@@ -0,0 +1,142 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History
+! May 2015 - D. Swales - Original version
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MODULE MOD_COSP_CLOUDSAT_INTERFACE
+  USE COSP_KINDS,      ONLY: wp
+  USE quickbeam,       ONLY: quickbeam_init,radar_cfg,Re_MAX_BIN,Re_BIN_LENGTH
+  IMPLICIT NONE
+
+  ! Directory where LUTs will be stored
+  character(len=120) :: RADAR_SIM_LUT_DIRECTORY = './'
+  logical :: RADAR_SIM_LOAD_scale_LUTs_flag   = .false.
+  logical :: RADAR_SIM_UPDATE_scale_LUTs_flag = .false.
+  
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! TYPE cloudsat_IN
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  type cloudsat_IN
+     integer,pointer ::            &
+          Npoints,         & ! Number of horizontal grid-points
+          Nlevels,         & ! Number of vertical levels
+          Ncolumns           ! Number of subcolumns
+     real(wp),pointer ::   &
+          hgt_matrix(:,:),   & ! Height of hydrometeors (km)
+          z_vol(:,:,:),      & ! Effective reflectivity factor (mm^6/m^3)
+          kr_vol(:,:,:),     & ! Attenuation coefficient hydro (dB/km)
+          g_vol(:,:,:),      & ! Attenuation coefficient gases (dB/km)
+          g_to_vol_in(:,:)     ! Gaseous atteunation, radar to vol (dB)
+     type(radar_cfg),pointer :: rcfg   ! Radar simulator configuration
+  end type cloudsat_IN
+
+CONTAINS
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  !                              SUBROUTINE cosp_cloudsat_in
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  SUBROUTINE COSP_CLOUDSAT_INIT(radar_freq,k2,use_gas_abs,do_ray,undef,nhydro,   &
+                                surface_radar,rcfg,cloudsat_micro_scheme,load_LUT)
+    ! INPUTS
+    real(wp),intent(in) :: &
+         radar_freq,  & ! Radar frequency (GHz)
+         k2,          & ! |K|^2, the dielectric constant
+         undef          ! Undefined
+    integer,intent(in) :: &
+         use_gas_abs, & ! 1 = do gaseous abs calcs, 0=no gasesous absorbtion calculated,
+                        ! 2 = calculate absorption for first profile on all profiles
+         do_ray,      & !
+         nhydro,      & !
+         surface_radar
+    logical,intent(in),optional :: &
+         load_LUT
+    character(len=64),intent(in) :: &
+       cloudsat_micro_scheme
+
+    ! OUTPUTS
+    type(radar_cfg) :: &
+         rcfg           !
+
+    ! LOCAL VARIABLES
+    character(len=240) :: LUT_file_name
+    logical       :: local_load_LUT
+    integer       :: j
+
+    if (present(load_LUT)) then
+       local_load_LUT = load_LUT
+    else
+       local_load_LUT = RADAR_SIM_LOAD_scale_LUTs_flag
+    endif
+    
+    ! LUT file name
+    LUT_file_name = trim(RADAR_SIM_LUT_DIRECTORY) // &
+         trim(cloudsat_micro_scheme)
+
+    ! Initialize for NEW radar-configurarion derived type (radar_cfg)
+    rcfg%freq                = radar_freq
+    rcfg%k2                  = k2
+    rcfg%use_gas_abs         = use_gas_abs
+    rcfg%do_ray              = do_ray
+    rcfg%nhclass             = nhydro
+    rcfg%load_scale_LUTs     = local_load_LUT
+    rcfg%update_scale_LUTs   = .false.
+    rcfg%scale_LUT_file_name = LUT_file_name
+    rcfg%N_scale_flag        = .false.
+    rcfg%fc                  = undef
+    rcfg%rho_eff             = undef
+    rcfg%Z_scale_flag        = .false.
+    rcfg%Ze_scaled           = 0._wp
+    rcfg%Zr_scaled           = 0._wp
+    rcfg%kr_scaled           = 0._wp
+
+    ! Set up Re bin "structure" for z_scaling
+    rcfg%base_list(1)=0
+    do j=1,Re_MAX_BIN
+       rcfg%step_list(j)=0.1_wp+0.1_wp*((j-1)**1.5)
+       if(rcfg%step_list(j)>Re_BIN_LENGTH) then
+          rcfg%step_list(j)=Re_BIN_LENGTH
+       endif
+       if(j>1) then
+          rcfg%base_list(j)=rcfg%base_list(j-1)+floor(Re_BIN_LENGTH/rcfg%step_list(j-1))
+       endif
+    enddo
+
+    ! Set flag denoting position of radar
+    if (surface_radar == 1) then
+       rcfg%radar_at_layer_one = .false.
+    else
+       rcfg%radar_at_layer_one = .true.
+    endif
+
+  END SUBROUTINE COSP_CLOUDSAT_INIT
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  !                              	  END MODULE
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+END MODULE MOD_COSP_CLOUDSAT_INTERFACE
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_config.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_config.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_config.F90	(revision 3605)
@@ -0,0 +1,427 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History:
+! Jul 2007 - A. Bodas-Salcedo - Initial version
+! Jul 2008 - A. Bodas-Salcedo - Added definitions of ISCCP axes
+! Oct 2008 - H. Chepfer       - Added PARASOL_NREFL
+! Jun 2010 - R. Marchand      - Modified to support quickbeam V3, added ifdef for  
+!                               hydrometeor definitions
+! May 2015 - D. Swales        - Tidied up. Set up appropriate fields during initialization. 
+! June 2015- D. Swales        - Moved hydrometeor class variables to hydro_class_init in
+!                               the module quickbeam_optics.
+! Mar 2016 - D. Swales        - Added scops_ccfrac. Was previously hardcoded in prec_scops.f90.  
+! Mar 2018 - R. Guzman        - Added LIDAR_NTYPE for the OPAQ diagnostics
+! Apr 2018 - R. Guzman        - Added parameters for GROUND LIDAR and ATLID simulators
+!
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+MODULE MOD_COSP_CONFIG
+    USE COSP_KINDS, ONLY: wp,dp
+    IMPLICIT NONE
+
+   ! #####################################################################################
+   ! Common COSP information
+   ! #####################################################################################
+    character(len=32) ::   &
+         COSP_VERSION              ! COSP Version ID (set in cosp_interface_init)
+    real(wp),parameter ::  &
+         R_UNDEF      = -1.0E30, & ! Missing value
+         R_GROUND     = -1.0E20, & ! Flag for below ground results
+         scops_ccfrac = 0.05       ! Fraction of column (or subcolumn) covered with convective
+                                   ! precipitation (default is 5%). *NOTE* This quantity may vary
+                                   ! between modeling centers.
+    logical :: &
+         use_vgrid                 ! True=Use new grid for L3 CLOUDAT and CALIPSO
+    integer,parameter ::   &
+         SR_BINS = 15,           & ! Number of bins (backscattering coefficient) in CALOPSO LIDAR simulator.
+         N_HYDRO = 9               ! Number of hydrometeor classes used by quickbeam radar simulator.
+
+    ! ####################################################################################  
+    ! Joint histogram bin-boundaries
+    ! tau is used by ISCCP and MISR
+    ! pres is used by ISCCP
+    ! hgt is used by MISR
+    ! ReffLiq is used by MODIS
+    ! ReffIce is used by MODIS
+    ! *NOTE* ALL JOINT-HISTOGRAM BIN BOUNDARIES ARE DECLARED AND DEFINED HERE IN
+    !        COSP_CONFIG, WITH THE EXCEPTION OF THE TAU AXIS USED BY THE MODIS SIMULATOR,
+    !        WHICH IS SET DURING INITIALIZATION IN COSP_INTERFACE_INIT.
+    ! ####################################################################################
+    ! Optical depth bin axis
+    integer,parameter :: &
+         ntau=7  
+    real(wp),parameter,dimension(ntau+1) :: &
+       tau_binBounds = (/0.0, 0.3, 1.3, 3.6, 9.4, 23., 60., 10000./)
+    real(wp),parameter,dimension(ntau) :: &
+         tau_binCenters = (/0.15, 0.80, 2.45, 6.5, 16.2, 41.5, 100.0/)
+    real(wp),parameter,dimension(2,ntau) :: &
+         tau_binEdges = reshape(source=(/0.0, 0.3,  0.3,  1.3,  1.3,  3.6,      3.6,     &
+                                         9.4, 9.4, 23.0, 23.0, 60.0, 60.0, 100000.0/),   &
+                                         shape=(/2,ntau/)) 
+
+    ! Optical depth bin axes (ONLY USED BY MODIS SIMULATOR IN v1.4)
+    integer :: l,k
+    integer,parameter :: &
+         ntauV1p4 = 6
+    real(wp),parameter,dimension(ntauV1p4+1) :: &
+         tau_binBoundsV1p4 = (/0.3, 1.3, 3.6, 9.4, 23., 60., 10000./)
+    real(wp),parameter,dimension(2,ntauV1p4) :: &
+         tau_binEdgesV1p4 = reshape(source =(/tau_binBoundsV1p4(1),((tau_binBoundsV1p4(k),l=1,2),   &
+                                             k=2,ntauV1p4),100000._wp/),shape = (/2,ntauV1p4/)) 
+    real(wp),parameter,dimension(ntauV1p4) :: &
+         tau_binCentersV1p4 = (tau_binEdgesV1p4(1,:)+tau_binEdgesV1p4(2,:))/2._wp  
+    
+    ! Cloud-top height pressure bin axis
+    integer,parameter :: &
+         npres = 7     
+    real(wp),parameter,dimension(npres+1) :: &
+         pres_binBounds = (/0., 180., 310., 440., 560., 680., 800., 10000./)
+    real(wp),parameter,dimension(npres) :: &
+         pres_binCenters = (/90000., 74000., 62000., 50000., 37500., 24500., 9000./)   
+    real(wp),parameter,dimension(2,npres) :: &
+         pres_binEdges = reshape(source=(/100000.0, 80000.0, 80000.0, 68000.0, 68000.0,    &
+                                           56000.0, 56000.0, 44000.0, 44000.0, 31000.0,    &
+                                           31000.0, 18000.0, 18000.0,     0.0/),           &
+                                           shape=(/2,npres/))
+
+    ! Cloud-top height bin axis #1
+    integer,parameter :: &
+         nhgt = 16
+    real(wp),parameter,dimension(nhgt+1) :: &
+         hgt_binBounds = (/-.99,0.,0.5,1.,1.5,2.,2.5,3.,4.,5.,7.,9.,11.,13.,15.,17.,99./)
+    real(wp),parameter,dimension(nhgt) :: &
+         hgt_binCenters = 1000*(/0.,0.25,0.75,1.25,1.75,2.25,2.75,3.5,4.5,6.,8.,10.,12.,   &
+         14.5,16.,18./)  
+    real(wp),parameter,dimension(2,nhgt) :: &
+         hgt_binEdges = 1000.0*reshape(source=(/-99.0, 0.0, 0.0, 0.5, 0.5, 1.0, 1.0, 1.5,  &
+                                                  1.5, 2.0, 2.0, 2.5, 2.5, 3.0, 3.0, 4.0,  &
+                                                  4.0, 5.0, 5.0, 7.0, 7.0, 9.0, 9.0,11.0,  &
+                                                  11.0,13.0,13.0,15.0,15.0,17.0,17.0,99.0/),&
+                                                  shape=(/2,nhgt/))    
+
+    ! Liquid and Ice particle bins for MODIS joint histogram of optical-depth and particle
+    ! size
+    integer :: i,j
+    integer,parameter :: &
+         nReffLiq = 6, & ! Number of bins for tau/ReffLiq joint-histogram
+         nReffIce = 6    ! Number of bins for tau/ReffICE joint-histogram
+    real(wp),parameter,dimension(nReffLiq+1) :: &
+         reffLIQ_binBounds = (/0., 8e-6, 1.0e-5, 1.3e-5, 1.5e-5, 2.0e-5, 3.0e-5/)
+    real(wp),parameter,dimension(nReffIce+1) :: &
+         reffICE_binBounds = (/0., 1.0e-5, 2.0e-5, 3.0e-5, 4.0e-5, 6.0e-5, 9.0e-5/)
+    real(wp),parameter,dimension(2,nReffICE) :: &
+         reffICE_binEdges = reshape(source=(/reffICE_binBounds(1),((reffICE_binBounds(k),  &
+                                    l=1,2),k=2,nReffICE),reffICE_binBounds(nReffICE+1)/),  &
+                                    shape = (/2,nReffICE/)) 
+    real(wp),parameter,dimension(2,nReffLIQ) :: &
+         reffLIQ_binEdges = reshape(source=(/reffLIQ_binBounds(1),((reffLIQ_binBounds(k),  &
+                                    l=1,2),k=2,nReffLIQ),reffLIQ_binBounds(nReffICE+1)/),  &
+                                    shape = (/2,nReffLIQ/))             
+    real(wp),parameter,dimension(nReffICE) :: &
+         reffICE_binCenters = (reffICE_binEdges(1,:)+reffICE_binEdges(2,:))/2._wp
+    real(wp),parameter,dimension(nReffLIQ) :: &
+         reffLIQ_binCenters = (reffLIQ_binEdges(1,:)+reffLIQ_binEdges(2,:))/2._wp
+
+    ! ####################################################################################  
+    ! Constants used by RTTOV.
+    ! ####################################################################################  
+    integer,parameter :: &
+         RTTOV_MAX_CHANNELS = 20
+    character(len=256),parameter :: &
+         rttovDir = '/homedata/rguzman/CALIPSO/RTTOV/rttov_11.3/'
+    ! ####################################################################################  
+    ! Constants used by the PARASOL simulator.
+    ! ####################################################################################  
+    integer,parameter :: &
+         PARASOL_NREFL = 5,  & ! Number of angles in LUT
+         PARASOL_NTAU  = 7     ! Number of optical depths in LUT
+    real(wp),parameter,dimension(PARASOL_NREFL) :: &
+         PARASOL_SZA = (/0.0, 20.0, 40.0, 60.0, 80.0/)
+    REAL(WP),parameter,dimension(PARASOL_NTAU) :: &
+         PARASOL_TAU = (/0., 1., 5., 10., 20., 50., 100./)
+    
+    ! LUTs
+    REAL(WP),parameter,dimension(PARASOL_NREFL,PARASOL_NTAU) :: &
+         ! LUT for liquid particles
+         rlumA = reshape(source=(/ 0.03,     0.03,     0.03,     0.03,     0.03,         &
+                                   0.090886, 0.072185, 0.058410, 0.052498, 0.034730,     &
+                                   0.283965, 0.252596, 0.224707, 0.175844, 0.064488,     &
+                                   0.480587, 0.436401, 0.367451, 0.252916, 0.081667,     &
+                                   0.695235, 0.631352, 0.509180, 0.326551, 0.098215,     &
+                                   0.908229, 0.823924, 0.648152, 0.398581, 0.114411,     &
+                                   1.0,      0.909013, 0.709554, 0.430405, 0.121567/),   &
+                                   shape=(/PARASOL_NREFL,PARASOL_NTAU/)),                & 
+         ! LUT for ice particles         			     
+         rlumB = reshape(source=(/ 0.03,     0.03,     0.03,     0.03,     0.03,         &
+                                   0.092170, 0.087082, 0.083325, 0.084935, 0.054157,     &
+                                   0.311941, 0.304293, 0.285193, 0.233450, 0.089911,     &
+                                   0.511298, 0.490879, 0.430266, 0.312280, 0.107854,     &
+                                   0.712079, 0.673565, 0.563747, 0.382376, 0.124127,     &
+                                   0.898243, 0.842026, 0.685773, 0.446371, 0.139004,     &
+                                   0.976646, 0.912966, 0.737154, 0.473317, 0.145269/),   &
+                                   shape=(/PARASOL_NREFL,PARASOL_NTAU/))  
+
+    ! ####################################################################################
+    ! ISCCP simulator tau/CTP joint histogram information
+    ! ####################################################################################
+    integer,parameter :: &
+         numISCCPTauBins  = ntau, &              ! Number of optical depth bins
+         numISCCPPresBins = npres                ! Number of pressure bins     
+    real(wp),parameter,dimension(ntau+1) :: &
+         isccp_histTau = tau_binBounds           ! Joint-histogram boundaries (optical depth)
+    real(wp),parameter,dimension(npres+1) :: &
+         isccp_histPres = pres_binBounds         ! Joint-histogram boundaries (cloud pressure)
+    real(wp),parameter,dimension(ntau) :: &
+         isccp_histTauCenters = tau_binCenters   ! Joint histogram bin centers (optical depth)
+    real(wp),parameter,dimension(npres) :: &   
+         isccp_histPresCenters = pres_binCenters ! Joint histogram bin centers (cloud pressure) 
+    real(wp),parameter,dimension(2,ntau) :: &
+         isccp_histTauEdges = tau_binEdges       ! Joint histogram bin edges (optical depth)
+    real(wp),parameter,dimension(2,npres) :: &    
+         isccp_histPresEdges = pres_binEdges     ! Joint histogram bin edges (cloud pressure)   
+    
+    ! ####################################################################################
+    ! MISR simulator tau/CTH joint histogram information 
+    ! ####################################################################################
+    integer,parameter ::  &
+         numMISRHgtBins = nhgt, &             ! Number of cloud-top height bins
+         numMISRTauBins = ntau                ! Number of optical depth bins
+    ! Joint histogram boundaries
+    real(wp),parameter,dimension(numMISRHgtBins+1) :: &
+         misr_histHgt = hgt_binBounds         ! Joint-histogram boundaries (cloud height)
+    real(wp),parameter,dimension(numMISRTauBins+1) :: &
+         misr_histTau = tau_binBounds         ! Joint-histogram boundaries (optical-depth)
+    real(wp),parameter,dimension(numMISRHgtBins) :: &
+         misr_histHgtCenters = hgt_binCenters ! Joint-histogram bin centers (cloud height)
+    real(wp),parameter,dimension(2,numMISRHgtBins) :: &
+         misr_histHgtEdges = hgt_BinEdges     ! Joint-histogram bin edges (cloud height)
+ 
+    ! ####################################################################################
+    ! MODIS simulator tau/CTP joint histogram information 
+    ! ####################################################################################
+    integer,parameter :: &
+         numMODISPresBins = npres                    ! Number of pressure bins for joint-histogram    
+    real(wp),parameter,dimension(numMODISPresBins + 1) :: & 
+         modis_histPres = 100*pres_binBounds         ! Joint-histogram boundaries (cloud pressure)
+    real(wp),parameter,dimension(2, numMODISPresBins) :: &
+         modis_histPresEdges = 100*pres_binEdges     ! Joint-histogram bin edges (cloud pressure)
+    real(wp),parameter,dimension(numMODISPresBins) :: &
+         modis_histPresCenters = 100*pres_binCenters ! Joint-histogram bin centers (cloud pressure)
+
+    ! For the MODIS simulator we want to preserve the ability for cospV1.4.0 to use the
+    ! old histogram bin boundaries for optical depth, so these are set up in initialization.
+    integer :: &
+         numMODISTauBins          ! Number of tau bins for joint-histogram
+    real(wp),save,allocatable,dimension(:) :: &
+         modis_histTau            ! Joint-histogram boundaries (optical depth)
+    !$OMP THREADPRIVATE(modis_histTau)
+    real(wp),save,allocatable,dimension(:,:) :: &
+         modis_histTauEdges       ! Joint-histogram bin edges (optical depth)
+    !$OMP THREADPRIVATE(modis_histTauEdges)
+    real(wp),save,allocatable,dimension(:) :: &
+         modis_histTauCenters     ! Joint-histogram bin centers (optical depth)
+    !$OMP THREADPRIVATE(modis_histTauCenters)
+    
+    ! ####################################################################################
+    ! MODIS simulator tau/ReffICE and tau/ReffLIQ joint-histogram information
+    ! ####################################################################################
+    ! Ice
+    integer,parameter :: &
+         numMODISReffIceBins = nReffIce                ! Number of bins for joint-histogram
+    real(wp),parameter,dimension(nReffIce+1) :: &
+         modis_histReffIce = reffICE_binBounds         ! Effective radius bin boundaries
+    real(wp),parameter,dimension(nReffIce) :: &
+         modis_histReffIceCenters = reffICE_binCenters ! Effective radius bin centers
+    real(wp),parameter,dimension(2,nReffICE) :: &
+         modis_histReffIceEdges = reffICE_binEdges     ! Effective radius bin edges
+       
+    ! Liquid
+    integer,parameter :: &
+         numMODISReffLiqBins = nReffLiq                ! Number of bins for joint-histogram
+    real(wp),parameter,dimension(nReffLiq+1) :: &
+         modis_histReffLiq = reffLIQ_binBounds         ! Effective radius bin boundaries 
+    real(wp),parameter,dimension(nReffLiq) :: &
+         modis_histReffLiqCenters = reffICE_binCenters ! Effective radius bin centers
+    real(wp),parameter,dimension(2,nReffICE) :: &
+         modis_histReffLiqEdges = reffLIQ_binEdges     ! Effective radius bin edges
+
+    ! ####################################################################################
+    ! CLOUDSAT reflectivity histogram information 
+    ! ####################################################################################
+    integer,parameter :: &
+       CLOUDSAT_DBZE_BINS     =   15, & ! Number of dBZe bins in histogram (cfad)
+       CLOUDSAT_DBZE_MIN      = -100, & ! Minimum value for radar reflectivity
+       CLOUDSAT_DBZE_MAX      =   80, & ! Maximum value for radar reflectivity
+       CLOUDSAT_CFAD_ZE_MIN   =  -50, & ! Lower value of the first CFAD Ze bin
+       CLOUDSAT_CFAD_ZE_WIDTH =    5    ! Bin width (dBZe)
+
+    real(wp),parameter,dimension(CLOUDSAT_DBZE_BINS+1) :: &
+         cloudsat_histRef = (/CLOUDSAT_DBZE_MIN,(/(i, i=int(CLOUDSAT_CFAD_ZE_MIN+CLOUDSAT_CFAD_ZE_WIDTH),&
+                             int(CLOUDSAT_CFAD_ZE_MIN+(CLOUDSAT_DBZE_BINS-1)*CLOUDSAT_CFAD_ZE_WIDTH),    &
+                             int(CLOUDSAT_CFAD_ZE_WIDTH))/),CLOUDSAT_DBZE_MAX/)
+    real(wp),parameter,dimension(2,CLOUDSAT_DBZE_BINS) :: &
+         cloudsat_binEdges = reshape(source=(/cloudsat_histRef(1),((cloudsat_histRef(k), &
+                                   l=1,2),k=2,CLOUDSAT_DBZE_BINS),cloudsat_histRef(CLOUDSAT_DBZE_BINS+1)/),&
+                                   shape = (/2,CLOUDSAT_DBZE_BINS/))     
+    real(wp),parameter,dimension(CLOUDSAT_DBZE_BINS) :: &
+         cloudsat_binCenters = (cloudsat_binEdges(1,:)+cloudsat_binEdges(2,:))/2._wp
+    
+    ! Parameters for Cloudsat near-surface precipitation diagnostics.
+    ! Precipitation classes.
+    integer, parameter :: &
+         nCloudsatPrecipClass = 10
+    integer, parameter :: &
+         pClass_noPrecip      = 0, & ! No precipitation
+         pClass_Rain1         = 1, & ! Rain possible
+         pClass_Rain2         = 2, & ! Rain probable
+         pClass_Rain3         = 3, & ! Rain certain
+         pClass_Snow1         = 4, & ! Snow possible
+         pClass_Snow2         = 5, & ! Snow certain
+         pClass_Mixed1        = 6, & ! Mixed-precipitation possible
+         pClass_Mixed2        = 7, & ! Mixed-precipitation certain
+         pClass_Rain4         = 8, & ! Heavy rain
+         pClass_default       = 9    ! Default
+    ! Reflectivity bin boundaries, used by decision tree to classify precipitation type.
+    real(wp), dimension(4),parameter :: &
+         Zenonbinval =(/0._wp, -5._wp, -7.5_wp, -15._wp/)
+    real(wp), dimension(6),parameter :: &
+         Zbinvallnd = (/10._wp, 5._wp, 2.5_wp, -2.5_wp, -5._wp, -15._wp/)
+    ! Vertical level index(Nlvgrid) for Cloudsat precipitation occurence/frequency diagnostics.
+    ! Level 39 of Nlvgrid(40) is 480-960m.
+!    integer, parameter :: &    !PREC_BUG
+!         cloudsat_preclvl = 39 !PREC_BUG
+    
+    ! ####################################################################################
+    ! Parameters used by the CALIPSO LIDAR simulator
+    ! #################################################################################### 
+    ! CALISPO backscatter histogram bins 
+    real(wp),parameter ::     &
+       S_cld       = 5.0,     & ! Threshold for cloud detection
+       S_att       = 0.01,    & !
+       S_cld_att   = 30.        ! Threshold for undefined cloud phase detection
+    real(wp),parameter,dimension(SR_BINS+1) :: &
+         calipso_histBsct = (/-1.,0.01,1.2,3.0,5.0,7.0,10.0,15.0,20.0,25.0,30.0,40.0,50.0,   &
+                              60.0,80.0,999./)         ! Backscatter histogram bins
+    real(wp),parameter,dimension(2,SR_BINS) :: &
+         calipso_binEdges = reshape(source=(/calipso_histBsct(1),((calipso_histBsct(k),  &
+                                    l=1,2),k=2,SR_BINS),calipso_histBsct(SR_BINS+1)/),   &
+                                    shape = (/2,SR_BINS/))     
+    real(wp),parameter,dimension(SR_BINS) :: &
+         calipso_binCenters = (calipso_binEdges(1,:)+calipso_binEdges(2,:))/2._wp  
+
+    integer,parameter  ::     &
+       LIDAR_NTEMP = 40, & 
+       LIDAR_NCAT  = 4,  & ! Number of categories for cloudtop heights (high/mid/low/tot)
+       LIDAR_NTYPE = 3     ! Number of categories for OPAQ (opaque/thin cloud + z_opaque)
+    real(wp),parameter,dimension(LIDAR_NTEMP) :: &
+       LIDAR_PHASE_TEMP=                                                                 &
+       (/-91.5,-88.5,-85.5,-82.5,-79.5,-76.5,-73.5,-70.5,-67.5,-64.5,                    &
+         -61.5,-58.5,-55.5,-52.5,-49.5,-46.5,-43.5,-40.5,-37.5,-34.5,                    &
+         -31.5,-28.5,-25.5,-22.5,-19.5,-16.5,-13.5,-10.5, -7.5, -4.5,                    &
+          -1.5,  1.5,  4.5,  7.5, 10.5, 13.5, 16.5, 19.5, 22.5, 25.5/)
+    real(wp),parameter,dimension(2,LIDAR_NTEMP) :: &
+       LIDAR_PHASE_TEMP_BNDS=reshape(source=                                             &
+          (/-273.15, -90., -90., -87., -87., -84., -84., -81., -81., -78.,               &
+             -78.,   -75., -75., -72., -72., -69., -69., -66., -66., -63.,               &
+             -63.,   -60., -60., -57., -57., -54., -54., -51., -51., -48.,               &
+             -48.,   -45., -45., -42., -42., -39., -39., -36., -36., -33.,               &
+             -33.,   -30., -30., -27., -27., -24., -24., -21., -21., -18.,               &
+             -18.,   -15., -15., -12., -12.,  -9.,  -9.,  -6.,  -6.,  -3.,               &
+              -3.,     0.,   0.,   3.,   3.,   6.,   6.,   9.,   9.,  12.,               &
+              12.,    15.,  15.,  18.,  18.,  21.,  21.,  24.,  24., 100. /),            &
+              shape=(/2,40/))        
+
+    ! ####################################################################################
+    ! Parameters used by the GROUND LIDAR simulator
+    ! #################################################################################### 
+    ! GROUND LIDAR backscatter histogram bins 
+!    real(wp),parameter ::     &
+!       S_cld       = 5.0,     & ! Threshold for cloud detection
+!       S_att       = 0.01,    & !
+!       S_cld_att   = 30.        ! Threshold for undefined cloud phase detection
+    real(wp),parameter,dimension(SR_BINS+1) :: &
+         grLidar532_histBsct = (/-1.,0.01,1.2,3.0,5.0,7.0,10.0,15.0,20.0,25.0,30.0,40.0,50.0,  &
+                                 60.0,80.0,999./)         ! Backscatter histogram bins
+    real(wp),parameter,dimension(2,SR_BINS) :: &
+         grLidar532_binEdges = reshape(source=(/grLidar532_histBsct(1),((grLidar532_histBsct(k),  &
+                                    l=1,2),k=2,SR_BINS),grLidar532_histBsct(SR_BINS+1)/),   &
+                                    shape = (/2,SR_BINS/))     
+    real(wp),parameter,dimension(SR_BINS) :: &
+         grLidar532_binCenters = (grLidar532_binEdges(1,:)+grLidar532_binEdges(2,:))/2._wp  
+
+!    integer,parameter  ::     &
+!       LIDAR_NCAT  = 4       ! Number of categories for cloudtop heights (high/mid/low/tot)
+
+    ! ####################################################################################
+    ! Parameters used by the ATLID LIDAR simulator
+    ! #################################################################################### 
+    ! ATLID LIDAR backscatter histogram bins 
+    real(wp),parameter ::     &
+       S_cld_atlid       = 1.74,    & ! Threshold for cloud detection
+       S_att_atlid       = 0.01,    & !
+       S_cld_att_atlid   = 6.67        ! Threshold for undefined cloud phase detection
+    real(wp),parameter,dimension(SR_BINS+1) :: &
+         atlid_histBsct = (/-1.,0.01,1.03,1.38,1.74,2.07,2.62,3.65,4.63,5.63,6.67,8.8,11.25,  &
+                                 13.2,17.2,999./)         ! Backscatter histogram bins
+    real(wp),parameter,dimension(2,SR_BINS) :: &
+         atlid_binEdges = reshape(source=(/atlid_histBsct(1),((atlid_histBsct(k),  &
+                                    l=1,2),k=2,SR_BINS),atlid_histBsct(SR_BINS+1)/),   &
+                                    shape = (/2,SR_BINS/))     
+    real(wp),parameter,dimension(SR_BINS) :: &
+         atlid_binCenters = (atlid_binEdges(1,:)+atlid_binEdges(2,:))/2._wp  
+
+!    integer,parameter  ::     &
+!       LIDAR_NCAT  = 4       ! Number of categories for cloudtop heights (high/mid/low/tot)
+
+    ! ####################################################################################
+    ! New vertical grid used by CALIPSO and CLOUDSAT L3 (set up during initialization)
+    ! ####################################################################################
+    integer :: &
+         Nlvgrid      ! Number of levels in New grid
+    real(wp),dimension(:), save, allocatable :: &
+       vgrid_zl,  & ! New grid bottoms
+       vgrid_zu,  & ! New grid tops
+       vgrid_z      ! New grid center
+    !$OMP THREADPRIVATE(vgrid_zl,vgrid_zu,vgrid_z)
+
+    ! ####################################################################################
+    ! Vertical grid used by CALIPSO and CLOUDSAT L3 (LMDZ parameter)
+    ! ####################################################################################
+
+    integer, parameter :: &
+         niv_sorties = 40
+    real(wp),parameter,dimension(niv_sorties) :: &
+         vgrid_z_in = (/240.0, 720.0, 1200.0, 1680.0, 2160.0, 2640.0, 3120.0, 3600.0, &
+                        4080.0, 4560.0, 5040.0, 5520.0, 6000.0, 6480.0, 6960.0, 7440.0, &
+			7920.0, 8400.0, 8880.0, 9360.0, 9840.0, 10320.0, 10800.0, &
+			11280.0, 11760.0, 12240.0, 12720.0, 13200.0, 13680.0, 14160.0, &
+			14640.0, 15120.0, 15600.0, 16080.0, 16560.0, 17040.0, 17520.0, &
+			18000.0, 18480.0, 18960.0/)
+
+END MODULE MOD_COSP_CONFIG
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_errorHandling.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_errorHandling.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_errorHandling.F90	(revision 3605)
@@ -0,0 +1,50 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History:
+! May 2015- D. Swales - Original version
+! 
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+module mod_cosp_error
+  use cosp_kinds, ONLY: wp
+contains
+  ! ######################################################################################
+  ! Subroutine errorMessage_print
+  ! ######################################################################################
+  subroutine errorMessage(message)
+    ! Inputs
+    character(len=*),intent(in) :: message
+
+    print*,message
+  end subroutine errorMessage
+  
+  ! ######################################################################################
+  ! END MODULE
+  ! ######################################################################################
+end module mod_cosp_error
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_grLidar532_interface.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_grLidar532_interface.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_grLidar532_interface.F90	(revision 3605)
@@ -0,0 +1,62 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History
+! Apr 2018 - R. Guzman - Original version
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MODULE MOD_COSP_GRLIDAR532_INTERFACE
+  USE COSP_KINDS,              ONLY: wp
+  IMPLICIT NONE
+  
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! TYPE grLidar532_in
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+  type grLidar532_IN
+     integer,pointer ::       &
+          Npoints,      & ! Number of gridpoints.
+          Ncolumns,     & ! Number of columns.
+          Nlevels         ! Number of levels.
+     real(wp),dimension(:,:),pointer :: &
+          beta_mol,  &
+          tau_mol 
+     real(wp),dimension(:,:,:),pointer :: &
+          betatot,   & 
+          tautot  
+  end type grLidar532_IN
+contains
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! SUBROUTINE cosp_grLidar532_init
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  subroutine cosp_grLidar532_init() 
+        
+  end subroutine cosp_grLidar532_init
+  
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  !	END MODULE
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+END MODULE MOD_COSP_GRLIDAR532_INTERFACE
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_isccp_interface.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_isccp_interface.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_isccp_interface.F90	(revision 3605)
@@ -0,0 +1,85 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History
+! May 2015 - D. Swales - Original version
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MODULE MOD_COSP_ISCCP_INTERFACE
+  USE COSP_KINDS,      ONLY: wp
+  USE mod_icarus,      ONLY: isccp_top_height,isccp_top_height_direction
+  IMPLICIT NONE
+  
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  !                                  TYPE isccp_in
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! Derived input type for ISCCP simulator
+  type isccp_IN
+     integer,pointer  ::       &
+          Npoints,             & ! Number of gridpoints.
+          Ncolumns,            & ! Number of columns.
+          Nlevels,             & ! Number of levels.
+          top_height,          & !
+          top_height_direction   !
+     integer,pointer ::        &
+          sunlit(:)              ! Sunlit points (npoints)
+     real(wp),pointer ::       &
+          emsfc_lw
+     real(wp),pointer ::       &
+          skt(:)                 ! Surface temperature (npoints)
+     real(wp),pointer ::       &
+          at(:,:),             & ! Temperature (npoint,nlev)
+          pfull(:,:),          & ! Pressure (npoints,nlev)
+          qv(:,:)                ! Specific humidity (npoints,nlev)
+     real(wp),pointer  ::       &          
+          phalf(:,:)             ! Pressure at half levels (npoints,nlev+1)
+     real(wp),pointer ::       &
+          frac_out(:,:,:),     & ! Cloud fraction (npoints,ncolumns,nlevels)
+          dtau(:,:,:),         & ! Optical depth (npoints,ncolumns,nlevels)
+          dem(:,:,:)             ! Emissivity (npoints,ncolumns,nlevels)
+  end type isccp_IN
+
+CONTAINS
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  !  							SUBROUTINE cosp_isccp_init
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  SUBROUTINE COSP_ISCCP_INIT(top_height,top_height_direction)
+     integer,intent(in) :: &
+         top_height, &
+         top_height_direction
+
+    ! Cloud-top height determination
+    isccp_top_height           = top_height
+    isccp_top_height_direction = top_height_direction
+
+  END SUBROUTINE COSP_ISCCP_INIT
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  !                                    END MODULE
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+END MODULE MOD_COSP_ISCCP_INTERFACE
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_kinds.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_kinds.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_kinds.F90	(revision 3605)
@@ -0,0 +1,39 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History:
+! May 2015- D. Swales - Original version
+!
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MODULE cosp_kinds
+  implicit none
+  INTEGER, PARAMETER :: sp = SELECTED_REAL_KIND( 6, 37)
+  INTEGER, PARAMETER :: dp = SELECTED_REAL_KIND(12,307)
+  INTEGER, PARAMETER :: wp = dp
+
+END MODULE cosp_kinds
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_math_constants.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_math_constants.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_math_constants.F90	(revision 3605)
@@ -0,0 +1,6 @@
+MODULE cosp_math_constants
+  USE cosp_kinds, only: wp
+  IMPLICIT NONE
+  REAL(wp), PARAMETER :: pi =  acos(-1.0_wp)
+
+END MODULE cosp_math_constants
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_misr_interface.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_misr_interface.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_misr_interface.F90	(revision 3605)
@@ -0,0 +1,67 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History
+! May 2015 - D. Swales - Original version
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MODULE MOD_COSP_MISR_INTERFACE
+  USE COSP_KINDS,  ONLY: wp
+ 
+  IMPLICIT NONE
+
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! 								TYPE misr_in
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  type misr_IN
+     integer,pointer  ::  &
+          Npoints,        & ! Number of gridpoints.
+          Ncolumns,       & ! Number of columns.
+          Nlevels           ! Number of levels.
+     integer,pointer ::   &
+          sunlit(:)         ! Sunlit points (npoints).
+     real(wp),pointer ::  &
+          zfull(:,:),     & ! Height of full model levels (i.e. midpoints). (npoints,nlev)
+          at(:,:)           ! Temperature. (npoints,nlev)
+     real(wp),pointer ::  &                           
+          dtau(:,:,:)       ! Optical depth. (npoints,ncolumns,nlev)
+          
+  end type misr_IN
+
+CONTAINS
+
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  !  							SUBROUTINE cosp_misr_init
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  SUBROUTINE COSP_MISR_INIT()
+
+  END SUBROUTINE COSP_MISR_INIT
+
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! 							    	END MODULE
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+END MODULE MOD_COSP_MISR_INTERFACE
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_modis_interface.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_modis_interface.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_modis_interface.F90	(revision 3605)
@@ -0,0 +1,113 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History
+! May 2015 - D. Swales - Original version
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MODULE MOD_COSP_Modis_INTERFACE
+  USE COSP_KINDS,      ONLY: wp
+  USE MOD_COSP_CONFIG, ONLY: R_UNDEF
+  use mod_modis_sim,   ONLY: num_trial_res,min_OpticalThickness,CO2Slicing_PressureLimit,&
+                             CO2Slicing_TauLimit,phase_TauLimit,size_TauLimit,re_fill,   &
+                             phaseDiscrimination_Threshold,re_water_min,     &
+                             re_water_max,re_ice_min,re_ice_max,               &
+                             highCloudPressureLimit,lowCloudPressureLimit,phaseIsNone,   &
+                             phaseIsLiquid,phaseIsIce,phaseIsUndetermined,trial_re_w,    &
+                             trial_re_i,g_w,g_i,w0_w,w0_i, get_g_nir,get_ssa_nir
+  implicit none
+
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  !  TYPE modis_in
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+  type modis_IN
+     integer,pointer :: &
+          Npoints,        & ! Number of horizontal gridpoints
+          Ncolumns,       & ! Number of subcolumns
+          Nlevels           ! Number of vertical levels
+     integer :: &
+          Nsunlit           ! Number of sunlit lit pixels
+     real(wp),allocatable,dimension(:) :: &
+          sunlit,         & ! Sunlit scenes
+          notSunlit         ! Dark scenes
+     real(wp),allocatable,dimension(:,:) :: &
+          pres              ! Gridmean pressure at layer edges (Pa) 
+     real(wp),pointer ::  &
+          tau(:,:,:),     & ! Subcolumn optical thickness @ 0.67 microns.
+          liqFrac(:,:,:), & ! Liquid water fraction
+          g(:,:,:),       & ! Subcolumn assymetry parameter  
+          w0(:,:,:)         ! Subcolumn single-scattering albedo
+  end type modis_IN
+contains
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! SUBROTUINE cosp_modis_init
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  SUBROUTINE COSP_MODIS_INIT()
+    integer :: i 
+    
+    ! Retrieval parameters
+    min_OpticalThickness          = 0.3_wp     ! Minimum detectable optical thickness
+    CO2Slicing_PressureLimit      = 70000._wp  ! Cloud with higher pressures use thermal 
+                                               ! methods, units Pa
+    CO2Slicing_TauLimit           = 1._wp      ! How deep into the cloud does CO2 slicing 
+                                               ! see? 
+    phase_TauLimit                = 1._wp      ! How deep into the cloud does the phase 
+                                               ! detection see?
+    size_TauLimit                 = 2._wp      ! Depth of the re retreivals
+    phaseDiscrimination_Threshold = 0.7_wp     ! What fraction of total extincton needs to 
+                                               ! be in a single category to make phase 
+                                               ! discrim. work? 
+    re_fill                       = -999._wp   ! Fill value
+    re_water_min                  = 4._wp      ! Minimum effective radius (liquid)
+    re_water_max                  = 30._wp     ! Maximum effective radius (liquid)
+    re_ice_min                    = 5._wp      ! Minimum effective radius (ice)
+    re_ice_max                    = 90._wp     ! Minimum effective radius (ice)
+    highCloudPressureLimit        = 44000._wp  ! High cloud pressure limit (Pa)
+    lowCloudPressureLimit         = 68000._wp  ! Low cloud pressure limit (Pa)
+    phaseIsNone                   = 0          ! No cloud
+    phaseIsLiquid                 = 1          ! Liquid cloud
+    phaseIsIce                    = 2          ! Ice cloud
+    phaseIsUndetermined           = 3          ! Undetermined cloud
+
+    ! Precompute near-IR optical params vs size for retrieval scheme    
+    trial_re_w(1:num_trial_res) = re_water_min + (re_water_max - re_water_min) /         &
+         (num_trial_res-1) * (/(i, i=0, num_trial_res-1)/)
+    trial_re_i(1:num_trial_res) = re_ice_min   + (re_ice_max -   re_ice_min) /           &
+         (num_trial_res-1) * (/(i, i=0, num_trial_res-1)/)
+
+    ! Initialize estimates for size retrieval
+    g_w(1:num_trial_res)  = get_g_nir(phaseIsLiquid,trial_re_w(1:num_trial_res))
+    w0_w(1:num_trial_res) = get_ssa_nir(phaseIsLiquid,trial_re_w(1:num_trial_res))
+    g_i(1:num_trial_res)  = get_g_nir(phaseIsIce,trial_re_i(1:num_trial_res))
+    w0_i(1:num_trial_res) = get_ssa_nir(phaseIsIce,trial_re_i(1:num_trial_res))
+
+  END SUBROUTINE COSP_MODIS_INIT
+  
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! END MODULE MOD_COSP_Modis_INTERFACE
+  ! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+END MODULE MOD_COSP_Modis_INTERFACE
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_optics.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_optics.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_optics.F90	(revision 3605)
@@ -0,0 +1,492 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History:
+! 05/01/15  Dustin Swales - Original version
+! 04/04/18  Rodrigo Guzman- Added CALIOP-like Ground LIDar routines (GLID)
+! 10/04/18  Rodrigo Guzman- Added ATLID-like (EarthCare) lidar routines (ATLID)
+! 
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+module cosp_optics
+  USE COSP_KINDS, ONLY: wp,dp
+  USE COSP_MATH_CONSTANTS,  ONLY: pi
+  USE COSP_PHYS_CONSTANTS,  ONLY: rholiq,km,rd,grav
+  USE MOD_MODIS_SIM,        ONLY: get_g_nir,get_ssa_nir,phaseIsLiquid,phaseIsIce
+  implicit none
+  
+  real(wp),parameter ::        & !
+       ice_density   = 0.93_wp   ! Ice density used in MODIS phase partitioning
+
+  interface cosp_simulator_optics
+     module procedure cosp_simulator_optics2D, cosp_simulator_optics3D
+  end interface cosp_simulator_optics
+  
+contains
+  ! ##########################################################################
+  !                          COSP_SIMULATOR_OPTICS
+  !
+  ! Used by: ISCCP, MISR and MODIS simulators
+  ! ##########################################################################
+  subroutine cosp_simulator_optics2D(dim1,dim2,dim3,flag,varIN1,varIN2,varOUT)
+    ! INPUTS
+    integer,intent(in) :: &
+         dim1,   & ! Dimension 1 extent (Horizontal)
+         dim2,   & ! Dimension 2 extent (Subcolumn)
+         dim3      ! Dimension 3 extent (Vertical)
+    real(wp),intent(in),dimension(dim1,dim2,dim3) :: &
+         flag      ! Logical to determine the of merge var1IN and var2IN
+    real(wp),intent(in),dimension(dim1,     dim3) :: &
+         varIN1, & ! Input field 1
+         varIN2    ! Input field 2
+    ! OUTPUTS
+    real(wp),intent(out),dimension(dim1,dim2,dim3) :: &
+         varOUT    ! Merged output field
+    ! LOCAL VARIABLES
+    integer :: j
+    
+    varOUT(1:dim1,1:dim2,1:dim3) = 0._wp
+    do j=1,dim2
+       where(flag(:,j,:) .eq. 1)
+          varOUT(:,j,:) = varIN2
+       endwhere
+       where(flag(:,j,:) .eq. 2)
+          varOUT(:,j,:) = varIN1
+       endwhere
+    enddo
+  end subroutine cosp_simulator_optics2D
+  subroutine cosp_simulator_optics3D(dim1,dim2,dim3,flag,varIN1,varIN2,varOUT)
+    ! INPUTS
+    integer,intent(in) :: &
+         dim1,   & ! Dimension 1 extent (Horizontal)
+         dim2,   & ! Dimension 2 extent (Subcolumn)
+         dim3      ! Dimension 3 extent (Vertical)
+    real(wp),intent(in),dimension(dim1,dim2,dim3) :: &
+         flag      ! Logical to determine the of merge var1IN and var2IN
+    real(wp),intent(in),dimension(dim1,dim2,dim3) :: &
+         varIN1, & ! Input field 1
+         varIN2    ! Input field 2
+    ! OUTPUTS
+    real(wp),intent(out),dimension(dim1,dim2,dim3) :: &
+         varOUT    ! Merged output field
+    
+    varOUT(1:dim1,1:dim2,1:dim3) = 0._wp
+   where(flag(:,:,:) .eq. 1)
+       varOUT(:,:,:) = varIN2
+    endwhere
+    where(flag(:,:,:) .eq. 2)
+       varOUT(:,:,:) = varIN1
+    endwhere
+    
+  end subroutine cosp_simulator_optics3D
+  
+  ! ##############################################################################
+  !                           MODIS_OPTICS_PARTITION
+  !
+  ! For the MODIS simulator, there are times when only a sinlge optical depth
+  ! profile, cloud-ice and cloud-water are provided. In this case, the optical
+  ! depth is partitioned by phase.
+  ! ##############################################################################
+  subroutine MODIS_OPTICS_PARTITION(npoints,nlev,ncolumns,cloudWater,cloudIce,waterSize, &
+                                    iceSize,tau,tauL,tauI)
+    ! INPUTS
+    INTEGER,intent(in) :: &
+         npoints,   & ! Number of horizontal gridpoints
+         nlev,      & ! Number of levels
+         ncolumns     ! Number of subcolumns
+    REAL(wp),intent(in),dimension(npoints,nlev,ncolumns) :: &
+         cloudWater, & ! Subcolumn cloud water content
+         cloudIce,   & ! Subcolumn cloud ice content
+         waterSize,  & ! Subcolumn cloud water effective radius
+         iceSize,    & ! Subcolumn cloud ice effective radius
+         tau           ! Optical thickness
+    
+    ! OUTPUTS
+    real(wp),intent(out),dimension(npoints,nlev,ncolumns) :: &
+         tauL,       & ! Partitioned liquid optical thickness.
+         tauI          ! Partitioned ice optical thickness.
+    ! LOCAL VARIABLES
+    real(wp),dimension(nlev,ncolumns) :: fracL
+    integer                           :: i
+    
+    
+    do i=1,npoints
+       where(cloudIce(i,:, :) <= 0.) 
+          fracL(:, :) = 1._wp
+       elsewhere
+          where (cloudWater(i,:, :) <= 0.) 
+             fracL(:, :) = 0._wp
+          elsewhere 
+             ! Geometic optics limit - tau as LWP/re  (proportional to LWC/re) 
+             fracL(:, :) = (cloudWater(i,:, :)/waterSize(i,:, :)) / &
+                  (cloudWater(i,:, :)/waterSize(i,:, :) + cloudIce(i,:, :)/(ice_density * iceSize(i,:, :)) ) 
+          end where
+       end where
+       tauL(i,:, :) = fracL(:, :) * tau(i,:, :) 
+       tauI(i,:, :) = tau(i,:, :) - tauL(i,:, :)
+    enddo
+    
+  end subroutine MODIS_OPTICS_PARTITION
+  ! ########################################################################################
+  !                                   MODIS_OPTICS
+  ! 
+  ! ########################################################################################
+  subroutine modis_optics(nPoints,nLevels,nSubCols,tauLIQ,sizeLIQ,tauICE,sizeICE,fracLIQ, g, w0)
+    ! INPUTS
+    integer, intent(in)                                      :: nPoints,nLevels,nSubCols
+    real(wp),intent(in),dimension(nPoints,nSubCols,nLevels)  :: tauLIQ, sizeLIQ, tauICE, sizeICE
+    ! OUTPUTS
+    real(wp),intent(out),dimension(nPoints,nSubCols,nLevels) :: g,w0,fracLIQ
+    ! LOCAL VARIABLES
+    real(wp), dimension(nLevels)            :: water_g, water_w0, ice_g, ice_w0,tau
+    integer :: i,j
+    
+    ! Initialize
+    g(1:nPoints,1:nSubCols,1:nLevels)  = 0._wp
+    w0(1:nPoints,1:nSubCols,1:nLevels) = 0._wp
+    
+    do j =1,nPoints
+       do i=1,nSubCols
+          water_g(1:nLevels)  = get_g_nir(  phaseIsLiquid, sizeLIQ(j,i,1:nLevels)) 
+          water_w0(1:nLevels) = get_ssa_nir(phaseIsLiquid, sizeLIQ(j,i,1:nLevels))
+          ice_g(1:nLevels)    = get_g_nir(  phaseIsIce,    sizeICE(j,i,1:nLevels))
+          ice_w0(1:nLevels)   = get_ssa_nir(phaseIsIce,    sizeICE(j,i,1:nLevels))
+          
+          ! Combine ice and water optical properties
+          tau(1:nLevels) = tauICE(j,i,1:nLevels) + tauLIQ(j,i,1:nLevels) 
+          where (tau(1:nLevels) > 0) 
+             w0(j,i,1:nLevels) = (tauLIQ(j,i,1:nLevels)*water_w0(1:nLevels) + tauICE(j,i,1:nLevels) *ice_w0(1:nLevels)) / &
+                                  (tau(1:nLevels))
+             g(j,i,1:nLevels) = (tauLIQ(j,i,1:nLevels)*water_g(1:nLevels)*water_w0(1:nLevels) + tauICE(j,i,1:nLevels) * &
+                  ice_g(1:nLevels) * ice_w0(1:nLevels)) / (w0(j,i,1:nLevels) * tau(1:nLevels))
+          end where
+       enddo
+    enddo
+    
+    ! Compute the total optical thickness and the proportion due to liquid in each cell
+    do i=1,npoints
+       where(tauLIQ(i,1:nSubCols,1:nLevels) + tauICE(i,1:nSubCols,1:nLevels) > 0.) 
+          fracLIQ(i,1:nSubCols,1:nLevels) = tauLIQ(i,1:nSubCols,1:nLevels)/ &
+               (tauLIQ(i,1:nSubCols,1:nLevels) + tauICE(i,1:nSubCols,1:nLevels))
+       elsewhere
+          fracLIQ(i,1:nSubCols,1:nLevels) = 0._wp
+       end  where
+    enddo
+    
+  end subroutine modis_optics
+  
+  ! ######################################################################################
+  ! SUBROUTINE lidar_optics
+  ! ######################################################################################
+  subroutine lidar_optics(npoints, ncolumns, nlev, npart, ice_type, lidar_freq, lground, &
+       q_lsliq, q_lsice, q_cvliq, q_cvice, ls_radliq, ls_radice, cv_radliq, cv_radice,   &
+       pres, presf, temp, beta_mol, betatot, tau_mol, tautot, tautot_S_liq, tautot_S_ice,&
+       betatot_ice, betatot_liq, tautot_ice, tautot_liq)
+
+    ! ####################################################################################
+    ! NOTE: Using "grav" from cosp_constants.f90, instead of grav=9.81, introduces
+    ! changes of up to 2% in atb532 adn 0.003% in parasolRefl and lidarBetaMol532. 
+    ! This also results in  small changes in the joint-histogram, cfadLidarsr532.
+    ! ####################################################################################
+    
+    ! INPUTS
+    INTEGER,intent(in) :: & 
+         npoints,      & ! Number of gridpoints
+         ncolumns,     & ! Number of subcolumns
+         nlev,         & ! Number of levels
+         npart,        & ! Number of cloud meteors (stratiform_liq, stratiform_ice, conv_liq, conv_ice). 
+         ice_type,     & ! Ice particle shape hypothesis (0 for spheres, 1 for non-spherical)
+         lidar_freq      ! Lidar frequency (nm). Use to change between lidar platforms
+    logical,intent(in) :: &
+         lground         ! True for ground-based lidar
+    REAL(WP),intent(in),dimension(npoints,nlev) :: &
+         temp,         & ! Temperature of layer k
+         pres,         & ! Pressure at full levels
+         ls_radliq,    & ! Effective radius of LS liquid particles (meters)
+         ls_radice,    & ! Effective radius of LS ice particles (meters)
+         cv_radliq,    & ! Effective radius of CONV liquid particles (meters)
+         cv_radice       ! Effective radius of CONV ice particles (meters)
+    REAL(WP),intent(in),dimension(npoints,ncolumns,nlev) :: &
+         q_lsliq,      & ! LS sub-column liquid water mixing ratio (kg/kg)
+         q_lsice,      & ! LS sub-column ice water mixing ratio (kg/kg)
+         q_cvliq,      & ! CONV sub-column liquid water mixing ratio (kg/kg)
+         q_cvice         ! CONV sub-column ice water mixing ratio (kg/kg)
+    REAL(WP),intent(in),dimension(npoints,nlev+1) :: &
+         presf           ! Pressure at half levels
+    
+    ! OUTPUTS
+    REAL(WP),intent(out),dimension(npoints,ncolumns,nlev)       :: &
+         betatot,        & ! 
+         tautot            ! Optical thickess integrated from top
+    REAL(WP),intent(out),dimension(npoints,nlev) :: &
+         beta_mol,       & ! Molecular backscatter coefficient
+         tau_mol           ! Molecular optical depth
+    ! OUTPUTS (optional)
+    REAL(WP),optional,intent(out),dimension(npoints,ncolumns) :: &
+         tautot_S_liq,   & ! TOA optical depth for liquid
+         tautot_S_ice      ! TOA optical depth for ice
+    REAL(WP),optional,intent(out),dimension(npoints,ncolumns,nlev)       :: &
+         betatot_ice,    & ! Backscatter coefficient for ice particles
+         betatot_liq,    & ! Backscatter coefficient for liquid particles
+         tautot_ice,     & ! Total optical thickness of ice
+         tautot_liq        ! Total optical thickness of liq
+    
+    ! LOCAL VARIABLES
+    REAL(WP),dimension(npart)              :: rhopart
+    REAL(WP),dimension(npart,5)            :: polpart 
+    REAL(WP),dimension(npoints,nlev)       :: rhoair,alpha_mol
+    REAL(WP),dimension(npoints,nlev+1)     :: zheight          
+    REAL(WP),dimension(npoints,nlev,npart) :: rad_part,kp_part,qpart,alpha_part,tau_part
+    real(wp)                               :: Cmol,rdiffm
+    logical                                :: lparasol,lphaseoptics
+    INTEGER                                :: i,k,icol,zi,zf,zinc,zoffset
+    
+    ! Local data
+    REAL(WP),PARAMETER :: rhoice     = 0.5e+03    ! Density of ice (kg/m3) 
+    REAL(WP),PARAMETER :: Cmol_532nm = 6.2446e-32 ! Wavelength dependent
+    REAL(WP),PARAMETER :: Cmol_355nm = 3.2662e-31! Wavelength dependent
+    REAL(WP),PARAMETER :: rdiffm_532nm = 0.7_wp     ! Multiple scattering correction parameter
+    REAL(WP),PARAMETER :: rdiffm_355nm = 0.6_wp     ! Multiple scattering correction parameter
+    REAL(WP),PARAMETER :: Qscat      = 2.0_wp     ! Particle scattering efficiency at 532 nm
+    ! Local indicies for large-scale and convective ice and liquid 
+    INTEGER,PARAMETER  :: INDX_LSLIQ  = 1
+    INTEGER,PARAMETER  :: INDX_LSICE  = 2
+    INTEGER,PARAMETER  :: INDX_CVLIQ  = 3
+    INTEGER,PARAMETER  :: INDX_CVICE  = 4
+    
+    ! Polarized optics parameterization
+    ! Polynomial coefficients for spherical liq/ice particles derived from Mie theory.
+    ! Polynomial coefficients for non spherical particles derived from a composite of
+    ! Ray-tracing theory for large particles (e.g. Noel et al., Appl. Opt., 2001)
+    ! and FDTD theory for very small particles (Yang et al., JQSRT, 2003).
+    ! We repeat the same coefficients for LS and CONV cloud to make code more readable
+    REAL(WP),PARAMETER,dimension(5) :: &
+         polpartCVLIQ  = (/ 2.6980e-8_wp,  -3.7701e-6_wp,  1.6594e-4_wp,    -0.0024_wp,    0.0626_wp/), &
+         polpartLSLIQ  = (/ 2.6980e-8_wp,  -3.7701e-6_wp,  1.6594e-4_wp,    -0.0024_wp,    0.0626_wp/), &
+         polpartCVICE0 = (/-1.0176e-8_wp,   1.7615e-6_wp, -1.0480e-4_wp,     0.0019_wp,    0.0460_wp/), &
+         polpartLSICE0 = (/-1.0176e-8_wp,   1.7615e-6_wp, -1.0480e-4_wp,     0.0019_wp,    0.0460_wp/), &
+         polpartCVICE1 = (/ 1.3615e-8_wp, -2.04206e-6_wp, 7.51799e-5_wp, 0.00078213_wp, 0.0182131_wp/), &
+         polpartLSICE1 = (/ 1.3615e-8_wp, -2.04206e-6_wp, 7.51799e-5_wp, 0.00078213_wp, 0.0182131_wp/)
+    ! ##############################################################################
+
+    ! Which LIDAR frequency are we using?
+    if (lidar_freq .eq. 355) then
+       Cmol   = Cmol_355nm
+       rdiffm = rdiffm_355nm
+    endif
+    if (lidar_freq .eq. 532) then
+       Cmol   = Cmol_532nm
+       rdiffm = rdiffm_532nm
+    endif
+    
+    ! Do we need to generate optical inputs for Parasol simulator?
+    lparasol = .false.
+    if (present(tautot_S_liq) .and. present(tautot_S_ice)) lparasol = .true.
+    
+    ! Are optical-depths and backscatter coefficients for ice and liquid requested?
+    lphaseoptics=.false.
+    if (present(betatot_ice) .and. present(betatot_liq) .and. present(tautot_liq) .and. &
+         present(tautot_ice)) lphaseoptics=.true.
+
+    ! Is this lidar spaceborne (default) or ground-based (lground=.true.)?
+    zi   = 2
+    zf   = nlev
+    zinc = 1
+    zoffset = -1
+    if (lground) then
+       zi   = nlev-1
+       zf   = 1
+       zinc = -1
+       zoffset = 1
+    endif
+    
+    ! Liquid/ice particles
+    rhopart(INDX_LSLIQ)  = rholiq
+    rhopart(INDX_LSICE)  = rhoice
+    rhopart(INDX_CVLIQ)  = rholiq
+    rhopart(INDX_CVICE)  = rhoice
+    
+    ! LS and CONV Liquid water coefficients
+    polpart(INDX_LSLIQ,1:5)  = polpartLSLIQ
+    polpart(INDX_CVLIQ,1:5)  = polpartCVLIQ
+    
+    ! LS and CONV Ice water coefficients
+    if (ice_type .eq. 0) then
+       polpart(INDX_LSICE,1:5) = polpartLSICE0
+       polpart(INDX_CVICE,1:5) = polpartCVICE0
+    endif
+    if (ice_type .eq. 1) then
+       polpart(INDX_LSICE,1:5) = polpartLSICE1
+       polpart(INDX_CVICE,1:5) = polpartCVICE1
+    endif
+    
+    ! Effective radius particles:
+    rad_part(1:npoints,1:nlev,INDX_LSLIQ)  = ls_radliq(1:npoints,1:nlev)
+    rad_part(1:npoints,1:nlev,INDX_LSICE)  = ls_radice(1:npoints,1:nlev)
+    rad_part(1:npoints,1:nlev,INDX_CVLIQ)  = cv_radliq(1:npoints,1:nlev)
+    rad_part(1:npoints,1:nlev,INDX_CVICE)  = cv_radice(1:npoints,1:nlev)    
+    rad_part(1:npoints,1:nlev,1:npart)     = MAX(rad_part(1:npoints,1:nlev,1:npart),0._wp)
+    rad_part(1:npoints,1:nlev,1:npart)     = MIN(rad_part(1:npoints,1:nlev,1:npart),70.0e-6_wp)
+    
+    ! Density (clear-sky air)
+    rhoair(1:npoints,1:nlev) = pres(1:npoints,1:nlev)/(rd*temp(1:npoints,1:nlev))
+    
+    ! Altitude at half pressure levels:
+    zheight(1:npoints,nlev+1) = 0._wp
+    do k=nlev,1,-1
+       zheight(1:npoints,k) = zheight(1:npoints,k+1) &
+            -(presf(1:npoints,k)-presf(1:npoints,k+1))/(rhoair(1:npoints,k)*grav)
+    enddo
+    
+    ! ##############################################################################
+    ! *) Molecular alpha, beta and optical thickness
+    ! ##############################################################################
+    
+    beta_mol(1:npoints,1:nlev)  = pres(1:npoints,1:nlev)/km/temp(1:npoints,1:nlev)*Cmol
+    alpha_mol(1:npoints,1:nlev) = 8._wp*pi/3._wp * beta_mol(1:npoints,1:nlev)
+    
+    ! Optical thickness of each layer (molecular)  
+    tau_mol(1:npoints,1:nlev) = alpha_mol(1:npoints,1:nlev)*(zheight(1:npoints,1:nlev)-&
+         zheight(1:npoints,2:nlev+1))
+             
+    ! Optical thickness from TOA to layer k (molecular)
+    DO k = zi,zf,zinc
+       tau_mol(1:npoints,k) = tau_mol(1:npoints,k) + tau_mol(1:npoints,k+zoffset)
+    ENDDO    
+
+    betatot    (1:npoints,1:ncolumns,1:nlev) = spread(beta_mol(1:npoints,1:nlev), dim=2, NCOPIES=ncolumns)
+    tautot     (1:npoints,1:ncolumns,1:nlev) = spread(tau_mol (1:npoints,1:nlev), dim=2, NCOPIES=ncolumns)
+    if (lphaseoptics) then
+       betatot_liq(1:npoints,1:ncolumns,1:nlev) = betatot(1:npoints,1:ncolumns,1:nlev)
+       betatot_ice(1:npoints,1:ncolumns,1:nlev) = betatot(1:npoints,1:ncolumns,1:nlev)
+       tautot_liq (1:npoints,1:ncolumns,1:nlev) = tautot(1:npoints,1:ncolumns,1:nlev)
+       tautot_ice (1:npoints,1:ncolumns,1:nlev) = tautot(1:npoints,1:ncolumns,1:nlev)      
+    endif
+
+    ! ##############################################################################
+    ! *) Particles alpha, beta and optical thickness
+    ! ##############################################################################
+    ! Polynomials kp_lidar derived from Mie theory
+    do i = 1, npart
+       where (rad_part(1:npoints,1:nlev,i) .gt. 0.0)
+          kp_part(1:npoints,1:nlev,i) = &
+               polpart(i,1)*(rad_part(1:npoints,1:nlev,i)*1e6)**4 &
+               + polpart(i,2)*(rad_part(1:npoints,1:nlev,i)*1e6)**3 &
+               + polpart(i,3)*(rad_part(1:npoints,1:nlev,i)*1e6)**2 &
+               + polpart(i,4)*(rad_part(1:npoints,1:nlev,i)*1e6) &
+               + polpart(i,5)
+       elsewhere
+          kp_part(1:npoints,1:nlev,i) = 0._wp
+       endwhere
+    enddo    
+
+    ! Initialize (if necessary)
+    if (lparasol) then
+       tautot_S_liq(1:npoints,1:ncolumns) = 0._wp
+       tautot_S_ice(1:npoints,1:ncolumns) = 0._wp
+    endif
+
+    ! Loop over all subcolumns
+    do icol=1,ncolumns
+       ! ##############################################################################
+       ! Mixing ratio particles in each subcolum
+       ! ##############################################################################
+       qpart(1:npoints,1:nlev,INDX_LSLIQ) =  q_lsliq(1:npoints,icol,1:nlev)
+       qpart(1:npoints,1:nlev,INDX_LSICE)  = q_lsice(1:npoints,icol,1:nlev)
+       qpart(1:npoints,1:nlev,INDX_CVLIQ)  = q_cvliq(1:npoints,icol,1:nlev)
+       qpart(1:npoints,1:nlev,INDX_CVICE)  = q_cvice(1:npoints,icol,1:nlev)
+
+       ! ##############################################################################
+       ! Alpha and optical thickness (particles)
+       ! ##############################################################################
+       ! Alpha of particles in each subcolumn:
+       do i = 1, npart
+          where (rad_part(1:npoints,1:nlev,i) .gt. 0.0)
+             alpha_part(1:npoints,1:nlev,i) = 3._wp/4._wp * Qscat &
+                  * rhoair(1:npoints,1:nlev) * qpart(1:npoints,1:nlev,i) &
+                  / (rhopart(i) * rad_part(1:npoints,1:nlev,i) )
+          elsewhere
+             alpha_part(1:npoints,1:nlev,i) = 0._wp
+          endwhere
+       enddo
+       
+       ! Optical thicknes
+       tau_part(1:npoints,1:nlev,1:npart) = rdiffm * alpha_part(1:npoints,1:nlev,1:npart)
+       do i = 1, npart
+          ! Optical thickness of each layer (particles)
+          tau_part(1:npoints,1:nlev,i) = tau_part(1:npoints,1:nlev,i) &
+               & * (zheight(1:npoints,1:nlev)-zheight(1:npoints,2:nlev+1) )
+          ! Optical thickness from TOA to layer k (particles)
+          do k=zi,zf,zinc
+             tau_part(1:npoints,k,i) = tau_part(1:npoints,k,i) + tau_part(1:npoints,k+zoffset,i)
+          enddo
+       enddo
+ 
+       ! ##############################################################################
+       ! Beta and optical thickness (total=molecular + particules)
+       ! ##############################################################################
+       
+       DO i = 1, npart
+          betatot(1:npoints,icol,1:nlev) = betatot(1:npoints,icol,1:nlev) + &
+               kp_part(1:npoints,1:nlev,i)*alpha_part(1:npoints,1:nlev,i)
+          tautot(1:npoints,icol,1:nlev) = tautot(1:npoints,icol,1:nlev)  + &
+              tau_part(1:npoints,1:nlev,i)
+       ENDDO
+       
+       ! ##############################################################################
+       ! Beta and optical thickness (liquid/ice)
+       ! ##############################################################################
+       if (lphaseoptics) then
+          ! Ice
+          betatot_ice(1:npoints,icol,1:nlev) = betatot_ice(1:npoints,icol,1:nlev)+ &
+               kp_part(1:npoints,1:nlev,INDX_LSICE)*alpha_part(1:npoints,1:nlev,INDX_LSICE)+ &
+               kp_part(1:npoints,1:nlev,INDX_CVICE)*alpha_part(1:npoints,1:nlev,INDX_CVICE)
+          tautot_ice(1:npoints,icol,1:nlev) = tautot_ice(1:npoints,icol,1:nlev)  + &
+               tau_part(1:npoints,1:nlev,INDX_LSICE) + &
+               tau_part(1:npoints,1:nlev,INDX_CVICE)
+          
+          ! Liquid
+          betatot_liq(1:npoints,icol,1:nlev) = betatot_liq(1:npoints,icol,1:nlev)+ &
+               kp_part(1:npoints,1:nlev,INDX_LSLIQ)*alpha_part(1:npoints,1:nlev,INDX_LSLIQ)+ &
+               kp_part(1:npoints,1:nlev,INDX_CVLIQ)*alpha_part(1:npoints,1:nlev,INDX_CVLIQ)
+          tautot_liq(1:npoints,icol,1:nlev) = tautot_liq(1:npoints,icol,1:nlev)  + &
+               tau_part(1:npoints,1:nlev,INDX_LSLIQ) + &
+               tau_part(1:npoints,1:nlev,INDX_CVLIQ)
+       endif
+
+       ! ##############################################################################    
+       ! Optical depths used by the PARASOL simulator
+       ! ##############################################################################             
+       if (lparasol) then
+          tautot_S_liq(:,icol) = tau_part(:,nlev,1)+tau_part(:,nlev,3)
+          tautot_S_ice(:,icol) = tau_part(:,nlev,2)+tau_part(:,nlev,4)              
+       endif
+    enddo
+    
+  end subroutine lidar_optics
+
+end module cosp_optics
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_parasol_interface.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_parasol_interface.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_parasol_interface.F90	(revision 3605)
@@ -0,0 +1,90 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History
+! May 2015 - D. Swales - Original version
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MODULE MOD_COSP_PARASOL_INTERFACE
+  USE COSP_KINDS,  ONLY: WP
+  implicit none
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  !									TYPE cosp_parasol
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  TYPE PARASOL_SGX
+     ! Dimensions
+     integer :: &
+          Npoints,  & ! Number of gridpoints
+          Ncolumns, & ! Number of columns
+          Nrefl       ! Number of parasol reflectances
+     
+     ! Arrays with dimensions (Npoints,Ncolumns,Nrefl)
+     real(wp),dimension(:,:,:),pointer :: &
+          refl        ! parasol reflectances
+
+  END TYPE PARASOL_SGX
+  TYPE PARASOL_GBX
+     integer :: &
+          Npoints,  & ! Number of gridpoints
+          Ncolumns, & ! Number of columns
+          Nrefl       ! Number of parasol reflectances
+     real(wp), dimension(:,:),pointer :: &
+          parasolrefl ! Mean parasol reflectance
+
+  END TYPE PARASOL_GBX
+  TYPE COSP_PARASOL 
+     type(PARASOL_SGX) :: PARASOL_SGX
+     type(PARASOL_GBX) :: PARASOL_GBX
+  END TYPE COSP_PARASOL
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  !										TYPE parasol_in
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  TYPE parasol_IN
+     integer,pointer :: &
+        Npoints,       & ! Number of horizontal gridpoints
+        Nlevels,       & ! Number of vertical levels
+        Ncolumns,      & ! Number of columns
+        Nrefl            ! Number of angles for which the reflectance is computed
+     real(wp),dimension(:,:),pointer ::   &
+        tautot_S_liq,  & ! Liquid water optical thickness, from TOA to SFC
+        tautot_S_ice     ! Ice water optical thickness, from TOA to SFC
+  END TYPE parasol_IN
+  
+contains
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  !                           SUBROUTINE cosp_parasol_init
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  SUBROUTINE COSP_PARASOL_INIT()
+    
+  end subroutine COSP_PARASOL_INIT
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! 								    END MODULE
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+end module MOD_COSP_PARASOL_INTERFACE
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_phys_constants.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_phys_constants.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_phys_constants.F90	(revision 3605)
@@ -0,0 +1,65 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History:
+! May 2015- D. Swales - Original version
+!
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MODULE cosp_phys_constants
+  USE cosp_kinds, only: wp
+  IMPLICIT NONE
+
+  REAL(wp), PARAMETER :: &
+       tmelt  = 273.15_wp,      & ! Melting temperature of ice/snow [K]
+       rhoice = 917._wp,        & ! Density of ice [kg/m3]
+       rholiq = 1000._wp          ! Density of liquid water [kg/m3]
+
+  ! Molecular weights
+  REAL(wp), PARAMETER :: &
+       amw   = 18.01534_wp,     & ! Water   [g/mol]
+       amd   = 28.9644_wp,      & ! Dry air [g/mol]
+       amO3  = 47.9983_wp,      & ! Ozone   [g/mol]
+       amCO2 = 44.0096_wp,      & ! CO2     [g/mol]
+       amCH4 = 16.0426_wp,      & ! Methane [g/mol]
+       amN2O = 44.0129_wp,      & ! N2O     [g/mol]
+       amCO  = 28.0102_wp         ! CO      [g/mol]
+
+  ! WMO/SI value
+  REAL(wp), PARAMETER :: &
+       avo   = 6.023E23_wp,     & ! Avogadro constant used by ISCCP simulator [1/mol]
+       grav  = 9.806650_wp        ! Av. gravitational acceleration used by ISCCP simulator [m/s2]
+
+  ! Thermodynamic constants for the dry and moist atmosphere
+  REAL(wp), PARAMETER :: &
+       rd  = 287.04_wp,         & ! Gas constant for dry air [J/K/Kg]
+       cpd = 1004.64_wp,        & ! Specific heat at constant pressure for dry air [J/K/Kg]
+       rv  = 461.51_wp,         & ! Gas constant for water vapor [J/K/Kg]
+       cpv = 1869.46_wp,        & ! Specific heat at constant pressure for water vapor [J/K/Kg]
+       km  = 1.38e-23_wp          ! Boltzmann constant [J/K]
+
+END MODULE cosp_phys_constants
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_stats.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_stats.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_stats.F90	(revision 3605)
@@ -0,0 +1,307 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History:
+! Jul 2007 - A. Bodas-Salcedo - Initial version
+! Jul 2008 - A. Bodas-Salcedo - Added capability of producing outputs in standard grid
+! Oct 2008 - J.-L. Dufresne   - Bug fixed. Assignment of Npoints,Nlevels,Nhydro,Ncolumns 
+!                               in COSP_STATS
+! Oct 2008 - H. Chepfer       - Added PARASOL reflectance arguments
+! Jun 2010 - T. Yokohata, T. Nishimura and K. Ogochi - Added NEC SXs optimisations
+! Jan 2013 - G. Cesana        - Added betaperp and temperature arguments 
+!                             - Added phase 3D/3Dtemperature/Map output variables in diag_lidar 
+! May 2015 - D. Swales        - Modified for cosp2.0 
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MODULE MOD_COSP_STATS
+  USE COSP_KINDS, ONLY: wp
+  USE MOD_COSP_CONFIG, ONLY: R_UNDEF,R_GROUND
+
+  IMPLICIT NONE
+CONTAINS
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  !---------- SUBROUTINE COSP_CHANGE_VERTICAL_GRID ----------------
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SUBROUTINE COSP_CHANGE_VERTICAL_GRID(Npoints,Ncolumns,Nlevels,zfull,zhalf,y,Nglevels,newgrid_bot,newgrid_top,r,log_units)
+   implicit none
+   ! Input arguments
+   integer,intent(in) :: Npoints  !# of grid points
+   integer,intent(in) :: Nlevels  !# of levels
+   integer,intent(in) :: Ncolumns !# of columns
+   real(wp),dimension(Npoints,Nlevels),intent(in) :: zfull ! Height at model levels [m] (Bottom of model layer)
+   real(wp),dimension(Npoints,Nlevels),intent(in) :: zhalf ! Height at half model levels [m] (Bottom of model layer)
+   real(wp),dimension(Npoints,Ncolumns,Nlevels),intent(in) :: y     ! Variable to be changed to a different grid
+   integer,intent(in) :: Nglevels  !# levels in the new grid
+   real(wp),dimension(Nglevels),intent(in) :: newgrid_bot ! Lower boundary of new levels  [m]
+   real(wp),dimension(Nglevels),intent(in) :: newgrid_top ! Upper boundary of new levels  [m]
+   logical,optional,intent(in) :: log_units ! log units, need to convert to linear units
+   ! Output
+   real(wp),dimension(Npoints,Ncolumns,Nglevels),intent(out) :: r ! Variable on new grid
+
+   ! Local variables
+   integer :: i,j,k
+   logical :: lunits
+   integer :: l
+   real(wp) :: w ! Weight
+   real(wp) :: dbb, dtb, dbt, dtt ! Distances between edges of both grids
+   integer :: Nw  ! Number of weights
+   real(wp) :: wt  ! Sum of weights
+   real(wp),dimension(Nlevels) :: oldgrid_bot,oldgrid_top ! Lower and upper boundaries of model grid
+   real(wp) :: yp ! Local copy of y at a particular point.
+              ! This allows for change of units.
+
+   lunits=.false.
+   if (present(log_units)) lunits=log_units
+
+   r = 0._wp
+
+   do i=1,Npoints
+     ! Calculate tops and bottoms of new and old grids
+     oldgrid_bot = zhalf(i,:)
+     oldgrid_top(1:Nlevels-1) = oldgrid_bot(2:Nlevels)
+     oldgrid_top(Nlevels) = zfull(i,Nlevels) +  zfull(i,Nlevels) - zhalf(i,Nlevels) ! Top level symmetric
+     l = 0 ! Index of level in the old grid
+     ! Loop over levels in the new grid
+     do k = 1,Nglevels
+       Nw = 0 ! Number of weigths
+       wt = 0._wp ! Sum of weights
+       ! Loop over levels in the old grid and accumulate total for weighted average
+       do
+         l = l + 1
+         w = 0.0 ! Initialise weight to 0
+         ! Distances between edges of both grids
+         dbb = oldgrid_bot(l) - newgrid_bot(k)
+         dtb = oldgrid_top(l) - newgrid_bot(k)
+         dbt = oldgrid_bot(l) - newgrid_top(k)
+         dtt = oldgrid_top(l) - newgrid_top(k)
+         if (dbt >= 0.0) exit ! Do next level in the new grid
+         if (dtb > 0.0) then
+           if (dbb <= 0.0) then
+             if (dtt <= 0) then
+               w = dtb
+             else
+               w = newgrid_top(k) - newgrid_bot(k)
+             endif
+           else
+             if (dtt <= 0) then
+               w = oldgrid_top(l) - oldgrid_bot(l)
+             else
+               w = -dbt
+             endif
+           endif
+           ! If layers overlap (w/=0), then accumulate
+           if (w /= 0.0) then
+             Nw = Nw + 1
+             wt = wt + w
+             do j=1,Ncolumns
+               if (lunits) then
+                 if (y(i,j,l) /= R_UNDEF) then
+                   yp = 10._wp**(y(i,j,l)/10._wp)
+                 else
+                   yp = 0._wp
+                 endif
+               else
+                 yp = y(i,j,l)
+               endif
+               r(i,j,k) = r(i,j,k) + w*yp
+             enddo
+           endif
+         endif
+       enddo
+       l = l - 2
+       if (l < 1) l = 0
+       ! Calculate average in new grid
+       if (Nw > 0) then
+         do j=1,Ncolumns
+           r(i,j,k) = r(i,j,k)/wt
+         enddo
+       endif
+     enddo
+   enddo
+
+   ! Set points under surface to R_UNDEF, and change to dBZ if necessary
+   do k=1,Nglevels
+     do j=1,Ncolumns
+       do i=1,Npoints
+         if (newgrid_top(k) > zhalf(i,1)) then ! Level above model bottom level
+           if (lunits) then
+             if (r(i,j,k) <= 0.0) then
+               r(i,j,k) = R_UNDEF
+             else
+               r(i,j,k) = 10._wp*log10(r(i,j,k))
+             endif
+           endif
+         else ! Level below surface
+           r(i,j,k) = R_GROUND
+         endif
+       enddo
+     enddo
+   enddo
+
+END SUBROUTINE COSP_CHANGE_VERTICAL_GRID
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  !------------- SUBROUTINE COSP_LIDAR_ONLY_CLOUD -----------------
+  ! (c) 2008, Lawrence Livermore National Security Limited Liability Corporation.
+  ! All rights reserved.
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  SUBROUTINE COSP_LIDAR_ONLY_CLOUD(Npoints, Ncolumns, Nlevels, beta_tot, beta_mol,       &
+     Ze_tot, lidar_only_freq_cloud, tcc, radar_tcc, radar_tcc2)
+    ! Inputs
+    integer,intent(in) :: &
+         Npoints,       & ! Number of horizontal gridpoints
+         Ncolumns,      & ! Number of subcolumns
+         Nlevels          ! Number of vertical layers
+    real(wp),dimension(Npoints,Nlevels),intent(in) :: &
+         beta_mol         ! Molecular backscatter
+    real(wp),dimension(Npoints,Ncolumns,Nlevels),intent(in) :: &
+         beta_tot,      & ! Total backscattered signal
+         Ze_tot           ! Radar reflectivity
+    ! Outputs
+    real(wp),dimension(Npoints,Nlevels),intent(out) :: &
+         lidar_only_freq_cloud
+    real(wp),dimension(Npoints),intent(out) ::&
+         tcc,       & !
+         radar_tcc, & !
+         radar_tcc2   !
+    
+    ! local variables
+    real(wp) :: sc_ratio
+    real(wp),parameter :: &
+         s_cld=5.0, &
+         s_att=0.01
+    integer :: flag_sat,flag_cld,pr,i,j,flag_radarcld,flag_radarcld_no1km,j_1km
+    
+    lidar_only_freq_cloud = 0._wp
+    tcc = 0._wp
+    radar_tcc = 0._wp
+    radar_tcc2 = 0._wp
+    do pr=1,Npoints
+       do i=1,Ncolumns
+          flag_sat = 0
+          flag_cld = 0
+          flag_radarcld = 0 !+JEK
+          flag_radarcld_no1km=0 !+JEK
+          ! look for j_1km from bottom to top
+          j = 1
+          do while (Ze_tot(pr,i,j) .eq. R_GROUND)
+             j = j+1
+          enddo
+          j_1km = j+1  !this is the vertical index of 1km above surface  
+          
+          do j=1,Nlevels
+             sc_ratio = beta_tot(pr,i,j)/beta_mol(pr,j)
+             if ((sc_ratio .le. s_att) .and. (flag_sat .eq. 0)) flag_sat = j
+             if (Ze_tot(pr,i,j) .lt. -30.) then  !radar can't detect cloud
+                if ( (sc_ratio .gt. s_cld) .or. (flag_sat .eq. j) ) then  !lidar sense cloud
+                   lidar_only_freq_cloud(pr,j)=lidar_only_freq_cloud(pr,j)+1. !top->surf
+                   flag_cld=1
+                endif
+             else  !radar sense cloud (z%Ze_tot(pr,i,j) .ge. -30.)
+                flag_cld=1
+                flag_radarcld=1
+                if (j .gt. j_1km) flag_radarcld_no1km=1              
+             endif
+          enddo !levels
+          if (flag_cld .eq. 1) tcc(pr)=tcc(pr)+1._wp
+          if (flag_radarcld .eq. 1) radar_tcc(pr)=radar_tcc(pr)+1.
+          if (flag_radarcld_no1km .eq. 1) radar_tcc2(pr)=radar_tcc2(pr)+1.        
+       enddo !columns
+    enddo !points
+    lidar_only_freq_cloud=lidar_only_freq_cloud/Ncolumns
+    tcc=tcc/Ncolumns
+    radar_tcc=radar_tcc/Ncolumns
+    radar_tcc2=radar_tcc2/Ncolumns
+    
+    ! Unit conversion
+    where(lidar_only_freq_cloud /= R_UNDEF) &
+            lidar_only_freq_cloud = lidar_only_freq_cloud*100._wp
+    where(tcc /= R_UNDEF) tcc = tcc*100._wp
+    where(radar_tcc /= R_UNDEF) radar_tcc = radar_tcc*100._wp
+    where(radar_tcc2 /= R_UNDEF) radar_tcc2 = radar_tcc2*100._wp
+    
+  END SUBROUTINE COSP_LIDAR_ONLY_CLOUD
+  
+  ! ######################################################################################
+  ! FUNCTION hist1D
+  ! ######################################################################################
+  function hist1d(Npoints,var,nbins,bins)
+    ! Inputs
+    integer,intent(in) :: &
+         Npoints, & ! Number of points in input array
+         Nbins      ! Number of bins for sorting
+    real(wp),intent(in),dimension(Npoints) :: &
+         var        ! Input variable to be sorted
+    real(wp),intent(in),dimension(Nbins+1) :: &
+         bins       ! Histogram bins [lowest,binTops]  
+    ! Outputs
+    real(wp),dimension(Nbins) :: &
+         hist1d     ! Output histogram      
+    ! Local variables
+    integer :: ij
+    
+    do ij=2,Nbins+1  
+       hist1D(ij-1) = count(var .ge. bins(ij-1) .and. var .lt. bins(ij))
+       if (count(var .eq. R_GROUND) .ge. 1) hist1D(ij-1)=R_UNDEF
+    enddo
+    
+  end function hist1D
+  
+  ! ######################################################################################
+  ! SUBROUTINE hist2D
+  ! ######################################################################################
+  subroutine hist2D(var1,var2,npts,bin1,nbin1,bin2,nbin2,jointHist)
+    implicit none
+    
+    ! INPUTS
+    integer, intent(in) :: &
+         npts,  & ! Number of data points to be sorted
+         nbin1, & ! Number of bins in histogram direction 1 
+         nbin2    ! Number of bins in histogram direction 2
+    real(wp),intent(in),dimension(npts) :: &
+         var1,  & ! Variable 1 to be sorted into bins
+         var2     ! variable 2 to be sorted into bins
+    real(wp),intent(in),dimension(nbin1+1) :: &
+         bin1     ! Histogram bin 1 boundaries
+    real(wp),intent(in),dimension(nbin2+1) :: &
+         bin2     ! Histogram bin 2 boundaries
+    ! OUTPUTS
+    real(wp),intent(out),dimension(nbin1,nbin2) :: &
+         jointHist
+    
+    ! LOCAL VARIABLES
+    integer :: ij,ik
+    
+    do ij=2,nbin1+1
+       do ik=2,nbin2+1
+          jointHist(ij-1,ik-1)=count(var1 .ge. bin1(ij-1) .and. var1 .lt. bin1(ij) .and. &
+               var2 .ge. bin2(ik-1) .and. var2 .lt. bin2(ik))        
+       enddo
+    enddo
+  end subroutine hist2D
+END MODULE MOD_COSP_STATS
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_utils.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_utils.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/cosp_utils.F90	(revision 3605)
@@ -0,0 +1,94 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History:
+! Jul 2007 - A. Bodas-Salcedo - Initial version
+! May 2015 - Dustin Swales    - Modified for COSPv2.0
+! 
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MODULE MOD_COSP_UTILS
+  USE COSP_KINDS, ONLY: wp
+  USE MOD_COSP_CONFIG
+  IMPLICIT NONE
+
+CONTAINS
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!------------------- SUBROUTINE COSP_PRECIP_MXRATIO --------------
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SUBROUTINE COSP_PRECIP_MXRATIO(Npoints,Nlevels,Ncolumns,p,T,prec_frac,prec_type, &
+                          n_ax,n_bx,alpha_x,c_x,d_x,g_x,a_x,b_x,gamma1,gamma2,gamma3,gamma4, &
+                          flux,mxratio,reff)
+
+    ! Input arguments, (IN)
+    integer,intent(in) :: Npoints,Nlevels,Ncolumns
+    real(wp),intent(in),dimension(Npoints,Nlevels) :: p,T,flux
+    real(wp),intent(in),dimension(Npoints,Ncolumns,Nlevels) :: prec_frac
+    real(wp),intent(in) :: n_ax,n_bx,alpha_x,c_x,d_x,g_x,a_x,b_x,gamma1,gamma2,gamma3,gamma4,prec_type
+    ! Input arguments, (OUT)
+    real(wp),intent(out),dimension(Npoints,Ncolumns,Nlevels) :: mxratio
+    real(wp),intent(inout),dimension(Npoints,Ncolumns,Nlevels) :: reff
+    ! Local variables
+    integer :: i,j,k
+    real(wp) :: sigma,one_over_xip1,xi,rho0,rho,lambda_x,gamma_4_3_2,delta
+    
+    mxratio = 0.0
+
+    if (n_ax >= 0.0) then ! N_ax is used to control which hydrometeors need to be computed
+        xi      = d_x/(alpha_x + b_x - n_bx + 1._wp)
+        rho0    = 1.29_wp
+        sigma   = (gamma2/(gamma1*c_x))*(n_ax*a_x*gamma2)**xi
+        one_over_xip1 = 1._wp/(xi + 1._wp)
+        gamma_4_3_2 = 0.5_wp*gamma4/gamma3
+        delta = (alpha_x + b_x + d_x - n_bx + 1._wp)
+        
+        do k=1,Nlevels
+            do j=1,Ncolumns
+                do i=1,Npoints
+                    if ((prec_frac(i,j,k)==prec_type).or.(prec_frac(i,j,k)==3.)) then
+                        rho = p(i,k)/(287.05_wp*T(i,k))
+                        mxratio(i,j,k)=(flux(i,k)*((rho/rho0)**g_x)*sigma)**one_over_xip1
+                        mxratio(i,j,k)=mxratio(i,j,k)/rho
+                        ! Compute effective radius
+                        if ((reff(i,j,k) <= 0._wp).and.(flux(i,k) /= 0._wp)) then
+                           lambda_x = (a_x*c_x*((rho0/rho)**g_x)*n_ax*gamma1/flux(i,k))**(1._wp/delta)
+                           reff(i,j,k) = gamma_4_3_2/lambda_x
+                        endif
+                    endif
+
+!Test Artem MxRatio
+!print '(a8, i5, i8, i8, f10.2, f10.2, f10.2, f10.2, f10.2)',&
+!'MxRatio ', k, j, i, rho, p(i,k), T(i,k), flux(i,k), mxratio(i,j,k)
+
+                enddo
+            enddo
+        enddo
+    endif
+END SUBROUTINE COSP_PRECIP_MXRATIO
+
+
+END MODULE MOD_COSP_UTILS
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/icarus.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/icarus.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/icarus.F90	(revision 3605)
@@ -0,0 +1,645 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2009, Lawrence Livemore National Security Limited Liability
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History
+! May 2015 - D. Swales - Modified for COSPv2.0
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MODULE MOD_ICARUS
+  USE COSP_KINDS,          ONLY: wp
+  USE COSP_PHYS_CONSTANTS, ONLY: amd,amw,avo,grav
+  use MOD_COSP_STATS,      ONLY: hist2D
+  USE MOD_COSP_CONFIG,     ONLY: R_UNDEF,numISCCPTauBins,numISCCPPresBins,isccp_histTau, &
+                                 isccp_histPres
+  implicit none
+  
+  ! Shared Parameters                   
+  integer,parameter :: &
+       ncolprint = 0 ! Flag for debug printing (set as parameter to increase performance)
+
+  ! Cloud-top height determination
+  integer :: &
+       isccp_top_height,          & ! Top height adjustment method
+       isccp_top_height_direction   ! Direction for finding atmosphere pressure level
+
+  ! Parameters used by icarus
+  real(wp),parameter :: &
+       tauchk = -1._wp*log(0.9999999_wp), & ! Lower limit on optical depth
+       isccp_taumin = 0.3_wp,             & ! Minimum optical depth for joint-hostogram
+       pstd = 1013250._wp,                & ! Mean sea-level pressure (Pa)
+       isccp_t0 = 296._wp,                & ! Mean surface temperature (K)
+       output_missing_value = -1.E+30       ! Missing values
+
+contains
+  ! ##########################################################################
+  ! ##########################################################################
+  SUBROUTINE ICARUS(debug,debugcol,npoints,sunlit,nlev,ncol,pfull,          &
+                    phalf,qv,cc,conv,dtau_s,dtau_c,th,thd,frac_out,skt,emsfc_lw,at,&
+                    dem_s,dem_c,fq_isccp,totalcldarea, meanptop,meantaucld, &
+                    meanalbedocld, meantb,meantbclr,boxtau,boxptop,levmatch)
+        
+    ! INPUTS 
+    INTEGER,intent(in) ::      & !
+         npoints,              & ! Number of model points in the horizontal
+         nlev,                 & ! Number of model levels in column
+         ncol,                 & ! Number of subcolumns
+         debug,                & ! Debug flag
+         debugcol                ! Debug column flag
+    INTEGER,intent(in),dimension(npoints) :: & !
+         sunlit                  ! 1 for day points, 0 for night time 
+    REAL(WP),intent(in) ::     & !
+         emsfc_lw                ! 10.5 micron emissivity of surface (fraction)  
+    REAL(WP),intent(in),dimension(npoints) :: & !
+         skt                     ! Skin Temperature (K)
+    REAL(WP),intent(in),dimension(npoints,ncol,nlev) :: & !
+         frac_out                ! Boxes gridbox divided up into subcolumns
+    REAL(WP),intent(in),dimension(npoints,nlev) :: & !
+         pfull,                & ! Pressure of full model levels (Pascals)
+         qv,                   & ! Water vapor specific humidity (kg vapor/ kg air)
+         cc,                   & ! Cloud cover in each model level (fraction)
+         conv,                 & ! Convective cloud cover in each model
+         at,                   & ! Temperature in each model level (K) 
+         dem_c,                & ! Emissivity for convective clouds
+         dem_s,                & ! Emissivity for stratiform clouds
+         dtau_c,               & ! Optical depth for convective clouds
+         dtau_s                  ! Optical depth for stratiform clouds 
+    REAL(WP),intent(in),dimension(npoints,nlev+1) :: & !
+         phalf                   ! Pressure of half model levels (Pascals)!
+    integer,intent(in) :: th,thd
+
+    ! OUTPUTS 
+    REAL(WP),intent(out),dimension(npoints,7,7) :: & 
+         fq_isccp                ! The fraction of the model grid box covered by clouds
+    REAL(WP),intent(out),dimension(npoints) :: & 
+         totalcldarea,         & ! The fraction of model grid box columns with cloud present
+         meanptop,             & ! Mean cloud top pressure (mb) - linear averaging
+         meantaucld,           & ! Mean optical thickness
+         meanalbedocld,        & ! Mean cloud albedo  
+         meantb,               & ! Mean all-sky 10.5 micron brightness temperature
+         meantbclr               ! Mean clear-sky 10.5 micron brightness temperature
+    REAL(WP),intent(out),dimension(npoints,ncol) :: & 
+         boxtau,               & ! Optical thickness in each column
+         boxptop                 ! Cloud top pressure (mb) in each column
+    INTEGER,intent(out),dimension(npoints,ncol) :: &
+         levmatch                ! Used for icarus unit testing only
+
+
+    ! INTERNAL VARIABLES
+    CHARACTER(len=10)                     :: ftn09
+    REAL(WP),dimension(npoints,ncol)      :: boxttop
+    REAL(WP),dimension(npoints,ncol,nlev) :: dtau,demIN
+    INTEGER                               :: j,ilev,ibox
+    INTEGER,dimension(nlev,ncol   )       :: acc
+
+    ! PARAMETERS
+    character ,parameter, dimension(6) :: cchar=(/' ','-','1','+','I','+'/)
+    character(len=1),parameter,dimension(6) :: cchar_realtops=(/ ' ',' ','1','1','I','I'/)
+    ! ##########################################################################
+    
+    call cosp_simulator_optics(npoints,ncol,nlev,frac_out,dem_c,dem_s,demIN)
+    call cosp_simulator_optics(npoints,ncol,nlev,frac_out,dtau_c,dtau_s,dtau)
+
+    call ICARUS_SUBCOLUMN(npoints,ncol,nlev,sunlit,dtau,demIN,skt,emsfc_lw,qv,at,        &
+                      pfull,phalf,frac_out,levmatch,boxtau,boxptop,boxttop,meantbclr)
+
+    call ICARUS_COLUMN(npoints,ncol,boxtau,boxptop/100._wp,sunlit,boxttop,&
+                       fq_isccp,meanalbedocld,meanptop,meantaucld,totalcldarea,meantb)
+
+    ! ##########################################################################
+    ! OPTIONAL PRINTOUT OF DATA TO CHECK PROGRAM
+    ! ##########################################################################
+    
+    if (debugcol.ne.0) then
+       do j=1,npoints,debugcol
+          
+          ! Produce character output
+          do ilev=1,nlev
+             acc(ilev,1:ncol)=frac_out(j,1:ncol,ilev)*2
+             where(levmatch(j,1:ncol) .eq. ilev) acc(ilev,1:ncol)=acc(ilev,1:ncol)+1
+          enddo
+          
+          write(ftn09,11) j
+11        format('ftn09.',i4.4)
+          open(9, FILE=ftn09, FORM='FORMATTED')
+          
+          write(9,'(a1)') ' '
+          write(9,'(10i5)') (ilev,ilev=5,nlev,5)
+          write(9,'(a1)') ' '
+          
+          do ibox=1,ncol
+             write(9,'(40(a1),1x,40(a1))') &
+                  (cchar_realtops(acc(ilev,ibox)+1),ilev=1,nlev),&
+                  (cchar(acc(ilev,ibox)+1),ilev=1,nlev) 
+          end do
+          close(9)
+
+       enddo       
+    end if
+    
+    return
+  end SUBROUTINE ICARUS
+  
+  ! ############################################################################
+  ! ############################################################################
+  ! ############################################################################
+  SUBROUTINE ICARUS_SUBCOLUMN(npoints,ncol,nlev,sunlit,dtau,demiN,skt,emsfc_lw,qv,at,        &
+                          pfull,phalf,frac_out,levmatch,boxtau,boxptop,boxttop,meantbclr)
+    ! Inputs
+    INTEGER, intent(in) ::   &
+         ncol,               & ! Number of subcolumns
+         npoints,            & ! Number of horizontal gridpoints
+         nlev                  ! Number of vertical levels
+    INTEGER, intent(in), dimension(npoints) :: &
+         sunlit                ! 1=day 0=night
+    REAL(WP),intent(in) :: &
+         emsfc_lw              ! 10.5 micron emissivity of surface (fraction) 
+    REAL(WP),intent(in), dimension(npoints) ::  &
+         skt                   ! Skin temperature
+    REAL(WP),intent(in), dimension(npoints,nlev) ::  &
+         at,                 & ! Temperature 
+         pfull,              & ! Presure
+         qv                    ! Specific humidity
+    REAL(WP),intent(in), dimension(npoints,ncol,nlev) :: &
+         frac_out,           & ! Subcolumn cloud cover
+         dtau,               & ! Subcolumn optical thickness
+         demIN                 ! Subcolumn emissivity
+    REAL(WP),intent(in), dimension(npoints,nlev+1) :: &
+         phalf                 ! Pressure at model half levels
+
+    ! Outputs
+    REAL(WP),intent(inout),dimension(npoints) :: &
+         meantbclr             ! Mean clear-sky 10.5 micron brightness temperature
+    REAL(WP),intent(inout),dimension(npoints,ncol) :: &
+         boxtau,             & ! Optical thickness in each column
+         boxptop,            & ! Cloud top pressure (mb) in each column
+         boxttop               ! Cloud top temperature in each column
+    INTEGER, intent(inout),dimension(npoints,ncol)      :: levmatch
+
+    ! Local Variables
+    INTEGER :: &
+       j,ibox,ilev,k1,k2,icycle
+    INTEGER,dimension(npoints) :: &
+       nmatch,itrop
+    INTEGER,dimension(npoints,nlev-1) :: &
+       match
+    REAL(WP) :: &
+       logp,logp1,logp2,atd
+    REAL(WP),dimension(npoints) :: &
+       bb,attropmin,attrop,ptrop,atmax,btcmin,transmax,tauir,taumin,fluxtopinit,press,   &
+       dpress,atmden,rvh20,rhoave,rh20s,rfrgn,tmpexp,tauwv,wk,trans_layers_above_clrsky, &
+       fluxtop_clrsky
+    REAL(WP),dimension(npoints,nlev) :: &
+       dem_wv
+    REAL(WP),dimension(npoints,ncol) :: &
+       trans_layers_above,dem,tb,emcld,fluxtop,tau,ptop
+
+    ! ####################################################################################
+    ! Compute cloud optical depth for each column by summing up subcolumns
+    tau(1:npoints,1:ncol) = 0._wp
+    tau(1:npoints,1:ncol) = sum(dtau,dim=3)
+
+    ! Set tropopause values
+    if (isccp_top_height .eq. 1 .or. isccp_top_height .eq. 3) then 
+       ptrop(1:npoints)     = 5000._wp
+       attropmin(1:npoints) = 400._wp
+       atmax(1:npoints)     = 0._wp
+       attrop(1:npoints)    = 120._wp
+       itrop(1:npoints)     = 1
+
+       do ilev=1,nlev
+          where(pfull(1:npoints,ilev) .lt. 40000. .and. &
+                pfull(1:npoints,ilev) .gt.  5000. .and. &
+                at(1:npoints,ilev)    .lt. attropmin(1:npoints))
+             ptrop(1:npoints)     = pfull(1:npoints,ilev)
+             attropmin(1:npoints) = at(1:npoints,ilev)
+             attrop(1:npoints)    = attropmin(1:npoints)
+             itrop     = ilev
+          endwhere
+       enddo
+
+       do ilev=1,nlev
+          atmax(1:npoints) = merge(at(1:npoints,ilev),atmax(1:npoints),&
+               at(1:npoints,ilev) .gt. atmax(1:npoints) .and. ilev  .ge. itrop(1:npoints))
+       enddo
+    end if
+  
+    if (isccp_top_height .eq. 1 .or. isccp_top_height .eq. 3) then
+       ! ############################################################################
+       !                        Clear-sky radiance calculation
+       !       
+       ! Compute water vapor continuum emissivity this treatment follows Schwarkzopf 
+       ! and Ramasamy JGR 1999,vol 104, pages 9467-9499. The emissivity is calculated
+       ! at a wavenumber of 955 cm-1, or 10.47 microns 
+       ! ############################################################################
+       do ilev=1,nlev
+          press(1:npoints)  = pfull(1:npoints,ilev)*10._wp
+          dpress(1:npoints) = (phalf(1:npoints,ilev+1)-phalf(1:npoints,ilev))*10
+          atmden(1:npoints) = dpress(1:npoints)/(grav*100._wp)
+          rvh20(1:npoints)  = qv(1:npoints,ilev)*amd/amw
+          wk(1:npoints)     = rvh20(1:npoints)*avo*atmden/amd
+          rhoave(1:npoints) = (press(1:npoints)/pstd)*(isccp_t0/at(1:npoints,ilev))
+          rh20s(1:npoints)  = rvh20(1:npoints)*rhoave(1:npoints)
+          rfrgn(1:npoints)  = rhoave(1:npoints)-rh20s(1:npoints)
+          tmpexp(1:npoints) = exp(-0.02_wp*(at(1:npoints,ilev)-isccp_t0))
+          tauwv(1:npoints)  = wk(1:npoints)*1.e-20*((0.0224697_wp*rh20s(1:npoints)*      &
+                              tmpexp(1:npoints))+(3.41817e-7*rfrgn(1:npoints)))*0.98_wp
+          dem_wv(1:npoints,ilev) = 1._wp - exp( -1._wp * tauwv(1:npoints))
+       enddo
+
+       fluxtop_clrsky(1:npoints)            = 0._wp
+       trans_layers_above_clrsky(1:npoints) = 1._wp
+       do ilev=1,nlev
+          ! Black body emission at temperature of the layer
+          bb(1:npoints) = 1._wp / ( exp(1307.27_wp/at(1:npoints,ilev)) - 1._wp )
+          
+          ! Increase TOA flux by flux emitted from layer times total transmittance in layers above
+          fluxtop_clrsky(1:npoints) = fluxtop_clrsky(1:npoints) + &
+               dem_wv(1:npoints,ilev)*bb(1:npoints)*trans_layers_above_clrsky(1:npoints)
+          
+          ! Update trans_layers_above with transmissivity from this layer for next time around loop
+          trans_layers_above_clrsky(1:npoints) = trans_layers_above_clrsky(1:npoints)*&
+              (1.-dem_wv(1:npoints,ilev))                
+       enddo
+
+       ! Add in surface emission
+       bb(1:npoints) = 1._wp/( exp(1307.27_wp/skt(1:npoints)) - 1._wp )
+       fluxtop_clrsky(1:npoints) = fluxtop_clrsky(1:npoints) + &
+           emsfc_lw * bb(1:npoints)*trans_layers_above_clrsky(1:npoints)
+
+       ! Clear Sky brightness temperature
+       meantbclr(1:npoints) = 1307.27_wp/(log(1._wp+(1._wp/fluxtop_clrsky(1:npoints))))
+       
+       ! #################################################################################
+       !                        All-sky radiance calculation
+       ! #################################################################################
+       
+       fluxtop(1:npoints,1:ncol)            = 0._wp
+       trans_layers_above(1:npoints,1:ncol) = 1._wp
+       do ilev=1,nlev
+          ! Black body emission at temperature of the layer
+          bb=1._wp/(exp(1307.27_wp/at(1:npoints,ilev)) - 1._wp)
+          
+          do ibox=1,ncol
+             ! Emissivity
+             dem(1:npoints,ibox) = merge(dem_wv(1:npoints,ilev), &
+                                         1._wp-(1._wp-demIN(1:npoints,ibox,ilev))*(1._wp-dem_wv(1:npoints,ilev)), &
+                                         demIN(1:npoints,ibox,ilev) .eq. 0)
+
+             ! Increase TOA flux emitted from layer
+             fluxtop(1:npoints,ibox) = fluxtop(1:npoints,ibox) + dem(1:npoints,ibox)*bb*trans_layers_above(1:npoints,ibox) 
+             
+             ! Update trans_layer by emitted layer from above
+             trans_layers_above(1:npoints,ibox) = trans_layers_above(1:npoints,ibox)*(1._wp-dem(1:npoints,ibox))
+          enddo
+       enddo
+
+       ! Add in surface emission
+       bb(1:npoints)=1._wp/( exp(1307.27_wp/skt(1:npoints)) - 1._wp )
+       do ibox=1,ncol
+          fluxtop(1:npoints,ibox) = fluxtop(1:npoints,ibox) + emsfc_lw*bb(1:npoints)*trans_layers_above(1:npoints,ibox) 
+       end do
+
+       ! All Sky brightness temperature
+       boxttop(1:npoints,1:ncol) = 1307.27_wp/(log(1._wp+(1._wp/fluxtop(1:npoints,1:ncol))))
+
+       ! #################################################################################  
+       !                            Cloud-Top Temperature
+       !
+       ! Now that you have the top of atmosphere radiance, account for ISCCP 
+       ! procedures to determine cloud top temperature account for partially
+       ! transmitting cloud recompute flux ISCCP would see assuming a single layer
+       ! cloud. *NOTE* choice here of 2.13, as it is primarily ice clouds which have 
+       ! partial emissivity and need the adjustment performed in this section. If it
+       ! turns out that the cloud brightness temperature is greater than 260K, then 
+       ! the liquid cloud conversion factor of 2.56 is used. *NOTE* that this is 
+       ! discussed on pages 85-87 of the ISCCP D level documentation 
+       ! (Rossow et al. 1996)
+       ! #################################################################################
+
+       ! Compute minimum brightness temperature and optical depth
+       btcmin(1:npoints) = 1._wp /  ( exp(1307.27_wp/(attrop(1:npoints)-5._wp)) - 1._wp ) 
+
+       do ibox=1,ncol
+          transmax(1:npoints) = (fluxtop(1:npoints,ibox)-btcmin) /(fluxtop_clrsky(1:npoints)-btcmin(1:npoints))
+          tauir(1:npoints)    = tau(1:npoints,ibox)/2.13_wp
+          taumin(1:npoints)   = -log(max(min(transmax(1:npoints),0.9999999_wp),0.001_wp))
+          if (isccp_top_height .eq. 1) then
+             do j=1,npoints  
+                if (transmax(j) .gt. 0.001 .and.  transmax(j) .le. 0.9999999) then
+                   fluxtopinit(j) = fluxtop(j,ibox)
+                   tauir(j) = tau(j,ibox)/2.13_wp
+                endif
+             enddo
+             do icycle=1,2
+                do j=1,npoints  
+                   if (tau(j,ibox) .gt. (tauchk)) then 
+                      if (transmax(j) .gt. 0.001 .and.  transmax(j) .le. 0.9999999) then
+                         emcld(j,ibox) = 1._wp - exp(-1._wp * tauir(j)  )
+                         fluxtop(j,ibox) = fluxtopinit(j) - ((1.-emcld(j,ibox))*fluxtop_clrsky(j))
+                         fluxtop(j,ibox)=max(1.E-06_wp,(fluxtop(j,ibox)/emcld(j,ibox)))
+                         tb(j,ibox)= 1307.27_wp / (log(1._wp + (1._wp/fluxtop(j,ibox))))
+                         if (tb(j,ibox) .gt. 260.) then
+                            tauir(j) = tau(j,ibox) / 2.56_wp
+                         end if
+                      end if
+                   end if
+                enddo
+            enddo
+          endif
+
+          ! Cloud-top temperature
+          where(tau(1:npoints,ibox) .gt. tauchk)
+             tb(1:npoints,ibox)= 1307.27_wp/ (log(1. + (1._wp/fluxtop(1:npoints,ibox))))
+             where (isccp_top_height .eq. 1 .and. tauir(1:npoints) .lt. taumin(1:npoints))
+                tb(1:npoints,ibox) = attrop(1:npoints) - 5._wp 
+                tau(1:npoints,ibox) = 2.13_wp*taumin(1:npoints)
+             endwhere
+          endwhere
+          
+          ! Clear-sky brightness temperature
+          where(tau(1:npoints,ibox) .le. tauchk) 
+             tb(1:npoints,ibox) = meantbclr(1:npoints)
+          endwhere
+       enddo
+    else
+       meantbclr(1:npoints) = output_missing_value
+    end if
+
+    ! ####################################################################################
+    !                           Cloud-Top Pressure
+    !
+    ! The 2 methods differ according to whether or not you use the physical cloud
+    ! top pressure (isccp_top_height = 2) or the radiatively determined cloud top
+    ! pressure (isccp_top_height = 1 or 3)
+    ! ####################################################################################
+    do ibox=1,ncol
+       !segregate according to optical thickness
+       if (isccp_top_height .eq. 1 .or. isccp_top_height .eq. 3) then  
+          
+          ! Find level whose temperature most closely matches brightness temperature
+          nmatch(1:npoints)=0
+          do k1=1,nlev-1
+             ilev = merge(nlev-k1,k1,isccp_top_height_direction .eq. 2)        
+             do j=1,npoints 
+                if (ilev           .ge. itrop(j)     .and. &
+                     ((at(j,ilev)  .ge. tb(j,ibox)   .and. &  
+                      at(j,ilev+1) .le. tb(j,ibox))  .or.  &
+                      (at(j,ilev)  .le. tb(j,ibox)   .and. &
+                      at(j,ilev+1) .ge. tb(j,ibox)))) then 
+                   nmatch(j)=nmatch(j)+1
+                   match(j,nmatch(j))=ilev
+                endif
+             enddo
+          enddo
+
+          do j=1,npoints 
+             if (nmatch(j) .ge. 1) then
+                k1 = match(j,nmatch(j))
+                k2 = k1 + 1
+                logp1 = log(pfull(j,k1))
+                logp2 = log(pfull(j,k2))
+                atd = max(tauchk,abs(at(j,k2) - at(j,k1)))
+                logp=logp1+(logp2-logp1)*abs(tb(j,ibox)-at(j,k1))/atd
+                ptop(j,ibox) = exp(logp)
+                levmatch(j,ibox) = merge(k1,k2,abs(pfull(j,k1)-ptop(j,ibox)) .lt. abs(pfull(j,k2)-ptop(j,ibox)))
+             else
+                if (tb(j,ibox) .le. attrop(j)) then
+                   ptop(j,ibox)=ptrop(j)
+                   levmatch(j,ibox)=itrop(j)
+                end if
+                if (tb(j,ibox) .ge. atmax(j)) then
+                   ptop(j,ibox)=pfull(j,nlev)
+                   levmatch(j,ibox)=nlev
+                end if
+             end if
+          enddo
+       else
+          ptop(1:npoints,ibox)=0.
+          do ilev=1,nlev
+             where((ptop(1:npoints,ibox) .eq. 0. ) .and.(frac_out(1:npoints,ibox,ilev) .ne. 0))
+                ptop(1:npoints,ibox)=phalf(1:npoints,ilev)
+                levmatch(1:npoints,ibox)=ilev
+             endwhere
+          end do
+       end if
+       where(tau(1:npoints,ibox) .le. tauchk)
+          ptop(1:npoints,ibox)=0._wp
+          levmatch(1:npoints,ibox)=0._wp
+       endwhere
+    enddo
+
+    ! ####################################################################################
+    !                Compute subcolumn pressure and optical depth
+    ! ####################################################################################
+    boxtau(1:npoints,1:ncol)  = output_missing_value
+    boxptop(1:npoints,1:ncol) = output_missing_value
+    do ibox=1,ncol
+       do j=1,npoints 
+          if (tau(j,ibox) .gt. (tauchk) .and. ptop(j,ibox) .gt. 0.) then
+             if (sunlit(j).eq.1 .or. isccp_top_height .eq. 3) then
+                boxtau(j,ibox) = tau(j,ibox)
+                boxptop(j,ibox) = ptop(j,ibox)!/100._wp
+             endif
+          endif
+       enddo
+    enddo
+
+  end SUBROUTINE ICARUS_SUBCOLUMN
+
+  ! ######################################################################################
+  ! SUBROUTINE icarus_column
+  ! ######################################################################################
+  SUBROUTINE ICARUS_column(npoints,ncol,boxtau,boxptop,sunlit,boxttop,fq_isccp,     &
+                           meanalbedocld,meanptop,meantaucld,totalcldarea,meantb)
+    ! Inputs
+    INTEGER, intent(in) :: &
+         ncol,    & ! Number of subcolumns
+         npoints    ! Number of horizontal gridpoints
+    INTEGER, intent(in),dimension(npoints) :: &
+         sunlit     ! day=1 night=0 
+    REAL(WP),intent(in),dimension(npoints,ncol) ::  &
+         boxttop,  & ! Subcolumn top temperature
+         boxptop,  & ! Subcolumn cloud top pressure
+         boxtau      ! Subcolumn optical depth
+
+    ! Outputs
+    REAL(WP),intent(inout),dimension(npoints) :: &
+         meanalbedocld, & ! Gridmean cloud albedo
+         meanptop,      & ! Gridmean cloud top pressure (mb) - linear averaging
+         meantaucld,    & ! Gridmean optical thickness
+         totalcldarea,  & ! The fraction of model grid box columns with cloud present
+         meantb           ! Gridmean all-sky 10.5 micron brightness temperature 
+    REAL(WP),intent(inout),dimension(npoints,7,7) :: &
+         fq_isccp         ! The fraction of the model grid box covered by clouds
+
+    ! Local Variables
+    INTEGER :: j,ilev,ilev2
+    REAL(WP),dimension(npoints,ncol) :: albedocld
+    LOGICAL, dimension(npoints,ncol) :: box_cloudy
+
+    ! Variables for new joint-histogram implementation
+    logical,dimension(ncol) :: box_cloudy2
+
+    ! ####################################################################################
+    !                           Brightness Temperature
+    ! ####################################################################################
+    if (isccp_top_height .eq. 1 .or. isccp_top_height .eq. 3) then
+       meantb(1:npoints)=sum(boxttop,2)/ncol
+    else
+       meantb(1:npoints) = output_missing_value
+    endif
+
+    ! ####################################################################################
+    !                 Determines ISCCP cloud type frequencies
+    !
+    ! Now that boxptop and boxtau have been determined, determine amount of each of the 
+    ! 49 ISCCP cloud types. Also compute grid box mean cloud top pressure and 
+    ! optical thickness.  The mean cloud top pressure and optical thickness are 
+    ! averages over the cloudy area only. The mean cloud top pressure is a linear
+    ! average of the cloud top pressures. The mean cloud optical thickness is 
+    ! computed by converting optical thickness to an albedo, averaging in albedo 
+    ! units, then converting the average albedo back to a mean optical thickness.  
+    ! ####################################################################################
+
+    ! Initialize
+    albedocld(1:npoints,1:ncol)  = 0._wp
+    box_cloudy(1:npoints,1:ncol) = .false.
+    
+    ! Reset frequencies
+    !fq_isccp = spread(spread(merge(0._wp,output_missing_value,sunlit .eq. 1 .or. isccp_top_height .eq. 3),2,7),2,7)
+    do ilev=1,7
+       do ilev2=1,7
+          do j=1,npoints ! 
+             if (sunlit(j).eq.1 .or. isccp_top_height .eq. 3) then 
+                fq_isccp(j,ilev,ilev2)= 0.
+	     else 
+                fq_isccp(j,ilev,ilev2)= output_missing_value
+             end if
+          enddo
+       enddo
+    enddo
+
+    
+    ! Reset variables need for averaging cloud properties
+    where(sunlit .eq. 1 .or. isccp_top_height .eq. 3)
+       totalcldarea(1:npoints)  = 0._wp
+       meanalbedocld(1:npoints) = 0._wp
+       meanptop(1:npoints)      = 0._wp
+       meantaucld(1:npoints)    = 0._wp
+    elsewhere
+       totalcldarea(1:npoints)  = output_missing_value
+       meanalbedocld(1:npoints) = output_missing_value
+       meanptop(1:npoints)      = output_missing_value
+       meantaucld(1:npoints)    = output_missing_value
+    endwhere
+    
+    ! Compute column quantities and joint-histogram
+    do j=1,npoints 
+       ! Subcolumns that are cloudy(true) and not(false)
+       box_cloudy2(1:ncol) = merge(.true.,.false.,boxtau(j,1:ncol) .gt. tauchk .and. boxptop(j,1:ncol) .gt. 0.)
+
+       ! Compute joint histogram and column quantities for points that are sunlit and cloudy
+       if (sunlit(j) .eq.1 .or. isccp_top_height .eq. 3) then 
+          ! Joint-histogram
+          call hist2D(boxtau(j,1:ncol),boxptop(j,1:ncol),ncol,isccp_histTau,numISCCPTauBins, &
+               isccp_histPres,numISCCPPresBins,fq_isccp(j,1:numISCCPTauBins,1:numISCCPPresBins))
+          fq_isccp(j,1:numISCCPTauBins,1:numISCCPPresBins) = &
+               fq_isccp(j,1:numISCCPTauBins,1:numISCCPPresBins)/ncol
+          
+          ! Column cloud area
+          totalcldarea(j) = real(count(box_cloudy2(1:ncol) .and. boxtau(j,1:ncol) .gt. isccp_taumin))/ncol
+             
+          ! Subcolumn cloud albedo
+          !albedocld(j,1:ncol) = merge((boxtau(j,1:ncol)**0.895_wp)/((boxtau(j,1:ncol)**0.895_wp)+6.82_wp),&
+          !     0._wp,box_cloudy2(1:ncol) .and. boxtau(j,1:ncol) .gt. isccp_taumin)
+          where(box_cloudy2(1:ncol) .and. boxtau(j,1:ncol) .gt. isccp_taumin)
+             albedocld(j,1:ncol) = (boxtau(j,1:ncol)**0.895_wp)/((boxtau(j,1:ncol)**0.895_wp)+6.82_wp)
+          elsewhere
+             albedocld(j,1:ncol) = 0._wp
+          endwhere
+          
+          ! Column cloud albedo
+          meanalbedocld(j) = sum(albedocld(j,1:ncol))/ncol
+          
+          ! Column cloud top pressure
+          meanptop(j) = sum(boxptop(j,1:ncol),box_cloudy2(1:ncol) .and. boxtau(j,1:ncol) .gt. isccp_taumin)/ncol
+       endif
+    enddo
+    
+    ! Compute mean cloud properties. Set to mssing value in the event that totalcldarea=0
+    where(totalcldarea(1:npoints) .gt. 0)
+       meanptop(1:npoints)      = 100._wp*meanptop(1:npoints)/totalcldarea(1:npoints)
+       meanalbedocld(1:npoints) = meanalbedocld(1:npoints)/totalcldarea(1:npoints)
+       meantaucld(1:npoints)    = (6.82_wp/((1._wp/meanalbedocld(1:npoints))-1.))**(1._wp/0.895_wp)
+    elsewhere
+       meanptop(1:nPoints)      = output_missing_value
+       meanalbedocld(1:nPoints) = output_missing_value
+       meantaucld(1:nPoints)    = output_missing_value
+    endwhere
+    !meanptop(1:npoints)      = merge(100._wp*meanptop(1:npoints)/totalcldarea(1:npoints),&
+    !                                 output_missing_value,totalcldarea(1:npoints) .gt. 0)
+    !meanalbedocld(1:npoints) = merge(meanalbedocld(1:npoints)/totalcldarea(1:npoints), &
+    !                                 output_missing_value,totalcldarea(1:npoints) .gt. 0)
+    !meantaucld(1:npoints)    = merge((6.82_wp/((1._wp/meanalbedocld(1:npoints))-1.))**(1._wp/0.895_wp), &
+    !                                 output_missing_value,totalcldarea(1:npoints) .gt. 0)
+
+    ! Represent in percent
+    where(totalcldarea .ne. output_missing_value) totalcldarea = totalcldarea*100._wp
+    where(fq_isccp     .ne. output_missing_value) fq_isccp     = fq_isccp*100._wp
+    
+    
+  end SUBROUTINE ICARUS_column
+  
+  subroutine cosp_simulator_optics(dim1,dim2,dim3,flag,varIN1,varIN2,varOUT)
+    ! INPUTS
+    integer,intent(in) :: &
+         dim1,   & ! Dimension 1 extent (Horizontal)
+         dim2,   & ! Dimension 2 extent (Subcolumn)
+         dim3      ! Dimension 3 extent (Vertical)
+    real(wp),intent(in),dimension(dim1,dim2,dim3) :: &
+         flag      ! Logical to determine the of merge var1IN and var2IN
+    real(wp),intent(in),dimension(dim1,     dim3) :: &
+         varIN1, & ! Input field 1
+         varIN2    ! Input field 2
+    ! OUTPUTS
+    real(wp),intent(out),dimension(dim1,dim2,dim3) :: &
+         varOUT    ! Merged output field
+    ! LOCAL VARIABLES
+    integer :: j
+    
+    varOUT(1:dim1,1:dim2,1:dim3) = 0._wp
+    do j=1,dim2
+       where(flag(:,j,:) .eq. 1)
+          varOUT(:,j,:) = varIN2
+       endwhere
+       where(flag(:,j,:) .eq. 2)
+          varOUT(:,j,:) = varIN1
+       endwhere
+    enddo
+  end subroutine cosp_simulator_optics
+end module MOD_ICARUS
+
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lidar_simulator.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lidar_simulator.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lidar_simulator.F90	(revision 3605)
@@ -0,0 +1,1561 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2009, Centre National de la Recherche Scientifique
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History
+! May 2007: ActSim code of M. Chiriaco and H. Chepfer rewritten by S. Bony
+!
+! May 2008, H. Chepfer:
+! - Units of pressure inputs: Pa 
+! - Non Spherical particles : LS Ice NS coefficients, CONV Ice NS coefficients
+! - New input: ice_type (0=ice-spheres ; 1=ice-non-spherical)
+!
+! June 2008, A. Bodas-Salcedo:
+! - Ported to Fortran 90 and optimisation changes
+!
+! August 2008, J-L Dufresne:
+! - Optimisation changes (sum instructions suppressed)
+!
+! October 2008, S. Bony,  H. Chepfer and J-L. Dufresne :  
+! - Interface with COSP v2.0:
+!      cloud fraction removed from inputs
+!      in-cloud condensed water now in input (instead of grid-averaged value)
+!      depolarisation diagnostic removed
+!      parasol (polder) reflectances (for 5 different solar zenith angles) added
+!
+! December 2008, S. Bony,  H. Chepfer and J-L. Dufresne : 
+! - Modification of the integration of the lidar equation.
+! - change the cloud detection threshold
+!
+! April 2008, A. Bodas-Salcedo:
+! - Bug fix in computation of pmol and pnorm of upper layer
+!
+! April 2008, J-L. Dufresne
+! - Bug fix in computation of pmol and pnorm, thanks to Masaki Satoh: a factor 2 
+! was missing. This affects the ATB values but not the cloud fraction. 
+!
+! January 2013, G. Cesana and H. Chepfer:
+! - Add the perpendicular component of the backscattered signal (pnorm_perp_tot) in the arguments
+! - Add the temperature for each levels (temp) in the arguments
+! - Add the computation of the perpendicular component of the backscattered lidar signal 
+! Reference: Cesana G. and H. Chepfer (2013): Evaluation of the cloud water phase
+! in a climate model using CALIPSO-GOCCP, J. Geophys. Res., doi: 10.1002/jgrd.50376
+!
+! May 2015 - D. Swales - Modified for COSPv2.0
+!
+! Mar 2018 - R. Guzman - Added OPAQ subroutines
+! References OPAQ:
+!
+!       Guzman et al. (2017): Direct atmosphere opacity observations from CALIPSO provide 
+! new constraints on cloud-radiation interactions. JGR-Atmospheres, DOI: 10.1002/2016JD025946
+!       Vaillant de Guelis et al. (2017a): The link between outgoing longwave radiation and
+! the altitude at which a spaceborne lidar beam is fully attenuated. AMT, 10, 4659-4685,
+! https://doi.org/10.5194/amt-10-4659-2017
+!
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+module mod_lidar_simulator
+  USE COSP_KINDS,         ONLY: wp
+  USE MOD_COSP_CONFIG,    ONLY: SR_BINS,S_CLD,S_ATT,S_CLD_ATT,R_UNDEF,calipso_histBsct,  &
+                                use_vgrid,vgrid_zl,vgrid_zu,vgrid_z,atlid_histBsct,      &
+                                grLidar532_histBsct,S_CLD_ATLID,S_ATT_ATLID,S_CLD_ATT_ATLID
+  USE MOD_COSP_STATS,     ONLY: COSP_CHANGE_VERTICAL_GRID,hist1d
+  implicit none
+  
+  ! Polynomial coefficients (Alpha, Beta, Gamma) which allow to compute the 
+  ! ATBperpendicular as a function of the ATB for ice or liquid cloud particles 
+  ! derived from CALIPSO-GOCCP observations at 120m vertical grid 
+  ! (Cesana and Chepfer, JGR, 2013).
+  !
+  ! Relationship between ATBice and ATBperp,ice for ice particles:
+  !                ATBperp,ice = Alpha*ATBice 
+  ! Relationship between ATBice and ATBperp,ice for liquid particles:
+  !          ATBperp,ice = Beta*ATBice^2 + Gamma*ATBice
+  real(wp) :: &
+       alpha,beta,gamma    
+
+contains
+  ! ######################################################################################
+  ! SUBROUTINE lidar_subcolumn
+  ! Inputs with a vertical dimensions (nlev) should ordered in along the vertical 
+  ! dimension from TOA-2-SFC, for example: varIN(nlev) is varIN @ SFC. 
+  ! ######################################################################################
+  subroutine lidar_subcolumn(npoints, ncolumns, nlev, lground, beta_mol, tau_mol,        &
+       betatot, tautot, pmol, pnorm, betatot_ice, tautot_ice, betatot_liq, tautot_liq,   &
+       pnorm_perp_tot)
+
+    ! INPUTS
+    INTEGER,intent(in) :: & 
+         npoints,      & ! Number of gridpoints
+         ncolumns,     & ! Number of subcolumns
+         nlev            ! Number of levels
+    logical,intent(in) :: &
+         lground         ! True for ground-based lidar simulator
+    REAL(WP),intent(in),dimension(npoints,nlev) :: &
+         beta_mol,     & ! Molecular backscatter coefficient
+         tau_mol         ! Molecular optical depth
+    REAL(WP),intent(in),dimension(npoints,ncolumns,nlev)       :: &
+         betatot,      & ! 
+         tautot          ! Optical thickess integrated from top
+    ! Optional Inputs
+    REAL(WP),intent(in),dimension(npoints,ncolumns,nlev),optional       :: &         
+         betatot_ice,  & ! Backscatter coefficient for ice particles
+         betatot_liq,  & ! Backscatter coefficient for liquid particles
+         tautot_ice,   & ! Total optical thickness of ice
+         tautot_liq      ! Total optical thickness of liq
+
+    ! OUTPUTS
+    REAL(WP),intent(out),dimension(npoints,nlev) :: &
+         pmol            ! Molecular attenuated backscatter lidar signal power(m^-1.sr^-1)
+    REAL(WP),intent(out),dimension(npoints,ncolumns,nlev) :: &
+         pnorm           ! Molecular backscatter signal power (m^-1.sr^-1)
+    ! Optional outputs
+    REAL(WP),intent(out),dimension(npoints,ncolumns,nlev),optional :: &
+         pnorm_perp_tot  ! Perpendicular lidar backscattered signal power
+
+    ! LOCAL VARIABLES
+    INTEGER :: k,icol,zi,zf,zinc
+    logical :: lphaseoptics
+    REAL(WP),dimension(npoints) :: &
+         tautot_lay        !
+    REAL(WP),dimension(npoints,ncolumns,nlev) :: &
+         pnorm_liq,      & ! Lidar backscattered signal power for liquid
+         pnorm_ice,      & ! Lidar backscattered signal power for ice
+         pnorm_perp_ice, & ! Perpendicular lidar backscattered signal power for ice
+         pnorm_perp_liq, & ! Perpendicular lidar backscattered signal power for liq
+         beta_perp_ice,  & ! Perpendicular backscatter coefficient for ice
+         beta_perp_liq     ! Perpendicular backscatter coefficient for liquid
+
+    ! Phase optics?
+    lphaseoptics=.false.
+    if (present(betatot_ice) .and. present(betatot_liq) .and. present(tautot_liq) .and. &
+         present(tautot_ice)) lphaseoptics=.true.
+    
+    ! Is this lidar spaceborne (default) or ground-based?
+    if (lground) then
+       zi   = nlev
+       zf   = 1
+       zinc = -1
+    else
+       zi   = 1
+       zf   = nlev
+       zinc = 1
+    endif    
+
+    ! ####################################################################################
+    ! *) Molecular signal
+    ! ####################################################################################
+    call cmp_backsignal(nlev,npoints,beta_mol(1:npoints,zi:zf:zinc),&
+                        tau_mol(1:npoints,zi:zf:zinc),pmol(1:npoints,zi:zf:zinc))
+                        
+    ! ####################################################################################
+    ! PLANE PARRALLEL FIELDS
+    ! ####################################################################################
+    do icol=1,ncolumns
+       ! #################################################################################
+       ! *) Total Backscatter signal
+       ! #################################################################################
+       call cmp_backsignal(nlev,npoints,betatot(1:npoints,icol,zi:zf:zinc),&
+            tautot(1:npoints,icol,zi:zf:zinc),pnorm(1:npoints,icol,zi:zf:zinc))
+       
+       ! #################################################################################
+       ! *) Ice/Liq Backscatter signal
+       ! #################################################################################
+       if (lphaseoptics) then
+          ! Computation of the ice and liquid lidar backscattered signal (ATBice and ATBliq)
+          ! Ice only
+          call cmp_backsignal(nlev,npoints,betatot_ice(1:npoints,icol,zi:zf:zinc),&
+               tautot_ice(1:npoints,icol,zi:zf:zinc), pnorm_ice(1:npoints,icol,zi:zf:zinc))
+          ! Liquid only
+          call cmp_backsignal(nlev,npoints,betatot_liq(1:npoints,icol,zi:zf:zinc),&
+               tautot_liq(1:npoints,icol,zi:zf:zinc), pnorm_liq(1:npoints,icol,zi:zf:zinc))
+       endif
+    enddo
+
+    ! ####################################################################################
+    ! PERDENDICULAR FIELDS (Only needed if distinguishing by phase (ice/liquid))
+    ! ####################################################################################
+    if (lphaseoptics) then
+       do icol=1,ncolumns
+          ! #################################################################################
+          ! *) Ice/Liq Perpendicular Backscatter signal
+          ! #################################################################################
+          ! Computation of ATBperp,ice/liq from ATBice/liq including the multiple scattering 
+          ! contribution (Cesana and Chepfer 2013, JGR)
+          do k=1,nlev
+             ! Ice particles
+             pnorm_perp_ice(1:npoints,icol,k) = Alpha * pnorm_ice(1:npoints,icol,k)
+             
+             ! Liquid particles
+             pnorm_perp_liq(1:npoints,icol,k) = 1000._wp*Beta*pnorm_liq(1:npoints,icol,k)**2+&
+                  Gamma*pnorm_liq(1:npoints,icol,k) 
+          enddo
+          
+          ! #################################################################################
+          ! *) Computation of beta_perp_ice/liq using the lidar equation
+          ! #################################################################################
+          ! Ice only
+          call cmp_beta(nlev,npoints,pnorm_perp_ice(1:npoints,icol,zi:zf:zinc),&
+               tautot_ice(1:npoints,icol,zi:zf:zinc),beta_perp_ice(1:npoints,icol,zi:zf:zinc))        
+          
+          ! Liquid only
+          call cmp_beta(nlev,npoints,pnorm_perp_liq(1:npoints,icol,zi:zf:zinc),&
+               tautot_liq(1:npoints,icol,zi:zf:zinc),beta_perp_liq(1:npoints,icol,zi:zf:zinc))
+          
+          ! #################################################################################
+          ! *) Perpendicular Backscatter signal
+          ! #################################################################################
+          ! Computation of the total perpendicular lidar signal (ATBperp for liq+ice)
+          ! Upper layer
+          WHERE(tautot(1:npoints,icol,1) .gt. 0)
+             pnorm_perp_tot(1:npoints,icol,1) = (beta_perp_ice(1:npoints,icol,1)+           &
+                  beta_perp_liq(1:npoints,icol,1)-                                          &
+                  (beta_mol(1:npoints,1)/(1._wp+1._wp/0.0284_wp))) /                        &
+                  (2._wp*tautot(1:npoints,icol,1))*                                         &
+                  (1._wp-exp(-2._wp*tautot(1:npoints,icol,1)))
+          ELSEWHERE
+             pnorm_perp_tot(1:npoints,icol,1) = 0._wp
+          ENDWHERE
+          
+          ! Other layers
+          do k=2,nlev
+             ! Optical thickness of layer k
+             tautot_lay(1:npoints) = tautot(1:npoints,icol,k)-tautot(1:npoints,icol,k-1) 
+             
+             ! The perpendicular component of the molecular backscattered signal (Betaperp) 
+             ! has been taken into account two times (once for liquid and once for ice). 
+             ! We remove one contribution using 
+             ! Betaperp=beta_mol(:,k)/(1+1/0.0284)) [bodhaine et al. 1999] in the following 
+             ! equations:
+             WHERE (pnorm(1:npoints,icol,k) .eq. 0)
+                pnorm_perp_tot(1:npoints,icol,k)=0._wp
+             ELSEWHERE
+                where(tautot_lay(1:npoints) .gt. 0.)
+                   pnorm_perp_tot(1:npoints,icol,k) = (beta_perp_ice(1:npoints,icol,k)+     &
+                        beta_perp_liq(1:npoints,icol,k)-(beta_mol(1:npoints,k)/(1._wp+1._wp/  &
+                        0.0284_wp)))*EXP(-2._wp*tautot(1:npoints,icol,k-1))/                  &
+                        (2._wp*tautot_lay(1:npoints))* (1._wp-EXP(-2._wp*tautot_lay(1:npoints)))
+                elsewhere
+                   pnorm_perp_tot(1:npoints,icol,k) = (beta_perp_ice(1:npoints,icol,k)+     &
+                        beta_perp_liq(1:npoints,icol,k)-(beta_mol(1:npoints,k)/(1._wp+1._wp/  &
+                        0.0284_wp)))*EXP(-2._wp*tautot(1:npoints,icol,k-1))
+                endwhere
+             ENDWHERE
+          END DO
+       enddo
+    end if
+  end subroutine lidar_subcolumn
+
+  ! ######################################################################################
+  ! SUBROUTINE lidar_column
+  ! ######################################################################################
+  subroutine lidar_column(npoints, ncol, nlevels, llm, max_bin, ntype, platform, pnorm, pmol,             &
+       pplay, zlev, zlev_half, vgrid_z, ok_lidar_cfad, ncat, cfad2, lidarcld, cldlayer,  &
+       ! Optional stuff below
+       tmp, pnorm_perp, surfelev,  lidarcldphase, lidarcldtype, cldtype, cldtypetemp, &
+       cldtypemeanz, cldtypemeanzse, cldthinemis, cldlayerphase, lidarcldtmp)
+
+    integer,parameter :: &
+         nphase = 6 ! Number of cloud layer phase types
+
+    ! Inputs
+    integer,intent(in) :: &
+         npoints, & ! Number of horizontal grid points
+         ncol,    & ! Number of subcolumns
+         nlevels, & ! Number of vertical layers (OLD grid)
+         llm,     & ! Number of vertical layers (NEW grid)
+         max_bin, & ! Number of bins for SR CFADs
+         ncat,    & ! Number of cloud layer types (low,mid,high,total) 
+         ntype      ! Number of OPAQ products (opaque/thin cloud + z_opaque)
+    character(len=*),intent(in) :: &
+         platform   ! Name of platform (e.g. calipso,atlid,grLidar532)
+    real(wp),intent(in),dimension(npoints,ncol,Nlevels) :: &
+         pnorm      ! Lidar ATB
+    real(wp),intent(in),dimension(npoints,Nlevels) :: &
+         pmol,    & ! Molecular ATB
+         pplay      ! Pressure on model levels (Pa)
+    logical,intent(in) :: &
+         ok_lidar_cfad ! True if lidar CFAD diagnostics need to be computed
+    real(wp),intent(in),dimension(npoints,nlevels) :: &
+         zlev        ! Model full levels
+    real(wp),intent(in),dimension(npoints,nlevels+1) :: &
+         zlev_half   ! Model half levels
+    real(wp),intent(in),dimension(llm) :: & 
+         vgrid_z     ! mid-level altitude of the output vertical grid
+    ! Optional Inputs
+    real(wp),intent(in),dimension(npoints,ncol,Nlevels),optional :: &
+         pnorm_perp ! Lidar perpendicular ATB
+    real(wp),intent(in),dimension(npoints),optional :: &
+         surfelev   ! Surface Elevation (m)
+    real(wp),intent(in),dimension(npoints,Nlevels),optional :: &
+         tmp        ! Temperature at each levels
+    
+    ! Outputs
+    real(wp),intent(inout),dimension(npoints,llm) :: &
+         lidarcld      ! 3D "lidar" cloud fraction
+    real(wp),intent(inout),dimension(npoints,ncat) :: &
+         cldlayer      ! "lidar" cloud layer fraction (low, mid, high, total)
+    real(wp),intent(inout),dimension(npoints,max_bin,llm) :: &
+         cfad2         ! CFADs of SR
+    ! Optional Outputs
+    real(wp),intent(out),dimension(npoints,ntype),optional :: & 
+         cldtype,    & ! "lidar" OPAQ type covers (opaque/thin cloud + z_opaque)
+         cldtypetemp   ! Opaque and thin clouds + z_opaque temperature
+    real(wp),intent(out),dimension(npoints,2),optional :: &  
+         cldtypemeanz  ! Opaque and thin clouds altitude 
+    real(wp),intent(out),dimension(npoints,3),optional :: &  
+         cldtypemeanzse ! Opaque, thin clouds and z_opaque altitude with respect to SE
+    real(wp),intent(out),dimension(npoints),optional :: &   
+         cldthinemis   ! Thin clouds emissivity computed from SR
+    real(wp),intent(out),dimension(npoints,llm,nphase),optional :: &
+         lidarcldphase ! 3D "lidar" phase cloud fraction
+    real(wp),intent(out),dimension(npoints,llm,ntype+1),optional :: & 
+         lidarcldtype ! 3D "lidar" OPAQ type fraction 
+    real(wp),intent(out),dimension(npoints,40,5),optional :: &
+         lidarcldtmp   ! 3D "lidar" phase cloud fraction as a function of temp
+    real(wp),intent(out),dimension(npoints,ncat,nphase),optional :: &
+         cldlayerphase ! "lidar" phase low mid high cloud fraction
+
+    ! Local Variables
+    integer :: ic,i,j
+    logical :: lcalipso,latlid,lgrlidar532
+    real(wp),dimension(npoints,ncol,llm) :: &
+         x3d
+    real(wp),dimension(npoints,llm) :: &
+         x3d_c,pnorm_c
+    real(wp)  :: &
+         xmax
+    real(wp),dimension(npoints,1,Nlevels) :: t_in,ph_in,betamol_in
+    real(wp),dimension(npoints,ncol,llm)  :: pnormFlip,pnorm_perpFlip
+    real(wp),dimension(npoints,1,llm)     :: tmpFlip,pplayFlip,betamolFlip
+    real(wp),dimension(SR_BINS+1)         :: histBsct
+    
+    ! Which lidar platform?
+    lcalipso = .false.
+    latlid = .false.
+    lgrlidar532 = .false.
+    if (platform .eq. 'calipso') lcalipso=.true.
+    if (platform .eq. 'atlid') latlid=.true.
+    if (platform .eq. 'grlidar532') lgrlidar532=.true.
+        
+    ! Vertically regrid input data
+    if (use_vgrid) then 
+       ph_in(:,1,:) = pplay(:,nlevels:1:-1)
+       call cosp_change_vertical_grid(Npoints,1,Nlevels,zlev(:,nlevels:1:-1),zlev_half(:,nlevels:1:-1),&
+            ph_in,llm,vgrid_zl(llm:1:-1),vgrid_zu(llm:1:-1),pplayFlip(:,1,llm:1:-1))
+       betamol_in(:,1,:) = pmol(:,nlevels:1:-1)
+       call cosp_change_vertical_grid(Npoints,1,Nlevels,zlev(:,nlevels:1:-1),zlev_half(:,nlevels:1:-1),&
+            betamol_in,llm,vgrid_zl(llm:1:-1),vgrid_zu(llm:1:-1),betamolFlip(:,1,llm:1:-1))
+       call cosp_change_vertical_grid(Npoints,Ncol,Nlevels,zlev(:,nlevels:1:-1),zlev_half(:,nlevels:1:-1),&
+            pnorm(:,:,nlevels:1:-1),llm,vgrid_zl(llm:1:-1),vgrid_zu(llm:1:-1),pnormFlip(:,:,llm:1:-1))
+       if (lcalipso) then
+          t_in(:,1,:)=tmp(:,nlevels:1:-1)
+          call cosp_change_vertical_grid(Npoints,1,Nlevels,zlev(:,nlevels:1:-1),zlev_half(:,nlevels:1:-1),&
+               t_in,llm,vgrid_zl(llm:1:-1),vgrid_zu(llm:1:-1),tmpFlip(:,1,llm:1:-1))
+          call cosp_change_vertical_grid(Npoints,Ncol,Nlevels,zlev(:,nlevels:1:-1),zlev_half(:,nlevels:1:-1),&
+               pnorm_perp(:,:,nlevels:1:-1),llm,vgrid_zl(llm:1:-1),vgrid_zu(llm:1:-1),pnorm_perpFlip(:,:,llm:1:-1))
+       endif
+    endif
+
+    ! Initialization (The histogram bins, are set up during initialization and the
+    ! maximum value is used as the upper bounds.)
+    if (lcalipso)    then
+       xmax = maxval(calipso_histBsct)
+       histBsct = calipso_histBsct
+    endif
+    if (latlid)      then
+       xmax = maxval(atlid_histBsct)
+       histBsct = atlid_histBsct
+    endif
+    if (lgrlidar532) then
+       xmax = maxval(grLidar532_histBsct)
+       histBsct = grLidar532_histBsct
+    endif
+       
+    ! Compute LIDAR scattering ratio
+    if (use_vgrid) then
+       do ic = 1, ncol
+          pnorm_c = pnormFlip(:,ic,:)
+          where ((pnorm_c .lt. xmax) .and. (betamolFlip(:,1,:) .lt. xmax) .and.          &
+                (betamolFlip(:,1,:) .gt. 0.0 ))
+             x3d_c = pnorm_c/betamolFlip(:,1,:)
+          elsewhere
+             x3d_c = R_UNDEF
+          end where
+          x3d(:,ic,:) = x3d_c
+       enddo
+       if (lcalipso) then
+          ! Diagnose cloud fractions for subcolumn lidar scattering ratios
+          CALL COSP_CLDFRAC(npoints,ncol,llm,ncat,nphase,tmpFlip,x3d,pnormFlip,pnorm_perpFlip,&
+               pplayFlip,S_att,S_cld,S_cld_att,R_UNDEF,lidarcld,cldlayer,lidarcldphase,&
+               cldlayerphase,lidarcldtmp)                         
+
+          ! Calipso opaque cloud diagnostics
+          CALL COSP_OPAQ(npoints,ncol,llm,ntype,tmpFlip,x3d,S_att,S_cld,R_UNDEF,lidarcldtype, &
+               cldtype,cldtypetemp,cldtypemeanz,cldtypemeanzse,cldthinemis,vgrid_z,surfelev)
+       endif
+       if (latlid) then
+          CALL COSP_CLDFRAC_NOPHASE(npoints,ncol,llm,ncat,x3d,pnormFlip,pplayFlip,  &
+               S_att_atlid,S_cld_atlid,S_cld_att_atlid,R_UNDEF,lidarcld,cldlayer)   
+       endif
+       if (lgrLidar532) then
+          CALL COSP_CLDFRAC_NOPHASE(npoints,ncol,llm,ncat,x3d,pnormFlip,pplayFlip,  &
+               S_att,S_cld,S_cld_att,R_UNDEF,lidarcld,cldlayer)
+       endif
+    else
+       do ic = 1, ncol
+          pnorm_c = pnorm(:,ic,:)
+          where ((pnorm_c.lt.xmax) .and. (pmol.lt.xmax) .and. (pmol.gt. 0.0 ))
+             x3d_c = pnorm_c/pmol
+          elsewhere
+             x3d_c = R_UNDEF
+          end where
+          x3d(:,ic,:) = x3d_c
+       enddo
+       if (lcalipso) then
+          ! Diagnose cloud fractions for subcolumn lidar scattering ratios
+          CALL COSP_CLDFRAC(npoints,ncol,nlevels,ncat,nphase,tmp,x3d,pnorm,pnorm_perp,pplay,&
+               S_att,S_cld,S_cld_att,R_UNDEF,lidarcld,cldlayer,lidarcldphase,  &
+               cldlayerphase,lidarcldtmp)
+          ! Calipso opaque cloud diagnostics
+          CALL COSP_OPAQ(npoints,ncol,nlevels,ntype,tmp,x3d,S_att,S_cld,R_UNDEF,lidarcldtype, &
+               cldtype,cldtypetemp,cldtypemeanz,cldtypemeanzse,cldthinemis,vgrid_z,surfelev)
+       endif
+       if (latlid) then
+          CALL COSP_CLDFRAC_NOPHASE(npoints,ncol,nlevels,ncat,x3d,pnorm,pplay,  &
+               S_att_atlid,S_cld_atlid,S_cld_att_atlid, R_UNDEF,lidarcld,cldlayer)
+       endif
+       if (lgrlidar532) then
+          CALL COSP_CLDFRAC_NOPHASE(npoints,ncol,nlevels,ncat,x3d,pnorm,pplay,      &
+               S_att,S_cld,S_cld_att,R_UNDEF,lidarcld,cldlayer)
+       endif
+    endif
+
+    ! CFADs
+    if (ok_lidar_cfad) then
+       ! CFADs of subgrid-scale lidar scattering ratios
+       do i=1,Npoints
+          do j=1,llm
+             cfad2(i,:,j) = hist1D(ncol,x3d(i,:,j),SR_BINS,histBsct)
+          enddo
+       enddo
+       where(cfad2 .ne. R_UNDEF) cfad2=cfad2/ncol
+    endif 
+    
+    ! Unit conversions
+    where(lidarcld /= R_UNDEF)      lidarcld      = lidarcld*100._wp
+    where(cldlayer /= R_UNDEF)      cldlayer      = cldlayer*100._wp
+    if (lcalipso) then
+       where(cldtype(:,1) /= R_UNDEF)  cldtype(:,1)  = cldtype(:,1)*100._wp
+       where(cldtype(:,2) /= R_UNDEF)  cldtype(:,2)  = cldtype(:,2)*100._wp
+       where(cldlayerphase /= R_UNDEF) cldlayerphase = cldlayerphase*100._wp
+       where(lidarcldphase /= R_UNDEF) lidarcldphase = lidarcldphase*100._wp
+       where(lidarcldtype /= R_UNDEF)  lidarcldtype  = lidarcldtype*100._wp
+       where(lidarcldtmp /= R_UNDEF)   lidarcldtmp   = lidarcldtmp*100._wp
+    endif
+  end subroutine lidar_column
+
+  ! ######################################################################################
+  ! The subroutines below compute the attenuated backscatter signal and the lidar 
+  ! backscatter coefficients using eq (1) from doi:0094-8276/08/2008GL034207
+  ! ######################################################################################
+  subroutine cmp_backsignal(nlev,npoints,beta,tau,pnorm)
+    ! INPUTS
+    integer, intent(in) :: nlev,npoints
+    real(wp),intent(in),dimension(npoints,nlev) :: beta,tau
+
+    ! OUTPUTS
+    real(wp),intent(out),dimension(npoints,nlev) :: pnorm
+
+    ! Internal Variables
+    real(wp), dimension(npoints) :: tautot_lay
+    integer :: k
+
+    ! Uppermost layer 
+    pnorm(:,1) = beta(:,1) / (2._wp*tau(:,1)) * (1._wp-exp(-2._wp*tau(:,1)))
+
+    ! Other layers
+    do k=2,nlev
+       tautot_lay(:) = tau(:,k)-tau(:,k-1) 
+       WHERE (tautot_lay(:) .gt. 0.)
+          pnorm(:,k) = beta(:,k)*EXP(-2._wp*tau(:,k-1)) /&
+               (2._wp*tautot_lay(:))*(1._wp-EXP(-2._wp*tautot_lay(:)))
+       ELSEWHERE
+          ! This must never happen, but just in case, to avoid div. by 0
+          pnorm(:,k) = beta(:,k) * EXP(-2._wp*tau(:,k-1))
+       END WHERE
+
+    END DO
+  end subroutine cmp_backsignal
+
+  subroutine cmp_beta(nlev,npoints,pnorm,tau,beta)
+    ! INPUTS
+    integer, intent(in) :: nlev,npoints
+    real(wp),intent(in),dimension(npoints,nlev) :: pnorm,tau
+
+    ! OUTPUTS
+    real(wp),intent(out),dimension(npoints,nlev) :: beta
+
+    ! Internal Variables
+    real(wp), dimension(npoints) :: tautot_lay
+    integer :: k
+    real(wp) :: epsrealwp
+
+    epsrealwp = epsilon(1._wp)
+    beta(:,1) = pnorm(:,1) * (2._wp*tau(:,1))/(1._wp-exp(-2._wp*tau(:,1)))
+    do k=2,nlev
+       tautot_lay(:) = tau(:,k)-tau(:,k-1)       
+       WHERE ( EXP(-2._wp*tau(:,k-1)) .gt. epsrealwp )
+          WHERE (tautot_lay(:) .gt. 0.)
+             beta(:,k) = pnorm(:,k)/ EXP(-2._wp*tau(:,k-1))* &
+                  (2._wp*tautot_lay(:))/(1._wp-exp(-2._wp*tautot_lay(:)))
+          ELSEWHERE
+             beta(:,k)=pnorm(:,k)/EXP(-2._wp*tau(:,k-1))
+          END WHERE
+       ELSEWHERE
+          beta(:,k)=pnorm(:,k)/epsrealwp
+       END WHERE
+    ENDDO
+
+  end subroutine cmp_beta
+    ! ####################################################################################
+    ! SUBROUTINE cosp_cldfrac
+    ! Conventions: Ncat must be equal to 4
+    ! ####################################################################################
+    SUBROUTINE COSP_CLDFRAC(Npoints,Ncolumns,Nlevels,Ncat,Nphase,tmp,x,ATB,ATBperp,      &
+                               pplay,S_att,S_cld,S_cld_att,undef,lidarcld,cldlayer,      &
+                               lidarcldphase,cldlayerphase,lidarcldtemp)
+    ! Parameters
+    integer,parameter :: Ntemp=40 ! indice of the temperature vector
+    real(wp),parameter,dimension(Ntemp+1) :: &
+       tempmod = [0.0,   183.15,186.15,189.15,192.15,195.15,198.15,201.15,204.15,207.15, &
+                  210.15,213.15,216.15,219.15,222.15,225.15,228.15,231.15,234.15,237.15, &
+                  240.15,243.15,246.15,249.15,252.15,255.15,258.15,261.15,264.15,267.15, &
+                  270.15,273.15,276.15,279.15,282.15,285.15,288.15,291.15,294.15,297.15, &
+                  473.15]
+         
+    ! Polynomial coefficient of the phase discrimination line used to separate liquid from ice
+    ! (Cesana and Chepfer, JGR, 2013)
+    ! ATBperp = ATB^5*alpha50 + ATB^4*beta50 + ATB^3*gamma50 + ATB^2*delta50 + ATB*epsilon50 + zeta50
+    real(wp),parameter :: &
+       alpha50   = 9.0322e+15_wp,  & !
+       beta50    = -2.1358e+12_wp, & !
+       gamma50   = 173.3963e06_wp, & !
+       delta50   = -3.9514e03_wp,  & !
+       epsilon50 = 0.2559_wp,      & !
+       zeta50    = -9.4776e-07_wp    ! 
+       
+	! Inputs
+    integer,intent(in) :: &
+       Npoints,  & ! Number of gridpoints
+       Ncolumns, & ! Number of subcolumns
+       Nlevels,  & ! Number of vertical levels
+       Ncat,     & ! Number of cloud layer types
+       Nphase      ! Number of cloud layer phase types
+	               ! [ice,liquid,undefined,false ice,false liquid,Percent of ice]
+    real(wp),intent(in) :: &
+       S_att,    & !
+       S_cld,    & !
+       S_cld_att,& ! New threshold for undefine cloud phase detection
+       undef       ! Undefined value
+    real(wp),intent(in),dimension(Npoints,Ncolumns,Nlevels) :: &
+       x,        & ! 
+       ATB,      & ! 3D attenuated backscatter
+       ATBperp     ! 3D attenuated backscatter (perpendicular)
+    real(wp),intent(in),dimension(Npoints,Nlevels) :: &
+       tmp,      & ! Temperature   
+       pplay       ! Pressure
+
+	! Outputs
+    real(wp),intent(out),dimension(Npoints,Ntemp,5) :: &
+       lidarcldtemp  ! 3D Temperature 1=tot,2=ice,3=liq,4=undef,5=ice/ice+liq
+    real(wp),intent(out),dimension(Npoints,Nlevels,Nphase) :: &
+       lidarcldphase ! 3D cloud phase fraction
+    real(wp),intent(out),dimension(Npoints,Nlevels) :: &
+       lidarcld      ! 3D cloud fraction
+    real(wp),intent(out),dimension(Npoints,Ncat) :: &
+       cldlayer      ! Low, middle, high, total cloud fractions
+    real(wp),intent(out),dimension(Npoints,Ncat,Nphase) :: &
+       cldlayerphase ! Low, middle, high, total cloud fractions for ice liquid and undefine phase    
+    
+    ! Local variables
+    integer  :: &
+       ip, k, iz, ic, ncol, nlev, i, itemp, toplvlsat 
+    real(wp) :: &
+       p1,checktemp, ATBperp_tmp,checkcldlayerphase, checkcldlayerphase2
+    real(wp),dimension(Npoints,Nlevels) :: &
+       nsub,lidarcldphasetmp   
+    real(wp),dimension(Npoints,Ntemp) :: &
+       sumlidarcldtemp,lidarcldtempind
+    real(wp),dimension(Npoints,Ncolumns,Ncat) :: &
+       cldlay,nsublay   
+    real(wp),dimension(Npoints,Ncat) :: &
+       nsublayer,cldlayerphasetmp,cldlayerphasesum
+    real(wp),dimension(Npoints,Ncolumns,Nlevels) :: &   
+       tmpi, & ! Temperature of ice cld
+       tmpl, & ! Temperature of liquid cld
+       tmpu, & ! Temperature of undef cld
+       cldy, & ! 
+       srok    !
+    real(wp),dimension(Npoints,Ncolumns,Ncat,Nphase) :: &
+       cldlayphase ! subgrided low mid high phase cloud fraction
+             
+    ! ####################################################################################
+	! 1) Initialize    
+    ! ####################################################################################
+    lidarcld              = 0._wp
+    nsub                  = 0._wp
+    cldlay                = 0._wp
+    nsublay               = 0._wp
+    ATBperp_tmp           = 0._wp
+    lidarcldphase(:,:,:)  = 0._wp
+    cldlayphase(:,:,:,:)  = 0._wp
+    cldlayerphase(:,:,:)  = 0._wp
+    tmpi(:,:,:)           = 0._wp
+    tmpl(:,:,:)           = 0._wp
+    tmpu(:,:,:)           = 0._wp
+    cldlayerphasesum(:,:) = 0._wp
+    lidarcldtemp(:,:,:)   = 0._wp
+    lidarcldtempind(:,:)  = 0._wp
+    sumlidarcldtemp(:,:)  = 0._wp
+    lidarcldphasetmp(:,:) = 0._wp
+    toplvlsat             = 0
+
+    ! ####################################################################################
+    ! 2) Cloud detection
+    ! ####################################################################################
+    do k=1,Nlevels
+       ! Cloud detection at subgrid-scale:
+       where ((x(:,:,k) .gt. S_cld) .and. (x(:,:,k) .ne. undef) )
+          cldy(:,:,k)=1._wp
+       elsewhere
+          cldy(:,:,k)=0._wp
+       endwhere
+       
+       ! Number of usefull sub-columns:
+       where ((x(:,:,k) .gt. S_att) .and. (x(:,:,k) .ne. undef) )
+          srok(:,:,k)=1._wp
+       elsewhere
+          srok(:,:,k)=0._wp
+       endwhere
+    enddo    
+    
+    ! ####################################################################################
+    ! 3) Grid-box 3D cloud fraction and layered cloud fractions(ISCCP pressure categories)
+    ! ####################################################################################
+    lidarcld = 0._wp
+    nsub     = 0._wp
+    cldlay   = 0._wp
+    nsublay  = 0._wp
+    do k=1,Nlevels
+       do ic = 1, Ncolumns
+          do ip = 1, Npoints
+          
+             ! Computation of the cloud fraction as a function of the temperature instead
+             ! of height, for ice,liquid and all clouds
+             if(srok(ip,ic,k).gt.0.)then
+                do itemp=1,Ntemp
+                   if( (tmp(ip,k).ge.tempmod(itemp)).and.(tmp(ip,k).lt.tempmod(itemp+1)) )then
+                      lidarcldtempind(ip,itemp)=lidarcldtempind(ip,itemp)+1._wp
+                   endif
+                enddo
+             endif
+             
+             if(cldy(ip,ic,k).eq.1.)then
+                do itemp=1,Ntemp 
+                   if( (tmp(ip,k) .ge. tempmod(itemp)).and.(tmp(ip,k) .lt. tempmod(itemp+1)) )then
+                      lidarcldtemp(ip,itemp,1)=lidarcldtemp(ip,itemp,1)+1._wp
+                   endif
+                enddo
+             endif
+
+             iz=1
+             p1 = pplay(ip,k)
+             if ( p1.gt.0. .and. p1.lt.(440._wp*100._wp)) then ! high clouds
+                iz=3
+             else if(p1.ge.(440._wp*100._wp) .and. p1.lt.(680._wp*100._wp)) then ! mid clouds
+                iz=2
+             endif
+             
+             cldlay(ip,ic,iz) = MAX(cldlay(ip,ic,iz),cldy(ip,ic,k))
+             cldlay(ip,ic,4)  = MAX(cldlay(ip,ic,4),cldy(ip,ic,k))
+             lidarcld(ip,k)   = lidarcld(ip,k) + cldy(ip,ic,k)
+             
+             nsublay(ip,ic,iz) = MAX(nsublay(ip,ic,iz),srok(ip,ic,k))
+             nsublay(ip,ic,4)  = MAX(nsublay(ip,ic,4),srok(ip,ic,k))
+             nsub(ip,k)        = nsub(ip,k) + srok(ip,ic,k)
+             
+          enddo
+       enddo
+    enddo   
+    
+    ! Grid-box 3D cloud fraction
+    where ( nsub(:,:).gt.0.0 )
+       lidarcld(:,:) = lidarcld(:,:)/nsub(:,:)
+    elsewhere
+       lidarcld(:,:) = undef
+    endwhere
+    
+    ! Layered cloud fractions
+    cldlayer  = 0._wp
+    nsublayer = 0._wp
+    do iz = 1, Ncat
+       do ic = 1, Ncolumns
+          cldlayer(:,iz)  = cldlayer(:,iz)  + cldlay(:,ic,iz)
+          nsublayer(:,iz) = nsublayer(:,iz) + nsublay(:,ic,iz)
+       enddo
+    enddo
+    where (nsublayer(:,:) .gt. 0.0)
+       cldlayer(:,:) = cldlayer(:,:)/nsublayer(:,:)
+    elsewhere
+       cldlayer(:,:) = undef
+    endwhere
+              
+    ! ####################################################################################
+    ! 4) Grid-box 3D cloud Phase
+    ! ####################################################################################
+    
+    ! ####################################################################################
+    ! 4.1) For Cloudy pixels with 8.16km < z < 19.2km
+    ! ####################################################################################
+    do ncol=1,Ncolumns
+       do i=1,Npoints          
+          do nlev=1,23 ! from 19.2km until 8.16km
+               p1 = pplay(1,nlev)
+
+             ! Avoid zero values
+             if( (cldy(i,ncol,nlev).eq.1.) .and. (ATBperp(i,ncol,nlev).gt.0.) )then
+                ! Computation of the ATBperp along the phase discrimination line
+                ATBperp_tmp = (ATB(i,ncol,nlev)**5)*alpha50 + (ATB(i,ncol,nlev)**4)*beta50 + &
+                     (ATB(i,ncol,nlev)**3)*gamma50 + (ATB(i,ncol,nlev)**2)*delta50 + &
+                     ATB(i,ncol,nlev)*epsilon50 + zeta50     
+                ! ########################################################################
+                ! 4.1.a) Ice: ATBperp above the phase discrimination line
+                ! ########################################################################
+                if((ATBperp(i,ncol,nlev)-ATBperp_tmp) .ge. 0.)then ! Ice clouds
+
+                   ! ICE with temperature above 273,15°K = Liquid (false ice)
+                   if(tmp(i,nlev) .gt. 273.15) then ! Temperature above 273,15 K
+                     ! Liquid: False ice corrected by the temperature to Liquid
+                      lidarcldphase(i,nlev,2) = lidarcldphase(i,nlev,2)+1._wp ! False ice detection ==> added to Liquid
+                                    
+                      tmpl(i,ncol,nlev)       = tmp(i,nlev)
+                      lidarcldphase(i,nlev,5) = lidarcldphase(i,nlev,5)+1._wp ! Keep the information "temperature criterium used"                      
+                                                                              ! to classify the phase cloud
+                      cldlayphase(i,ncol,4,2) = 1. ! tot cloud
+                      if (p1 .gt. 0. .and. p1.lt.(440._wp*100._wp)) then ! high cloud
+                         cldlayphase(i,ncol,3,2) = 1._wp
+                      else if(p1 .ge. (440._wp*100._wp) .and. p1 .lt. (680._wp*100._wp)) then ! mid cloud
+                         cldlayphase(i,ncol,2,2) = 1._wp
+                      else ! low cloud
+                         cldlayphase(i,ncol,1,2) = 1._wp
+                      endif
+                      cldlayphase(i,ncol,4,5) = 1._wp ! tot cloud
+                      ! High cloud
+                      if (p1 .gt. 0. .and. p1 .lt. (440._wp*100._wp)) then 
+                         cldlayphase(i,ncol,3,5) = 1._wp
+                      ! Middle cloud
+                      else if(p1 .ge. (440._wp*100._wp) .and. p1 .lt. (680._wp*100._wp)) then
+                         cldlayphase(i,ncol,2,5) = 1._wp
+                      ! Low cloud
+                      else 
+                         cldlayphase(i,ncol,1,5) = 1._wp
+                      endif
+                   else
+                      ! ICE with temperature below 273,15°K
+                      lidarcldphase(i,nlev,1) = lidarcldphase(i,nlev,1)+1._wp
+                      tmpi(i,ncol,nlev)       = tmp(i,nlev)
+                      cldlayphase(i,ncol,4,1) = 1._wp ! tot cloud 
+                      ! High cloud
+                      if (p1 .gt. 0. .and. p1 .lt. (440._wp*100._wp)) then 
+                         cldlayphase(i,ncol,3,1) = 1._wp
+                      ! Middle cloud   
+                      else if(p1 .ge. (440._wp*100._wp) .and. p1 .lt. (680._wp*100._wp)) then 
+                         cldlayphase(i,ncol,2,1) = 1._wp
+                      ! Low cloud
+                      else
+                         cldlayphase(i,ncol,1,1) = 1._wp
+                      endif
+                   endif
+                ! ########################################################################
+                ! 4.1.b) Liquid: ATBperp below the phase discrimination line
+                ! ########################################################################
+                else
+                   ! Liquid with temperature above 231,15°K
+                   if(tmp(i,nlev) .gt. 231.15_wp) then
+                      lidarcldphase(i,nlev,2) = lidarcldphase(i,nlev,2)+1._wp
+                      tmpl(i,ncol,nlev)       = tmp(i,nlev)
+                      cldlayphase(i,ncol,4,2) = 1._wp ! tot cloud
+                      ! High cloud
+                      if (p1 .gt. 0. .and. p1 .lt. (440._wp*100._wp)) then
+                         cldlayphase(i,ncol,3,2) = 1._wp
+                      ! Middle cloud   
+                      else if(p1 .ge. (440._wp*100._wp) .and. p1 .lt. (680._wp*100._wp)) then
+                         cldlayphase(i,ncol,2,2) = 1._wp
+                      ! Low cloud   
+                      else
+                         cldlayphase(i,ncol,1,2) = 1._wp
+                      endif
+                   else
+                      ! Liquid with temperature below 231,15°K = Ice (false liquid)
+                      tmpi(i,ncol,nlev)       = tmp(i,nlev)
+                      lidarcldphase(i,nlev,1) = lidarcldphase(i,nlev,1)+1._wp ! false liquid detection ==> added to ice
+                      lidarcldphase(i,nlev,4) = lidarcldphase(i,nlev,4)+1._wp
+                      cldlayphase(i,ncol,4,4) = 1._wp ! tot cloud
+                      ! High cloud
+                      if (p1 .gt. 0. .and. p1 .lt. (440._wp*100._wp)) then
+                         cldlayphase(i,ncol,3,4) = 1._wp
+                      ! Middle cloud   
+                      else if(p1 .ge. (440._wp*100._wp) .and. p1 .lt. (680._wp*100._wp)) then
+                         cldlayphase(i,ncol,2,4) = 1._wp
+                      ! Low cloud
+                      else
+                         cldlayphase(i,ncol,1,4) = 1._wp
+                      endif
+                      cldlayphase(i,ncol,4,1) = 1._wp ! tot cloud
+                      ! High cloud
+                      if (p1 .gt. 0. .and. p1 .lt. (440._wp*100._wp)) then
+                         cldlayphase(i,ncol,3,1) = 1._wp
+                      ! Middle cloud   
+                      else if(p1 .ge. (440._wp*100._wp) .and. p1 .lt. (680._wp*100._wp)) then
+                         cldlayphase(i,ncol,2,1) = 1._wp
+                      ! Low cloud   
+                      else
+                         cldlayphase(i,ncol,1,1) = 1._wp
+                      endif
+                   endif
+                endif ! end of discrimination condition
+             endif ! end of cloud condition
+          enddo ! end of altitude loop
+
+          ! ##############################################################################
+          ! 4.2) For Cloudy pixels with 0km < z < 8.16km
+          ! ##############################################################################
+          toplvlsat = 0
+          do nlev=24,Nlevels! from 8.16km until 0km
+             p1 = pplay(i,nlev)
+
+             if((cldy(i,ncol,nlev) .eq. 1.) .and. (ATBperp(i,ncol,nlev) .gt. 0.) )then
+                ! Computation of the ATBperp of the phase discrimination line
+                ATBperp_tmp = (ATB(i,ncol,nlev)**5)*alpha50 + (ATB(i,ncol,nlev)**4)*beta50 + &
+                     (ATB(i,ncol,nlev)**3)*gamma50 + (ATB(i,ncol,nlev)**2)*delta50 + &
+                     ATB(i,ncol,nlev)*epsilon50 + zeta50
+                ! ########################################################################
+                ! 4.2.a) Ice: ATBperp above the phase discrimination line
+                ! ########################################################################
+                ! ICE with temperature above 273,15°K = Liquid (false ice)
+                if((ATBperp(i,ncol,nlev)-ATBperp_tmp) .ge. 0.)then ! Ice clouds
+                   if(tmp(i,nlev) .gt. 273.15)then
+                      lidarcldphase(i,nlev,2) = lidarcldphase(i,nlev,2)+1._wp ! false ice ==> liq
+                      tmpl(i,ncol,nlev)       = tmp(i,nlev)
+                      lidarcldphase(i,nlev,5) = lidarcldphase(i,nlev,5)+1._wp
+                      cldlayphase(i,ncol,4,2) = 1._wp ! tot cloud
+                      ! High cloud
+                      if (p1 .gt. 0. .and. p1 .lt. (440._wp*100._wp)) then 
+                         cldlayphase(i,ncol,3,2) = 1._wp
+                      ! Middle cloud   
+                      else if(p1 .ge. (440._wp*100._wp) .and. p1 .lt. (680._wp*100._wp)) then 
+                         cldlayphase(i,ncol,2,2) = 1._wp
+                      ! Low cloud
+                      else 
+                         cldlayphase(i,ncol,1,2) = 1._wp
+                      endif
+                      
+                      cldlayphase(i,ncol,4,5) = 1. ! tot cloud
+                      ! High cloud
+                      if (p1 .gt. 0. .and. p1 .lt. (440._wp*100._wp)) then
+                         cldlayphase(i,ncol,3,5) = 1._wp
+                      ! Middle cloud   
+                      else if(p1 .ge. (440._wp*100._wp) .and. p1 .lt. (680._wp*100._wp)) then
+                         cldlayphase(i,ncol,2,5) = 1._wp
+                      ! Low cloud   
+                      else
+                         cldlayphase(i,ncol,1,5) = 1._wp
+                      endif
+                   else
+                      ! ICE with temperature below 273,15°K
+                      lidarcldphase(i,nlev,1) = lidarcldphase(i,nlev,1)+1._wp
+                     tmpi(i,ncol,nlev)       = tmp(i,nlev)
+                      cldlayphase(i,ncol,4,1) = 1._wp ! tot cloud
+                      ! High cloud
+                      if (p1 .gt. 0. .and. p1 .lt. (440._wp*100._wp)) then
+                         cldlayphase(i,ncol,3,1) = 1._wp
+                      ! Middle cloud   
+                      else if(p1 .ge. (440._wp*100._wp) .and. p1 .lt.(680._wp*100._wp)) then
+                         cldlayphase(i,ncol,2,1) = 1._wp
+                      ! Low cloud   
+                      else
+                         cldlayphase(i,ncol,1,1) = 1._wp
+                      endif
+                   endif
+                   
+                ! ########################################################################
+                ! 4.2.b) Liquid: ATBperp below the phase discrimination line
+                ! ########################################################################
+                else
+                   ! Liquid with temperature above 231,15°K
+                   if(tmp(i,nlev) .gt. 231.15)then
+                      lidarcldphase(i,nlev,2) = lidarcldphase(i,nlev,2)+1._wp
+                      tmpl(i,ncol,nlev)       = tmp(i,nlev)
+                      cldlayphase(i,ncol,4,2) = 1._wp ! tot cloud
+                      ! High cloud
+                      if (p1 .gt. 0. .and. p1 .lt. (440._wp*100._wp)) then
+                         cldlayphase(i,ncol,3,2) = 1._wp
+                      ! Middle cloud   
+                      else if(p1 .ge. (440._wp*100._wp) .and. p1 .lt. (680._wp*100._wp)) then
+                         cldlayphase(i,ncol,2,2) = 1._wp
+                      ! Low cloud   
+                      else
+                         cldlayphase(i,ncol,1,2) = 1._wp
+                      endif
+                   else
+                      ! Liquid with temperature below 231,15°K = Ice (false liquid)
+                      tmpi(i,ncol,nlev)       = tmp(i,nlev)
+                      lidarcldphase(i,nlev,1) = lidarcldphase(i,nlev,1)+1._wp ! false liq ==> ice
+                      lidarcldphase(i,nlev,4) = lidarcldphase(i,nlev,4)+1._wp ! false liq ==> ice
+                      cldlayphase(i,ncol,4,4) = 1._wp ! tot cloud
+                      ! High cloud
+                      if (p1 .gt. 0. .and. p1 .lt. (440._wp*100._wp)) then
+                         cldlayphase(i,ncol,3,4) = 1._wp
+                      ! Middle   
+                      else if(p1 .ge. (440._wp*100._wp) .and. p1 .lt. (680._wp*100._wp)) then
+                         cldlayphase(i,ncol,2,4) = 1._wp
+                      ! Low cloud   
+                      else
+                         cldlayphase(i,ncol,1,4) = 1._wp
+                      endif
+                      
+                      cldlayphase(i,ncol,4,1) = 1._wp ! tot cloud
+                      ! High cloud
+                      if (p1 .gt. 0. .and. p1 .lt. (440._wp*100._wp)) then
+                         cldlayphase(i,ncol,3,1) = 1._wp
+                      ! Middle cloud   
+                      else if(p1 .ge. (440._wp*100._wp) .and. p1 .lt. (680._wp*100._wp)) then
+                         cldlayphase(i,ncol,2,1) = 1._wp
+                      ! Low cloud   
+                      else
+                         cldlayphase(i,ncol,1,1) = 1._wp
+                      endif
+                   endif
+                endif ! end of discrimination condition
+                
+                toplvlsat=0
+                
+                ! Find the level of the highest cloud with SR>30
+                if(x(i,ncol,nlev) .gt. S_cld_att) then ! SR > 30.
+                    toplvlsat = nlev+1
+                    goto 99
+                endif
+             endif ! end of cloud condition
+          enddo ! end of altitude loop
+99        continue
+          
+          ! ##############################################################################
+          ! Undefined phase: For a cloud located below another cloud with SR>30
+          ! see Cesana and Chepfer 2013 Sect.III.2
+          ! ##############################################################################
+          if(toplvlsat.ne.0) then
+             do nlev = toplvlsat,Nlevels
+                p1 = pplay(i,nlev)
+                if(cldy(i,ncol,nlev).eq.1.)then
+                   lidarcldphase(i,nlev,3) = lidarcldphase(i,nlev,3)+1._wp
+                   tmpu(i,ncol,nlev)       = tmp(i,nlev)
+                   cldlayphase(i,ncol,4,3) = 1._wp ! tot cloud
+                   ! High cloud
+                   if (p1 .gt. 0. .and. p1 .lt. (440._wp*100._wp)) then
+                      cldlayphase(i,ncol,3,3) = 1._wp
+                   ! Middle cloud   
+                   else if(p1 .ge. (440._wp*100._wp) .and. p1 .lt. (680._wp*100._wp)) then
+                      cldlayphase(i,ncol,2,3) = 1._wp
+                   ! Low cloud   
+                   else
+                      cldlayphase(i,ncol,1,3) = 1._wp
+                   endif
+                endif
+             enddo
+          endif
+          toplvlsat=0
+       enddo
+    enddo
+     
+    ! ####################################################################################
+    ! Computation of final cloud phase diagnosis
+    ! ####################################################################################
+
+    ! Compute the Ice percentage in cloud = ice/(ice+liq) as a function of the occurrences
+    lidarcldphasetmp(:,:) = lidarcldphase(:,:,1)+lidarcldphase(:,:,2);
+    WHERE (lidarcldphasetmp(:,:) .gt. 0.)
+       lidarcldphase(:,:,6)=lidarcldphase(:,:,1)/lidarcldphasetmp(:,:)
+    ELSEWHERE
+       lidarcldphase(:,:,6) = undef
+    ENDWHERE
+    
+    ! Compute Phase 3D Cloud Fraction
+    !WHERE (nsub(:,Nlevels:1:-1) .gt. 0.0 )
+    WHERE (nsub(:,:) .gt. 0.0 )  
+       lidarcldphase(:,:,1)=lidarcldphase(:,:,1)/nsub(:,:)
+       lidarcldphase(:,:,2)=lidarcldphase(:,:,2)/nsub(:,:)
+       lidarcldphase(:,:,3)=lidarcldphase(:,:,3)/nsub(:,:)
+       lidarcldphase(:,:,4)=lidarcldphase(:,:,4)/nsub(:,:)
+       lidarcldphase(:,:,5)=lidarcldphase(:,:,5)/nsub(:,:)
+    ELSEWHERE
+       lidarcldphase(:,:,1) = undef
+       lidarcldphase(:,:,2) = undef
+       lidarcldphase(:,:,3) = undef
+       lidarcldphase(:,:,4) = undef
+       lidarcldphase(:,:,5) = undef
+    ENDWHERE
+
+    ! Compute Phase low mid high cloud fractions
+    do iz = 1, Ncat
+       do i=1,Nphase-3
+          do ic = 1, Ncolumns
+             cldlayerphase(:,iz,i)  = cldlayerphase(:,iz,i)  + cldlayphase(:,ic,iz,i)
+             cldlayerphasesum(:,iz) = cldlayerphasesum(:,iz) + cldlayphase(:,ic,iz,i)
+          enddo
+       enddo
+    enddo
+    do iz = 1, Ncat
+       do i=4,5
+          do ic = 1, Ncolumns
+             cldlayerphase(:,iz,i) = cldlayerphase(:,iz,i) + cldlayphase(:,ic,iz,i)
+          enddo
+       enddo
+    enddo
+    
+    ! Compute the Ice percentage in cloud = ice/(ice+liq)
+    cldlayerphasetmp(:,:)=cldlayerphase(:,:,1)+cldlayerphase(:,:,2)
+    WHERE (cldlayerphasetmp(:,:).gt. 0.)
+       cldlayerphase(:,:,6)=cldlayerphase(:,:,1)/cldlayerphasetmp(:,:)
+    ELSEWHERE
+       cldlayerphase(:,:,6) = undef
+    ENDWHERE
+    
+    do i=1,Nphase-1
+       WHERE ( cldlayerphasesum(:,:).gt.0.0 )
+          cldlayerphase(:,:,i) = (cldlayerphase(:,:,i)/cldlayerphasesum(:,:)) * cldlayer(:,:)
+       ENDWHERE
+    enddo
+    
+    do i=1,Npoints
+       do iz=1,Ncat
+          checkcldlayerphase=0.
+          checkcldlayerphase2=0.
+          if (cldlayerphasesum(i,iz) .gt. 0.0 )then
+             do ic=1,Nphase-3
+                checkcldlayerphase = checkcldlayerphase+cldlayerphase(i,iz,ic)
+             enddo
+             checkcldlayerphase2 = cldlayer(i,iz)-checkcldlayerphase
+             if((checkcldlayerphase2 .gt. 0.01) .or. (checkcldlayerphase2 .lt. -0.01) ) print *, checkcldlayerphase,cldlayer(i,iz)
+          endif
+       enddo
+    enddo
+    
+    do i=1,Nphase-1
+       WHERE (nsublayer(:,:) .eq. 0.0)
+          cldlayerphase(:,:,i) = undef
+       ENDWHERE
+    enddo
+ 
+    ! Compute Phase 3D as a function of temperature
+    do nlev=1,Nlevels
+       do ncol=1,Ncolumns
+          do i=1,Npoints
+             do itemp=1,Ntemp
+                if(tmpi(i,ncol,nlev).gt.0.)then
+                   if((tmpi(i,ncol,nlev) .ge. tempmod(itemp)) .and. (tmpi(i,ncol,nlev) .lt. tempmod(itemp+1)) )then
+                      lidarcldtemp(i,itemp,2)=lidarcldtemp(i,itemp,2)+1._wp
+                   endif
+                elseif(tmpl(i,ncol,nlev) .gt. 0.)then
+                   if((tmpl(i,ncol,nlev) .ge. tempmod(itemp)) .and. (tmpl(i,ncol,nlev) .lt. tempmod(itemp+1)) )then
+                      lidarcldtemp(i,itemp,3)=lidarcldtemp(i,itemp,3)+1._wp
+                   endif
+                elseif(tmpu(i,ncol,nlev) .gt. 0.)then
+                   if((tmpu(i,ncol,nlev) .ge. tempmod(itemp)) .and. (tmpu(i,ncol,nlev) .lt. tempmod(itemp+1)) )then
+                      lidarcldtemp(i,itemp,4)=lidarcldtemp(i,itemp,4)+1._wp
+                   endif
+                endif
+             enddo
+          enddo
+       enddo
+    enddo
+    
+    ! Check temperature cloud fraction
+    do i=1,Npoints
+       do itemp=1,Ntemp
+          checktemp=lidarcldtemp(i,itemp,2)+lidarcldtemp(i,itemp,3)+lidarcldtemp(i,itemp,4)
+          !if(checktemp .NE. lidarcldtemp(i,itemp,1))then
+          !   print *, i,itemp
+          !   print *, lidarcldtemp(i,itemp,1:4)
+          !endif
+          
+       enddo
+    enddo
+    
+    ! Compute the Ice percentage in cloud = ice/(ice+liq)
+    sumlidarcldtemp(:,:)=lidarcldtemp(:,:,2)+lidarcldtemp(:,:,3)    
+    WHERE(sumlidarcldtemp(:,:) .gt. 0.)
+       lidarcldtemp(:,:,5)=lidarcldtemp(:,:,2)/sumlidarcldtemp(:,:)
+    ELSEWHERE
+       lidarcldtemp(:,:,5)=undef
+    ENDWHERE
+    
+    do i=1,4
+       WHERE(lidarcldtempind(:,:) .gt. 0.)
+          lidarcldtemp(:,:,i) = lidarcldtemp(:,:,i)/lidarcldtempind(:,:)
+       ELSEWHERE
+          lidarcldtemp(:,:,i) = undef
+       ENDWHERE
+    enddo
+    
+    RETURN
+  END SUBROUTINE COSP_CLDFRAC
+  
+  ! ####################################################################################
+  ! SUBROUTINE cosp_cldfrac_nophase
+  ! Conventions: Ncat must be equal to 4
+  ! ####################################################################################
+  SUBROUTINE COSP_CLDFRAC_NOPHASE(Npoints,Ncolumns,Nlevels,Ncat,x,ATB,pplay,      &
+       S_att,S_cld,S_cld_att,undef,lidarcld,cldlayer)
+    
+    ! Inputs
+    integer,intent(in) :: &
+         Npoints,  & ! Number of gridpoints
+         Ncolumns, & ! Number of subcolumns
+         Nlevels,  & ! Number of vertical levels
+         Ncat        ! Number of cloud layer types
+    real(wp),intent(in) :: &
+         S_att,    & !
+         S_cld,    & !
+         S_cld_att,& ! New threshold for undefine cloud phase detection
+         undef       ! Undefined value
+    real(wp),intent(in),dimension(Npoints,Ncolumns,Nlevels) :: &
+         x,        & ! 
+         ATB         ! 3D attenuated backscatter
+    real(wp),intent(in),dimension(Npoints,Nlevels) :: &
+         pplay       ! Pressure
+    
+    ! Outputs
+    real(wp),intent(out),dimension(Npoints,Nlevels) :: &
+         lidarcld      ! 3D cloud fraction
+    real(wp),intent(out),dimension(Npoints,Ncat) :: &
+         cldlayer      ! Low, middle, high, total cloud fractions
+    
+    ! Local variables
+    integer  :: &
+         ip, k, iz, ic, ncol, nlev, i
+    real(wp) :: &
+         p1
+    real(wp),dimension(Npoints,Nlevels) :: &
+         nsub
+    real(wp),dimension(Npoints,Ncolumns,Ncat) :: &
+         cldlay,nsublay   
+    real(wp),dimension(Npoints,Ncat) :: &
+         nsublayer
+    real(wp),dimension(Npoints,Ncolumns,Nlevels) :: &   
+         cldy, & ! 
+         srok    !
+    
+    ! ####################################################################################
+    ! 1) Initialize    
+    ! ####################################################################################
+    lidarcld           = 0._wp
+    nsub               = 0._wp
+    cldlay             = 0._wp
+    nsublay            = 0._wp
+    
+    ! ####################################################################################
+    ! 2) Cloud detection
+    ! ####################################################################################
+    do k=1,Nlevels
+       ! Cloud detection at subgrid-scale:
+       where ((x(:,:,k) .gt. S_cld) .and. (x(:,:,k) .ne. undef) )
+          cldy(:,:,k)=1._wp
+       elsewhere
+          cldy(:,:,k)=0._wp
+       endwhere
+       
+       ! Number of usefull sub-columns:
+       where ((x(:,:,k) .gt. S_att) .and. (x(:,:,k) .ne. undef) )
+          srok(:,:,k)=1._wp
+       elsewhere
+          srok(:,:,k)=0._wp
+       endwhere
+    enddo    
+
+    ! ####################################################################################
+    ! 3) Grid-box 3D cloud fraction and layered cloud fractions(ISCCP pressure categories)
+    ! ####################################################################################
+    do k=1,Nlevels
+       do ic = 1, Ncolumns
+          do ip = 1, Npoints
+
+             iz=1
+             p1 = pplay(ip,k)
+             if ( p1.gt.0. .and. p1.lt.(440._wp*100._wp)) then ! high clouds
+                iz=3
+             else if(p1.ge.(440._wp*100._wp) .and. p1.lt.(680._wp*100._wp)) then ! mid clouds
+                iz=2
+             endif
+             
+             cldlay(ip,ic,iz) = MAX(cldlay(ip,ic,iz),cldy(ip,ic,k))
+             cldlay(ip,ic,4)  = MAX(cldlay(ip,ic,4),cldy(ip,ic,k))
+             lidarcld(ip,k)   = lidarcld(ip,k) + cldy(ip,ic,k)
+             
+             nsublay(ip,ic,iz) = MAX(nsublay(ip,ic,iz),srok(ip,ic,k))
+             nsublay(ip,ic,4)  = MAX(nsublay(ip,ic,4),srok(ip,ic,k))
+             nsub(ip,k)        = nsub(ip,k) + srok(ip,ic,k)
+             
+          enddo
+       enddo
+    enddo   
+    
+    ! Grid-box 3D cloud fraction
+    where ( nsub(:,:).gt.0.0 )
+       lidarcld(:,:) = lidarcld(:,:)/nsub(:,:)
+    elsewhere
+       lidarcld(:,:) = undef
+    endwhere
+    
+    ! Layered cloud fractions
+    cldlayer  = 0._wp
+    nsublayer = 0._wp
+    do iz = 1, Ncat
+       do ic = 1, Ncolumns
+          cldlayer(:,iz)  = cldlayer(:,iz)  + cldlay(:,ic,iz)
+          nsublayer(:,iz) = nsublayer(:,iz) + nsublay(:,ic,iz)
+       enddo
+    enddo
+    where (nsublayer(:,:) .gt. 0.0)
+       cldlayer(:,:) = cldlayer(:,:)/nsublayer(:,:)
+    elsewhere
+       cldlayer(:,:) = undef
+    endwhere
+
+    RETURN
+  END SUBROUTINE COSP_CLDFRAC_NOPHASE
+
+    ! ####################################################################################
+    ! SUBROUTINE cosp_opaq
+    ! Conventions: Ntype must be equal to 3
+    ! ####################################################################################
+    SUBROUTINE COSP_OPAQ(Npoints,Ncolumns,Nlevels,Ntype,tmp,x,S_att,S_cld,undef,lidarcldtype,   &
+                         cldtype,cldtypetemp,cldtypemeanz,cldtypemeanzse,cldthinemis,vgrid_z,   &
+                         surfelev)
+
+    ! Local parameter
+    real(wp),parameter  :: &
+       S_att_opaq = 0.06_wp, & ! Fully Attenuated threshold (Guzman et al. 2017, JGR-Atmospheres)
+       eta = 0.6_wp            ! Multiple-scattering factor (Vaillant de Guelis et al. 2017a, AMT)
+
+	! Inputs
+    integer,intent(in) :: &
+       Npoints,  & ! Number of gridpoints
+       Ncolumns, & ! Number of subcolumns
+       Nlevels,  & ! Number of vertical levels
+       Ntype       ! Number of OPAQ cloud types (opaque, thin clouds and z_opaque)
+    real(wp),intent(in) :: &
+       S_att,    & ! Fully Attenuated legacy threshold
+       S_cld,    & ! Cloud detection threshold
+       undef       ! Undefined value
+    real(wp),intent(in),dimension(Nlevels) :: &
+       vgrid_z     ! mid-level vertical profile altitude (subcolumns)
+    real(wp),intent(in),dimension(Npoints,Ncolumns,Nlevels) :: &
+       x           ! SR profiles (subcolumns)
+    real(wp),intent(in),dimension(Npoints,Nlevels) :: &
+       tmp         ! Temperature profiles
+    real(wp),intent(in),dimension(Npoints) :: &
+       surfelev    ! Surface Elevation (SE)
+
+	! Outputs
+    real(wp),intent(out),dimension(Npoints,Nlevels,Ntype+1) :: &
+       lidarcldtype   ! 3D OPAQ product fraction (opaque clouds, thin clouds, z_opaque, opacity)
+    real(wp),intent(out),dimension(Npoints,Ntype) :: &
+       cldtype,     & ! Opaque/thin cloud covers + z_opaque altitude
+       cldtypetemp    ! Opaque and thin clouds + z_opaque temperature
+    real(wp),intent(out),dimension(Npoints,2) :: &
+       cldtypemeanz   ! Opaque and thin clouds altitude
+    real(wp),intent(out),dimension(Npoints,3) :: & 
+       cldtypemeanzse ! Opaque, thin clouds and z_opaque altitude with respect to SE
+    real(wp),intent(out),dimension(Npoints) :: &
+       cldthinemis    ! Thin clouds emissivity
+   
+    ! Local variables
+    integer  :: &
+       ip, k, zopac, ic, iz, z_top, z_base, topcloud
+    real(wp)  :: &
+       srmean, srcount, trans2, tau_app, tau_vis, tau_ir, cloudemis
+    real(wp),dimension(Npoints) :: &
+       count_emis
+    real(wp),dimension(Npoints,Nlevels) :: &
+       nsub, nsubopaq 
+    real(wp),dimension(Npoints,Ncolumns,Ntype+1) :: & ! Opaque, thin, z_opaque and all cloud cover
+       cldlay, nsublay   
+    real(wp),dimension(Npoints,Ntype) :: &
+       nsublayer
+    real(wp),dimension(Npoints,Ncolumns,Nlevels) :: &   
+       cldy,     & ! 
+       cldyopaq, & ! 
+       srok,     & !
+       srokopaq    !
+
+    ! ####################################################################################
+	! 1) Initialize    
+    ! ####################################################################################
+    cldtype(:,:)          = 0._wp
+    cldtypetemp(:,:)      = 0._wp
+    cldtypemeanz(:,:)     = 0._wp
+    cldtypemeanzse(:,:)   = 0._wp
+    cldthinemis(:)        = 0._wp
+    count_emis(:)         = 0._wp
+    lidarcldtype(:,:,:)   = 0._wp
+    nsub                  = 0._wp
+    nsubopaq              = 0._wp
+    cldlay                = 0._wp
+    nsublay               = 0._wp
+    nsublayer             = 0._wp
+
+    ! ####################################################################################
+    ! 2) Cloud detection and Fully attenuated layer detection
+    ! ####################################################################################
+    do k=1,Nlevels
+       ! Cloud detection at subgrid-scale:
+       where ( (x(:,:,k) .gt. S_cld) .and. (x(:,:,k) .ne. undef) )
+          cldy(:,:,k)=1._wp
+       elsewhere
+          cldy(:,:,k)=0._wp
+       endwhere
+       ! Fully attenuated layer detection at subgrid-scale:
+       where ( (x(:,:,k) .lt. S_att_opaq) .and. (x(:,:,k) .ge. 0.) .and. (x(:,:,k) .ne. undef) ) !DEBUG
+          cldyopaq(:,:,k)=1._wp
+       elsewhere
+          cldyopaq(:,:,k)=0._wp
+       endwhere
+
+
+       ! Number of usefull sub-column layers:
+       where ( (x(:,:,k) .gt. S_att) .and. (x(:,:,k) .ne. undef) )
+          srok(:,:,k)=1._wp
+       elsewhere
+          srok(:,:,k)=0._wp
+       endwhere
+       ! Number of usefull sub-columns layers for z_opaque 3D fraction:
+       where ( (x(:,:,k) .ge. 0.) .and. (x(:,:,k) .ne. undef) ) !DEBUG
+          srokopaq(:,:,k)=1._wp
+       elsewhere
+          srokopaq(:,:,k)=0._wp
+       endwhere
+    enddo
+
+    ! ####################################################################################
+    ! 3) Grid-box 3D OPAQ product fraction and cloud type cover (opaque/thin) + mean z_opaque
+    ! ####################################################################################
+
+    do k=1,Nlevels
+       do ic = 1, Ncolumns
+          do ip = 1, Npoints
+
+             cldlay(ip,ic,1)   = MAX(cldlay(ip,ic,1),cldyopaq(ip,ic,k)) ! Opaque cloud
+             cldlay(ip,ic,4)   = MAX(cldlay(ip,ic,4),cldy(ip,ic,k))     ! All cloud
+
+             nsublay(ip,ic,1)  = MAX(nsublay(ip,ic,1),srok(ip,ic,k))
+             nsublay(ip,ic,2)  = MAX(nsublay(ip,ic,2),srok(ip,ic,k))
+!             nsublay(ip,ic,4)  = MAX(nsublay(ip,ic,4),srok(ip,ic,k))
+             nsub(ip,k)        = nsub(ip,k) + srok(ip,ic,k)
+             nsubopaq(ip,k)    = nsubopaq(ip,k) + srokopaq(ip,ic,k)
+
+          enddo
+       enddo
+    enddo   
+
+! OPAQ variables
+     do ic = 1, Ncolumns
+        do ip = 1, Npoints
+
+     ! Declaring non-opaque cloudy profiles as thin cloud profiles
+	   if ( cldlay(ip,ic,4).gt. 0. .and. cldlay(ip,ic,1) .eq. 0. ) then
+	      cldlay(ip,ic,2)  =  1._wp
+ 	   endif
+
+     ! Filling in 3D and 2D variables
+
+     ! Opaque cloud profiles
+	   if ( cldlay(ip,ic,1) .eq. 1. ) then
+	      zopac = 0._wp
+	      z_top = 0._wp
+	      do k=1,Nlevels-1
+     ! Declaring z_opaque altitude and opaque cloud fraction for 3D and 2D variables
+     ! From SFC-2-TOA ( actually from vgrid_z(SFC+1) = vgrid_z(Nlevels-1) )
+	         if ( cldy(ip,ic,Nlevels-k) .eq. 1. .and. zopac .eq. 0. ) then
+		    lidarcldtype(ip,Nlevels-k + 1,3) = lidarcldtype(ip,Nlevels-k + 1,3) + 1._wp
+		    cldlay(ip,ic,3)                  = vgrid_z(Nlevels-k+1)      ! z_opaque altitude
+		    nsublay(ip,ic,3)                 = 1._wp
+		    zopac = Nlevels-k+1                        ! z_opaque vertical index on vgrid_z
+		 endif
+	         if ( cldy(ip,ic,Nlevels-k) .eq. 1. ) then
+		    lidarcldtype(ip,Nlevels-k ,1)    = lidarcldtype(ip,Nlevels-k ,1) + 1._wp
+		    z_top = Nlevels-k    ! top cloud layer vertical index on vgrid_z
+                 endif
+	      enddo
+     ! Summing opaque cloud mean temperatures and altitudes
+     ! as defined in Vaillant de Guelis et al. 2017a, AMT
+              if (zopac .ne. 0) then 
+                 cldtypetemp(ip,1) = cldtypetemp(ip,1) + ( tmp(ip,zopac) + tmp(ip,z_top) )/2.
+                 cldtypetemp(ip,3) = cldtypetemp(ip,3) + tmp(ip,zopac)                 ! z_opaque
+                 cldtypemeanz(ip,1) = cldtypemeanz(ip,1) + ( vgrid_z(zopac) + vgrid_z(z_top) )/2.
+                 cldtypemeanzse(ip,1) = cldtypemeanzse(ip,1) + (( vgrid_z(zopac) + vgrid_z(z_top) )/2.) - surfelev(ip)
+                 cldtypemeanzse(ip,3) = cldtypemeanzse(ip,3) + ( vgrid_z(zopac) - surfelev(ip) )
+              else
+                 cldlay(ip,ic,1) = 0
+              endif
+	   endif
+
+     ! Thin cloud profiles
+	   if ( cldlay(ip,ic,2) .eq. 1. ) then
+	      topcloud = 0._wp
+	      z_top = 0._wp
+	      z_base = 0._wp
+	      do k=1,Nlevels
+     ! Declaring thin cloud fraction for 3D variable
+     ! From TOA-2-SFC
+                 if ( cldy(ip,ic,k) .eq. 1. .and. topcloud .eq. 1. ) then
+                    lidarcldtype(ip,k,2) = lidarcldtype(ip,k,2) + 1._wp
+		    z_base = k ! bottom cloud layer
+                 endif
+	         if ( cldy(ip,ic,k) .eq. 1. .and. topcloud .eq. 0. ) then
+                    lidarcldtype(ip,k,2) = lidarcldtype(ip,k,2) + 1._wp
+		    z_top = k  ! top cloud layer
+		    z_base = k ! bottom cloud layer
+                    topcloud = 1._wp
+		 endif
+	      enddo
+     ! Computing mean emissivity using layers below the bottom cloud layer to the surface
+     	      srmean = 0._wp
+	      srcount = 0._wp
+	      cloudemis = 0._wp
+     	      do k=z_base+1,Nlevels
+	         if (  (x(ip,ic,k) .gt. S_att_opaq) .and. (x(ip,ic,k) .lt. 1.0) .and. (x(ip,ic,k) .ne. undef)  ) then
+		    srmean = srmean + x(ip,ic,k)
+		    srcount = srcount + 1.
+                 endif
+	      enddo
+	      ! If clear sky layers exist below bottom cloud layer
+	      if ( srcount .gt. 0. ) then
+	      	 trans2 = srmean/srcount              ! thin cloud transmittance**2
+	      	 tau_app = -(log(trans2))/2.          ! apparent cloud optical depth
+	      	 tau_vis = tau_app/eta                ! cloud visible optical depth (multiple scat.)
+	      	 tau_ir = tau_vis/2.                  ! approx. relation between visible and IR ODs
+	      	 cloudemis = 1. - exp(-tau_ir)        ! no diffusion in IR considered : emis = 1-T
+		 count_emis(ip) = count_emis(ip) + 1.
+	      endif
+     ! Summing thin cloud mean temperatures and altitudes
+     ! as defined in Vaillant de Guelis et al. 2017a, AMT
+              cldtypetemp(ip,2) = cldtypetemp(ip,2) + ( tmp(ip,z_base) + tmp(ip,z_top) )/2.
+              cldtypemeanz(ip,2) = cldtypemeanz(ip,2) + ( vgrid_z(z_base) + vgrid_z(z_top) )/2.
+              cldtypemeanzse(ip,2) = cldtypemeanzse(ip,2) + (( vgrid_z(z_base) + vgrid_z(z_top) )/2.) - surfelev(ip)
+              cldthinemis(ip) = cldthinemis(ip) + cloudemis
+           endif
+
+       enddo
+    enddo   
+
+    ! 3D cloud types fraction (opaque=1 and thin=2 clouds)
+    where ( nsub(:,:) .gt. 0. )
+       lidarcldtype(:,:,1) = lidarcldtype(:,:,1)/nsub(:,:)
+       lidarcldtype(:,:,2) = lidarcldtype(:,:,2)/nsub(:,:)
+    elsewhere
+       lidarcldtype(:,:,1) = undef
+       lidarcldtype(:,:,2) = undef
+    endwhere
+    ! 3D z_opaque fraction (=3)
+    where ( nsubopaq(:,:) .gt. 0. )
+       lidarcldtype(:,:,3) = lidarcldtype(:,:,3)/nsubopaq(:,:)
+    elsewhere
+       lidarcldtype(:,:,3) = undef
+       lidarcldtype(:,:,4) = undef !declaring undef for opacity as well
+    endwhere
+    ! 3D opacity fraction (=4) !Summing z_opaque fraction from TOA(k=1) to SFC(k=Nlevels)
+       lidarcldtype(:,1,4) = lidarcldtype(:,1,3) !top layer equal to 3D z_opaque fraction
+    do ip = 1, Npoints
+     	do k = 2, Nlevels
+            if ( (lidarcldtype(ip,k,3) .ne. undef) .and. (lidarcldtype(ip,k-1,4) .ne. undef) ) then
+	        lidarcldtype(ip,k,4) = lidarcldtype(ip,k,3) + lidarcldtype(ip,k-1,4)
+	    else
+	        lidarcldtype(ip,k,4) = undef
+	    endif
+	enddo
+    enddo
+
+    ! Layered cloud types (opaque, thin and z_opaque 2D variables)
+
+    do iz = 1, Ntype
+       do ic = 1, Ncolumns
+          cldtype(:,iz)  = cldtype(:,iz)  + cldlay(:,ic,iz)
+          nsublayer(:,iz) = nsublayer(:,iz) + nsublay(:,ic,iz)
+       enddo
+    enddo
+
+    ! Mean temperature and altitude
+    where (cldtype(:,1) .gt. 0.)
+       cldtypetemp(:,1) = cldtypetemp(:,1)/cldtype(:,1) ! opaque cloud temp
+       cldtypetemp(:,3) = cldtypetemp(:,3)/cldtype(:,1) ! z_opaque
+       cldtypemeanz(:,1) = cldtypemeanz(:,1)/cldtype(:,1) ! opaque cloud alt
+       cldtypemeanzse(:,1) = cldtypemeanzse(:,1)/cldtype(:,1) ! opaque cloud alt - SE 
+       cldtypemeanzse(:,3) = cldtypemeanzse(:,3)/cldtype(:,1) ! z_opaque - SE 
+    elsewhere
+       cldtypetemp(:,1) = undef
+       cldtypetemp(:,3) = undef
+       cldtypemeanz(:,1) = undef
+       cldtypemeanzse(:,1) = undef
+       cldtypemeanzse(:,3) = undef
+    endwhere
+
+    where (cldtype(:,2) .gt. 0.) ! thin cloud
+       cldtypetemp(:,2) = cldtypetemp(:,2)/cldtype(:,2)
+       cldtypemeanz(:,2) = cldtypemeanz(:,2)/cldtype(:,2)
+       cldtypemeanzse(:,2) = cldtypemeanzse(:,2)/cldtype(:,2)
+    elsewhere
+       cldtypetemp(:,2) = undef
+       cldtypemeanz(:,2) = undef
+       cldtypemeanzse(:,2) = undef
+    endwhere
+
+    ! Mean thin cloud emissivity
+    where (count_emis(:) .gt. 0.) ! thin cloud
+       cldthinemis(:) = cldthinemis(:)/count_emis(:)
+    elsewhere
+       cldthinemis(:) = undef
+    endwhere
+
+    where (nsublayer(:,:) .gt. 0.)
+       cldtype(:,:) = cldtype(:,:)/nsublayer(:,:)
+    elsewhere
+       cldtype(:,:) = undef
+    endwhere
+
+  END SUBROUTINE COSP_OPAQ
+
+end module mod_lidar_simulator
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_construct_destroy_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_construct_destroy_mod.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_construct_destroy_mod.F90	(revision 3605)
@@ -0,0 +1,675 @@
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!
+! Module pour construir et detruire les variables "cospIN", "cospstateIN" et "cospOUT"
+!
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+MODULE LMDZ_COSP_CONSTRUCT_DESTROY_MOD
+
+use cosp_kinds, only: wp
+use mod_cosp,   only: cosp_optical_inputs,cosp_column_inputs,cosp_outputs
+use lmdz_cosp_read_outputkeys, only: cosp_config
+
+   USE mod_cosp_config, only : R_UNDEF, CLOUDSAT_DBZE_BINS, SR_BINS, PARASOL_NREFL, & 
+                              LIDAR_NTEMP, LIDAR_NCAT, LIDAR_NTYPE, & 
+                              numMODISReffIceBins,reffICE_binCenters, &
+                              numMODISReffLiqBins, reffLIQ_binCenters, &
+			      numISCCPTauBins,numISCCPPresBins, &
+			      numMISRTauBins,numMISRHgtBins, &
+			      numModisTauBins,numMODISPresBins
+
+  implicit none
+
+contains
+
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! SUBROUTINE construct_cospIN
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  subroutine construct_cospIN(cfg,npoints,ncolumns,nlevels,y)
+    ! Inputs
+    integer,intent(in) :: &
+         npoints,  & ! Number of horizontal gridpoints
+         ncolumns, & ! Number of subcolumns
+         nlevels     ! Number of vertical levels
+
+     type(cosp_config),intent(in) :: &
+          cfg         ! COSP output config (logical keys)
+
+    ! Outputs 
+    type(cosp_optical_inputs),intent(out) :: y
+    
+    ! Dimensions
+    y%Npoints  = Npoints
+    y%Ncolumns = Ncolumns
+    y%Nlevels  = Nlevels
+    y%Npart    = 4
+    y%Nrefl    = PARASOL_NREFL
+    allocate(y%frac_out(npoints,       ncolumns,nlevels))
+
+    if (cfg%Lmodis .or. cfg%Lmisr .or. cfg%Lisccp) then
+       allocate(y%tau_067(npoints,        ncolumns,nlevels),&
+                y%emiss_11(npoints,       ncolumns,nlevels))
+    endif
+    if (cfg%Lcalipso) then
+       allocate(y%betatot_calipso(npoints,        ncolumns,nlevels),&
+                y%betatot_ice_calipso(npoints,    ncolumns,nlevels),&
+                y%betatot_liq_calipso(npoints,    ncolumns,nlevels),&
+                y%tautot_calipso(npoints,         ncolumns,nlevels),&
+                y%tautot_ice_calipso(npoints,     ncolumns,nlevels),&
+                y%tautot_liq_calipso(npoints,     ncolumns,nlevels),&
+                y%beta_mol_calipso(npoints,                nlevels),&
+                y%tau_mol_calipso(npoints,                 nlevels),&
+                y%tautot_S_ice(npoints,   ncolumns        ),&
+                y%tautot_S_liq(npoints,   ncolumns        ))
+    endif
+
+    if (cfg%LgrLidar532) then
+       allocate(y%beta_mol_grLidar532(npoints,          nlevels),& 
+                y%betatot_grLidar532(npoints,  ncolumns,nlevels),& 
+                y%tau_mol_grLidar532(npoints,           nlevels),& 
+                y%tautot_grLidar532(npoints,   ncolumns,nlevels)) 
+    endif
+
+    if (cfg%Latlid) then
+       allocate(y%beta_mol_atlid(npoints,             nlevels),& 
+                y%betatot_atlid(npoints,     ncolumns,nlevels),& 
+                y%tau_mol_atlid(npoints,              nlevels),& 
+                y%tautot_atlid(npoints,      ncolumns,nlevels))
+    endif 
+
+    if (cfg%Lcloudsat) then
+       allocate(y%z_vol_cloudsat(npoints,  ncolumns,nlevels),&
+                y%kr_vol_cloudsat(npoints, ncolumns,nlevels),&
+                y%g_vol_cloudsat(npoints,  ncolumns,nlevels),&
+                y%fracPrecipIce(npoints,   ncolumns))
+    endif
+    if (cfg%Lmodis) then
+       allocate(y%fracLiq(npoints,        ncolumns,nlevels),&
+                y%asym(npoints,           ncolumns,nlevels),&
+                y%ss_alb(npoints,         ncolumns,nlevels))
+    endif
+    
+
+  end subroutine construct_cospIN  
+  
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! SUBROUTINE construct_cospstateIN
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%     
+  subroutine construct_cospstateIN(npoints,nlevels,nchan,y)
+    ! Inputs
+    integer,intent(in) :: &
+         npoints, & ! Number of horizontal gridpoints
+         nlevels, & ! Number of vertical levels
+         nchan      ! Number of channels
+    ! Outputs
+    type(cosp_column_inputs),intent(out) :: y         
+    
+    allocate(y%sunlit(npoints),y%skt(npoints),y%land(npoints),y%at(npoints,nlevels),     &
+             y%pfull(npoints,nlevels),y%phalf(npoints,nlevels+1),y%qv(npoints,nlevels),  &
+             y%o3(npoints,nlevels),y%hgt_matrix(npoints,nlevels),y%u_sfc(npoints),       &
+             y%v_sfc(npoints),y%lat(npoints),y%lon(nPoints),y%emis_sfc(nchan),           &
+             y%cloudIce(nPoints,nLevels),y%cloudLiq(nPoints,nLevels),y%surfelev(npoints),&
+             y%fl_snow(nPoints,nLevels),y%fl_rain(nPoints,nLevels),y%seaice(npoints),    &
+             y%tca(nPoints,nLevels),y%hgt_matrix_half(npoints,nlevels+1))
+
+  end subroutine construct_cospstateIN
+
+  ! ######################################################################################
+  ! SUBROUTINE construct_cosp_outputs
+  !
+  ! This subroutine allocates output fields based on input logical flag switches.
+  ! ######################################################################################  
+  subroutine construct_cosp_outputs(cfg,Npoints,Ncolumns,Nlevels,Nlvgrid,Nchan,x)
+     ! Inputs        
+     integer,intent(in) :: &
+          Npoints,         & ! Number of sampled points
+          Ncolumns,        & ! Number of subgrid columns
+          Nlevels,         & ! Number of model levels
+          Nlvgrid,         & ! Number of levels in L3 stats computation
+          Nchan              ! Number of RTTOV channels            
+     type(cosp_config),intent(in) :: &
+          cfg         ! COSP output config (logical keys)
+
+     ! Outputs
+     type(cosp_outputs),intent(out) :: &
+          x           ! COSP output structure  
+   
+     ! ISCCP simulator outputs
+    if (cfg%Lboxtauisccp)    allocate(x%isccp_boxtau(Npoints,Ncolumns)) 
+    if (cfg%Lboxptopisccp)   allocate(x%isccp_boxptop(Npoints,Ncolumns))
+    if (cfg%Lclisccp)        allocate(x%isccp_fq(Npoints,numISCCPTauBins,numISCCPPresBins))
+    if (cfg%Lcltisccp)       allocate(x%isccp_totalcldarea(Npoints))
+    if (cfg%Lpctisccp)       allocate(x%isccp_meanptop(Npoints))
+    if (cfg%Ltauisccp)       allocate(x%isccp_meantaucld(Npoints))
+    if (cfg%Lmeantbisccp)    allocate(x%isccp_meantb(Npoints))
+    if (cfg%Lmeantbclrisccp) allocate(x%isccp_meantbclr(Npoints))
+    if (cfg%Lalbisccp)       allocate(x%isccp_meanalbedocld(Npoints))
+    
+    ! MISR simulator
+    if (cfg%LclMISR) then 
+       allocate(x%misr_fq(Npoints,numMISRTauBins,numMISRHgtBins))
+       ! *NOTE* These 3 fields are not output, but were part of the v1.4.0 cosp_misr, so
+       !        they are still computed. Should probably have a logical to control these
+       !        outputs.
+       allocate(x%misr_dist_model_layertops(Npoints,numMISRHgtBins))
+       allocate(x%misr_meanztop(Npoints))
+       allocate(x%misr_cldarea(Npoints))    
+    endif
+    
+    ! MODIS simulator
+    if (cfg%Lcltmodis)     allocate(x%modis_Cloud_Fraction_Total_Mean(Npoints))
+    if (cfg%Lclwmodis)     allocate(x%modis_Cloud_Fraction_Water_Mean(Npoints))
+    if (cfg%Lclimodis)     allocate(x%modis_Cloud_Fraction_Ice_Mean(Npoints))
+    if (cfg%Lclhmodis)     allocate(x%modis_Cloud_Fraction_High_Mean(Npoints))
+    if (cfg%Lclmmodis)     allocate(x%modis_Cloud_Fraction_Mid_Mean(Npoints))
+    if (cfg%Lcllmodis)     allocate(x%modis_Cloud_Fraction_Low_Mean(Npoints))
+    if (cfg%Ltautmodis)    allocate(x%modis_Optical_Thickness_Total_Mean(Npoints))
+    if (cfg%Ltauwmodis)    allocate(x%modis_Optical_Thickness_Water_Mean(Npoints))
+    if (cfg%Ltauimodis)    allocate(x%modis_Optical_Thickness_Ice_Mean(Npoints))
+    if (cfg%Ltautlogmodis) allocate(x%modis_Optical_Thickness_Total_LogMean(Npoints))
+    if (cfg%Ltauwlogmodis) allocate(x%modis_Optical_Thickness_Water_LogMean(Npoints))
+    if (cfg%Ltauilogmodis) allocate(x%modis_Optical_Thickness_Ice_LogMean(Npoints))
+    if (cfg%Lreffclwmodis) allocate(x%modis_Cloud_Particle_Size_Water_Mean(Npoints))
+    if (cfg%Lreffclimodis) allocate(x%modis_Cloud_Particle_Size_Ice_Mean(Npoints))
+    if (cfg%Lpctmodis)     allocate(x%modis_Cloud_Top_Pressure_Total_Mean(Npoints))
+    if (cfg%Llwpmodis)     allocate(x%modis_Liquid_Water_Path_Mean(Npoints))
+    if (cfg%Liwpmodis)     allocate(x%modis_Ice_Water_Path_Mean(Npoints))
+    if (cfg%Lclmodis) then
+        allocate(x%modis_Optical_Thickness_vs_Cloud_Top_Pressure(nPoints,numModisTauBins,numMODISPresBins))
+        allocate(x%modis_Optical_thickness_vs_ReffLIQ(nPoints,numMODISTauBins,numMODISReffLiqBins))   
+        allocate(x%modis_Optical_Thickness_vs_ReffICE(nPoints,numMODISTauBins,numMODISReffIceBins))
+    endif
+    
+    ! LIDAR simulator
+    if (cfg%LlidarBetaMol532) allocate(x%calipso_beta_mol(Npoints,Nlevels))
+    if (cfg%Latb532)          allocate(x%calipso_beta_tot(Npoints,Ncolumns,Nlevels))
+    if (cfg%LcfadLidarsr532)  then
+        allocate(x%calipso_srbval(SR_BINS+1))
+        allocate(x%calipso_cfad_sr(Npoints,SR_BINS,Nlvgrid))
+        allocate(x%calipso_betaperp_tot(Npoints,Ncolumns,Nlevels))  
+    endif
+    if (cfg%Lclcalipso)       allocate(x%calipso_lidarcld(Npoints,Nlvgrid))
+    if (cfg%Lclhcalipso .or. cfg%Lclmcalipso .or. cfg%Lcllcalipso .or. cfg%Lcltcalipso) then
+        allocate(x%calipso_cldlayer(Npoints,LIDAR_NCAT))
+    endif   
+    if (cfg%Lclcalipsoice .or. cfg%Lclcalipsoliq .or. cfg%Lclcalipsoun) then
+        allocate(x%calipso_lidarcldphase(Npoints,Nlvgrid,6))
+    endif
+    if (cfg%Lclcalipsotmp .or. cfg%Lclcalipsotmpliq .or. cfg%Lclcalipsoice .or. &
+                          cfg%Lclcalipsotmpun .or. cfg%Lclcalipsotmpice) then
+        allocate(x%calipso_lidarcldtmp(Npoints,LIDAR_NTEMP,5))
+    endif
+    if (cfg%Lcllcalipsoice .or. cfg%Lclmcalipsoice .or. cfg%Lclhcalipsoice .or.             &
+        cfg%Lcltcalipsoice .or. cfg%Lcllcalipsoliq .or. cfg%Lclmcalipsoliq .or.             &
+        cfg%Lclhcalipsoliq .or. cfg%Lcltcalipsoliq .or. cfg%Lcllcalipsoun  .or.             &
+        cfg%Lclmcalipsoun  .or. cfg%Lclhcalipsoun  .or. cfg%Lcltcalipsoun) then
+        allocate(x%calipso_cldlayerphase(Npoints,LIDAR_NCAT,6))     
+    endif
+    if (cfg%Lclopaquecalipso .or. cfg%Lclthincalipso .or. cfg%Lclzopaquecalipso) then
+        allocate(x%calipso_cldtype(Npoints,LIDAR_NTYPE))
+    endif 
+    if (cfg%Lclopaquetemp .or. cfg%Lclthintemp .or. cfg%Lclzopaquetemp) then 
+        allocate(x%calipso_cldtypetemp(Npoints,LIDAR_NTYPE))  
+    endif
+    if (cfg%Lclopaquemeanz .or. cfg%Lclthinmeanz) then 
+        allocate(x%calipso_cldtypemeanz(Npoints,2))
+    endif 
+    if (cfg%Lclopaquemeanzse .or. cfg%Lclthinmeanzse .or. cfg%Lclzopaquecalipsose) then 
+        allocate(x%calipso_cldtypemeanzse(Npoints,3)) 
+    endif 
+    if (cfg%Lclthinemis) then 
+        allocate(x%calipso_cldthinemis(Npoints))
+    endif
+    if (cfg%Lclcalipsoopaque .or. cfg%Lclcalipsothin .or. cfg%Lclcalipsozopaque .or. &
+             cfg%Lclcalipsoopacity) then 
+        allocate(x%calipso_lidarcldtype(Npoints,Nlvgrid,LIDAR_NTYPE+1))
+    endif
+    ! These 2 outputs are part of the calipso output type, but are not controlled by an 
+    ! logical switch in the output namelist, so if all other fields are on, then allocate
+    if (cfg%LlidarBetaMol532 .or. cfg%Latb532        .or. cfg%LcfadLidarsr532 .or. cfg%Lclcalipso  .or.  &
+        cfg%Lclcalipsoice    .or. cfg%Lclcalipsoliq  .or. cfg%Lclcalipsoun    .or. cfg%Lclcalipso2 .or.  &
+        cfg%Lclhcalipso      .or. cfg%Lclmcalipso    .or. cfg%Lcllcalipso     .or. cfg%Lcltcalipso .or.  &
+        cfg%Lclcalipsotmp    .or. cfg%Lclcalipsoice  .or. cfg%Lclcalipsotmpun .or.                       &
+        cfg%Lclcalipsotmpliq .or. cfg%Lcllcalipsoice .or. cfg%Lclmcalipsoice  .or.                       &
+        cfg%Lclhcalipsoice   .or. cfg%Lcltcalipsoice .or. cfg%Lcllcalipsoliq  .or.                       &
+        cfg%Lclmcalipsoliq   .or. cfg%Lclhcalipsoliq .or. cfg%Lcltcalipsoliq  .or.                       &
+        cfg%Lcllcalipsoun    .or. cfg%Lclmcalipsoun  .or. cfg%Lclhcalipsoun   .or. cfg%Lcltcalipsoun) then
+       allocate(x%calipso_tau_tot(Npoints,Ncolumns,Nlevels))       
+       allocate(x%calipso_temp_tot(Npoints,Nlevels))               
+    endif
+
+    ! GROUND LIDAR @ 532NM simulator
+    if (cfg%LlidarBetaMol532gr) allocate(x%grLidar532_beta_mol(Npoints,Nlevels))
+    if (cfg%Latb532gr)          allocate(x%grLidar532_beta_tot(Npoints,Ncolumns,Nlevels))
+    if (cfg%LcfadLidarsr532gr) then 
+        allocate(x%grLidar532_srbval(SR_BINS+1)) 
+        allocate(x%grLidar532_cfad_sr(Npoints,SR_BINS,Nlvgrid))
+    endif
+    if (cfg%LclgrLidar532)     allocate(x%grLidar532_lidarcld(Npoints,Nlvgrid)) 
+    if (cfg%LclhgrLidar532 .or. cfg%LclmgrLidar532 .or. cfg%LcllgrLidar532 .or. cfg%LcltgrLidar532) then
+        allocate(x%grLidar532_cldlayer(Npoints,LIDAR_NCAT))  
+    endif
+      
+    ! ATLID simulator
+    if (cfg%LlidarBetaMol355) allocate(x%atlid_beta_mol(Npoints,Nlevels))
+    if (cfg%Latb355)          allocate(x%atlid_beta_tot(Npoints,Ncolumns,Nlevels))
+    if (cfg%LcfadLidarsr355) then
+        allocate(x%atlid_srbval(SR_BINS+1)) 
+        allocate(x%atlid_cfad_sr(Npoints,SR_BINS,Nlvgrid))
+    endif 
+    if (cfg%Lclatlid)     allocate(x%atlid_lidarcld(Npoints,Nlvgrid)) 
+    if (cfg%Lclhatlid .or. cfg%Lclmatlid .or. cfg%Lcllatlid .or. cfg%Lcltatlid) then
+        allocate(x%atlid_cldlayer(Npoints,LIDAR_NCAT)) 
+    endif
+      
+    ! PARASOL
+    if (cfg%Lparasolrefl) then
+        allocate(x%parasolPix_refl(Npoints,Ncolumns,PARASOL_NREFL))
+        allocate(x%parasolGrid_refl(Npoints,PARASOL_NREFL))
+    endif 
+
+    ! Cloudsat simulator
+    if (cfg%Ldbze94)        allocate(x%cloudsat_Ze_tot(Npoints,Ncolumns,Nlevels))
+    if (cfg%LcfadDbze94)    allocate(x%cloudsat_cfad_ze(Npoints,cloudsat_DBZE_BINS,Nlvgrid))
+    if (cfg%Lptradarflag0 .or. cfg%Lptradarflag1 .or. cfg%Lptradarflag2 .or. cfg%Lptradarflag3 .or. &
+        cfg%Lptradarflag4 .or. cfg%Lptradarflag5 .or. cfg%Lptradarflag6 .or. cfg%Lptradarflag7 .or. &
+        cfg%Lptradarflag8 .or. cfg%Lptradarflag9) then
+       allocate(x%cloudsat_precip_cover(Npoints,cloudsat_DBZE_BINS))
+    endif
+    if (cfg%Lradarpia) allocate(x%cloudsat_pia(Npoints))
+
+    ! Combined CALIPSO/CLOUDSAT fields
+    if (cfg%Lclcalipso2)    allocate(x%lidar_only_freq_cloud(Npoints,Nlvgrid))
+    if (cfg%Lcltlidarradar) allocate(x%radar_lidar_tcc(Npoints))
+    if (cfg%Lcloudsat_tcc)  allocate(x%cloudsat_tcc(Npoints))
+    if (cfg%Lcloudsat_tcc2) allocate(x%cloudsat_tcc2(Npoints))
+            
+    ! RTTOV
+    if (cfg%Ltbrttov) allocate(x%rttov_tbs(Npoints,Nchan))
+ 
+  end subroutine construct_cosp_outputs
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! SUBROUTINE destroy_cospIN     
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  subroutine destroy_cospIN(y)
+    type(cosp_optical_inputs),intent(inout) :: y
+
+    if (allocated(y%tau_067))       	  deallocate(y%tau_067)
+    if (allocated(y%emiss_11))      	  deallocate(y%emiss_11)
+    if (allocated(y%frac_out))    	  deallocate(y%frac_out)
+    if (allocated(y%beta_mol_calipso))    deallocate(y%beta_mol_calipso)
+    if (allocated(y%tau_mol_calipso))     deallocate(y%tau_mol_calipso)
+    if (allocated(y%betatot_calipso))     deallocate(y%betatot_calipso)
+    if (allocated(y%betatot_ice_calipso)) deallocate(y%betatot_ice_calipso)
+    if (allocated(y%betatot_liq_calipso)) deallocate(y%betatot_liq_calipso)
+    if (allocated(y%tautot_calipso))      deallocate(y%tautot_calipso)
+    if (allocated(y%tautot_ice_calipso))  deallocate(y%tautot_ice_calipso)
+    if (allocated(y%tautot_liq_calipso))  deallocate(y%tautot_liq_calipso)
+    if (allocated(y%tautot_S_liq))	  deallocate(y%tautot_S_liq)
+    if (allocated(y%tautot_S_ice))    	  deallocate(y%tautot_S_ice)
+    if (allocated(y%z_vol_cloudsat))  	  deallocate(y%z_vol_cloudsat)
+    if (allocated(y%kr_vol_cloudsat)) 	  deallocate(y%kr_vol_cloudsat)
+    if (allocated(y%g_vol_cloudsat)) 	  deallocate(y%g_vol_cloudsat)
+    if (allocated(y%asym))            	  deallocate(y%asym)
+    if (allocated(y%ss_alb))         	  deallocate(y%ss_alb)
+    if (allocated(y%fracLiq))       	  deallocate(y%fracLiq)
+    if (allocated(y%beta_mol_grLidar532)) deallocate(y%beta_mol_grLidar532)
+    if (allocated(y%betatot_grLidar532))  deallocate(y%betatot_grLidar532)
+    if (allocated(y%tau_mol_grLidar532))  deallocate(y%tau_mol_grLidar532)
+    if (allocated(y%tautot_grLidar532))   deallocate(y%tautot_grLidar532)
+    if (allocated(y%beta_mol_atlid))      deallocate(y%beta_mol_atlid) 
+    if (allocated(y%betatot_atlid))       deallocate(y%betatot_atlid) 
+    if (allocated(y%tau_mol_atlid))       deallocate(y%tau_mol_atlid) 
+    if (allocated(y%tautot_atlid))        deallocate(y%tautot_atlid)
+    if (allocated(y%fracPrecipIce))       deallocate(y%fracPrecipIce)
+
+  end subroutine destroy_cospIN
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! SUBROUTINE destroy_cospstateIN     
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
+  subroutine destroy_cospstateIN(y)
+    type(cosp_column_inputs),intent(inout) :: y
+
+    if (allocated(y%sunlit))          deallocate(y%sunlit)
+    if (allocated(y%skt))             deallocate(y%skt)
+    if (allocated(y%land))            deallocate(y%land)
+    if (allocated(y%at))              deallocate(y%at)
+    if (allocated(y%pfull))           deallocate(y%pfull)
+    if (allocated(y%phalf))           deallocate(y%phalf)
+    if (allocated(y%qv))              deallocate(y%qv)
+    if (allocated(y%o3))              deallocate(y%o3)
+    if (allocated(y%hgt_matrix))      deallocate(y%hgt_matrix)
+    if (allocated(y%u_sfc))           deallocate(y%u_sfc)
+    if (allocated(y%v_sfc))           deallocate(y%v_sfc)
+    if (allocated(y%lat))             deallocate(y%lat)
+    if (allocated(y%lon))             deallocate(y%lon)
+    if (allocated(y%emis_sfc))        deallocate(y%emis_sfc)
+    if (allocated(y%cloudIce))        deallocate(y%cloudIce)
+    if (allocated(y%cloudLiq))        deallocate(y%cloudLiq)
+    if (allocated(y%seaice))          deallocate(y%seaice)
+    if (allocated(y%fl_rain))         deallocate(y%fl_rain)
+    if (allocated(y%fl_snow))         deallocate(y%fl_snow)
+    if (allocated(y%tca))             deallocate(y%tca)
+    if (allocated(y%hgt_matrix_half)) deallocate(y%hgt_matrix_half)    
+    if (allocated(y%surfelev))        deallocate(y%surfelev)
+    
+  end subroutine destroy_cospstateIN
+  
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! SUBROUTINE destroy_cosp_outputs
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
+  subroutine destroy_cosp_outputs(y)
+     type(cosp_outputs),intent(inout) :: y
+
+     ! Deallocate and nullify
+     if (associated(y%calipso_beta_mol))          then
+        deallocate(y%calipso_beta_mol)
+        nullify(y%calipso_beta_mol)
+     endif
+     if (associated(y%calipso_temp_tot))          then
+        deallocate(y%calipso_temp_tot)
+        nullify(y%calipso_temp_tot)     
+     endif
+     if (associated(y%calipso_betaperp_tot))      then
+        deallocate(y%calipso_betaperp_tot)
+        nullify(y%calipso_betaperp_tot)     
+     endif
+     if (associated(y%calipso_beta_tot))          then
+        deallocate(y%calipso_beta_tot)    
+        nullify(y%calipso_beta_tot)     
+     endif
+     if (associated(y%calipso_tau_tot))           then
+        deallocate(y%calipso_tau_tot) 
+        nullify(y%calipso_tau_tot)     
+     endif
+     if (associated(y%calipso_lidarcldphase))     then
+        deallocate(y%calipso_lidarcldphase)
+        nullify(y%calipso_lidarcldphase)     
+     endif
+     if (associated(y%calipso_lidarcldtype))     then
+        deallocate(y%calipso_lidarcldtype) 
+        nullify(y%calipso_lidarcldtype) 
+     endif
+     if (associated(y%calipso_cldlayerphase))     then
+        deallocate(y%calipso_cldlayerphase)
+        nullify(y%calipso_cldlayerphase)     
+     endif
+     if (associated(y%calipso_lidarcldtmp))       then
+        deallocate(y%calipso_lidarcldtmp)
+        nullify(y%calipso_lidarcldtmp)     
+     endif
+     if (associated(y%calipso_cldlayer))          then
+        deallocate(y%calipso_cldlayer)
+        nullify(y%calipso_cldlayer)     
+     endif
+     if (associated(y%calipso_cldtype))          then
+        deallocate(y%calipso_cldtype)
+        nullify(y%calipso_cldtype)  
+     endif  
+     if (associated(y%calipso_cldtypetemp))      then
+        deallocate(y%calipso_cldtypetemp) 
+        nullify(y%calipso_cldtypetemp) 
+     endif 
+     if (associated(y%calipso_cldtypemeanz))     then
+        deallocate(y%calipso_cldtypemeanz)
+        nullify(y%calipso_cldtypemeanz)  
+     endif  
+     if (associated(y%calipso_cldtypemeanzse))   then 
+        deallocate(y%calipso_cldtypemeanzse) 
+        nullify(y%calipso_cldtypemeanzse)  
+     endif 
+     if (associated(y%calipso_cldthinemis))      then
+        deallocate(y%calipso_cldthinemis)
+        nullify(y%calipso_cldthinemis)
+     endif 
+     if (associated(y%calipso_lidarcld))         then
+        deallocate(y%calipso_lidarcld)
+        nullify(y%calipso_lidarcld)     
+     endif
+     if (associated(y%calipso_srbval))            then
+        deallocate(y%calipso_srbval)
+        nullify(y%calipso_srbval)     
+     endif
+     if (associated(y%calipso_cfad_sr))          then
+        deallocate(y%calipso_cfad_sr)
+        nullify(y%calipso_cfad_sr)     
+     endif
+     if (associated(y%grLidar532_beta_mol))     then
+        deallocate(y%grLidar532_beta_mol)
+        nullify(y%grLidar532_beta_mol)  
+     endif
+     if (associated(y%grLidar532_beta_tot))     then 
+        deallocate(y%grLidar532_beta_tot) 
+        nullify(y%grLidar532_beta_tot)
+     endif 
+     if (associated(y%grLidar532_cldlayer))     then 
+        deallocate(y%grLidar532_cldlayer) 
+        nullify(y%grLidar532_cldlayer) 
+     endif 
+     if (associated(y%grLidar532_lidarcld))     then 
+        deallocate(y%grLidar532_lidarcld) 
+        nullify(y%grLidar532_lidarcld) 
+     endif 
+     if (associated(y%grLidar532_cfad_sr))      then 
+        deallocate(y%grLidar532_cfad_sr)  
+        nullify(y%grLidar532_cfad_sr) 
+     endif 
+     if (associated(y%grLidar532_srbval))       then
+        deallocate(y%grLidar532_srbval) 
+        nullify(y%grLidar532_srbval) 
+     endif  
+     if (associated(y%atlid_beta_mol))           then
+        deallocate(y%atlid_beta_mol) 
+        nullify(y%atlid_beta_mol) 
+     endif 
+     if (associated(y%atlid_beta_tot))           then
+        deallocate(y%atlid_beta_tot) 
+        nullify(y%atlid_beta_tot) 
+     endif
+     if (associated(y%atlid_cldlayer))           then 
+        deallocate(y%atlid_cldlayer)  
+        nullify(y%atlid_cldlayer) 
+     endif 
+     if (associated(y%atlid_lidarcld))           then 
+        deallocate(y%atlid_lidarcld)  
+        nullify(y%atlid_lidarcld) 
+     endif  
+     if (associated(y%atlid_cfad_sr))            then
+        deallocate(y%atlid_cfad_sr) 
+        nullify(y%atlid_cfad_sr) 
+     endif
+     if (associated(y%atlid_srbval))             then 
+        deallocate(y%atlid_srbval) 
+        nullify(y%atlid_srbval) 
+     endif
+     if (associated(y%parasolPix_refl))           then
+        deallocate(y%parasolPix_refl)
+        nullify(y%parasolPix_refl)     
+     endif
+     if (associated(y%parasolGrid_refl))          then
+        deallocate(y%parasolGrid_refl) 
+        nullify(y%parasolGrid_refl)     
+     endif
+     if (associated(y%cloudsat_Ze_tot))           then
+        deallocate(y%cloudsat_Ze_tot) 
+        nullify(y%cloudsat_Ze_tot)  
+     endif
+     if (associated(y%cloudsat_cfad_ze))          then
+        deallocate(y%cloudsat_cfad_ze)
+        nullify(y%cloudsat_cfad_ze)     
+     endif
+     if (associated(y%cloudsat_precip_cover))     then
+        deallocate(y%cloudsat_precip_cover)
+        nullify(y%cloudsat_precip_cover)
+     endif
+     if (associated(y%cloudsat_pia))              then
+        deallocate(y%cloudsat_pia)
+        nullify(y%cloudsat_pia)
+     endif
+     if (associated(y%cloudsat_tcc))           then
+        deallocate(y%cloudsat_tcc) 
+        nullify(y%cloudsat_tcc)  
+     endif
+     if (associated(y%cloudsat_tcc2))           then
+        deallocate(y%cloudsat_tcc2) 
+        nullify(y%cloudsat_tcc2)  
+     endif
+     if (associated(y%radar_lidar_tcc))           then
+        deallocate(y%radar_lidar_tcc) 
+        nullify(y%radar_lidar_tcc)  
+     endif
+     if (associated(y%cloudsat_tcc))           then
+        deallocate(y%cloudsat_tcc) 
+        nullify(y%cloudsat_tcc)  
+     endif
+     if (associated(y%cloudsat_tcc2))           then
+        deallocate(y%cloudsat_tcc2) 
+        nullify(y%cloudsat_tcc2)  
+     endif
+     if (associated(y%lidar_only_freq_cloud))     then
+        deallocate(y%lidar_only_freq_cloud)
+        nullify(y%lidar_only_freq_cloud)     
+     endif
+     if (associated(y%isccp_totalcldarea))        then
+        deallocate(y%isccp_totalcldarea) 
+        nullify(y%isccp_totalcldarea)  
+     endif
+     if (associated(y%isccp_meantb))              then
+        deallocate(y%isccp_meantb) 
+        nullify(y%isccp_meantb)     
+     endif
+     if (associated(y%isccp_meantbclr))           then
+        deallocate(y%isccp_meantbclr)
+        nullify(y%isccp_meantbclr)  
+     endif
+     if (associated(y%isccp_meanptop))            then
+        deallocate(y%isccp_meanptop)
+        nullify(y%isccp_meanptop)     
+     endif
+     if (associated(y%isccp_meantaucld))          then
+        deallocate(y%isccp_meantaucld) 
+        nullify(y%isccp_meantaucld)       
+     endif
+     if (associated(y%isccp_meanalbedocld))       then
+        deallocate(y%isccp_meanalbedocld)
+        nullify(y%isccp_meanalbedocld)     
+     endif
+     if (associated(y%isccp_boxtau))              then
+        deallocate(y%isccp_boxtau)
+        nullify(y%isccp_boxtau)       
+     endif
+     if (associated(y%isccp_boxptop))             then
+        deallocate(y%isccp_boxptop)
+        nullify(y%isccp_boxptop)     
+     endif
+     if (associated(y%isccp_fq))                  then
+        deallocate(y%isccp_fq)
+        nullify(y%isccp_fq)       
+     endif
+     if (associated(y%misr_fq))                   then
+        deallocate(y%misr_fq) 
+        nullify(y%misr_fq)     
+     endif
+     if (associated(y%misr_dist_model_layertops)) then
+        deallocate(y%misr_dist_model_layertops)
+        nullify(y%misr_dist_model_layertops)       
+     endif
+     if (associated(y%misr_meanztop))             then
+        deallocate(y%misr_meanztop)
+        nullify(y%misr_meanztop)     
+     endif
+     if (associated(y%misr_cldarea))              then
+        deallocate(y%misr_cldarea)
+        nullify(y%misr_cldarea)      
+     endif
+     if (associated(y%rttov_tbs))                 then
+        deallocate(y%rttov_tbs)
+        nullify(y%rttov_tbs)     
+     endif
+     if (associated(y%modis_Cloud_Fraction_Total_Mean))                      then
+        deallocate(y%modis_Cloud_Fraction_Total_Mean)       
+        nullify(y%modis_Cloud_Fraction_Total_Mean)       
+     endif
+     if (associated(y%modis_Cloud_Fraction_Ice_Mean))                        then
+        deallocate(y%modis_Cloud_Fraction_Ice_Mean)     
+        nullify(y%modis_Cloud_Fraction_Ice_Mean)     
+     endif
+     if (associated(y%modis_Cloud_Fraction_Water_Mean))                      then
+        deallocate(y%modis_Cloud_Fraction_Water_Mean)           
+        nullify(y%modis_Cloud_Fraction_Water_Mean)           
+     endif
+     if (associated(y%modis_Cloud_Fraction_High_Mean))                       then
+        deallocate(y%modis_Cloud_Fraction_High_Mean)     
+        nullify(y%modis_Cloud_Fraction_High_Mean)     
+     endif
+     if (associated(y%modis_Cloud_Fraction_Mid_Mean))                        then
+        deallocate(y%modis_Cloud_Fraction_Mid_Mean)       
+        nullify(y%modis_Cloud_Fraction_Mid_Mean)       
+     endif
+     if (associated(y%modis_Cloud_Fraction_Low_Mean))                        then
+        deallocate(y%modis_Cloud_Fraction_Low_Mean)     
+        nullify(y%modis_Cloud_Fraction_Low_Mean)     
+     endif
+     if (associated(y%modis_Optical_Thickness_Total_Mean))                   then
+        deallocate(y%modis_Optical_Thickness_Total_Mean)  
+        nullify(y%modis_Optical_Thickness_Total_Mean)  
+     endif
+     if (associated(y%modis_Optical_Thickness_Water_Mean))                   then
+        deallocate(y%modis_Optical_Thickness_Water_Mean)     
+        nullify(y%modis_Optical_Thickness_Water_Mean)     
+     endif
+     if (associated(y%modis_Optical_Thickness_Ice_Mean))                     then
+        deallocate(y%modis_Optical_Thickness_Ice_Mean)       
+        nullify(y%modis_Optical_Thickness_Ice_Mean)       
+     endif
+     if (associated(y%modis_Optical_Thickness_Total_LogMean))                then
+        deallocate(y%modis_Optical_Thickness_Total_LogMean)    
+        nullify(y%modis_Optical_Thickness_Total_LogMean)    
+     endif
+     if (associated(y%modis_Optical_Thickness_Water_LogMean))                then
+        deallocate(y%modis_Optical_Thickness_Water_LogMean)     
+        nullify(y%modis_Optical_Thickness_Water_LogMean)     
+     endif
+     if (associated(y%modis_Optical_Thickness_Ice_LogMean))                  then
+        deallocate(y%modis_Optical_Thickness_Ice_LogMean)     
+        nullify(y%modis_Optical_Thickness_Ice_LogMean)     
+     endif
+     if (associated(y%modis_Cloud_Particle_Size_Water_Mean))                 then
+        deallocate(y%modis_Cloud_Particle_Size_Water_Mean)       
+        nullify(y%modis_Cloud_Particle_Size_Water_Mean)       
+     endif
+     if (associated(y%modis_Cloud_Particle_Size_Ice_Mean))                   then
+        deallocate(y%modis_Cloud_Particle_Size_Ice_Mean)     
+        nullify(y%modis_Cloud_Particle_Size_Ice_Mean)     
+     endif
+     if (associated(y%modis_Cloud_Top_Pressure_Total_Mean))                  then
+        deallocate(y%modis_Cloud_Top_Pressure_Total_Mean)           
+        nullify(y%modis_Cloud_Top_Pressure_Total_Mean)           
+     endif
+     if (associated(y%modis_Liquid_Water_Path_Mean))                         then
+        deallocate(y%modis_Liquid_Water_Path_Mean)     
+        nullify(y%modis_Liquid_Water_Path_Mean)     
+     endif
+     if (associated(y%modis_Ice_Water_Path_Mean))                            then
+        deallocate(y%modis_Ice_Water_Path_Mean)       
+        nullify(y%modis_Ice_Water_Path_Mean)       
+     endif
+     if (associated(y%modis_Optical_Thickness_vs_Cloud_Top_Pressure))        then
+        deallocate(y%modis_Optical_Thickness_vs_Cloud_Top_Pressure)     
+        nullify(y%modis_Optical_Thickness_vs_Cloud_Top_Pressure)     
+     endif
+     if (associated(y%modis_Optical_thickness_vs_ReffLIQ))                   then
+        deallocate(y%modis_Optical_thickness_vs_ReffLIQ)
+        nullify(y%modis_Optical_thickness_vs_ReffLIQ)
+     endif
+     if (associated(y%modis_Optical_thickness_vs_ReffICE))                   then
+        deallocate(y%modis_Optical_thickness_vs_ReffICE)
+        nullify(y%modis_Optical_thickness_vs_ReffICE)
+     endif
+        
+   end subroutine destroy_cosp_outputs
+
+END MODULE LMDZ_COSP_CONSTRUCT_DESTROY_MOD
+
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_interface.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_interface.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_interface.F90	(revision 3605)
@@ -0,0 +1,589 @@
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!
+! Nouveau code d'interface entre LMDZ et COSPv2 (version 2)
+! L'ancienne interface s'appelait "phys_cosp2" et avait ete concue pour COSPv1.4.
+! Dans cette nouvelle version de COSP, le code a ete restructure pour optimiser les calculs
+! des differents simulateurs et pour proposer de nouvelles fonctionnalites (par exemple,
+! intervenir sur les profils sous-maille, ou subcolumns, donnes en entre a COSP afin que
+! leur definition soit coherente avec les parametrisations du modele hote).
+! Cette version de COSP propose aussi de nombreux nouveaux diagnostics, notamment pour
+! le simulateur lidar (diagnostics CALIPSO-OPAQ, lidar sol 532nm et lidar ATLID 355nm).
+!
+! Interface reecrite par R.Guzman (01/2019), a partir de l'interface initiale concue
+! et ecrite par A.Idelkadi 
+!
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!  subroutine phys_cosp2( itap,dtime,freq_cosp, &
+  subroutine lmdz_cosp_interface(itap, dtime, freq_cosp, ok_mensuelCOSP, ok_journeCOSP,   &
+                         ok_hfCOSP, ecrit_mth, ecrit_day, ecrit_hf, ok_all_xml,   &
+                         missing_val, Nptslmdz, Nlevlmdz, lon, lat, presnivs,     &
+                         overlaplmdz, sunlit, ref_liq, ref_ice, fracTerLic,       &
+                         u_wind, v_wind, phis, phi, ph, p, skt, t, sh, rh,        &
+                         tca, cca, mr_lsliq, mr_lsice, fl_lsrainI, fl_lssnowI,    &
+                         fl_ccrainI, fl_ccsnowI, mr_ozone, dtau_s, dem_s)
+
+!--------------  Inputs  ---------------
+! itap,                                 !Increment de la physiq
+! dtime,                                !Pas de temps physiq
+! overlaplmdz,                          !Type Overlap venant de LMDZ
+! Npoints,                              !Nb de points de la grille physiq
+! Nlevels,                              !Nb de niveaux verticaux
+! Ncolumns,                             !Number of subcolumns
+! lon,lat,                              !Longitudes et latitudes de la grille LMDZ
+! ref_liq, ref_ice,                     !Rayons effectifs des particules liq et ice (en micron)
+! fracTerLic,                           !Fraction terre a convertir en masque
+! u_wind, v_wind,                       !Vents a 10m ???
+! phi,                                  !Geopotentiel
+! phis,                                 !Geopotentiel sol
+! ph,                                   !pression pour chaque inter-couche
+! p,                                    !Pression aux milieux des couches
+! skt, t,                               !Temp au sol et temp 3D
+! sh,                                   !Humidite specifique
+! rh,                                   !Humidite relative
+! tca,                                  !Fraction nuageuse
+! cca                                   !Fraction nuageuse convective
+! mr_lsliq,                             !Liq Cloud water content
+! mr_lsice,                             !Ice Cloud water content
+! mr_ccliq,                             !Convective Cloud Liquid water content  
+! mr_ccice,                             !Cloud ice water content
+! fl_lsrain,                            !Large scale precipitation lic
+! fl_lssnow,                            !Large scale precipitation ice
+! fl_ccrain,                            !Convective precipitation lic
+! fl_ccsnow,                            !Convective precipitation ice
+! mr_ozone,                             !Concentration ozone (Kg/Kg)
+! dem_s                                 !Cloud optical emissivity
+! dtau_s               			!Cloud optical thickness
+! emsfc_lw = 1.        			!Surface emissivity dans radlwsw.F90
+
+
+!--------------  Outputs  --------------
+! La liste complete des diagnostics de sortie (observables simulees) que l'on peut
+! avoir avec COSPv2 se trouve au debut du fichier : cosp_read_otputkeys.F90
+
+
+!!! Modules specifiques a l'interface LMDZ-COSP
+  use mod_phys_lmdz_para
+  use mod_grid_phy_lmdz
+  use ioipsl
+  use iophy
+  use lmdz_cosp_output_mod
+  use lmdz_cosp_output_write_mod
+  use lmdz_cosp_read_outputkeys
+  use lmdz_cosp_subsample_and_optics_mod, only : subsample_and_optics
+  use lmdz_cosp_construct_destroy_mod
+
+!!! Modules faisant partie du code source de COSPv2
+  use cosp_kinds,		  only: wp                         
+  use MOD_COSP_CONFIG,     		  only: N_HYDRO,RTTOV_MAX_CHANNELS, &
+      			   	 		niv_sorties, vgrid_z_in
+  use mod_quickbeam_optics,		  only: size_distribution,hydro_class_init, &
+                                 		quickbeam_optics_init
+  use quickbeam,           		  only: radar_cfg
+  use mod_cosp,            		  only: cosp_init,cosp_optical_inputs, &
+      						cosp_column_inputs,cosp_outputs, &
+						cosp_simulator
+
+
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!
+! Declaration des variables 
+!
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+  IMPLICIT NONE
+
+  ! Local variables
+  character(len=64),PARAMETER	:: cosp_input_nl  = 'cosp_input_nl.txt'
+  character(len=64),PARAMETER  	:: cosp_output_nl = 'cosp_output_nl.txt'
+
+  integer, save 	       	:: isccp_topheight, isccp_topheight_direction, overlap
+  integer, save  	       	:: Ncolumns    	    	! Number of subcolumns in SCOPS
+  integer, save 	       	:: Npoints            	! Number of gridpoints
+!$OMP THREADPRIVATE(Npoints)
+  integer, save			:: Nlevels		! Number of model vertical levels
+  integer  			:: Nptslmdz, Nlevlmdz  	! Nb de points issus de physiq.F
+  integer, save 		:: Npoints_it   	! Max number of gridpoints to be 
+  	   			   			! processed in one iteration
+  type(cosp_config), save 	:: cfg          	! Variable qui contient les cles
+  		     		   			! logiques des simulateurs et des
+							! diagnostics, definie dans:
+							! lmdz_cosp_construct_destroy_mod
+!$OMP THREADPRIVATE(cfg)
+
+  integer			:: t0, t1, count_rate, count_max
+  real(wp), save 		:: cloudsat_radar_freq, cloudsat_k2, rttov_ZenAng, co2, &
+  	    			   ch4, n2o, co, emsfc_lw
+!$OMP THREADPRIVATE(emsfc_lw)
+
+  integer, dimension(RTTOV_MAX_CHANNELS), save	 :: rttov_Channels
+  real(wp), dimension(RTTOV_MAX_CHANNELS), save  :: rttov_Surfem
+  integer, save 			   	 :: surface_radar, use_mie_tables, &
+  	   					    cloudsat_use_gas_abs, cloudsat_do_ray, &
+						    melt_lay
+  integer, save 				 :: lidar_ice_type
+  integer, save 				 :: rttov_platform, rttov_satellite, &
+  	   					    rttov_Instrument, rttov_Nchannels
+  logical, save 				 :: use_vgrid_in, csat_vgrid_in, &
+  	   					    use_precipitation_fluxes
+
+! Declaration necessaires pour les sorties IOIPSL
+  real        	:: ecrit_day, ecrit_hf, ecrit_mth, missing_val
+  logical 	:: ok_mensuelCOSP, ok_journeCOSP, ok_hfCOSP, ok_all_xml
+  logical, save :: debut_cosp=.true.
+!$OMP THREADPRIVATE(debut_cosp)
+
+  logical, save :: first_write=.true.
+!$OMP THREADPRIVATE(first_write)
+
+  integer, save :: cosp_init_flag = 0
+!$OMP THREADPRIVATE(cosp_init_flag)
+
+
+!-----------------------------  Input variables from LMDZ-GCM  -------------------------------
+  integer                             	     :: overlaplmdz   ! overlap type: 1=max, 
+  					       		      ! 2=rand, 3=max/rand
+  real, dimension(Nptslmdz,Nlevlmdz) 	     :: phi, p, ph, T, sh, rh, tca, cca, mr_lsliq,   &
+  					        mr_lsice, mr_ccliq, mr_ccice, fl_lsrain,     & 
+                                       	        fl_lssnow, fl_ccrain, fl_ccsnow, fl_lsgrpl,  &
+                                       	        zlev, zlev_half, mr_ozone, radliq, radice,   &
+					        dtau_s, dem_s, dtau_c, dem_c, ref_liq, ref_ice
+  real, dimension(Nptslmdz,Nlevlmdz) 	     :: fl_lsrainI, fl_lssnowI, fl_ccrainI, fl_ccsnowI
+  real, dimension(Nptslmdz)        	     :: lon, lat, skt, fracTerLic, u_wind, v_wind, &
+  					        phis, sunlit
+  real, dimension(Nptslmdz)        	     :: land ! variables intermediaire pour masque TerLic
+  real, dimension(Nlevlmdz)        	     :: presnivs
+  integer                         	     :: itap, k, ip
+  real                            	     :: dtime, freq_cosp
+  real, dimension(2)               	     :: time_bnds
+
+  double precision                           :: d_dtime
+  double precision, dimension(2)             :: d_time_bnds
+
+
+  ! ######################################################################################
+  ! Declarations specific to COSP2
+  ! ######################################################################################
+
+  ! Local variables
+  logical :: &
+       Lsingle     = .true.,  & ! True if using MMF_v3_single_moment CLOUDSAT
+       		     	      	! microphysical scheme (default)
+       Ldouble     = .false.    ! True if using MMF_v3.5_two_moment CLOUDSAT 
+       		     		! microphysical scheme
+  type(size_distribution), save   	     :: sd            ! Hydrometeor description
+!$OMP THREADPRIVATE(sd)
+  type(radar_cfg), save			     :: rcfg_cloudsat ! Radar configuration
+!$OMP THREADPRIVATE(rcfg_cloudsat)
+  real, dimension(Nptslmdz,Nlevlmdz,N_HYDRO) :: Reff	      ! Liquid and Ice particles
+  					     		      ! effective radius
+  type(cosp_outputs)			     :: cospOUT       ! COSP simulator outputs
+  type(cosp_optical_inputs) 		     :: cospIN        ! COSP optical (or derived?)
+  					     		      ! fields needed by simulators
+  type(cosp_column_inputs) 		     :: cospstateIN   ! COSP model fields needed
+  					     		      ! by simulators
+  character(len=256), dimension(100)	     :: cosp_status
+  character(len=64), save      		     :: cloudsat_micro_scheme
+
+  ! Indices to address arrays of LS and CONV hydrometeors
+  integer,parameter :: &
+       I_LSCLIQ = 1, & ! Large-scale (stratiform) liquid
+       I_LSCICE = 2, & ! Large-scale (stratiform) ice
+       I_LSRAIN = 3, & ! Large-scale (stratiform) rain
+       I_LSSNOW = 4, & ! Large-scale (stratiform) snow
+       I_CVCLIQ = 5, & ! Convective liquid
+       I_CVCICE = 6, & ! Convective ice
+       I_CVRAIN = 7, & ! Convective rain
+       I_CVSNOW = 8, & ! Convective snow
+       I_LSGRPL = 9    ! Large-scale (stratiform) groupel
+
+! Parametres qui sont lus a partir du fichier "cosp_input_nl.txt"
+   namelist/COSP_INPUT/overlap, isccp_topheight, isccp_topheight_direction,	  &
+              npoints_it, ncolumns, use_vgrid_in, csat_vgrid_in,		  &
+              cloudsat_radar_freq, surface_radar, use_mie_tables,		  &
+              cloudsat_use_gas_abs, cloudsat_do_ray, melt_lay, cloudsat_k2, 	  &
+              cloudsat_micro_scheme, lidar_ice_type, use_precipitation_fluxes, 	  &
+              rttov_platform, rttov_satellite, rttov_Instrument, rttov_Nchannels, &
+              rttov_Channels, rttov_Surfem, rttov_ZenAng, co2, ch4, n2o, co
+
+!------------------------   Fin declaration des variables   ------------------------
+
+
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!
+! 1) Lecture du fichier "cosp_input_nl.txt", parametres d'entree pour COSP
+!
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+ print*,'Entree lmdz_cosp_interface' !phys_cosp2'
+ if (debut_cosp) then
+  NPoints=Nptslmdz
+  Nlevels=Nlevlmdz
+! Surface emissivity
+        emsfc_lw = 1.
+  
+! Lecture du namelist input 
+!  CALL read_cosp_input
+   IF (is_master) THEN
+      OPEN(10,file=cosp_input_nl,status='old')
+      READ(10,nml=cosp_input)
+      CLOSE(10)
+   ENDIF
+
+
+!$OMP BARRIER 
+    CALL bcast(overlap)
+    CALL bcast(isccp_topheight)
+    CALL bcast(isccp_topheight_direction)
+    CALL bcast(npoints_it)
+    CALL bcast(ncolumns)
+    CALL bcast(use_vgrid_in)
+    CALL bcast(csat_vgrid_in)
+    CALL bcast(cloudsat_radar_freq)
+    CALL bcast(surface_radar)
+    CALL bcast(cloudsat_use_gas_abs)
+    CALL bcast(cloudsat_do_ray)
+    CALL bcast(cloudsat_k2)
+    CALL bcast(lidar_ice_type)
+    CALL bcast(use_precipitation_fluxes)
+    CALL bcast(rttov_platform)
+    CALL bcast(rttov_satellite)
+    CALL bcast(rttov_Instrument)
+    CALL bcast(rttov_Nchannels)
+    CALL bcast(rttov_Channels)
+    CALL bcast(rttov_Surfem)
+    CALL bcast(rttov_ZenAng)
+    CALL bcast(co2)
+    CALL bcast(ch4)
+    CALL bcast(n2o)
+    CALL bcast(co)
+    CALL bcast(cloudsat_micro_scheme)
+
+    print*,'ok read  cosp_input_nl'
+
+
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!
+! 2) Initialisation de COSPv2
+!
+! Il y a 2 options possibles pour ecrire les sorties : XIOS ou sorties standard
+!
+! Si le modele a ete compile AVEC l'option xios, le programme passe par les
+! bouts de code delimites par "#ifdef CPP_XIOS" et "#else". Dans ce cas,
+! l'initialisation de COSP se fait au deuxieme appel de cette interface.
+!
+! Si le modele a ete compile SANS l'option xios, le programme passe par les
+! bouts de code delimites par "#else" et "#endif". Dans ce cas,
+! l'initialisation de COSP se fait au premier appel de cette interface.
+!
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+! Clefs Outputs initialisation
+#ifdef CPP_XIOS
+  call cosp_outputkeys_init(cfg)
+#else
+   call read_cosp_output_nl(itap,cosp_output_nl,cfg)
+#endif
+
+  print*,' Cles des differents simulateurs cosp a itap :',itap
+print*,'cfg%Lcloudsat, cfg%Lcalipso, cfg%LgrLidar532, cfg%Latlid, cfg%Lparasol, &
+	cfg%Lisccp, cfg%Lmisr, cfg%Lmodis, cfg%Lrttov', &
+        cfg%Lcloudsat, cfg%Lcalipso, cfg%LgrLidar532, cfg%Latlid, cfg%Lparasol, &
+	cfg%Lisccp, cfg%Lmisr, cfg%Lmodis, cfg%Lrttov
+
+    if (overlaplmdz.ne.overlap) then
+       print*,'Attention overlaplmdz different de overlap lu dans namelist '
+    endif
+
+#ifdef CPP_XIOS
+   print*,'On passe par ifdef CPP_XIOS'
+#else
+if (cosp_init_flag .eq. 0) then
+
+    ! Initialize the distributional parameters for hydrometeors in radar simulator.
+    ! In COSPv1.4, this was declared in cosp_defs.f.
+    if (cloudsat_micro_scheme == 'MMF_v3.5_two_moment')  then
+       ldouble = .true. 
+       lsingle = .false.
+    endif
+    call hydro_class_init(lsingle,ldouble,sd)
+    call quickbeam_optics_init()
+
+ print*,' just before call COSP_INIT, cosp_init_flag =', cosp_init_flag
+  call COSP_INIT(cfg%Lisccp, cfg%Lmodis, cfg%Lmisr, cfg%Lcloudsat, cfg%Lcalipso, &
+       		 cfg%LgrLidar532, cfg%Latlid, cfg%Lparasol, cfg%Lrttov,          &
+       		 cloudsat_radar_freq, cloudsat_k2, cloudsat_use_gas_abs,         &
+       		 cloudsat_do_ray, isccp_topheight, isccp_topheight_direction,    &
+		 surface_radar, rcfg_cloudsat, use_vgrid_in, csat_vgrid_in,      &
+       		 niv_sorties, Nlevels, cloudsat_micro_scheme)
+cosp_init_flag = 1
+ print*,' just after call COSP_INIT, cosp_init_flag =', cosp_init_flag
+endif
+#endif
+
+   print*,'Fin lecture Namelists, debut_cosp =',debut_cosp
+
+  endif ! debut_cosp
+
+
+!!! Ici on modifie les cles logiques pour les outputs selon les champs actives dans les .xml
+  if ((itap.gt.1).and.(first_write))then
+#ifdef CPP_XIOS
+    call read_xiosfieldactive(cfg)
+#endif
+    first_write=.false.
+
+if (cosp_init_flag .eq. 0) then
+
+    ! Initialize the distributional parameters for hydrometeors in radar simulator.
+    ! In COSPv1.4, this was declared in cosp_defs.f.
+    if (cloudsat_micro_scheme == 'MMF_v3.5_two_moment')  then
+       ldouble = .true. 
+       lsingle = .false.
+    endif
+    call hydro_class_init(lsingle,ldouble,sd)
+    call quickbeam_optics_init()
+
+ print*,' just before call COSP_INIT, cosp_init_flag =', cosp_init_flag
+  call COSP_INIT(cfg%Lisccp, cfg%Lmodis, cfg%Lmisr, cfg%Lcloudsat, cfg%Lcalipso, &
+       		 cfg%LgrLidar532, cfg%Latlid, cfg%Lparasol, cfg%Lrttov,          &
+       		 cloudsat_radar_freq, cloudsat_k2, cloudsat_use_gas_abs,         &
+       		 cloudsat_do_ray, isccp_topheight, isccp_topheight_direction,    &
+		 surface_radar, rcfg_cloudsat, use_vgrid_in, csat_vgrid_in,      &
+       		 niv_sorties, Nlevels, cloudsat_micro_scheme)
+cosp_init_flag = 1
+ print*,' just after call COSP_INIT, cosp_init_flag =', cosp_init_flag
+endif ! cosp_init_flag
+
+
+print*,' Cles des differents simulateurs cosp a itap :',itap
+print*,'cfg%Lcloudsat, cfg%Lcalipso, cfg%LgrLidar532, cfg%Latlid, cfg%Lparasol, &
+	cfg%Lisccp, cfg%Lmisr, cfg%Lmodis, cfg%Lrttov', &
+        cfg%Lcloudsat, cfg%Lcalipso, cfg%LgrLidar532, cfg%Latlid, cfg%Lparasol, &
+	cfg%Lisccp, cfg%Lmisr, cfg%Lmodis, cfg%Lrttov
+
+  endif !(itap.gt.1).and.(first_write)
+
+  time_bnds(1) = dtime-dtime/2.
+  time_bnds(2) = dtime+dtime/2.
+
+  d_time_bnds=time_bnds
+  d_dtime=dtime
+
+!-------------------------   Fin initialisation de COSP   --------------------------
+
+
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!
+! 3) Calculs des champs d'entree COSP a partir des variables LMDZ
+!
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+    ! 0) Create ptop/ztop for gbx%pf and gbx%zlev are for the the interface, 
+    !    also reverse CAM height/pressure values for input into CSOP
+    !    CAM state%pint from top to surface, COSP wants surface to top.
+
+! 0) Altitudes du modele calculees a partir de la variable geopotentiel phi et phis    
+        zlev = phi/9.81
+
+        zlev_half(:,1) = phis(:)/9.81
+        do k = 2, Nlevels
+          do ip = 1, Npoints
+           zlev_half(ip,k) = phi(ip,k)/9.81 + &
+               (phi(ip,k)-phi(ip,k-1))/9.81 * (ph(ip,k)-p(ip,k)) / (p(ip,k)-p(ip,k-1))
+          enddo
+        enddo
+
+! 1) Quantite de nuages (couverture?), convectif (=0) et total
+        cca = 0._wp ! convective_cloud_amount (1)
+        tca = tca   ! total_cloud_amount (1)
+
+! 2) Humidite relative est donnee tel quel (variable rh)
+
+! 3) Masque terre/mer a partir de la variable fracTerLic
+        do ip = 1, Npoints
+          if (fracTerLic(ip).ge.0.5) then
+             land(ip) = 1.
+          else
+             land(ip) = 0.
+          endif
+        enddo
+
+
+! A voir l equivalent LMDZ
+  mr_ccliq = 0.0
+  mr_ccice = 0.0
+!!!        gbx%mr_hydro(:,:,I_LSCLIQ) = mr_lsliq !mixing_ratio_large_scale_cloud_liquid (kg/kg)
+!!!        gbx%mr_hydro(:,:,I_LSCICE) = mr_lsice !mixing_ratio_large_scale_cloud_ic
+!!!        gbx%mr_hydro(:,:,I_CVCLIQ) = mr_ccliq !mixing_ratio_convective_cloud_liquid
+!!!        gbx%mr_hydro(:,:,I_CVCICE) = mr_ccice !mixing_ratio_convective_cloud_ice
+! A revoir
+        fl_lsrain = fl_lsrainI + fl_ccrainI
+        fl_lssnow = fl_lssnowI + fl_ccsnowI
+!!!        gbx%rain_ls = fl_lsrain !flux_large_scale_cloud_rain (kg m^-2 s^-1)
+!!!        gbx%snow_ls = fl_lssnow !flux_large_scale_cloud_snow
+!  A voir l equivalent LMDZ
+        fl_lsgrpl = 0.
+        fl_ccsnow = 0.
+        fl_ccrain = 0.
+!!!        gbx%grpl_ls = fl_lsgrpl  !flux_large_scale_cloud_graupel
+!!!        gbx%rain_cv = fl_ccrain  !flux_convective_cloud_rain
+!!!        gbx%snow_cv = fl_ccsnow  !flux_convective_cloud_snow
+
+        ! ISCCP simulator
+        dtau_c  = 0.
+        dem_c   = 0.
+
+! note: reff_cosp dimensions should be same as cosp (reff_cosp has 9 hydrometeor dimension)
+     Reff(1:Npoints,1:Nlevels,1:N_HYDRO) = 0.
+     Reff(:,:,I_LSCLIQ) = ref_liq*1e-6
+     Reff(:,:,I_LSCICE) = ref_ice*1e-6
+     Reff(:,:,I_CVCLIQ) = ref_liq*1e-6
+     Reff(:,:,I_CVCICE) = ref_ice*1e-6
+
+
+if (cosp_init_flag .eq. 1) then      ! cosp_init_flag = 1
+
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!
+! 4a) On construit la variable cospOUT qui contient tous les diagnostics de sortie.
+! Elle sera remplie lors de l'appel du simulateur COSP
+!
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+    call construct_cosp_outputs(cfg,Npoints,Ncolumns,Nlevels,niv_sorties,0,cospOUT)
+
+
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!
+! 4b) On construit la variable cospstateIN que l'on va remplir avec les champs LMDZ
+! Les champ verticaux doivent etre donnes a l'envers, c-a-d : (Nlevels:1) = (TOA:SFC)
+!
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+    call construct_cospstateIN(Npoints,Nlevels,0,cospstateIN)
+
+    cospstateIN%lat                 		        = lat(1:Npoints)
+    cospstateIN%lon                     		= lon(1:Npoints) 
+    cospstateIN%at              	      		= t(1:Npoints,Nlevels:1:-1) 
+    cospstateIN%qv              	     		= sh(1:Npoints,Nlevels:1:-1)
+    cospstateIN%o3              	      		= mr_ozone(1:Npoints,Nlevels:1:-1)  
+    cospstateIN%sunlit          	      		= sunlit(1:Npoints)
+    cospstateIN%skt             	       		= skt(1:Npoints)
+    cospstateIN%land            	     		= land(1:Npoints)
+    cospstateIN%surfelev            	     		= zlev_half(1:Npoints,1)
+    cospstateIN%pfull           	      		= p(1:Npoints,Nlevels:1:-1)
+    cospstateIN%phalf(1:Npoints,1)	                = 0._wp
+    cospstateIN%phalf(1:Npoints,2:Nlevels+1)	        = ph(1:Npoints,Nlevels:1:-1)  
+    cospstateIN%hgt_matrix                  		= zlev(1:Npoints,Nlevels:1:-1) 
+    cospstateIN%hgt_matrix_half(1:Npoints,Nlevels+1) 	= 0._wp
+    cospstateIN%hgt_matrix_half(1:Npoints,1:Nlevels) 	= zlev_half(1:Npoints,Nlevels:1:-1) 
+
+
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!
+! 4c) On construit la variable cospIN qui contient les proprietes optiques subcolumn
+! pour COSP. Elle sera essentiellement remplie dans la subroutine subsample_and_optics
+! ou sont appeles SCOPS, PREC_SCOPS et les subroutines qui calculent les signaux
+! simules pour chaque simulateur actif.
+!
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+    call construct_cospIN(cfg,Npoints,Ncolumns,Nlevels,cospIN)
+    cospIN%emsfc_lw  = emsfc_lw
+    if (cfg%Lcloudsat) cospIN%rcfg_cloudsat = rcfg_cloudsat
+
+
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!
+! 5) Appel de subsample_and_optics : Les champs verticaux doivent etre donnes a
+! l'envers comme pour le remplissage de cospstateIN, c-a-d : (Nlevels:1) = (TOA:SFC)
+!
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+    call subsample_and_optics(cfg, Npoints, Nlevels, Ncolumns, N_HYDRO,overlap,	&
+        		      use_precipitation_fluxes, lidar_ice_type, sd, &
+			      tca(1:Npoints,Nlevels:1:-1), cca(1:Npoints,Nlevels:1:-1), &
+           		      fl_lsrain(1:Npoints,Nlevels:1:-1), &
+			      fl_lssnow(1:Npoints,Nlevels:1:-1), &
+			      fl_lsgrpl(1:Npoints,Nlevels:1:-1), &
+			      fl_ccrain(1:Npoints,Nlevels:1:-1), &
+          		      fl_ccsnow(1:Npoints,Nlevels:1:-1), &
+			      mr_lsliq(1:Npoints,Nlevels:1:-1), &
+			      mr_lsice(1:Npoints,Nlevels:1:-1), &
+			      mr_ccliq(1:Npoints,Nlevels:1:-1), &
+			      mr_ccice(1:Npoints,Nlevels:1:-1), &
+             		      Reff(1:Npoints,Nlevels:1:-1,:), &
+			      dtau_c(1:Npoints,Nlevels:1:-1), &
+			      dtau_s(1:Npoints,Nlevels:1:-1), &
+			      dem_c(1:Npoints,Nlevels:1:-1), &
+			      dem_s(1:Npoints,Nlevels:1:-1), cospstateIN, cospIN)
+
+
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!
+! 6) On appelle le simulateur COSPv2 
+!
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+      print*,'call simulateur'
+
+cosp_status = COSP_SIMULATOR(cospIN, cospstateIN, cospOUT, 1, Npoints, debug=.false.)
+
+endif ! cosp_init_flag = 1
+
+
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!
+! 7a) Ecriture des sorties 1: on cree d'abord les fichiers NCDF pour ecrire les sorties
+! en appelant lmdz_cosp_output_open (lors du premier appel de cette interface pour les
+! 2 options d'ecriture), ou sont definis les axes et les caracteristiques
+! des fichiers de sortie avec les diagnostics.
+!
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+    if (debut_cosp) then
+      !$OMP MASTER
+
+        print *, ' Open outpts files and define axis'
+        call lmdz_cosp_output_open(Nlevlmdz, Ncolumns, presnivs, dtime, freq_cosp,       &
+                                   ok_mensuelCOSP, ok_journeCOSP, ok_hfCOSP, ok_all_xml, &
+                                   ecrit_mth, ecrit_day, ecrit_hf, use_vgrid_in,         &
+			           niv_sorties, vgrid_z_in, zlev(1,:))
+
+      !$OMP END MASTER
+      !$OMP BARRIER
+       debut_cosp=.false.
+      endif ! debut_cosp
+
+if (cosp_init_flag .eq. 1) then
+
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!
+! 7b) Ecriture des sorties 2: le remplissage des fichiers de sortie se fait a chaque
+! appel de cette interface avec une difference entre les 2 options d'ecriture:
+!
+! AVEC xios, on commence a remplir les fichiers de sortie a partir du DEUXIEME
+! appel de cette interface (lorsque cosp_init_flag = 1).
+!
+! SANS xios, on commence a remplir les fichiers de sortie a partir du PREMIER
+! appel de cette interface (lorsque cosp_init_flag = 1).
+!
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+       print *, 'Calling write output'
+        call lmdz_cosp_output_write(Nlevlmdz, Npoints, Ncolumns, itap, dtime, freq_COSP, &
+			            missing_val, cfg, niv_sorties, cospOUT)
+
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!
+! 8) On libere la memoire allouee lors de cet appel a l'interface
+!
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+    call destroy_cospIN(cospIN)
+    call destroy_cospstateIN(cospstateIN)
+    call destroy_cosp_outputs(cospOUT) 
+
+endif ! cosp_init_flag = 1
+ 
+end subroutine lmdz_cosp_interface
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_output_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_output_mod.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_output_mod.F90	(revision 3605)
@@ -0,0 +1,520 @@
+! A.Idelkadi sept 2013 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! Module pour declarer et initialiser les parametres de controle des fichiers de sorties et des champs a sortir
+!! La routine cosp_output_open (appelee 1 seule fois dans phy_cosp.F90) permet :
+!! de creer les fichiers avec leurs grilles horizontales et verticales
+!
+! R.Guzman jan 2019 (mise a jour pour COSPv2)
+! On change le nom du module a "lmdz_cosp_output_mod" et celui de la routine a "lmdz_cosp_output_open"
+! pour qu'on sache qu'il s'agit d'un module specifique a l'implementation de COSP dans LMDZ
+!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+  MODULE lmdz_cosp_output_mod
+
+     USE COSP_KINDS, ONLY: wp,dp
+     IMPLICIT NONE
+! cosp_output_mod
+      INTEGER          :: i
+!!!!!!! Controle des fichier de sorties Cosp !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+      LOGICAL, DIMENSION(3), SAVE  :: cosp_outfilekeys
+      INTEGER, DIMENSION(3), SAVE  :: cosp_nidfiles
+!$OMP THREADPRIVATE(cosp_outfilekeys, cosp_nidfiles)
+      INTEGER, DIMENSION(3), SAVE  :: nhoricosp,nvert,nvertmcosp,nvertcol,nvertbze, &
+                                      nvertsratio,nvertisccp,nvertp,nverttemp,nvertmisr, &
+                                      nvertReffIce,nvertReffLiq,nverttau
+      REAL, DIMENSION(3), SAVE                :: zoutm_cosp
+!$OMP THREADPRIVATE(nhoricosp, nvert,nvertmcosp,nvertcol,nvertsratio,nvertbze,nvertisccp,nvertp,zoutm_cosp,nverttemp,nvertmisr)
+!$OMP THREADPRIVATE(nvertReffIce,nvertReffLiq,nverttau)
+      REAL, SAVE                   :: zdtimemoy_cosp
+!$OMP THREADPRIVATE(zdtimemoy_cosp) 
+      CHARACTER(LEN=20), DIMENSION(3), SAVE  :: cosp_outfiletypes
+      CHARACTER(LEN=20), DIMENSION(3), SAVE  :: cosp_outfilenames
+      REAL, DIMENSION(3), SAVE               :: cosp_ecritfiles 
+!$OMP THREADPRIVATE(cosp_outfiletypes, cosp_outfilenames, cosp_ecritfiles)
+
+!!!!  Controle des variables a sortir dans les fichiers !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+  TYPE ctrl_outcosp
+     LOGICAL,DIMENSION(3)                 :: cles             !!! Sortir ou non le champs
+     CHARACTER(len=20)                    :: name       
+     CHARACTER(len=150)                   :: description      !!! Nom
+     CHARACTER(len=20)                    :: unit             !!! Unite 
+     CHARACTER(len=20),DIMENSION(3)  :: cosp_typeecrit        !!! Operation (ave, inst, ...)
+  END TYPE ctrl_outcosp
+
+! CALIPSO vars (43)
+  TYPE(ctrl_outcosp), SAVE :: o_cllcalipso = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "cllcalipso", "CALIPSO Low-level Cloud Fraction", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clmcalipso = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clmcalipso", "CALIPSO Mid-level Cloud Fraction", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clhcalipso = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clhcalipso", "CALIPSO High-level Cloud Fraction", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_cltcalipso = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "cltcalipso", "CALIPSO Total Cloud Fraction", "1", (/ ('', i=1, 3) /)) 
+  TYPE(ctrl_outcosp), SAVE :: o_clcalipso = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clcalipso", "CALIPSO Cloud Fraction (532 nm)", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_cfadLidarsr532 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "cfadLidarsr532", "CALIPSO Scattering Ratio CFAD (532 nm)", "1", (/ ('', i=1, 3) /))   
+  TYPE(ctrl_outcosp), SAVE :: o_atb532 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "atb532", "CALIPSO Attenuated Total Backscatter (532 nm)","1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_lidarBetaMol532 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "lidarBetaMol532", "CALIPSO Molecular Backscatter (532 nm)","m-1 sr-1", (/ ('', i=1, 3) /))
+!! AI  11 2015
+  TYPE(ctrl_outcosp), SAVE :: o_cllcalipsoice = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), & 
+         "cllcalipsoice", "CALIPSO Ice-Phase Low Level Cloud Fraction", "%", (/ ('', i=1, 3) /))  
+  TYPE(ctrl_outcosp), SAVE :: o_cllcalipsoliq = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "cllcalipsoliq", "CALIPSO Liq-Phase Low Level Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clmcalipsoice = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clmcalipsoice", "CALIPSO Ice-Phase Mid Level Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clmcalipsoliq = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clmcalipsoliq", "CALIPSO Liq-Phase Mid Level Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clhcalipsoice = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), & 
+         "clhcalipsoice", "CALIPSO Ice-Phase High Level Cloud Fraction", "%", (/ ('', i=1, 3) /))  
+  TYPE(ctrl_outcosp), SAVE :: o_clhcalipsoliq = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clhcalipsoliq", "CALIPSO Liq-Phase High Level Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_cltcalipsoice = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "cltcalipsoice", "CALIPSO Ice-Phase Tot Level Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_cltcalipsoliq = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "cltcalipsoliq", "CALIPSO Liq-Phase Tot Level Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_cllcalipsoun = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), & 
+         "cllcalipsoun", "CALIPSO Undefined-Phase Low Level Cloud Fraction", "%", (/ ('', i=1, 3) /))  
+  TYPE(ctrl_outcosp), SAVE :: o_clmcalipsoun = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clmcalipsoun", "CALIPSO Undefined-Phase Mid Level Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clhcalipsoun = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clhcalipsoun", "CALIPSO Undefined-Phase High Level Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_cltcalipsoun = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "cltcalipsoun", "CALIPSO Undefined-Phase Tot Level Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clcalipsoice = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clcalipsoice", "CALIPSO Ice-Phase Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clcalipsoliq = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clcalipsoliq", "CALIPSO Liq-Phase Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clcalipsoun = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clcalipsoun", "CALIPSO Undef-Phase Cloud Fraction", "%", (/ ('', i=1, 3) /))	 
+  TYPE(ctrl_outcosp), SAVE :: o_clcalipsotmpice = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clcalipsotmpice", "CALIPSO Ice-Phase Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clcalipsotmpliq = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clcalipsotmpliq", "CALIPSO Liq-Phase Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clcalipsotmpun = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clcalipsotmpun", "CALIPSO Undef-Phase Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clcalipsotmp = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clcalipsotmp", "CALIPSO Cloud Fraction", "%", (/ ('', i=1, 3) /))
+
+  TYPE(ctrl_outcosp), SAVE :: o_clopaquecalipso = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clopaquecalipso", "CALIPSO Opaque Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clthincalipso = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clthincalipso", "CALIPSO Thin Cloud Fraction", "%", (/ ('', i=1, 3) /))      
+  TYPE(ctrl_outcosp), SAVE :: o_clzopaquecalipso = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clzopaquecalipso", "CALIPSO mean opacity altitude", "m", (/ ('', i=1, 3) /))    
+  TYPE(ctrl_outcosp), SAVE :: o_clcalipsoopaque = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clcalipsoopaque", "CALIPSO Opaque profile Cloud Fraction", "%", (/ ('', i=1, 3) /))  
+  TYPE(ctrl_outcosp), SAVE :: o_clcalipsothin = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), & 
+         "clcalipsothin", "CALIPSO Thin profile Cloud Fraction", "%", (/ ('', i=1, 3) /))      
+  TYPE(ctrl_outcosp), SAVE :: o_clcalipsozopaque = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clcalipsozopaque", "CALIPSO z_opaque Fraction", "%", (/ ('', i=1, 3) /))	   
+  TYPE(ctrl_outcosp), SAVE :: o_clcalipsoopacity = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clcalipsoopacity", "CALIPSO opacity Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clopaquetemp = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clopaquetemp", "CALIPSO Opaque Cloud Temperature", "K", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clthintemp = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clthintemp", "CALIPSO Thin Cloud Temperature", "K", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clzopaquetemp = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clzopaquetemp", "CALIPSO z_opaque Temperature", "K", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clopaquemeanz = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clopaquemeanz", "CALIPSO Opaque Cloud Altitude", "m", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clthinmeanz = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clthinmeanz", "CALIPSO Thin Cloud Altitude", "m", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clthinemis = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clthinemis", "CALIPSO Thin Cloud Emissivity", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clopaquemeanzse = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clopaquemeanzse", "CALIPSO Opaque Cloud Altitude with respect to Surface Elevation", "m", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clthinmeanzse = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clthinmeanzse", "CALIPSO Thin Cloud Altitude with respect to Surface Elevation", "m", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clzopaquecalipsose = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clzopaquecalipsose", "CALIPSO mean opacity Altitude with respect to Surface Elevation", "m", (/ ('', i=1, 3) /))
+
+! GROUND LIDAR 532 nm vars (8)
+  TYPE(ctrl_outcosp), SAVE :: o_cllgrLidar532 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "cllgrLidar532", "GROUND LIDAR 532 nm Low-level Cloud Fraction", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clmgrLidar532 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clmgrLidar532", "GROUND LIDAR 532 nm Mid-level Cloud Fraction", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clhgrLidar532 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clhgrLidar532", "GROUND LIDAR 532 nm High-level Cloud Fraction", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_cltgrLidar532 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "cltgrLidar532", "GROUND LIDAR 532 nm Total Cloud Fraction", "1", (/ ('', i=1, 3) /)) 
+  TYPE(ctrl_outcosp), SAVE :: o_clgrLidar532 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clgrLidar532", "GROUND LIDAR 532 nm Cloud Fraction", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_cfadLidarsr532gr = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "cfadLidarsr532gr", "GROUND LIDAR 532 nm Scattering Ratio CFAD", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_atb532gr = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "atb532gr", "GROUND LIDAR 532 nm Attenuated Total Backscatter (532 nm)","m-1 sr-1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_lidarBetaMol532gr = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "lidarBetaMol532gr", "GROUND LIDAR 532 nm Molecular Backscatter (532 nm)","m-1 sr-1", (/ ('', i=1, 3) /))
+
+! ATLID vars (8)
+  TYPE(ctrl_outcosp), SAVE :: o_cllatlid = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "cllatlid", "ATLID Low-level Cloud Fraction", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clmatlid = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clmatlid", "ATLID Mid-level Cloud Fraction", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clhatlid = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clhatlid", "ATLID High-level Cloud Fraction", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_cltatlid = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "cltatlid", "ATLID Total Cloud Fraction", "1", (/ ('', i=1, 3) /)) 
+  TYPE(ctrl_outcosp), SAVE :: o_clatlid = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clatlid", "ATLID Cloud Fraction (532 nm)", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_cfadLidarsr355 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "cfadLidarsr355", "ATLID Scattering Ratio CFAD (532 nm)", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_atb355 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "atb355", "ATLID Attenuated Total Backscatter (532 nm)","m-1 sr-1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_lidarBetaMol355 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "lidarBetaMol355", "ATLID Molecular Backscatter (532 nm)","m-1 sr-1", (/ ('', i=1, 3) /))
+
+! PARASOL vars (2)
+  TYPE(ctrl_outcosp), SAVE :: o_parasolGrid_refl = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "parasolGrid_refl", "PARASOL Reflectance","1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_parasolPix_refl = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), & 
+         "parasolPix_refl", "PARASOL Subcolumn Reflectance","1", (/ ('', i=1, 3) /))                  
+!  TYPE(ctrl_outcosp), SAVE :: o_Ncrefl = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+!         "Ncrefl", "Nb PARASOL-like mono-directional reflectance (integral)","1", (/ ('', i=1, 3) /))
+
+
+! Radar CloudSat vars (13)
+  TYPE(ctrl_outcosp), SAVE :: o_cfadDbze94 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "cfadDbze94", "CloudSat Radar Reflectivity CFAD", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_dbze94 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "dbze94", "CloudSat Radar Reflectivity", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_ptradarflag0 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "ptradarflag0", "CloudSat Radar Precipitation frequency flag 0", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_ptradarflag1 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "ptradarflag1", "CloudSat Radar Precipitation frequency flag 1", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_ptradarflag2 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "ptradarflag2", "CloudSat Radar Precipitation frequency flag 2", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_ptradarflag3 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "ptradarflag3", "CloudSat Radar Precipitation frequency flag 3", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_ptradarflag4 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "ptradarflag4", "CloudSat Radar Precipitation frequency flag 4", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_ptradarflag5 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "ptradarflag5", "CloudSat Radar Precipitation frequency flag 5", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_ptradarflag6 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "ptradarflag6", "CloudSat Radar Precipitation frequency flag 6", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_ptradarflag7 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "ptradarflag7", "CloudSat Radar Precipitation frequency flag 7", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_ptradarflag8 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "ptradarflag8", "CloudSat Radar Precipitation frequency flag 8", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_ptradarflag9 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "ptradarflag9", "CloudSat Radar Precipitation frequency flag 9", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_radarpia = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "radarpia", "CloudSat Radar PIA", "1", (/ ('', i=1, 3) /))
+
+! CALIPSO + CloudSat vars (4)
+  TYPE(ctrl_outcosp), SAVE :: o_clcalipso2 = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clcalipso2", "CALIPSO Cloud Fraction Undetected by CloudSat", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_cltlidarradar = ctrl_outcosp((/ .TRUE., .TRUE.,.TRUE. /), &          
+         "cltlidarradar", "CALIPSO and CloudSat Radar Total Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_cloudsat_tcc = ctrl_outcosp((/ .TRUE., .TRUE.,.TRUE. /), &          
+         "cloudsat_tcc", "CALIPSO and CloudSat Radar Total Cloud Fraction?", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_cloudsat_tcc2 = ctrl_outcosp((/ .TRUE., .TRUE.,.TRUE. /), &          
+         "cloudsat_tcc2", "CALIPSO and CloudSat Radar Total Cloud Fraction?", "%", (/ ('', i=1, 3) /))
+
+! ISCCP vars (9) + sunlit (1)
+!  TYPE(ctrl_outcosp), SAVE :: o_sunlit = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+!         "sunlit", "1 for day points, 0 for nightime", "1", (/ ('', i=1, 3) /))                   
+  TYPE(ctrl_outcosp), SAVE :: o_clisccp = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clisccp", "Cloud Fraction as Calculated by the ISCCP Simulator","%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_boxtauisccp = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "boxtauisccp", "Optical Depth in Each Column as Calculated by the ISCCP Simulator","1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_boxptopisccp = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "boxptopisccp", "Cloud Top Pressure in Each Column as Calculated by the ISCCP Simulator","Pa", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_cltisccp = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+          "cltisccp", "Total Cloud Fraction as Calculated by the ISCCP Simulator", "%", (/ ('', i=1, 3) /)) 
+  TYPE(ctrl_outcosp), SAVE :: o_pctisccp = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+          "pctisccp", "Mean Cloud Top Pressure as Calculated by the ISCCP Simulator", "Pa", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_tauisccp = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+          "tauisccp", "Optical Depth as Calculated by the ISCCP Simulator", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_albisccp = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+          "albisccp", "Mean Cloud Albedo as Calculated by the ISCCP Simulator", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_meantbisccp = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+          "meantbisccp", " Mean all-sky 10.5 micron brightness temperature as calculated &
+           by the ISCCP Simulator","K", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_meantbclrisccp = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+          "meantbclrisccp", "Mean clear-sky 10.5 micron brightness temperature as calculated &
+           by the ISCCP Simulator","K", (/ ('', i=1, 3) /))
+
+! MISR simulator var (3)
+  TYPE(ctrl_outcosp), SAVE :: o_misr_fq = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "misr_fq", "MISR joint-PDF of cloud top pressure and optical depth","%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_misr_meanztop = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "misr_meanztop", "MISR Mean Cloud Top Height","%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_misr_cldarea = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "misr_cldarea", "MISR cloud cover","%", (/ ('', i=1, 3) /))
+
+! MODIS simulator vars (20)
+  TYPE(ctrl_outcosp), SAVE :: o_cllmodis = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "cllmodis", "MODIS Low-level Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clmmodis = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clmmodis", "MODIS Mid-level Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_clhmodis = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clhmodis", "MODIS High-level Cloud Fraction", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_cltmodis = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "cltmodis", "MODIS Total Cloud Fraction", "%", (/ ('', i=1, 3) /)) 
+  TYPE(ctrl_outcosp), SAVE :: o_clwmodis = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "clwmodis", "MODIS Cloud Fraction water mean", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_climodis = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "climodis", "MODIS Cloud Fraction ice mean", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_tautmodis = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "tautmodis", "MODIS Optical_Thickness_Total_Mean", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_tauwmodis = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "tauwmodis", "MODIS Optical_Thickness_Water_Mean", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_tauimodis= ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "tauimodis", "MODIS Optical_Thickness_Ice_Mean", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_tautlogmodis = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "tautlogmodis", "MODIS Optical_Thickness_Total_logMean", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_tauwlogmodis = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "tauwlogmodis", "MODIS Optical_Thickness_Water_logMean", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_tauilogmodis = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "tauilogmodis", "MODIS Optical_Thickness_Ice_logMean", "1", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_reffclwmodis = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "reffclwmodis", "Modis Cloud_Particle_Size_Water_Mean", "m", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_reffclimodis = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "reffclimodis", "Modis Cloud_Particle_Size_Ice_Mean", "m", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_pctmodis = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "pctmodis", "Modis Cloud_Top_Pressure_Total_Mean", "Pa", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_lwpmodis = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "lwpmodis", "Modis Liquid_Water_Path_Mean", "kg m-2", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_iwpmodis = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "iwpmodis", "Modis Ice_Water_Path_Mean", "kg m-2", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_modis_ot_vs_ctp = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "modis_ot_vs_ctp", "MODIS joint-PDF of cloud top pressure and optical depth", "%", (/ ('', i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_modis_ot_vs_reffice = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "modis_ot_vs_reffice", "MODIS Joint-PDF of optical-depth and ice particle size", "%", (/ ('',i=1, 3) /))
+  TYPE(ctrl_outcosp), SAVE :: o_modis_ot_vs_reffliq = ctrl_outcosp((/ .TRUE., .TRUE.,.TRUE. /), &
+         "modis_ot_vs_reffliq", "MODIS Joint-PDF of optical-depth and liquid particle size", "%", (/ ('',i=1, 3) /))
+
+! Rttovs simulator var (1)
+  TYPE(ctrl_outcosp), SAVE :: o_tbrttov = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "tbrttov", "Rttovs Cloud Area Fraction", "%", (/ ('', i=1, 3) /))
+
+! Scops and others var (1)
+  TYPE(ctrl_outcosp), SAVE :: o_fracout = ctrl_outcosp((/ .TRUE., .TRUE., .TRUE. /), &
+         "fracout", "Subcolumn output from SCOPS", "%", (/ ('', i=1, 3) /))
+
+  LOGICAL, SAVE :: cosp_varsdefined = .FALSE. ! ug PAS THREADPRIVATE ET C'EST NORMAL
+  REAL, SAVE  :: Cosp_fill_value
+!$OMP THREADPRIVATE(Cosp_fill_value)
+ 
+
+CONTAINS
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!!!!!!!!! Ouverture des fichier et definition des  axes!!!!!!!!
+  !! histbeg, histvert
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
+
+  SUBROUTINE lmdz_cosp_output_open(Nlevlmdz, Ncolumns, presnivs, dtime, freq_cosp, &
+                              ok_mensuelCOSP, ok_journeCOSP, ok_hfCOSP, ok_all_xml,  &
+                              ecrit_mth, ecrit_day, ecrit_hf, use_vgrid, Nlvgrid, vgrid_z_loc, &
+			      vgrid_mz)
+
+  use mod_cosp_config, only : CLOUDSAT_DBZE_BINS, SR_BINS, CLOUDSAT_CFAD_ZE_MIN, PARASOL_NREFL, &
+                              CLOUDSAT_CFAD_ZE_WIDTH,PARASOL_SZA, &
+                              isccp_histPresCenters,tau_binCenters, LIDAR_NTEMP, &
+                              LIDAR_PHASE_TEMP,misr_histHgtCenters,numMISRHgtBins, &
+                              numMODISReffIceBins,reffICE_binCenters, &
+                              numMODISReffLiqBins, reffLIQ_binCenters, pres_binCenters, &
+			      cloudsat_binCenters, calipso_binCenters
+
+  USE iophy
+  USE ioipsl
+  USE phys_cal_mod
+  USE time_phylmdz_mod, ONLY: day_ref, annee_ref, day_ini, start_time, itau_phy
+  USE print_control_mod, ONLY: lunout
+
+#ifdef CPP_XIOS
+    ! ug Pour les sorties XIOS
+    USE wxios
+#endif
+
+  IMPLICIT NONE
+
+!!! Variables d'entree
+  integer                  :: Nlevlmdz, Ncolumns, Nlvgrid      ! Number of levels
+  real,dimension(Nlevlmdz) :: presnivs, vgrid_mz
+  real,dimension(Nlvgrid)  :: vgrid_z_loc
+  real                     :: dtime, freq_cosp, ecrit_day, ecrit_hf, ecrit_mth 
+  logical                  :: use_vgrid
+  logical                  :: ok_mensuelCOSP, ok_journeCOSP, ok_hfCOSP, ok_all_xml
+
+!!! Variables locales
+  integer                   :: idayref, iff, ii
+  real                      :: zjulian,zjulian_start
+  real(wp),dimension(Ncolumns)  :: column_ax
+  CHARACTER(LEN=20), DIMENSION(3)  :: chfreq = (/ '1day', '1d  ', '3h  ' /)            
+
+!!! Variables d'entree
+
+#ifdef CPP_XIOS
+    ! ug Variables utilisées pour récupérer le calendrier pour xios
+    INTEGER :: x_an, x_mois, x_jour
+    REAL :: x_heure
+    INTEGER :: ini_an, ini_mois, ini_jour
+    REAL :: ini_heure
+#endif
+
+    WRITE(lunout,*) 'Debut lmdz_cosp_output_mod.F90'
+    print*,'cosp_varsdefined',cosp_varsdefined
+    ! Initialisations (Valeurs par defaut)
+
+
+!! Definition valeurs axes
+    do ii=1,Ncolumns
+      column_ax(ii) = real(ii)
+    enddo
+
+ 
+    cosp_outfilenames(1) = 'histmthCOSP'
+    cosp_outfilenames(2) = 'histdayCOSP'
+    cosp_outfilenames(3) = 'histhfCOSP'
+
+    cosp_outfiletypes(1) = 'ave(X)'
+    cosp_outfiletypes(2) = 'ave(X)'
+    cosp_outfiletypes(3) = 'ave(X)'
+
+    cosp_outfilekeys(1) = ok_mensuelCOSP
+    cosp_outfilekeys(2) = ok_journeCOSP
+    cosp_outfilekeys(3) = ok_hfCOSP
+
+    cosp_ecritfiles(1) = mth_len*86400.
+    cosp_ecritfiles(2) = 1.*86400.
+    cosp_ecritfiles(3) = 0.125*86400.
+
+! Lecture des parametres dans output.def ou config.def
+
+    CALL getin('cosp_outfilenames',cosp_outfilenames)
+    CALL getin('cosp_outfilekeys',cosp_outfilekeys)
+    CALL getin('cosp_ecritfiles',cosp_ecritfiles)
+    CALL getin('cosp_outfiletypes',cosp_outfiletypes)
+
+    WRITE(lunout,*)'cosp_outfilenames=',cosp_outfilenames
+    WRITE(lunout,*)'cosp_outfilekeys=',cosp_outfilekeys
+    WRITE(lunout,*)'cosp_ecritfiles=',cosp_ecritfiles
+    WRITE(lunout,*)'cosp_outfiletypes=',cosp_outfiletypes
+    
+    idayref = day_ref
+    CALL ymds2ju(annee_ref, 1, idayref, 0.0, zjulian)
+    CALL ymds2ju(annee_ref, 1, day_ini, start_time, zjulian_start)
+
+#ifdef CPP_XIOS
+    
+! recuperer la valeur indefine Xios
+!    CALL xios_get_field_attr("clcalipso",default_value=Cosp_fill_value)
+!         Cosp_fill_value=missing_val
+          Cosp_fill_value=0.
+         print*,'Cosp_fill_value=',Cosp_fill_value
+
+    CALL wxios_add_vaxis("height", Nlvgrid, vgrid_z_loc)
+    print*,'wxios_add_vaxis Nlvgrid, vgrid_z_loc',Nlvgrid,vgrid_z_loc
+
+    WRITE(lunout,*) 'wxios_add_vaxis height_mlev, Nlevlmdz vgrid_mz ', &
+                     Nlevlmdz,vgrid_mz
+    CALL wxios_add_vaxis("height_mlev", Nlevlmdz, vgrid_mz)
+
+    WRITE(lunout,*) 'wxios_add_vaxis sza, PARASOL_NREFL ', &
+                     PARASOL_NREFL, PARASOL_SZA
+    CALL wxios_add_vaxis("sza", PARASOL_NREFL, PARASOL_SZA)
+
+    WRITE(lunout,*) 'wxios_add_vaxis pressure2 ',7,pres_binCenters
+    CALL wxios_add_vaxis("pressure2", 7, pres_binCenters)
+
+    WRITE(lunout,*) 'wxios_add_vaxis column ',Ncolumns,column_ax
+    CALL wxios_add_vaxis("column", Ncolumns, column_ax)
+
+   WRITE(lunout,*) 'wxios_add_vaxis temp LIDAR_NTEMP, LIDAR_PHASE_TEMP ', &
+                    LIDAR_NTEMP, LIDAR_PHASE_TEMP
+   CALL wxios_add_vaxis("temp", LIDAR_NTEMP, LIDAR_PHASE_TEMP)
+
+   WRITE(lunout,*) 'wxios_add_vaxis cth16 numMISRHgtBins, misr_histHgtCenters ', & 
+                    numMISRHgtBins, misr_histHgtCenters 
+   CALL wxios_add_vaxis("cth", numMISRHgtBins, misr_histHgtCenters)
+
+   WRITE(lunout,*) 'wxios_add_vaxis dbze CLOUDSAT_DBZE_BINS, cloudsat_binCenters ', &
+                    CLOUDSAT_DBZE_BINS, cloudsat_binCenters
+   CALL wxios_add_vaxis("dbze", CLOUDSAT_DBZE_BINS, cloudsat_binCenters) 
+
+   WRITE(lunout,*) 'wxios_add_vaxis scatratio SR_BINS, calipso_binCenters', &
+                   SR_BINS, calipso_binCenters
+   CALL wxios_add_vaxis("scatratio", SR_BINS, calipso_binCenters)
+
+   WRITE(lunout,*) 'wxios_add_vaxis ReffIce numMODISReffIceBins, &
+                   reffICE_binCenters',numMODISReffIceBins, reffICE_binCenters
+   CALL wxios_add_vaxis("ReffIce", numMODISReffIceBins, reffICE_binCenters)
+
+   WRITE(lunout,*) 'wxios_add_vaxis ReffLiq numMODISReffLiqBins, &
+                    reffLIQ_binCenters', numMODISReffLiqBins, reffLIQ_binCenters
+   CALL wxios_add_vaxis("ReffLiq", numMODISReffLiqBins, reffLIQ_binCenters)
+
+   WRITE(lunout,*) 'wxios_add_vaxis 7, tau_binCenters', &
+                    7, tau_binCenters
+   CALL wxios_add_vaxis("tau", 7, tau_binCenters)
+
+#endif
+   
+    zdtimemoy_cosp = freq_COSP         ! Frequence ou l on moyenne
+
+    DO iff=1,3
+       zoutm_cosp(iff) = cosp_ecritfiles(iff) ! Frequence ou l on ecrit en seconde
+
+       IF (cosp_outfilekeys(iff)) THEN
+           CALL histbeg_phy_all(cosp_outfilenames(iff),itau_phy,zjulian,&
+             dtime,nhoricosp(iff),cosp_nidfiles(iff))
+!           print*,'histbeg_phy nhoricosp(iff),cosp_nidfiles(iff)', &
+!                    nhoricosp(iff),cosp_nidfiles(iff)
+
+#ifdef CPP_XIOS
+        IF (.not. ok_all_xml) then
+         WRITE(lunout,*) 'wxios_add_file ',cosp_outfilenames(iff)
+         CALL wxios_add_file(cosp_outfilenames(iff),chfreq(iff),10)
+        ENDIF
+#endif
+
+#ifndef CPP_IOIPSL_NO_OUTPUT 
+! Definition de l'axe vertical
+       if (use_vgrid) then
+! Axe vertical Cosp 40 niveaux (en m)
+      CALL histvert(cosp_nidfiles(iff),"height","height","m",Nlvgrid,vgrid_z_loc,nvert(iff))
+       else
+! Axe vertical modele LMDZ presnivs
+      CALL histvert(cosp_nidfiles(iff),"presnivs","Vertical levels","Pa",Nlevlmdz,presnivs,nvert(iff),"down")
+       endif
+! Axe vertical niveaux modele (en m)
+      CALL histvert(cosp_nidfiles(iff),"height_mlev","height_mlev","m",Nlevlmdz,vgrid_mz,nvertmcosp(iff))
+
+      CALL histvert(cosp_nidfiles(iff),"sza","solar_zenith_angle","degrees",PARASOL_NREFL,PARASOL_SZA,nvertp(iff))
+
+      CALL histvert(cosp_nidfiles(iff),"pressure2","pressure","mb",7,pres_binCenters,nvertisccp(iff),"down")
+
+      CALL histvert(cosp_nidfiles(iff),"column","column","count",Ncolumns,column_ax,nvertcol(iff)) !DBUG
+
+      CALL histvert(cosp_nidfiles(iff),"temp","temperature","C",LIDAR_NTEMP,LIDAR_PHASE_TEMP,nverttemp(iff))
+
+      CALL histvert(cosp_nidfiles(iff),"cth","altitude","m",numMISRHgtBins,misr_histHgtCenters,nvertmisr(iff))
+  
+      CALL histvert(cosp_nidfiles(iff),"ReffIce","Effective_particle_size_Ice","microns",numMODISReffIceBins, reffICE_binCenters, &
+                    nvertReffIce(iff))                                         
+     
+      CALL histvert(cosp_nidfiles(iff),"ReffLiq","Effective_particle_size_Liq","microns",numMODISReffLiqBins, reffLIQ_binCenters, &                                  
+                    nvertReffLiq(iff))
+
+      CALL histvert(cosp_nidfiles(iff),"dbze","equivalent_reflectivity_factor","dBZ",CLOUDSAT_DBZE_BINS,cloudsat_binCenters,nvertbze(iff))
+     
+      CALL histvert(cosp_nidfiles(iff),"scatratio","backscattering_ratio","1",SR_BINS,calipso_binCenters,nvertsratio(iff))
+
+      CALL histvert(cosp_nidfiles(iff),"tau","cloud optical depth","1",7,tau_binCenters,nverttau(iff)) 
+     
+!!! Valeur indefinie en cas IOIPSL
+     Cosp_fill_value=0.
+
+#endif
+
+      ENDIF
+  ENDDO
+
+    end SUBROUTINE lmdz_cosp_output_open
+
+ END MODULE lmdz_cosp_output_mod
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_output_write_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_output_write_mod.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_output_write_mod.F90	(revision 3605)
@@ -0,0 +1,1055 @@
+!!!! Abderrahmane Idelkadi aout 2013 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+! Module pour definir (au 1er appel) et ecrire les variables dans les fichiers de sortie cosp
+!
+! R.Guzman jan 2019 (mise a jour pour COSPv2)
+! On change le nom du module a "lmdz_cosp_output_write_mod" et celui de la routine a "lmdz_cosp_output_write"
+! pour qu on sache qu il s agit d un module specifique a l implementation de COSP dans LMDZ
+!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+   MODULE lmdz_cosp_output_write_mod
+
+   USE lmdz_cosp_output_mod
+   USE mod_cosp_config, only : R_UNDEF, CLOUDSAT_DBZE_BINS, SR_BINS, PARASOL_NREFL, & 
+                              isccp_histPresCenters,tau_binCenters, LIDAR_NTEMP, & 
+                              LIDAR_PHASE_TEMP,misr_histHgtCenters,numMISRHgtBins, & 
+                              numMODISReffIceBins,reffICE_binCenters, &
+                              numMODISReffLiqBins, reffLIQ_binCenters
+
+   IMPLICIT NONE
+
+   INTEGER, SAVE  :: itau_iocosp
+!$OMP THREADPRIVATE(itau_iocosp)
+   INTEGER, save        :: Nlevout, Ncolout
+!$OMP THREADPRIVATE(Nlevout, Ncolout)
+
+!  INTERFACE histwrite_cosp
+!    MODULE PROCEDURE histwrite2d_cosp,histwrite3d_cosp
+!  END INTERFACE
+
+   CONTAINS
+
+  SUBROUTINE lmdz_cosp_output_write(Nlevlmdz, Npoints, Ncolumns, itap, dtime, freq_COSP, missing_cosp, &
+  				    cfg, Nlvgrid, cospOUT)
+
+
+    USE ioipsl
+    USE time_phylmdz_mod, ONLY: itau_phy, start_time, day_step_phy
+    USE print_control_mod, ONLY: lunout,prt_level
+    USE lmdz_cosp_read_outputkeys, only: cosp_config
+!COSPv2
+  use cosp_kinds, only: wp
+  use mod_cosp,   only: cosp_outputs
+
+#ifdef CPP_XIOS
+    USE wxios, only: wxios_closedef
+    USE xios, only: xios_update_calendar, xios_field_is_active
+#endif
+  IMPLICIT NONE  
+!!! Variables d'entree
+  integer               :: itap, Nlevlmdz, Ncolumns, Npoints, Nlvgrid
+  real                  :: freq_COSP, dtime, missing_val, missing_cosp
+  type(cosp_config)     :: cfg     ! Control outputs
+  type(cosp_outputs)    :: &
+       cospOUT           ! COSP simulator outputs
+
+
+!!! Variables locales
+  integer               :: icl,k,ip
+  logical               :: ok_sync
+  integer               :: itau_wcosp, iff
+  real, dimension(Npoints,PARASOL_NREFL) :: parasolcrefl, Ncref
+
+! Variables locals intermidiaires pour inverser les axes des champs 4D
+! Compatibilite avec sorties CMIP
+  real, dimension(Npoints,Nlevout,SR_BINS) :: tmp_fi4da_cfadL, tmp_fi4da_cfadLgr, tmp_fi4da_cfadLatlid
+  real, dimension(Npoints,Nlevout,CLOUDSAT_DBZE_BINS) :: tmp_fi4da_cfadR
+  real, dimension(Npoints,numMISRHgtBins,7) :: tmp_fi4da_misr
+
+#ifdef CPP_XIOS
+  missing_val=missing_cosp
+#else
+  missing_val=0.
+#endif
+
+  Nlevout = Nlvgrid
+  Ncolout = Ncolumns
+
+! A refaire
+       itau_wcosp = itau_phy + itap + start_time * day_step_phy
+        if (prt_level >= 10) then
+             WRITE(lunout,*)'itau_wcosp, itap, start_time, day_step_phy =', & 
+                             itau_wcosp, itap, start_time, day_step_phy
+        endif
+
+! On le donne a  cosp_output_write_mod pour que les histwrite y aient acces:
+       CALL set_itau_iocosp(itau_wcosp)
+        if (prt_level >= 10) then
+              WRITE(lunout,*)'itau_iocosp =',itau_iocosp
+        endif
+
+    ok_sync = .TRUE.
+    
+!DO iinit=1, iinitend
+! AI sept 2014 cette boucle supprimee
+! On n'ecrit pas quand itap=1 (cosp)
+
+!   if (prt_level >= 10) then
+!         WRITE(lunout,*)'DO iinit=1, iinitend ',iinitend
+!   endif
+
+!!#ifdef CPP_XIOS
+! !$OMP MASTER
+!IF (cosp_varsdefined) THEN
+!   if (prt_level >= 10) then
+!         WRITE(lunout,*)'Apell xios_update_calendar cosp_varsdefined iinitend ', &
+!                         cosp_varsdefined,iinitend
+!   endif 
+!    CALL xios_update_calendar(itau_wcosp)
+!ENDIF
+!  !$OMP END MASTER
+!  !$OMP BARRIER
+!!#endif
+
+!!!! Sorties Calipso
+ if (cfg%Lcalipso) then
+!!! AI 02 2018 
+! Traitement missing_val
+!!!   where(stlidar%lidarcld == R_UNDEF) stlidar%lidarcld = missing_val
+!!!   where(sglidar%beta_mol == R_UNDEF) sglidar%beta_mol = missing_val  
+!!!   where(sglidar%beta_tot == R_UNDEF) sglidar%beta_tot = missing_val 
+!!!   where(stlidar%cldlayer == R_UNDEF) stlidar%cldlayer = missing_val
+!   where(stlidar%cldtype == R_UNDEF) stlidar%cldtype = missing_val     !OPAQ
+!!!   where(stlidar%cfad_sr == R_UNDEF) stlidar%cfad_sr = missing_val
+! AI 11 / 2015
+!!!   where(stlidar%parasolrefl == R_UNDEF) stlidar%parasolrefl = missing_val
+!!!   where(stlidar%lidarcldtmp == R_UNDEF) stlidar%lidarcldtmp = missing_val
+!!!   where(stlidar%cldlayerphase == R_UNDEF) stlidar%cldlayerphase = missing_val
+!!!   where(stlidar%lidarcldphase == R_UNDEF) stlidar%lidarcldphase = missing_val
+!   where(stlidar%lidarcldtype == R_UNDEF) stlidar%lidarcldtype = missing_val   !OPAQ
+!!!   where(stlidar%lidarcldtmp == R_UNDEF) stlidar%lidarcldtmp = missing_val
+
+!!! missing values pour toutes les valeurs R_UNDEF des variables de CALIPSO
+!   where(cospOUT%calipso_betaperp_tot == R_UNDEF) cospOUT%calipso_betaperp_tot = missing_val
+   where(cospOUT%calipso_beta_tot == R_UNDEF) cospOUT%calipso_beta_tot = missing_val
+   where(cospOUT%calipso_tau_tot == R_UNDEF) cospOUT%calipso_tau_tot = missing_val
+   where(cospOUT%calipso_lidarcldphase == R_UNDEF) cospOUT%calipso_lidarcldphase = missing_val
+   where(cospOUT%calipso_lidarcldtype == R_UNDEF) cospOUT%calipso_lidarcldtype = missing_val
+   where(cospOUT%calipso_cldlayerphase == R_UNDEF) cospOUT%calipso_cldlayerphase = missing_val
+   where(cospOUT%calipso_lidarcldtmp == R_UNDEF)    cospOUT%calipso_lidarcldtmp = missing_val
+   where(cospOUT%calipso_cfad_sr == R_UNDEF) 	    cospOUT%calipso_cfad_sr = missing_val
+   where(cospOUT%calipso_lidarcld == R_UNDEF) 	    cospOUT%calipso_lidarcld = missing_val
+   where(cospOUT%calipso_cldlayer == R_UNDEF)	    cospOUT%calipso_cldlayer = missing_val
+   where(cospOUT%calipso_cldtype == R_UNDEF)	    cospOUT%calipso_cldtype = missing_val
+   where(cospOUT%calipso_cldtypetemp == R_UNDEF)    cospOUT%calipso_cldtypetemp = missing_val
+   where(cospOUT%calipso_cldtypemeanz == R_UNDEF)   cospOUT%calipso_cldtypemeanz = missing_val
+   where(cospOUT%calipso_cldtypemeanzse == R_UNDEF) cospOUT%calipso_cldtypemeanzse = missing_val
+   where(cospOUT%calipso_beta_mol == R_UNDEF) 	    cospOUT%calipso_beta_mol = missing_val
+   where(cospOUT%calipso_temp_tot == R_UNDEF) 	    cospOUT%calipso_temp_tot = missing_val
+   where(cospOUT%calipso_cldthinemis == R_UNDEF)    cospOUT%calipso_cldthinemis = missing_val
+   where(cospOUT%calipso_srbval == R_UNDEF) 	    cospOUT%calipso_srbval = missing_val
+
+
+!   print*,'Appel histwrite2d_cosp'
+   if (cfg%Lcllcalipso) CALL histwrite2d_cosp(o_cllcalipso,cospOUT%calipso_cldlayer(:,1))
+   if (cfg%Lclhcalipso) CALL histwrite2d_cosp(o_clhcalipso,cospOUT%calipso_cldlayer(:,3))
+   if (cfg%Lclmcalipso) CALL histwrite2d_cosp(o_clmcalipso,cospOUT%calipso_cldlayer(:,2)) 
+   if (cfg%Lcltcalipso) CALL histwrite2d_cosp(o_cltcalipso,cospOUT%calipso_cldlayer(:,4))
+   if (cfg%Lclcalipso) CALL histwrite3d_cosp(o_clcalipso,cospOUT%calipso_lidarcld,nvert)
+   if (cfg%Lclcalipsotmp) CALL histwrite3d_cosp(o_clcalipsotmp,cospOUT%calipso_lidarcldtmp(:,:,1),nverttemp)
+
+   if (cfg%Lcllcalipsoice) CALL histwrite2d_cosp(o_cllcalipsoice,cospOUT%calipso_cldlayerphase(:,1,1))
+   if (cfg%Lclhcalipsoice) CALL histwrite2d_cosp(o_clhcalipsoice,cospOUT%calipso_cldlayerphase(:,3,1))
+   if (cfg%Lclmcalipsoice) CALL histwrite2d_cosp(o_clmcalipsoice,cospOUT%calipso_cldlayerphase(:,2,1))
+   if (cfg%Lcltcalipsoice) CALL histwrite2d_cosp(o_cltcalipsoice,cospOUT%calipso_cldlayerphase(:,4,1))
+   if (cfg%Lclcalipsoice) CALL histwrite3d_cosp(o_clcalipsoice,cospOUT%calipso_lidarcldphase(:,:,1),nvert)
+   if (cfg%Lclcalipsotmpice) CALL histwrite3d_cosp(o_clcalipsotmpice,cospOUT%calipso_lidarcldtmp(:,:,2),nverttemp)
+
+   if (cfg%Lcllcalipsoliq) CALL histwrite2d_cosp(o_cllcalipsoliq,cospOUT%calipso_cldlayerphase(:,1,2))
+   if (cfg%Lclhcalipsoliq) CALL histwrite2d_cosp(o_clhcalipsoliq,cospOUT%calipso_cldlayerphase(:,3,2))
+   if (cfg%Lclmcalipsoliq) CALL histwrite2d_cosp(o_clmcalipsoliq,cospOUT%calipso_cldlayerphase(:,2,2))
+   if (cfg%Lcltcalipsoliq) CALL histwrite2d_cosp(o_cltcalipsoliq,cospOUT%calipso_cldlayerphase(:,4,2))
+   if (cfg%Lclcalipsoliq) CALL histwrite3d_cosp(o_clcalipsoliq,cospOUT%calipso_lidarcldphase(:,:,2),nvert)
+   if (cfg%Lclcalipsotmpliq) CALL histwrite3d_cosp(o_clcalipsotmpliq,cospOUT%calipso_lidarcldtmp(:,:,3),nverttemp)
+
+   if (cfg%Lcllcalipsoun) CALL histwrite2d_cosp(o_cllcalipsoun,cospOUT%calipso_cldlayerphase(:,1,3))
+   if (cfg%Lclhcalipsoun) CALL histwrite2d_cosp(o_clhcalipsoun,cospOUT%calipso_cldlayerphase(:,3,3))
+   if (cfg%Lclmcalipsoun) CALL histwrite2d_cosp(o_clmcalipsoun,cospOUT%calipso_cldlayerphase(:,2,3))
+   if (cfg%Lcltcalipsoun) CALL histwrite2d_cosp(o_cltcalipsoun,cospOUT%calipso_cldlayerphase(:,4,3))
+   if (cfg%Lclcalipsoun) CALL histwrite3d_cosp(o_clcalipsoun,cospOUT%calipso_lidarcldphase(:,:,3),nvert)
+   if (cfg%Lclcalipsotmpun) CALL histwrite3d_cosp(o_clcalipsotmpun,cospOUT%calipso_lidarcldtmp(:,:,4),nverttemp)
+
+   if (cfg%Lclopaquecalipso) CALL histwrite2d_cosp(o_clopaquecalipso,cospOUT%calipso_cldtype(:,1))
+   if (cfg%Lclthincalipso) CALL histwrite2d_cosp(o_clthincalipso,cospOUT%calipso_cldtype(:,2))   
+   if (cfg%Lclzopaquecalipso) CALL histwrite2d_cosp(o_clzopaquecalipso,cospOUT%calipso_cldtype(:,3))
+   if (cfg%Lclcalipsoopaque) CALL histwrite3d_cosp(o_clcalipsoopaque,cospOUT%calipso_lidarcldtype(:,:,1),nvert)
+   if (cfg%Lclcalipsothin) CALL histwrite3d_cosp(o_clcalipsothin,cospOUT%calipso_lidarcldtype(:,:,2),nvert)  
+   if (cfg%Lclcalipsozopaque) CALL histwrite3d_cosp(o_clcalipsozopaque,cospOUT%calipso_lidarcldtype(:,:,3),nvert)
+   if (cfg%Lclcalipsoopacity) CALL histwrite3d_cosp(o_clcalipsoopacity,cospOUT%calipso_lidarcldtype(:,:,4),nvert)
+
+   if (cfg%Lclopaquetemp) CALL histwrite2d_cosp(o_clopaquetemp,cospOUT%calipso_cldtypetemp(:,1))
+   if (cfg%Lclthintemp) CALL histwrite2d_cosp(o_clthintemp,cospOUT%calipso_cldtypetemp(:,2))
+   if (cfg%Lclzopaquetemp) CALL histwrite2d_cosp(o_clzopaquetemp,cospOUT%calipso_cldtypetemp(:,3))
+   if (cfg%Lclopaquemeanz) CALL histwrite2d_cosp(o_clopaquemeanz,cospOUT%calipso_cldtypemeanz(:,1))
+   if (cfg%Lclthinmeanz) CALL histwrite2d_cosp(o_clthinmeanz,cospOUT%calipso_cldtypemeanz(:,2))
+   if (cfg%Lclthinemis) CALL histwrite2d_cosp(o_clthinemis,cospOUT%calipso_cldthinemis)
+   if (cfg%Lclopaquemeanzse) CALL histwrite2d_cosp(o_clopaquemeanzse,cospOUT%calipso_cldtypemeanzse(:,1))
+   if (cfg%Lclthinmeanzse) CALL histwrite2d_cosp(o_clthinmeanzse,cospOUT%calipso_cldtypemeanzse(:,2))
+   if (cfg%Lclzopaquecalipsose) CALL histwrite2d_cosp(o_clzopaquecalipsose,cospOUT%calipso_cldtypemeanzse(:,3))
+
+
+#ifdef CPP_XIOS
+   do icl=1,SR_BINS
+      tmp_fi4da_cfadL(:,:,icl)=cospOUT%calipso_cfad_sr(:,icl,:)
+   enddo
+!   if (cfg%LcfadLidarsr532) CALL histwrite4d_cosp(o_cfad_lidarsr532,stlidar%cfad_sr)
+   if (cfg%LcfadLidarsr532) CALL histwrite4d_cosp(o_cfadLidarsr532,tmp_fi4da_cfadL)   !!! "_" enleve
+#else
+   if (cfg%LcfadLidarsr532) then
+     do icl=1,SR_BINS
+        CALL histwrite3d_cosp(o_cfadLidarsr532,cospOUT%calipso_cfad_sr(:,icl,:),nvert,icl)   !!! "_" enleve
+     enddo
+   endif
+#endif
+
+#ifdef CPP_XIOS
+   if (cfg%Latb532) CALL histwrite4d_cosp(o_atb532,cospOUT%calipso_beta_tot)
+#else
+   if (cfg%Latb532) then  
+     do icl=1,Ncolumns 
+        CALL histwrite3d_cosp(o_atb532,cospOUT%calipso_beta_tot(:,icl,:),nvertmcosp,icl)
+     enddo
+   endif 
+#endif
+
+   if (cfg%LlidarBetaMol532) CALL histwrite3d_cosp(o_lidarBetaMol532,cospOUT%calipso_beta_mol,nvertmcosp) 
+
+ endif !Calipso
+
+
+!!!! Sorties Ground Lidar
+ if (cfg%LgrLidar532) then
+
+   where(cospOUT%grLidar532_beta_tot == R_UNDEF) cospOUT%grLidar532_beta_tot = missing_val
+   where(cospOUT%grLidar532_cfad_sr == R_UNDEF) cospOUT%grLidar532_cfad_sr = missing_val
+   where(cospOUT%grLidar532_lidarcld == R_UNDEF) cospOUT%grLidar532_lidarcld = missing_val
+   where(cospOUT%grLidar532_cldlayer == R_UNDEF) cospOUT%grLidar532_cldlayer = missing_val
+   where(cospOUT%grLidar532_beta_mol == R_UNDEF) cospOUT%grLidar532_beta_mol = missing_val
+   where(cospOUT%grLidar532_srbval == R_UNDEF) cospOUT%grLidar532_srbval = missing_val
+
+   if (cfg%LcllgrLidar532) CALL histwrite2d_cosp(o_cllgrLidar532,cospOUT%grLidar532_cldlayer(:,1))
+   if (cfg%LclmgrLidar532) CALL histwrite2d_cosp(o_clmgrLidar532,cospOUT%grLidar532_cldlayer(:,2))
+   if (cfg%LclhgrLidar532) CALL histwrite2d_cosp(o_clhgrLidar532,cospOUT%grLidar532_cldlayer(:,3))
+   if (cfg%LcltgrLidar532) CALL histwrite2d_cosp(o_cltgrLidar532,cospOUT%grLidar532_cldlayer(:,4))
+
+   if (cfg%LclgrLidar532) CALL histwrite3d_cosp(o_clgrLidar532,cospOUT%grLidar532_lidarcld,nvert)
+   if (cfg%LlidarBetaMol532gr) CALL histwrite3d_cosp(o_lidarBetaMol532gr,cospOUT%grLidar532_beta_mol,nvertmcosp) 
+
+#ifdef CPP_XIOS
+   do icl=1,SR_BINS
+      tmp_fi4da_cfadLgr(:,:,icl)=cospOUT%grLidar532_cfad_sr(:,icl,:)
+   enddo
+   if (cfg%LcfadLidarsr532gr) CALL histwrite4d_cosp(o_cfadLidarsr532gr,tmp_fi4da_cfadLgr)
+#else
+   if (cfg%LcfadLidarsr532gr) then
+     do icl=1,SR_BINS
+        CALL histwrite3d_cosp(o_cfadLidarsr532gr,cospOUT%grLidar532_cfad_sr(:,icl,:),nvert,icl)
+     enddo
+   endif
+#endif
+
+#ifdef CPP_XIOS
+   if (cfg%Latb532gr) CALL histwrite4d_cosp(o_atb532gr,cospOUT%grLidar532_beta_tot)
+#else
+   if (cfg%Latb532gr) then  
+     do icl=1,Ncolumns 
+        CALL histwrite3d_cosp(o_atb532gr,cospOUT%grLidar532_beta_tot(:,icl,:),nvertmcosp,icl)
+     enddo
+   endif 
+#endif
+
+endif ! Ground Lidar 532 nm
+
+
+!!!! Sorties Atlid
+ if (cfg%Latlid) then
+
+   where(cospOUT%atlid_beta_tot == R_UNDEF) cospOUT%atlid_beta_tot = missing_val
+   where(cospOUT%atlid_cfad_sr == R_UNDEF) cospOUT%atlid_cfad_sr = missing_val
+   where(cospOUT%atlid_lidarcld == R_UNDEF) cospOUT%atlid_lidarcld = missing_val
+   where(cospOUT%atlid_cldlayer == R_UNDEF) cospOUT%atlid_cldlayer = missing_val
+   where(cospOUT%atlid_beta_mol == R_UNDEF) cospOUT%atlid_beta_mol = missing_val
+   where(cospOUT%atlid_srbval == R_UNDEF) cospOUT%atlid_srbval = missing_val
+
+   if (cfg%Lcllatlid) CALL histwrite2d_cosp(o_cllatlid,cospOUT%atlid_cldlayer(:,1))
+   if (cfg%Lclmatlid) CALL histwrite2d_cosp(o_clmatlid,cospOUT%atlid_cldlayer(:,2))
+   if (cfg%Lclhatlid) CALL histwrite2d_cosp(o_clhatlid,cospOUT%atlid_cldlayer(:,3))
+   if (cfg%Lcltatlid) CALL histwrite2d_cosp(o_cltatlid,cospOUT%atlid_cldlayer(:,4))
+
+   if (cfg%Lclatlid) CALL histwrite3d_cosp(o_clatlid,cospOUT%atlid_lidarcld,nvert)
+   if (cfg%LlidarBetaMol355) CALL histwrite3d_cosp(o_lidarBetaMol355,cospOUT%atlid_beta_mol,nvertmcosp) 
+
+#ifdef CPP_XIOS
+   do icl=1,SR_BINS
+      tmp_fi4da_cfadLatlid(:,:,icl)=cospOUT%atlid_cfad_sr(:,icl,:)
+   enddo
+   if (cfg%LcfadLidarsr355) CALL histwrite4d_cosp(o_cfadlidarsr355,tmp_fi4da_cfadLatlid)
+#else
+   if (cfg%LcfadLidarsr355) then
+     do icl=1,SR_BINS
+        CALL histwrite3d_cosp(o_cfadlidarsr355,cospOUT%atlid_cfad_sr(:,icl,:),nvert,icl)
+     enddo
+   endif
+#endif
+
+#ifdef CPP_XIOS
+   if (cfg%Latb355) CALL histwrite4d_cosp(o_atb355,cospOUT%atlid_beta_tot)
+#else
+   if (cfg%Latb355) then  
+     do icl=1,Ncolumns 
+        CALL histwrite3d_cosp(o_atb355,cospOUT%atlid_beta_tot(:,icl,:),nvertmcosp,icl)
+     enddo
+   endif 
+#endif
+
+endif ! Atlid
+
+
+ if (cfg%Lparasol) then
+   if (cfg%LparasolRefl) then
+! Ces 2 diagnostics sont controles par la clef logique "LparasolRefl"
+
+!!!   if (cfg%LparasolRefl) CALL histwrite3d_cosp(o_parasolrefl,cospOUT%parasolrefl,nvertp)
+     CALL histwrite3d_cosp(o_parasolGrid_refl,cospOUT%parasolGrid_refl,nvertp)
+
+#ifdef CPP_XIOS
+     CALL histwrite4d_cosp(o_parasolPix_refl,cospOUT%parasolPix_refl)
+#else 
+     do icl=1,Ncolumns 
+        CALL histwrite3d_cosp(o_parasolPix_refl,cospOUT%parasolPix_refl(:,icl,:),nvertp,icl)
+     enddo
+#endif
+
+    endif ! LparasolRefl
+   endif ! Parasol
+
+!  if (cfg%LparasolRefl) then 
+!    do k=1,PARASOL_NREFL
+!     do ip=1, Npoints
+!      if (stlidar%cldlayer(ip,4).gt.1.and.stlidar%parasolrefl(ip,k).ne.missing_val) then
+!        parasolcrefl(ip,k)=(stlidar%parasolrefl(ip,k)-0.03*(1.-stlidar%cldlayer(ip,4)/100.))/ &
+!                             (stlidar%cldlayer(ip,4)/100.)
+!         Ncref(ip,k) = 1.
+!      else
+!         parasolcrefl(ip,k)=missing_val
+!         Ncref(ip,k) = 0.
+!      endif
+!     enddo
+!    enddo
+!    CALL histwrite3d_cosp(o_Ncrefl,Ncref,nvertp)
+!    CALL histwrite3d_cosp(o_parasol_crefl,parasolcrefl,nvertp)
+!  endif
+
+
+!!! Sorties CloudSat
+ if (cfg%Lcloudsat) then
+
+   where(cospOUT%cloudsat_Ze_tot == R_UNDEF) cospOUT%cloudsat_Ze_tot = missing_val
+   where(cospOUT%cloudsat_cfad_ze == R_UNDEF) cospOUT%cloudsat_cfad_ze = missing_val
+   where(cospOUT%cloudsat_precip_cover == R_UNDEF) cospOUT%cloudsat_precip_cover = missing_val
+   where(cospOUT%cloudsat_pia == R_UNDEF) cospOUT%cloudsat_pia = missing_val
+
+   if (cfg%Lptradarflag0) CALL histwrite2d_cosp(o_ptradarflag0,cospOUT%cloudsat_precip_cover(:,1))
+   if (cfg%Lptradarflag1) CALL histwrite2d_cosp(o_ptradarflag1,cospOUT%cloudsat_precip_cover(:,2))
+   if (cfg%Lptradarflag2) CALL histwrite2d_cosp(o_ptradarflag2,cospOUT%cloudsat_precip_cover(:,3))
+   if (cfg%Lptradarflag3) CALL histwrite2d_cosp(o_ptradarflag3,cospOUT%cloudsat_precip_cover(:,4))
+   if (cfg%Lptradarflag4) CALL histwrite2d_cosp(o_ptradarflag4,cospOUT%cloudsat_precip_cover(:,5))
+   if (cfg%Lptradarflag5) CALL histwrite2d_cosp(o_ptradarflag5,cospOUT%cloudsat_precip_cover(:,6))
+   if (cfg%Lptradarflag6) CALL histwrite2d_cosp(o_ptradarflag6,cospOUT%cloudsat_precip_cover(:,7))
+   if (cfg%Lptradarflag7) CALL histwrite2d_cosp(o_ptradarflag7,cospOUT%cloudsat_precip_cover(:,8))
+   if (cfg%Lptradarflag8) CALL histwrite2d_cosp(o_ptradarflag8,cospOUT%cloudsat_precip_cover(:,9))
+   if (cfg%Lptradarflag9) CALL histwrite2d_cosp(o_ptradarflag9,cospOUT%cloudsat_precip_cover(:,10))
+   if (cfg%Lradarpia) CALL histwrite2d_cosp(o_radarpia,cospOUT%cloudsat_pia)
+
+#ifdef CPP_XIOS
+   do icl=1,CLOUDSAT_DBZE_BINS
+     tmp_fi4da_cfadR(:,:,icl)=cospOUT%cloudsat_cfad_ze(:,icl,:)
+   enddo
+   if (cfg%Ldbze94) CALL histwrite4d_cosp(o_dbze94,cospOUT%cloudsat_Ze_tot)
+!   if (cfg%LcfadDbze94) CALL histwrite4d_cosp(o_cfadDbze94,stradar%cfad_ze)
+   if (cfg%LcfadDbze94) CALL histwrite4d_cosp(o_cfadDbze94,tmp_fi4da_cfadR)
+#else
+   if (cfg%Ldbze94) then
+    do icl=1,Ncolumns
+       CALL histwrite3d_cosp(o_dbze94,cospOUT%cloudsat_Ze_tot(:,icl,:),nvert,icl)
+    enddo
+   endif
+   if (cfg%LcfadDbze94) then
+    do icl=1,CLOUDSAT_DBZE_BINS
+    CALL histwrite3d_cosp(o_cfadDbze94,cospOUT%cloudsat_cfad_ze(:,icl,:),nvert,icl)
+    enddo
+   endif
+#endif
+ endif
+! endif pour CloudSat
+
+
+!!! Sorties combinees Cloudsat et Calipso
+ if (cfg%Lcalipso .and. cfg%Lcloudsat) then
+   where(cospOUT%lidar_only_freq_cloud == R_UNDEF) &
+                           cospOUT%lidar_only_freq_cloud = missing_val
+   where(cospOUT%cloudsat_tcc == R_UNDEF) &
+                           cospOUT%cloudsat_tcc = missing_val
+   where(cospOUT%cloudsat_tcc2 == R_UNDEF) &
+                           cospOUT%cloudsat_tcc2 = missing_val
+   where(cospOUT%radar_lidar_tcc == R_UNDEF) &
+                           cospOUT%radar_lidar_tcc = missing_val
+
+   if (cfg%Lclcalipso2) CALL histwrite3d_cosp(o_clcalipso2,cospOUT%lidar_only_freq_cloud,nvert)
+   if (cfg%Lcloudsat_tcc) CALL histwrite2d_cosp(o_cloudsat_tcc,cospOUT%cloudsat_tcc)
+   if (cfg%Lcloudsat_tcc2) CALL histwrite2d_cosp(o_cloudsat_tcc2,cospOUT%cloudsat_tcc2)
+   if (cfg%Lcltlidarradar) CALL histwrite2d_cosp(o_cltlidarradar,cospOUT%radar_lidar_tcc)
+ endif
+
+
+!!! Sorties Isccp
+ if (cfg%Lisccp) then
+  where(cospOUT%isccp_totalcldarea == R_UNDEF) cospOUT%isccp_totalcldarea = missing_val
+  where(cospOUT%isccp_meanptop == R_UNDEF) cospOUT%isccp_meanptop = missing_val
+  where(cospOUT%isccp_meantaucld == R_UNDEF) cospOUT%isccp_meantaucld = missing_val
+  where(cospOUT%isccp_meanalbedocld == R_UNDEF) cospOUT%isccp_meanalbedocld = missing_val
+  where(cospOUT%isccp_meantb == R_UNDEF) cospOUT%isccp_meantb = missing_val
+  where(cospOUT%isccp_meantbclr == R_UNDEF) cospOUT%isccp_meantbclr = missing_val
+  where(cospOUT%isccp_fq == R_UNDEF) cospOUT%isccp_fq = missing_val
+  where(cospOUT%isccp_boxtau == R_UNDEF) cospOUT%isccp_boxtau = missing_val
+  where(cospOUT%isccp_boxptop == R_UNDEF) cospOUT%isccp_boxptop = missing_val 
+
+!   CALL histwrite2d_cosp(o_sunlit,gbx%sunlit)
+#ifdef CPP_XIOS
+  if (cfg%Lclisccp) CALL histwrite4d_cosp(o_clisccp,cospOUT%isccp_fq)
+#else
+   if (cfg%Lclisccp) then
+     do icl=1,7
+       CALL histwrite3d_cosp(o_clisccp,cospOUT%isccp_fq(:,icl,:),nvertisccp,icl) 
+     enddo
+   endif
+#endif
+
+   if (cfg%Lboxtauisccp) CALL histwrite3d_cosp(o_boxtauisccp,cospOUT%isccp_boxtau,nvertcol)
+   if (cfg%Lboxptopisccp) CALL histwrite3d_cosp(o_boxptopisccp,cospOUT%isccp_boxptop,nvertcol) 
+   if (cfg%Lcltisccp) CALL histwrite2d_cosp(o_cltisccp,cospOUT%isccp_totalcldarea) 
+   if (cfg%Lpctisccp) CALL histwrite2d_cosp(o_pctisccp,cospOUT%isccp_meanptop) 
+   if (cfg%Ltauisccp) CALL histwrite2d_cosp(o_tauisccp,cospOUT%isccp_meantaucld) 
+   if (cfg%Lalbisccp) CALL histwrite2d_cosp(o_albisccp,cospOUT%isccp_meanalbedocld) 
+   if (cfg%Lmeantbisccp) CALL histwrite2d_cosp(o_meantbisccp,cospOUT%isccp_meantb) 
+   if (cfg%Lmeantbclrisccp) CALL histwrite2d_cosp(o_meantbclrisccp,cospOUT%isccp_meantbclr)
+ endif ! Isccp
+
+
+!!! MISR simulator
+ if (cfg%Lmisr) then
+
+   if (cfg%LclMISR) then
+! Ces 3 diagnostics sont controles par la clef logique "LclMISR"
+   where(cospOUT%misr_fq == R_UNDEF) cospOUT%misr_fq = missing_val
+!   where(cospOUT%misr_dist_model_layertops == R_UNDEF) cospOUT%misr_dist_model_layertops = missing_val
+   where(cospOUT%misr_meanztop == R_UNDEF) cospOUT%misr_meanztop = missing_val
+   where(cospOUT%misr_cldarea == R_UNDEF) cospOUT%misr_cldarea = missing_val
+
+#ifdef CPP_XIOS
+   do icl=1,numMISRHgtBins
+      tmp_fi4da_misr(:,icl,:)=cospOUT%misr_fq(:,:,icl)
+   enddo
+!   if (cfg%LclMISR) CALL histwrite4d_cosp(o_clMISR,misr%fq_MISR)
+!   if (cfg%LclMISR) CALL histwrite4d_cosp(o_clMISR,tmp_fi4da_misr)
+   CALL histwrite4d_cosp(o_misr_fq,tmp_fi4da_misr)
+#else
+    do icl=1,7 
+      CALL histwrite3d_cosp(o_misr_fq,cospOUT%misr_fq(:,icl,:),nvertmisr,icl)
+    enddo
+#endif
+
+   CALL histwrite2d_cosp(o_misr_meanztop,cospOUT%misr_meanztop) 
+   CALL histwrite2d_cosp(o_misr_cldarea,cospOUT%misr_cldarea) 
+  endif ! LclMISR
+
+ endif ! Misr
+
+
+!!! Modis simulator
+ if (cfg%Lmodis) then
+  where(cospOUT%modis_Cloud_Fraction_Low_Mean == R_UNDEF) &
+        cospOUT%modis_Cloud_Fraction_Low_Mean = missing_val
+  where(cospOUT%modis_Cloud_Fraction_High_Mean == R_UNDEF) &
+        cospOUT%modis_Cloud_Fraction_High_Mean = missing_val
+  where(cospOUT%modis_Cloud_Fraction_Mid_Mean == R_UNDEF) &
+        cospOUT%modis_Cloud_Fraction_Mid_Mean = missing_val
+  where(cospOUT%modis_Cloud_Fraction_Total_Mean == R_UNDEF) &
+        cospOUT%modis_Cloud_Fraction_Total_Mean = missing_val
+  where(cospOUT%modis_Cloud_Fraction_Water_Mean == R_UNDEF) &
+        cospOUT%modis_Cloud_Fraction_Water_Mean = missing_val
+  where(cospOUT%modis_Cloud_Fraction_Ice_Mean == R_UNDEF) &
+        cospOUT%modis_Cloud_Fraction_Ice_Mean = missing_val
+  where(cospOUT%modis_Optical_Thickness_Total_Mean == R_UNDEF) &
+        cospOUT%modis_Optical_Thickness_Total_Mean = missing_val
+  where(cospOUT%modis_Optical_Thickness_Water_Mean == R_UNDEF) &
+        cospOUT%modis_Optical_Thickness_Water_Mean = missing_val
+  where(cospOUT%modis_Optical_Thickness_Ice_Mean == R_UNDEF) &
+        cospOUT%modis_Optical_Thickness_Ice_Mean = missing_val
+  where(cospOUT%modis_Cloud_Particle_Size_Water_Mean == R_UNDEF) &
+        cospOUT%modis_Cloud_Particle_Size_Water_Mean = missing_val
+  where(cospOUT%modis_Cloud_Particle_Size_Ice_Mean == R_UNDEF) &
+        cospOUT%modis_Cloud_Particle_Size_Ice_Mean = missing_val
+  where(cospOUT%modis_Cloud_Top_Pressure_Total_Mean == R_UNDEF) &
+        cospOUT%modis_Cloud_Top_Pressure_Total_Mean = missing_val
+  where(cospOUT%modis_Liquid_Water_Path_Mean == R_UNDEF) &
+        cospOUT%modis_Liquid_Water_Path_Mean = missing_val 
+  where(cospOUT%modis_Ice_Water_Path_Mean == R_UNDEF) &
+        cospOUT%modis_Ice_Water_Path_Mean = missing_val
+  where(cospOUT%modis_Optical_Thickness_Total_LogMean == R_UNDEF) &
+          cospOUT%modis_Optical_Thickness_Total_LogMean = missing_val
+  where(cospOUT%modis_Optical_Thickness_Water_LogMean == R_UNDEF) &
+          cospOUT%modis_Optical_Thickness_Water_LogMean = missing_val
+  where(cospOUT%modis_Optical_Thickness_Ice_LogMean == R_UNDEF) &
+          cospOUT%modis_Optical_Thickness_Ice_LogMean = missing_val
+    
+  if (cfg%Lcllmodis) CALL histwrite2d_cosp(o_cllmodis,cospOUT%modis_Cloud_Fraction_Low_Mean)
+  if (cfg%Lclhmodis) CALL histwrite2d_cosp(o_clhmodis,cospOUT%modis_Cloud_Fraction_High_Mean)
+  if (cfg%Lclmmodis) CALL histwrite2d_cosp(o_clmmodis,cospOUT%modis_Cloud_Fraction_Mid_Mean)
+  if (cfg%Lcltmodis) CALL histwrite2d_cosp(o_cltmodis,cospOUT%modis_Cloud_Fraction_Total_Mean)
+  if (cfg%Lclwmodis) CALL histwrite2d_cosp(o_clwmodis,cospOUT%modis_Cloud_Fraction_Water_Mean)
+  if (cfg%Lclimodis) CALL histwrite2d_cosp(o_climodis,cospOUT%modis_Cloud_Fraction_Ice_Mean)
+  if (cfg%Ltautmodis) CALL histwrite2d_cosp(o_tautmodis,cospOUT%modis_Optical_Thickness_Total_Mean)
+  if (cfg%Ltauwmodis) CALL histwrite2d_cosp(o_tauwmodis,cospOUT%modis_Optical_Thickness_Water_Mean)
+  if (cfg%Ltauimodis) CALL histwrite2d_cosp(o_tauimodis,cospOUT%modis_Optical_Thickness_Ice_Mean)
+  if (cfg%Ltautlogmodis) CALL histwrite2d_cosp(o_tautlogmodis,cospOUT%modis_Optical_Thickness_Total_LogMean)  
+  if (cfg%Ltauwlogmodis) CALL histwrite2d_cosp(o_tauwlogmodis,cospOUT%modis_Optical_Thickness_Water_LogMean)
+  if (cfg%Ltauilogmodis) CALL histwrite2d_cosp(o_tauilogmodis,cospOUT%modis_Optical_Thickness_Ice_LogMean)
+  if (cfg%Lreffclwmodis) CALL histwrite2d_cosp(o_reffclwmodis,cospOUT%modis_Cloud_Particle_Size_Water_Mean)
+  if (cfg%Lreffclimodis) CALL histwrite2d_cosp(o_reffclimodis,cospOUT%modis_Cloud_Particle_Size_Ice_Mean)
+  if (cfg%Lpctmodis) CALL histwrite2d_cosp(o_pctmodis,cospOUT%modis_Cloud_Top_Pressure_Total_Mean)
+  if (cfg%Llwpmodis) CALL histwrite2d_cosp(o_lwpmodis,cospOUT%modis_Liquid_Water_Path_Mean)
+  if (cfg%Liwpmodis) CALL histwrite2d_cosp(o_iwpmodis,cospOUT%modis_Ice_Water_Path_Mean)
+
+  if (cfg%Lclmodis) then
+! Ces 3 diagnostics sont controles par la clef logique "Lclmodis"
+    where(cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure == R_UNDEF) &
+          cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure = missing_val
+    where(cospOUT%modis_Optical_Thickness_vs_ReffICE == R_UNDEF) &
+          cospOUT%modis_Optical_Thickness_vs_ReffICE = missing_val
+    where(cospOUT%modis_Optical_thickness_vs_ReffLIQ == R_UNDEF) &
+          cospOUT%modis_Optical_thickness_vs_ReffLIQ = missing_val
+
+#ifdef CPP_XIOS
+    CALL histwrite4d_cosp(o_modis_ot_vs_ctp,cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure)
+    CALL histwrite4d_cosp(o_modis_ot_vs_reffice,cospOUT%modis_Optical_Thickness_vs_ReffICE)
+    CALL histwrite4d_cosp(o_modis_ot_vs_reffliq,cospOUT%modis_Optical_thickness_vs_ReffLIQ)
+#else
+   do icl=1,7
+   CALL histwrite3d_cosp(o_modis_ot_vs_ctp, &
+     cospOUT%modis_Optical_Thickness_vs_Cloud_Top_Pressure(:,icl,:),nvertisccp,icl)
+   CALL histwrite3d_cosp(o_modis_ot_vs_reffice, &
+     cospOUT%modis_Optical_Thickness_vs_ReffICE(:,icl,:),nvertReffIce,icl)
+   CALL histwrite3d_cosp(o_modis_ot_vs_reffliq, &
+     cospOUT%modis_Optical_thickness_vs_ReffLIQ(:,icl,:),nvertReffLiq,icl)
+   enddo
+#endif
+
+!#ifdef CPP_XIOS
+!  if (cfg%Lclmodis) CALL histwrite4d_cosp(o_crimodis,modis%Optical_Thickness_vs_ReffIce)
+!  if (cfg%Lclmodis) CALL histwrite4d_cosp(o_crlmodis,modis%Optical_Thickness_vs_ReffLiq)
+!#else
+!  if (cfg%Lclmodis) then
+!    do icl=1,7
+!     CALL histwrite3d_cosp(o_crimodis, &
+!          modis%Optical_Thickness_vs_ReffIce(:,icl,:),nvertReffIce,icl)
+!    enddo
+!  endif
+!  if (cfg%Lclmodis) then
+!    do icl=1,7 
+!     CALL histwrite3d_cosp(o_crlmodis, &
+!          modis%Optical_Thickness_vs_ReffLiq(:,icl,:),nvertReffLiq,icl)
+!    enddo
+!  endif 
+!#endif
+  endif ! Lclmodis
+
+ endif !modis
+
+
+ IF(.NOT.cosp_varsdefined) THEN
+!$OMP MASTER
+#ifndef CPP_IOIPSL_NO_OUTPUT
+            DO iff=1,3
+                IF (cosp_outfilekeys(iff)) THEN
+                  CALL histend(cosp_nidfiles(iff))
+                ENDIF ! cosp_outfilekeys
+            ENDDO !  iff
+#endif
+! Fermeture dans phys_output_write
+!#ifdef CPP_XIOS
+            !On finalise l'initialisation:
+            !CALL wxios_closedef()
+!#endif
+
+!$OMP END MASTER
+!$OMP BARRIER
+            cosp_varsdefined = .TRUE.
+ END IF
+
+    IF(cosp_varsdefined) THEN
+! On synchronise les fichiers pour IOIPSL
+#ifndef CPP_IOIPSL_NO_OUTPUT 
+!$OMP MASTER
+     DO iff=1,3
+         IF (ok_sync .AND. cosp_outfilekeys(iff)) THEN
+             CALL histsync(cosp_nidfiles(iff))
+         ENDIF
+     END DO
+!$OMP END MASTER
+#endif
+    ENDIF  !cosp_varsdefined
+
+    END SUBROUTINE lmdz_cosp_output_write
+
+
+! ug Routine pour definir itau_iocosp depuis cosp_output_write_mod:
+  SUBROUTINE set_itau_iocosp(ito)
+      IMPLICIT NONE
+      INTEGER, INTENT(IN) :: ito
+      itau_iocosp = ito
+  END SUBROUTINE
+
+  SUBROUTINE histdef2d_cosp (iff,var)
+
+    USE ioipsl
+    USE dimphy
+    use iophy
+    USE mod_phys_lmdz_para
+    USE mod_grid_phy_lmdz, ONLY: nbp_lon
+    USE print_control_mod, ONLY: lunout,prt_level
+#ifdef CPP_XIOS
+  USE wxios
+#endif
+
+    IMPLICIT NONE
+
+    INCLUDE "clesphys.h"
+
+    INTEGER                          :: iff
+    TYPE(ctrl_outcosp)               :: var
+
+    REAL zstophym
+    CHARACTER(LEN=20) :: typeecrit
+
+    ! ug On rÃ©cupÃ¨re le type Ã©crit de la structure:
+    !       Assez moche, Ã|  refaire si meilleure mÃ©thode...
+    IF (INDEX(var%cosp_typeecrit(iff), "once") > 0) THEN
+       typeecrit = 'once'
+    ELSE IF(INDEX(var%cosp_typeecrit(iff), "t_min") > 0) THEN
+       typeecrit = 't_min(X)'
+    ELSE IF(INDEX(var%cosp_typeecrit(iff), "t_max") > 0) THEN
+       typeecrit = 't_max(X)'
+    ELSE IF(INDEX(var%cosp_typeecrit(iff), "inst") > 0) THEN
+       typeecrit = 'inst(X)'
+    ELSE
+       typeecrit = cosp_outfiletypes(iff)
+    ENDIF
+
+    IF (typeecrit=='inst(X)'.OR.typeecrit=='once') THEN
+       zstophym=zoutm_cosp(iff)
+    ELSE
+       zstophym=zdtimemoy_cosp
+    ENDIF
+
+#ifdef CPP_XIOS
+     IF (.not. ok_all_xml) then
+       IF ( var%cles(iff) ) THEN
+         if (prt_level >= 10) then
+              WRITE(lunout,*)'Appel wxios_add_field_to_file var%name =',var%name 
+         endif
+        CALL wxios_add_field_to_file(var%name, 2, cosp_nidfiles(iff), cosp_outfilenames(iff), &
+                                     var%description, var%unit, 1, typeecrit)
+       ENDIF
+     ENDIF
+#endif
+
+#ifndef CPP_IOIPSL_NO_OUTPUT 
+       IF ( var%cles(iff) ) THEN
+          CALL histdef (cosp_nidfiles(iff), var%name, var%description, var%unit, &
+               nbp_lon,jj_nb,nhoricosp(iff), 1,1,1, -99, 32, &
+               typeecrit, zstophym,zoutm_cosp(iff))
+       ENDIF
+#endif
+
+  END SUBROUTINE histdef2d_cosp
+
+
+ SUBROUTINE histdef3d_cosp (iff,var,nvertsave,ncols)
+    USE ioipsl
+    USE dimphy
+    use iophy
+    USE mod_phys_lmdz_para
+    USE mod_grid_phy_lmdz, ONLY: nbp_lon
+    USE print_control_mod, ONLY: lunout,prt_level
+
+#ifdef CPP_XIOS
+  USE wxios
+#endif
+
+
+    IMPLICIT NONE
+
+    INCLUDE "clesphys.h"
+
+    INTEGER                        :: iff, klevs
+    INTEGER, INTENT(IN), OPTIONAL  :: ncols ! ug RUSTINE POUR LES variables 4D
+    INTEGER, INTENT(IN)           :: nvertsave
+    TYPE(ctrl_outcosp)             :: var
+
+    REAL zstophym
+    CHARACTER(LEN=20) :: typeecrit, nomi
+    CHARACTER(LEN=20) :: nom
+    character(len=2) :: str2
+    CHARACTER(len=20) :: nam_axvert
+
+! Axe vertical
+      IF (nvertsave.eq.nvertp(iff)) THEN
+          klevs=PARASOL_NREFL
+          nam_axvert="sza"
+      ELSE IF (nvertsave.eq.nvertisccp(iff)) THEN
+          klevs=7
+          nam_axvert="pressure2"
+      ELSE IF (nvertsave.eq.nvertcol(iff)) THEN
+          klevs=Ncolout
+          nam_axvert="column"
+      ELSE IF (nvertsave.eq.nverttemp(iff)) THEN
+          klevs=LIDAR_NTEMP
+          nam_axvert="temp"
+      ELSE IF (nvertsave.eq.nvertmisr(iff)) THEN
+          klevs=numMISRHgtBins
+          nam_axvert="cth16"
+      ELSE IF (nvertsave.eq.nvertReffIce(iff)) THEN
+          klevs= numMODISReffIceBins
+          nam_axvert="ReffIce"
+      ELSE IF (nvertsave.eq.nvertReffLiq(iff)) THEN
+          klevs= numMODISReffLiqBins
+          nam_axvert="ReffLiq"
+      ELSE
+           klevs=Nlevout
+           nam_axvert="presnivs"
+      ENDIF
+
+! ug RUSTINE POUR LES Champs 4D
+      IF (PRESENT(ncols)) THEN
+               write(str2,'(i2.2)')ncols
+               nomi=var%name
+               nom="c"//str2//"_"//nomi
+      ELSE
+               nom=var%name
+      END IF
+
+    ! ug On rÃ©cupÃ¨re le type Ã©crit de la structure:
+    !       Assez moche, Ã|  refaire si meilleure mÃ©thode...
+    IF (INDEX(var%cosp_typeecrit(iff), "once") > 0) THEN
+       typeecrit = 'once'
+    ELSE IF(INDEX(var%cosp_typeecrit(iff), "t_min") > 0) THEN
+       typeecrit = 't_min(X)'
+    ELSE IF(INDEX(var%cosp_typeecrit(iff), "t_max") > 0) THEN
+       typeecrit = 't_max(X)'
+    ELSE IF(INDEX(var%cosp_typeecrit(iff), "inst") > 0) THEN
+       typeecrit = 'inst(X)'
+    ELSE
+       typeecrit = cosp_outfiletypes(iff)
+    ENDIF
+
+    IF (typeecrit=='inst(X)'.OR.typeecrit=='once') THEN
+       zstophym=zoutm_cosp(iff)
+    ELSE
+       zstophym=zdtimemoy_cosp
+    ENDIF
+
+#ifdef CPP_XIOS
+      IF (.not. ok_all_xml) then
+        IF ( var%cles(iff) ) THEN
+          if (prt_level >= 10) then
+              WRITE(lunout,*)'Appel wxios_add_field_to_file 3d nom variable nam_axvert = ',nom, nam_axvert 
+          endif
+          CALL wxios_add_field_to_file(nom, 3, cosp_nidfiles(iff), cosp_outfilenames(iff), &
+                                       var%description, var%unit, 1, typeecrit, nam_axvert)
+        ENDIF
+      ENDIF
+#endif
+
+#ifndef CPP_IOIPSL_NO_OUTPUT
+       IF ( var%cles(iff) ) THEN
+          CALL histdef (cosp_nidfiles(iff), nom, var%description, var%unit, &
+               nbp_lon, jj_nb, nhoricosp(iff), klevs, 1, &
+               klevs, nvertsave, 32, typeecrit, &
+               zstophym, zoutm_cosp(iff))
+       ENDIF
+#endif
+
+  END SUBROUTINE histdef3d_cosp
+
+
+ SUBROUTINE histwrite2d_cosp(var,field)
+  USE dimphy
+  USE mod_phys_lmdz_para
+  USE ioipsl
+  use iophy
+  USE mod_grid_phy_lmdz, ONLY: nbp_lon
+  USE print_control_mod, ONLY: lunout,prt_level
+
+#ifdef CPP_XIOS
+  USE xios, only: xios_send_field
+#endif
+
+  IMPLICIT NONE
+  INCLUDE 'clesphys.h'
+
+    TYPE(ctrl_outcosp), INTENT(IN) :: var
+    REAL, DIMENSION(:), INTENT(IN) :: field
+
+    INTEGER :: iff
+
+    REAL,DIMENSION(klon_mpi) :: buffer_omp
+    INTEGER, allocatable, DIMENSION(:) :: index2d
+    REAL :: Field2d(nbp_lon,jj_nb)
+    CHARACTER(LEN=20) ::  nomi, nom
+    character(len=2) :: str2
+    LOGICAL, SAVE  :: firstx
+!$OMP THREADPRIVATE(firstx)
+
+    IF (prt_level >= 9) WRITE(lunout,*)'Begin histrwrite2d ',var%name
+
+  ! On regarde si on est dans la phase de dÃ©finition ou d'Ã©criture:
+  IF(.NOT.cosp_varsdefined) THEN
+!$OMP MASTER
+      !Si phase de dÃ©finition.... on dÃ©finit
+      CALL conf_cospoutputs(var%name,var%cles)
+      DO iff=1, 3
+         IF (cosp_outfilekeys(iff)) THEN
+            CALL histdef2d_cosp(iff, var)
+         ENDIF
+      ENDDO
+!$OMP END MASTER
+  ELSE
+    !Et sinon on.... Ã©crit
+    IF (SIZE(field)/=klon) &
+  CALL abort_physic('iophy::histwrite2d_cosp','Field first DIMENSION not equal to klon',1) 
+
+    CALL Gather_omp(field,buffer_omp)
+!$OMP MASTER
+    CALL grid1Dto2D_mpi(buffer_omp,Field2d)
+
+! La boucle sur les fichiers:
+      firstx=.true.
+      DO iff=1, 3
+           IF (var%cles(iff) .AND. cosp_outfilekeys(iff)) THEN
+                ALLOCATE(index2d(nbp_lon*jj_nb))
+#ifndef CPP_IOIPSL_NO_OUTPUT
+        CALL histwrite(cosp_nidfiles(iff),var%name,itau_iocosp,Field2d,nbp_lon*jj_nb,index2d) 
+#endif
+                deallocate(index2d)
+#ifdef CPP_XIOS
+              IF (.not. ok_all_xml) then
+                 if (firstx) then
+                  if (prt_level >= 10) then
+                    WRITE(lunout,*)'xios_send_field variable ',var%name
+                  endif
+                  CALL xios_send_field(var%name, Field2d)
+                   firstx=.false.
+                 endif
+              ENDIF
+#endif
+           ENDIF
+      ENDDO 
+
+#ifdef CPP_XIOS
+      IF (ok_all_xml) THEN
+        if (prt_level >= 1) then
+              WRITE(lunout,*)'xios_send_field variable ',var%name
+        endif
+       CALL xios_send_field(var%name, Field2d)
+      ENDIF
+#endif
+
+!$OMP END MASTER   
+  ENDIF ! vars_defined
+  IF (prt_level >= 9) WRITE(lunout,*)'End histrwrite2d_cosp ',var%name
+  END SUBROUTINE histwrite2d_cosp
+
+
+! ug NOUVELLE VERSION DES WRITE AVEC LA BOUCLE DO RENTREE
+! AI sept 2013
+  SUBROUTINE histwrite3d_cosp(var, field, nverts, ncols)
+  USE dimphy
+  USE mod_phys_lmdz_para
+  USE ioipsl
+  use iophy
+  USE mod_grid_phy_lmdz, ONLY: nbp_lon
+  USE print_control_mod, ONLY: lunout,prt_level
+
+#ifdef CPP_XIOS
+  USE xios, only: xios_send_field
+#endif
+
+
+  IMPLICIT NONE
+  INCLUDE 'clesphys.h'
+
+    TYPE(ctrl_outcosp), INTENT(IN)    :: var
+    REAL, DIMENSION(:,:), INTENT(IN)  :: field ! --> field(klon,:)
+    INTEGER, INTENT(IN), OPTIONAL     :: ncols ! ug RUSTINE POUR LES Champs 4D.....
+    INTEGER, DIMENSION(3), INTENT(IN) :: nverts
+
+    INTEGER :: iff, k
+
+    REAL,DIMENSION(klon_mpi,SIZE(field,2)) :: buffer_omp
+    REAL :: Field3d(nbp_lon,jj_nb,SIZE(field,2))
+    INTEGER :: ip, n, nlev
+    INTEGER, ALLOCATABLE, DIMENSION(:) :: index3d
+    CHARACTER(LEN=20) ::  nomi, nom
+    character(len=2) :: str2
+    LOGICAL, SAVE  :: firstx
+!$OMP THREADPRIVATE(firstx)
+
+  IF (prt_level >= 9) write(lunout,*)'Begin histrwrite3d ',var%name
+
+! ug RUSTINE POUR LES STD LEVS.....
+      IF (PRESENT(ncols)) THEN
+              write(str2,'(i2.2)')ncols
+              nomi=var%name
+              nom="c"//str2//"_"//nomi
+      ELSE
+               nom=var%name
+      END IF
+  ! On regarde si on est dans la phase de dÃ©finition ou d'Ã©criture:
+  IF(.NOT.cosp_varsdefined) THEN
+      !Si phase de dÃ©finition.... on dÃ©finit
+!$OMP MASTER
+      CALL conf_cospoutputs(var%name,var%cles)
+      DO iff=1, 3
+        IF (cosp_outfilekeys(iff)) THEN
+          CALL histdef3d_cosp(iff, var, nverts(iff), ncols)
+        ENDIF
+      ENDDO
+!$OMP END MASTER
+  ELSE
+    !Et sinon on.... Ã©crit
+    IF (SIZE(field,1)/=klon) &
+   CALL abort_physic('iophy::histwrite3d','Field first DIMENSION not equal to klon',1)                                  
+    nlev=SIZE(field,2)
+
+
+    CALL Gather_omp(field,buffer_omp)
+!$OMP MASTER
+    CALL grid1Dto2D_mpi(buffer_omp,field3d)
+
+! BOUCLE SUR LES FICHIERS
+     firstx=.true.
+     DO iff=1, 3
+        IF (var%cles(iff) .AND. cosp_outfilekeys(iff)) THEN
+           ALLOCATE(index3d(nbp_lon*jj_nb*nlev))
+#ifndef CPP_IOIPSL_NO_OUTPUT
+    CALL histwrite(cosp_nidfiles(iff),nom,itau_iocosp,Field3d,nbp_lon*jj_nb*nlev,index3d) 
+#endif
+
+#ifdef CPP_XIOS
+          IF (.not. ok_all_xml) then
+           IF (firstx) THEN
+               CALL xios_send_field(nom, Field3d(:,:,1:nlev))
+               IF (prt_level >= 9) WRITE(lunout,*)'xios_send_field ',var%name
+               firstx=.FALSE.
+           ENDIF
+          ENDIF
+#endif
+         deallocate(index3d)
+        ENDIF
+      ENDDO
+#ifdef CPP_XIOS
+    IF (ok_all_xml) THEN
+     CALL xios_send_field(nom, Field3d(:,:,1:nlev))
+     IF (prt_level >= 1) WRITE(lunout,*)'xios_send_field ',var%name
+    ENDIF
+#endif
+
+!$OMP END MASTER   
+  ENDIF ! vars_defined
+  IF (prt_level >= 9) write(lunout,*)'End histrwrite3d_cosp ',nom
+  END SUBROUTINE histwrite3d_cosp
+
+
+! ug NOUVELLE VERSION DES WRITE AVEC LA BOUCLE DO RENTREE
+! AI sept 2013
+  SUBROUTINE histwrite4d_cosp(var, field)
+  USE dimphy
+  USE mod_phys_lmdz_para
+  USE ioipsl
+  use iophy
+  USE mod_grid_phy_lmdz, ONLY: nbp_lon
+  USE print_control_mod, ONLY: lunout,prt_level
+
+#ifdef CPP_XIOS
+  USE xios, only: xios_send_field
+#endif
+
+
+  IMPLICIT NONE
+  INCLUDE 'clesphys.h'
+
+    TYPE(ctrl_outcosp), INTENT(IN)    :: var
+    REAL, DIMENSION(:,:,:), INTENT(IN)  :: field ! --> field(klon,:)
+
+    INTEGER :: iff, k
+
+    REAL,DIMENSION(klon_mpi,SIZE(field,2),SIZE(field,3)) :: buffer_omp
+    REAL :: field4d(nbp_lon,jj_nb,SIZE(field,2),SIZE(field,3))
+    INTEGER :: ip, n, nlev, nlev2
+    INTEGER, ALLOCATABLE, DIMENSION(:) :: index4d
+    CHARACTER(LEN=20) ::  nomi, nom
+
+  IF (prt_level >= 9) write(lunout,*)'Begin histrwrite4d ',var%name
+
+  IF(cosp_varsdefined) THEN
+    !Et sinon on.... Ã©crit
+    IF (SIZE(field,1)/=klon) &
+   CALL abort_physic('iophy::histwrite3d','Field first DIMENSION not equal to klon',1)            
+
+    nlev=SIZE(field,2)
+    nlev2=SIZE(field,3)
+    CALL Gather_omp(field,buffer_omp)
+!$OMP MASTER
+    CALL grid1Dto2D_mpi(buffer_omp,field4d)
+
+#ifdef CPP_XIOS
+!    IF (ok_all_xml) THEN
+     CALL xios_send_field(var%name, Field4d(:,:,1:nlev,1:nlev2))
+     IF (prt_level >= 1) WRITE(lunout,*)'xios_send_field ',var%name
+!    ENDIF
+#endif
+
+!$OMP END MASTER   
+  ENDIF ! vars_defined
+  IF (prt_level >= 9) write(lunout,*)'End histrwrite4d_cosp ',nom
+  END SUBROUTINE histwrite4d_cosp
+
+  SUBROUTINE conf_cospoutputs(nam_var,cles_var)
+!!! Lecture des noms et cles de sortie des variables dans config.def
+    !   en utilisant les routines getin de IOIPSL  
+    use ioipsl
+    USE print_control_mod, ONLY: lunout,prt_level
+
+    IMPLICIT NONE
+
+   CHARACTER(LEN=20)               :: nam_var, nnam_var
+   LOGICAL, DIMENSION(3)           :: cles_var
+
+! Lecture dans config.def ou output.def de cles_var et name_var
+    CALL getin('cles_'//nam_var,cles_var)
+    CALL getin('name_'//nam_var,nam_var)
+    IF(prt_level>10) WRITE(lunout,*)'nam_var cles_var ',nam_var,cles_var(:)
+
+  END SUBROUTINE conf_cospoutputs
+
+ END MODULE lmdz_cosp_output_write_mod
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_read_outputkeys.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_read_outputkeys.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_read_outputkeys.F90	(revision 3605)
@@ -0,0 +1,1723 @@
+!!!=============================================================================
+!!! AI mars 2018
+!!  Module permettant de controler les cles de sorties cosp
+!!  pour LMDZ
+!! 1. on initialise les cles au 1er passage a cosp itap de la physique = 1
+!! 2. on garde la routine de lecture du fichier namelist cosp_out...txt pour le
+!!    cas non XIOS (ioipsl)
+!! 3. on rajoutte une subroutine qui interoge XIOS si les champs sont demandes
+!!    dans les xml alors on les active et on active les simulateurs
+!!    correspondant 
+!!
+!!! RG janvier 2019
+!!  Mise a jour pour avoir toutes les sorties de COSPv2
+!!  Changement de nom a "lmdz_cosp_read_outputkeys"
+!!!=============================================================================
+
+module lmdz_cosp_read_outputkeys
+
+  USE mod_phys_lmdz_para
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! TYPE COSP_CONFIG
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  TYPE COSP_CONFIG
+     logical :: &
+         Lwrite_output,    & ! Control for output file
+         Lfracout,         & ! Control SCOPS cloud fraction out ?
+! simulators
+         Lcloudsat,        & ! CLOUDSAT simulator on/off switch 
+         Lcalipso,         & ! CALIPSO simulator on/off switch 
+	 LgrLidar532,      & ! GROUND LIDAR simulator on/off switch
+         Latlid,           & ! ATLID simulator on/off switch
+         Lisccp,           & ! ISCCP simulator on/off switch
+         Lmodis,           & ! MODIS simulatoe on/off switch
+         Lmisr,            & ! MISR simulator on/off switch 
+         Lrttov,           & ! RTTOV simulator on/off switch 
+         Lparasol,         & ! PARASOL simulator on/off switch
+
+! diagnostics 
+         Lpctisccp,        & ! ISCCP mean cloud top pressure
+         Lclisccp,         & ! ISCCP cloud area fraction
+         Lboxptopisccp,    & ! ISCCP CTP in each column
+         Lboxtauisccp,     & ! ISCCP optical epth in each column
+         Ltauisccp,        & ! ISCCP mean optical depth
+         Lcltisccp,        & ! ISCCP total cloud fraction
+         Lmeantbisccp,     & ! ISCCP mean all-sky 10.5micron brightness temperature
+         Lmeantbclrisccp,  & ! ISCCP mean clear-sky 10.5micron brightness temperature
+         Lalbisccp,        & ! ISCCP mean cloud albedo         
+         LclMISR,          & ! MISR cloud fraction
+         Lcltmodis,        & ! MODIS total cloud fraction
+         Lclwmodis,        & ! MODIS liquid cloud fraction
+         Lclimodis,        & ! MODIS ice cloud fraction
+         Lclhmodis,        & ! MODIS high-level cloud fraction
+         Lclmmodis,        & ! MODIS mid-level cloud fraction
+         Lcllmodis,        & ! MODIS low-level cloud fraction
+         Ltautmodis,       & ! MODIS total cloud optical thicknes
+         Ltauwmodis,       & ! MODIS liquid optical thickness
+         Ltauimodis,       & ! MODIS ice optical thickness
+         Ltautlogmodis,    & ! MODIS total cloud optical thickness (log10 mean)
+         Ltauwlogmodis,    & ! MODIS liquid optical thickness (log10 mean)
+         Ltauilogmodis,    & ! MODIS ice optical thickness (log10 mean)
+         Lreffclwmodis,    & ! MODIS liquid cloud particle size
+         Lreffclimodis,    & ! MODIS ice particle size
+         Lpctmodis,        & ! MODIS cloud top pressure
+         Llwpmodis,        & ! MODIS cloud liquid water path
+         Liwpmodis,        & ! MODIS cloud ice water path
+         Lclmodis,         & ! MODIS cloud area fraction
+         Latb532,          & ! CALIPSO attenuated total backscatter (532nm)
+         Latb532gr,        & ! GROUND LIDAR @ 532NM attenuated total backscatter (532nm)
+         Latb355,          & ! ATLID attenuated total backscatter (355nm)
+         LlidarBetaMol532, & ! CALIPSO molecular backscatter (532nm)         
+         LlidarBetaMol532gr,&! GROUND LIDAR @ 532NM molecular backscatter (532nm)
+         LlidarBetaMol355, & ! ATLID molecular backscatter (355nm) 
+         LcfadLidarsr532,  & ! CALIPSO scattering ratio CFAD
+         LcfadLidarsr532gr,& ! GROUND LIDAR @ 532NM scattering ratio CFAD  
+         LcfadLidarsr355,  & ! ATLID scattering ratio CFAD 
+         Lclcalipso2,      & ! CALIPSO cloud fraction undetected by cloudsat
+         Lclcalipso,       & ! CALIPSO cloud area fraction
+         LclgrLidar532,   & ! GROUND LIDAR @ 532NM cloud area fraction 
+         Lclatlid,         & ! ATLID cloud area fraction 
+         Lclhcalipso,      & ! CALIPSO high-level cloud fraction
+         Lcllcalipso,      & ! CALIPSO low-level cloud fraction
+         Lclmcalipso,      & ! CALIPSO mid-level cloud fraction
+         Lcltcalipso,      & ! CALIPSO total cloud fraction
+         LclhgrLidar532,  & ! GROUND LIDAR @ 532NM high-level cloud fraction 
+         LcllgrLidar532,  & ! GROUND LIDAR @ 532NM low-level cloud fraction 
+         LclmgrLidar532,  & ! GROUND LIDAR @ 532NM mid-level cloud fraction
+         LcltgrLidar532,  & ! GROUND LIDAR @ 532NM total cloud fraction
+         Lclhatlid,        & ! ATLID high-level cloud fraction
+         Lcllatlid,        & ! ATLID low-level cloud fraction  
+         Lclmatlid,        & ! ATLID mid-level cloud fraction 
+         Lcltatlid,        & ! ATLID total cloud fraction
+         Lcltlidarradar,   & ! CALIPSO-CLOUDSAT total cloud fraction
+         Lcloudsat_tcc,    & !
+         Lcloudsat_tcc2,   & !
+         Lclcalipsoliq,    & ! CALIPSO liquid cloud area fraction
+         Lclcalipsoice,    & ! CALIPSO ice cloud area fraction 
+         Lclcalipsoun,     & ! CALIPSO undetected cloud area fraction
+         Lclcalipsotmp,    & ! CALIPSO undetected cloud area fraction
+         Lclcalipsotmpliq, & ! CALIPSO liquid cloud area fraction
+         Lclcalipsotmpice, & ! CALIPSO ice cloud area fraction
+         Lclcalipsotmpun,  & ! CALIPSO undetected cloud area fraction
+         Lcltcalipsoliq,   & ! CALIPSO liquid total cloud fraction
+         Lcltcalipsoice,   & ! CALIPSO ice total cloud fraction
+         Lcltcalipsoun,    & ! CALIPSO undetected total cloud fraction
+         Lclhcalipsoliq,   & ! CALIPSO high-level liquid cloud fraction
+         Lclhcalipsoice,   & ! CALIPSO high-level ice cloud fraction
+         Lclhcalipsoun,    & ! CALIPSO high-level undetected cloud fraction
+         Lclmcalipsoliq,   & ! CALIPSO mid-level liquid cloud fraction
+         Lclmcalipsoice,   & ! CALIPSO mid-level ice cloud fraction
+         Lclmcalipsoun,    & ! CALIPSO mid-level undetected cloud fraction
+         Lcllcalipsoliq,   & ! CALIPSO low-level liquid cloud fraction
+         Lcllcalipsoice,   & ! CALIPSO low-level ice cloud fraction
+         Lcllcalipsoun,    & ! CALIPSO low-level undetected cloud fraction
+         Lclopaquecalipso, & ! CALIPSO opaque cloud cover (2D Map)
+         Lclthincalipso,   & ! CALIPSO thin cloud cover (2D Map)
+         Lclzopaquecalipso,& ! CALIPSO z_opaque altitude (opaque clouds only, 2D Map)
+         Lclcalipsoopaque, & ! CALIPSO opaque cloud profiles 3D fraction 
+         Lclcalipsothin,   & ! CALIPSO thin cloud profiles 3D fraction 
+         Lclcalipsozopaque,& ! CALIPSO z_opaque 3D fraction 
+         Lclcalipsoopacity,& ! CALIPSO opacity 3D fraction 
+         Lclopaquetemp,    & ! CALIPSO opaque cloud temperature 
+         Lclthintemp,      & ! CALIPSO thin cloud temperature
+         Lclzopaquetemp,   & ! CALIPSO z_opaque temperature  
+         Lclopaquemeanz,   & ! CALIPSO opaque cloud altitude  
+         Lclthinmeanz,     & ! CALIPSO thin cloud altitude 
+         Lclthinemis,      & ! CALIPSO thin cloud emissivity
+         Lclopaquemeanzse,   & ! CALIPSO opaque cloud altitude with respect to SE 
+         Lclthinmeanzse,     & ! CALIPSO thin cloud altitude with respect to SE
+         Lclzopaquecalipsose,& ! CALIPSO z_opaque altitude with respect to SE
+         LcfadDbze94,      & ! CLOUDSAT radar reflectivity CFAD
+         Ldbze94,          & ! CLOUDSAT radar reflectivity
+         LparasolRefl,     & ! PARASOL reflectance
+         Ltbrttov,         & ! RTTOV mean clear-sky brightness temperature
+         Lptradarflag0,    & ! CLOUDSAT no precipitation flag
+         Lptradarflag1,    & ! CLOUDSAT rain possible flag
+         Lptradarflag2,    & ! CLOUDSAT rain probable flag
+         Lptradarflag3,    & ! CLOUDSAT rain certain flag
+         Lptradarflag4,    & ! CLOUDSAT snow possible flag
+         Lptradarflag5,    & ! CLOUDSAT snow certain flag
+         Lptradarflag6,    & ! CLOUDSAT mixed-precipitation possible flag
+         Lptradarflag7,    & ! CLOUDSAT mixed-precipitation certain flag
+         Lptradarflag8,    & ! CLOUDSAT heavy rain flag
+         Lptradarflag9,    & ! CLOUDSAT default flag
+         Lradarpia           ! CLOUDSAT PIA
+
+
+!     character(len=32),dimension(:),allocatable :: out_list
+      character(len=32) :: out_list(107)
+  END TYPE COSP_CONFIG       
+
+
+CONTAINS
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!--------------- SUBROUTINE READ_COSP_OUTPUT_NL -------------------------
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ SUBROUTINE cosp_outputkeys_init(cfg)
+  implicit none
+  type(cosp_config),intent(inout) :: cfg 
+  character(len=32) :: out_list(107)
+  integer :: i
+                
+   do i=1,107
+      cfg%out_list(i)=''
+   enddo
+
+
+   cfg%Lcloudsat=.false.
+   cfg%Lcalipso=.false.
+   cfg%LgrLidar532=.false.
+   cfg%Latlid=.false.
+   cfg%Lisccp=.false.
+   cfg%Lmodis=.false.
+   cfg%Lmisr=.false.
+   cfg%Lrttov=.false.
+   cfg%Lparasol=.false.
+   cfg%Lwrite_output=.false.
+   cfg%Lfracout=.false.
+
+
+   cfg%Lpctisccp=.false.
+   cfg%Lclisccp=.false.
+   cfg%Lboxptopisccp=.false.
+   cfg%Lboxtauisccp=.false.
+   cfg%Ltauisccp=.false.
+   cfg%Lcltisccp=.false.
+   cfg%Lmeantbisccp=.false.
+   cfg%Lmeantbclrisccp=.false.
+   cfg%Lalbisccp=.false.
+   cfg%LclMISR=.false.
+   cfg%Lcltmodis=.false.
+   cfg%Lclwmodis=.false.
+   cfg%Lclimodis=.false.
+   cfg%Lclhmodis=.false.
+   cfg%Lclmmodis=.false.
+   cfg%Lcllmodis=.false.
+   cfg%Ltautmodis=.false.
+   cfg%Ltauwmodis=.false.
+   cfg%Ltauimodis=.false.
+   cfg%Ltautlogmodis=.false.
+   cfg%Ltauwlogmodis=.false.
+   cfg%Ltauilogmodis=.false.
+   cfg%Lreffclwmodis=.false.
+   cfg%Lreffclimodis=.false.
+   cfg%Lpctmodis=.false.
+   cfg%Llwpmodis=.false.
+   cfg%Liwpmodis=.false.
+   cfg%Lclmodis=.false.
+   cfg%Latb532=.false.
+   cfg%Latb532gr=.false.
+   cfg%Latb355=.false.
+   cfg%LlidarBetaMol532=.false.
+   cfg%LlidarBetaMol532gr=.false.
+   cfg%LlidarBetaMol355=.false.
+   cfg%LcfadLidarsr532=.false.
+   cfg%LcfadLidarsr532gr=.false.
+   cfg%LcfadLidarsr355 =.false.
+   cfg%Lclcalipso2=.false.
+   cfg%Lclcalipso=.false.
+   cfg%LclgrLidar532=.false.
+   cfg%Lclatlid=.false.
+   cfg%Lclhcalipso=.false.
+   cfg%Lcllcalipso=.false.
+   cfg%Lclmcalipso=.false.
+   cfg%Lcltcalipso=.false.
+   cfg%LclhgrLidar532=.false.
+   cfg%LcllgrLidar532=.false.
+   cfg%LclmgrLidar532 =.false.
+   cfg%LcltgrLidar532=.false.
+   cfg%Lclhatlid=.false.
+   cfg%Lcllatlid=.false.
+   cfg%Lclmatlid=.false.
+   cfg%Lcltatlid=.false.
+   cfg%Lcltlidarradar=.false.
+   cfg%Lcloudsat_tcc=.false.
+   cfg%Lcloudsat_tcc2=.false.
+   cfg%Lclcalipsoliq=.false.
+   cfg%Lclcalipsoice=.false.
+   cfg%Lclcalipsoun=.false.
+   cfg%Lclcalipsotmp=.false.
+   cfg%Lclcalipsotmpliq=.false.
+   cfg%Lclcalipsotmpice=.false.
+   cfg%Lclcalipsotmpun=.false.
+   cfg%Lcltcalipsoliq=.false.
+   cfg%Lcltcalipsoice=.false.
+   cfg%Lcltcalipsoun=.false.
+   cfg%Lclhcalipsoliq=.false.
+   cfg%Lclhcalipsoice=.false.
+   cfg%Lclhcalipsoun=.false.
+   cfg%Lclmcalipsoliq=.false.
+   cfg%Lclmcalipsoice=.false.
+   cfg%Lclmcalipsoun=.false.
+   cfg%Lcllcalipsoliq=.false.
+   cfg%Lcllcalipsoice=.false.
+   cfg%Lcllcalipsoun =.false.
+   cfg%Lclopaquecalipso=.false.
+   cfg%Lclthincalipso=.false.
+   cfg%Lclzopaquecalipso=.false.
+   cfg%Lclcalipsoopaque=.false.
+   cfg%Lclcalipsothin=.false.
+   cfg%Lclcalipsozopaque=.false.
+   cfg%Lclcalipsoopacity=.false.
+   cfg%Lclopaquetemp=.false.
+   cfg%Lclthintemp=.false.
+   cfg%Lclzopaquetemp=.false.
+   cfg%Lclopaquemeanz=.false.
+   cfg%Lclthinmeanz=.false.
+   cfg%Lclthinemis=.false.
+   cfg%Lclopaquemeanzse=.false.
+   cfg%Lclthinmeanzse=.false.
+   cfg%Lclzopaquecalipsose=.false.
+   cfg%LcfadDbze94=.false.
+   cfg%Ldbze94=.false.
+   cfg%Lparasolrefl=.false.
+   cfg%Ltbrttov=.false.
+   cfg%Lptradarflag0=.false.
+   cfg%Lptradarflag1=.false.
+   cfg%Lptradarflag2=.false.
+   cfg%Lptradarflag3=.false.
+   cfg%Lptradarflag4=.false.
+   cfg%Lptradarflag5=.false.
+   cfg%Lptradarflag6=.false.
+   cfg%Lptradarflag7=.false.
+   cfg%Lptradarflag8=.false.
+   cfg%Lptradarflag9=.false.
+   cfg%Lradarpia=.false.
+
+ end subroutine cosp_outputkeys_init
+
+
+ SUBROUTINE cosp_outputkeys_test(cfg)
+  implicit none
+  type(cosp_config),intent(out) :: cfg
+  character(len=32) :: out_list(107)
+  integer :: i
+
+   do i=1,107
+      cfg%out_list(i)=''
+   enddo
+
+   cfg%Lcloudsat=.false.
+   cfg%Lcalipso=.true.
+   cfg%LgrLidar532=.false.
+   cfg%Latlid=.false.
+   cfg%Lisccp=.false.
+   cfg%Lmodis=.false.
+   cfg%Lmisr=.false.
+   cfg%Lrttov=.false.
+   cfg%Lparasol=.false.
+   cfg%Lwrite_output=.false.
+!   cfg%Lfracout=.false.
+
+   cfg%Lpctisccp=.false.
+   cfg%Lclisccp=.false.
+   cfg%Lboxptopisccp=.false.
+   cfg%Lboxtauisccp=.false.
+   cfg%Ltauisccp=.false.
+   cfg%Lcltisccp=.false.
+   cfg%Lmeantbisccp=.false.
+   cfg%Lmeantbclrisccp=.false.
+   cfg%Lalbisccp=.false.
+   cfg%LclMISR=.false.
+   cfg%Lcltmodis=.false.
+   cfg%Lclwmodis=.false.
+   cfg%Lclimodis=.false.
+   cfg%Lclhmodis=.false.
+   cfg%Lclmmodis=.false.
+   cfg%Lcllmodis=.false.
+   cfg%Ltautmodis=.false.
+   cfg%Ltauwmodis=.false.
+   cfg%Ltauimodis=.false.
+   cfg%Ltautlogmodis=.false.
+   cfg%Ltauwlogmodis=.false.
+   cfg%Ltauilogmodis=.false.
+   cfg%Lreffclwmodis=.false.
+   cfg%Lreffclimodis=.false.
+   cfg%Lpctmodis=.false.
+   cfg%Llwpmodis=.false.
+   cfg%Liwpmodis=.false.
+   cfg%Lclmodis=.false.
+   cfg%Latb532=.false.
+   cfg%Latb532gr=.false.
+   cfg%Latb355=.false.
+   cfg%LlidarBetaMol532=.false.
+   cfg%LlidarBetaMol532gr=.false.
+   cfg%LlidarBetaMol355=.false.
+   cfg%LcfadLidarsr532=.false.
+   cfg%LcfadLidarsr532gr=.false.
+   cfg%LcfadLidarsr355 =.false.
+   cfg%Lclcalipso2=.false.
+   cfg%Lclcalipso=.false.
+   cfg%LclgrLidar532=.false.
+   cfg%Lclatlid=.false.
+   cfg%Lclhcalipso=.true.
+   cfg%Lcllcalipso=.true.
+   cfg%Lclmcalipso=.true.
+   cfg%Lcltcalipso=.true.
+   cfg%LclhgrLidar532=.false.
+   cfg%LcllgrLidar532=.false.
+   cfg%LclmgrLidar532 =.false.
+   cfg%LcltgrLidar532=.false.
+   cfg%Lclhatlid=.false.
+   cfg%Lcllatlid=.false.
+   cfg%Lclmatlid=.false.
+   cfg%Lcltatlid=.false.
+   cfg%Lcltlidarradar=.false.
+   cfg%Lcloudsat_tcc=.false.
+   cfg%Lcloudsat_tcc2=.false.
+   cfg%Lclcalipsoliq=.false.
+   cfg%Lclcalipsoice=.false.
+   cfg%Lclcalipsoun=.false.
+   cfg%Lclcalipsotmp=.false.
+   cfg%Lclcalipsotmpliq=.false.
+   cfg%Lclcalipsotmpice=.false.
+   cfg%Lclcalipsotmpun=.false.
+   cfg%Lcltcalipsoliq=.false.
+   cfg%Lcltcalipsoice=.false.
+   cfg%Lcltcalipsoun=.false.
+   cfg%Lclhcalipsoliq=.false.
+   cfg%Lclhcalipsoice=.false.
+   cfg%Lclhcalipsoun=.false.
+   cfg%Lclmcalipsoliq=.false.
+   cfg%Lclmcalipsoice=.false.
+   cfg%Lclmcalipsoun=.false.
+   cfg%Lcllcalipsoliq=.false.
+   cfg%Lcllcalipsoice=.false.
+   cfg%Lcllcalipsoun =.false.
+   cfg%Lclopaquecalipso=.false.
+   cfg%Lclthincalipso=.false.
+   cfg%Lclzopaquecalipso=.false.
+   cfg%Lclcalipsoopaque=.false.
+   cfg%Lclcalipsothin=.false.
+   cfg%Lclcalipsozopaque=.false.
+   cfg%Lclcalipsoopacity=.false.
+   cfg%Lclopaquetemp=.false.
+   cfg%Lclthintemp=.false.
+   cfg%Lclzopaquetemp=.false.
+   cfg%Lclopaquemeanz=.false.
+   cfg%Lclthinmeanz=.false.
+   cfg%Lclthinemis=.false.
+   cfg%Lclopaquemeanzse=.false.
+   cfg%Lclthinmeanzse=.false.
+   cfg%Lclzopaquecalipsose=.false.
+   cfg%LcfadDbze94=.false.
+   cfg%Ldbze94=.false.
+   cfg%Lparasolrefl=.false.
+   cfg%Ltbrttov=.false.
+   cfg%Lptradarflag0=.false.
+   cfg%Lptradarflag1=.false.
+   cfg%Lptradarflag2=.false.
+   cfg%Lptradarflag3=.false.
+   cfg%Lptradarflag4=.false.
+   cfg%Lptradarflag5=.false.
+   cfg%Lptradarflag6=.false.
+   cfg%Lptradarflag7=.false.
+   cfg%Lptradarflag8=.false.
+   cfg%Lptradarflag9=.false.
+   cfg%Lradarpia=.false.
+
+ end subroutine cosp_outputkeys_test
+
+
+ SUBROUTINE READ_COSP_OUTPUT_NL(itap,cosp_nl,cfg)
+
+#ifdef CPP_XIOS
+    USE xios, ONLY: xios_field_is_active
+#endif
+  implicit none
+  character(len=*),intent(in) :: cosp_nl
+  type(cosp_config),intent(inout) :: cfg
+  ! Local variables
+  integer :: i, itap
+
+!COSPv2
+  logical, save :: &
+       Lisccp      = .false. ,& ! Local on/off switch for simulators
+       Lmodis      = .false., & !
+       Lmisr       = .false., & !
+       Lcalipso    = .false., & !
+       LgrLidar532 = .false., & !
+       Latlid      = .false., & !
+       Lcloudsat   = .false., & !
+       Lrttov      = .false., & !
+       Lparasol    = .false.    !
+
+
+ logical, save :: Lcfaddbze94,Ldbze94,Latb532,LcfadLidarsr532,Lclcalipso,Lclhcalipso,    &
+             Lcllcalipso,Lclmcalipso,Lcltcalipso,LparasolRefl,Lclcalipsoliq,             &
+             Lclcalipsoice,Lclcalipsoun,Lclcalipsotmp,Lclcalipsotmpliq,Lclcalipsotmpice, &
+             Lclcalipsotmpun,Lclhcalipsoliq,Lcllcalipsoliq,Lclmcalipsoliq,Lcltcalipsoliq,& 
+             Lclhcalipsoice,Lcllcalipsoice,Lclmcalipsoice,Lcltcalipsoice,Lclhcalipsoun,  & 
+             Lcllcalipsoun,Lclmcalipsoun,Lcltcalipsoun,Lclopaquecalipso,Lclthincalipso,  & 
+             Lclzopaquecalipso,Lclcalipsoopaque,Lclcalipsothin,Lclcalipsozopaque,        & 
+             Lclcalipsoopacity,Lclopaquetemp,Lclthintemp,Lclzopaquetemp,Lclopaquemeanz,  &
+             Lclthinmeanz,Lclthinemis,Lclopaquemeanzse,Lclthinmeanzse,Lclzopaquecalipsose,&
+             LlidarBetaMol532gr,LcfadLidarsr532gr,Latb532gr,LclgrLidar532,LclhgrLidar532,&
+             LcllgrLidar532,LclmgrLidar532,LcltgrLidar532,LlidarBetaMol355,              &
+             LcfadLidarsr355,Latb355,Lclatlid,Lclhatlid,Lcllatlid,Lclmatlid,Lcltatlid,   &
+             Lalbisccp,Lboxptopisccp,Lboxtauisccp,Lpctisccp,Lclisccp,Ltauisccp,Lcltisccp,&
+             Lmeantbisccp,Lmeantbclrisccp,LclMISR,Lclcalipso2,Lcltlidarradar,            &
+             Lcloudsat_tcc, Lcloudsat_tcc2,Lfracout,   &
+             LlidarBetaMol532,Lcltmodis,Lclwmodis,Lclimodis,Lclhmodis,Lclmmodis,         &
+             Lcllmodis,Ltautmodis,Ltauwmodis,Ltauimodis,Ltautlogmodis,Ltauwlogmodis,     &
+             Ltauilogmodis,Lreffclwmodis,Lreffclimodis,Lpctmodis,Llwpmodis,Liwpmodis,    &
+             Lclmodis,Ltbrttov,Lptradarflag0,Lptradarflag1,Lptradarflag2,Lptradarflag3,  &
+             Lptradarflag4,Lptradarflag5,Lptradarflag6,Lptradarflag7,Lptradarflag8,      &
+             Lptradarflag9,Lradarpia
+
+  namelist/COSP_OUTPUT/Lcfaddbze94,Ldbze94,Latb532,LcfadLidarsr532,Lclcalipso,           &
+                       Lclhcalipso,Lcllcalipso,Lclmcalipso,Lcltcalipso,LparasolRefl,     &
+                       Lclcalipsoliq,Lclcalipsoice,Lclcalipsoun,Lclcalipsotmp,           &
+                       Lclcalipsotmpliq,Lclcalipsotmpice,Lclcalipsotmpun,Lclhcalipsoliq, &
+                       Lcllcalipsoliq,Lclmcalipsoliq,Lcltcalipsoliq,Lclhcalipsoice,      &
+                       Lcllcalipsoice,Lclmcalipsoice,Lcltcalipsoice,Lclhcalipsoun,       &
+                       Lcllcalipsoun,Lclmcalipsoun,Lcltcalipsoun,Lclopaquecalipso,       &
+                       Lclthincalipso,Lclzopaquecalipso,Lclcalipsoopaque,Lclcalipsothin, &
+                       Lclcalipsozopaque,Lclcalipsoopacity,Lclopaquetemp,Lclthintemp,    &
+                       Lclzopaquetemp,Lclopaquemeanz,Lclthinmeanz,Lclthinemis,           &
+                       Lclopaquemeanzse,Lclthinmeanzse,Lclzopaquecalipsose,              &
+                       LlidarBetaMol532gr,LcfadLidarsr532gr,Latb532gr,LclgrLidar532,     &
+                       LclhgrLidar532,LcllgrLidar532,LclmgrLidar532,LcltgrLidar532,      &
+                       LlidarBetaMol355,LcfadLidarsr355,Latb355,Lclatlid,                &
+                       Lclhatlid,Lcllatlid,Lclmatlid,Lcltatlid,Lalbisccp,Lboxptopisccp,  &
+                       Lboxtauisccp,Lpctisccp,Lclisccp,Ltauisccp,Lcltisccp,Lmeantbisccp, &
+                       Lmeantbclrisccp,LclMISR,Lclcalipso2,Lcltlidarradar,               &
+                       Lcloudsat_tcc, Lcloudsat_tcc2, Lfracout,                          &
+                       LlidarBetaMol532,Lcltmodis,Lclwmodis,Lclimodis,Lclhmodis,         &
+                       Lclmmodis,Lcllmodis,Ltautmodis,Ltauwmodis,Ltauimodis,             &
+                       Ltautlogmodis,Ltauwlogmodis,Ltauilogmodis,Lreffclwmodis,          &
+                       Lreffclimodis,Lpctmodis,Llwpmodis,Liwpmodis,Lclmodis,Ltbrttov,    &
+                       Lptradarflag0,Lptradarflag1,Lptradarflag2,Lptradarflag3,          &
+                       Lptradarflag4,Lptradarflag5,Lptradarflag6,Lptradarflag7,          &
+                       Lptradarflag8,Lptradarflag9,Lradarpia
+
+  do i=1,107
+    cfg%out_list(i)=''
+  enddo
+  
+! Lecture du fichier namelist
+  IF (is_master) THEN
+    open(10,file=cosp_nl,status='old')
+    read(10,nml=cosp_output)
+    close(10)
+  ENDIF
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! Which simulators need to be run? Look at which outputs are requested.
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  if (Lpctisccp .or. Lclisccp .or. Lboxptopisccp .or.  Lboxtauisccp .or. Ltauisccp .or. &
+       Lcltisccp .or. Lmeantbisccp .or. Lmeantbclrisccp .or. Lalbisccp) Lisccp = .true.
+  if (LclMISR) Lmisr = .true.
+  if (Lcltmodis .or. Lclwmodis .or. Lclimodis .or. Lclhmodis .or. Lclmmodis .or.         &
+       Lcllmodis .or. Ltautmodis .or. Ltauwmodis .or. Ltauimodis .or. Ltautlogmodis .or. &
+       Ltauwlogmodis .or. Ltauilogmodis .or. Lreffclwmodis .or. Lreffclimodis .or.       &
+       Lpctmodis .or. Llwpmodis .or. Liwpmodis .or. Lclmodis) Lmodis = .true.
+  if (Lclcalipso2 .or. Lclcalipso .or.  Lclhcalipso .or. Lcllcalipso .or. Lclmcalipso    &
+       .or. Lcltcalipso .or. Lcltlidarradar .or. Lclcalipsoliq .or. Lclcalipsoice .or.   &
+       Lclcalipsoun .or. Lclcalipsotmp .or. Lclcalipsotmpliq .or. Lclcalipsotmpice .or.  &
+       Lclcalipsotmpun .or. Lcltcalipsoliq .or. Lcltcalipsoice .or. Lcltcalipsoun .or.   &
+       Lclhcalipsoliq .or. Lclhcalipsoice .or. Lclhcalipsoun .or. Lclmcalipsoliq .or.    &
+       Lclmcalipsoice .or. Lclmcalipsoun .or. Lcllcalipsoliq .or. Lcllcalipsoice .or.    &
+       Lcllcalipsoun .or. LlidarBetaMol532 .or. LcfadLidarsr532 .or. Lcltlidarradar .or. &
+       Lcltlidarradar .or. Lclopaquecalipso .or. Lclthincalipso .or. Lclzopaquecalipso   &
+       .or. Lclcalipsoopaque .or. Lclcalipsothin .or. Lclcalipsozopaque .or.             &
+       Lclcalipsoopacity .or. Lclopaquetemp .or. Lclthintemp .or. Lclzopaquetemp .or.    &
+       Lclopaquemeanz .or. Lclthinmeanz .or. Lclthinemis .or. Lclopaquemeanzse .or.      & 
+       Lclthinmeanzse .or. Lclzopaquecalipsose) Lcalipso = .true. 
+
+  if (LlidarBetaMol532gr .or. LcfadLidarsr532gr .or. Latb532gr .or. LclgrLidar532 .or.  & 
+       LclhgrLidar532 .or. LcllgrLidar532 .or. LclmgrLidar532 .or. LcltgrLidar532)   & 
+       LgrLidar532 = .true.
+
+  if (LlidarBetaMol355 .or. LcfadLidarsr355 .or. Latb355 .or. Lclatlid .or.              & 
+       Lclhatlid .or. Lcllatlid .or. Lclmatlid .or. Lcltatlid)                           & 
+       Latlid = .true. 
+
+  if (LcfadDbze94 .or. Ldbze94 .or. Lcltlidarradar .or. Lptradarflag0 .or. Lptradarflag1 &
+       .or. Lptradarflag2 .or. Lptradarflag3 .or. Lptradarflag4 .or. Lptradarflag5 .or.  &
+       Lptradarflag6 .or. Lptradarflag7 .or. Lptradarflag8 .or. Lptradarflag9 .or.       &
+       Lradarpia) Lcloudsat = .true.
+  if (Lparasolrefl) Lparasol = .true.
+  if (Ltbrttov) Lrttov = .true.
+
+  CALL bcast(Lcloudsat)
+  CALL bcast(Lcalipso)
+  CALL bcast(LgrLidar532)
+  CALL bcast(Latlid)
+  CALL bcast(Lparasol)
+  CALL bcast(Lisccp)
+  CALL bcast(Lmodis)
+  CALL bcast(Lmisr)
+  CALL bcast(Lrttov)
+
+  CALL bcast(Lcfaddbze94)
+  CALL bcast(Ldbze94)
+  CALL bcast(Latb532)
+  CALL bcast(LcfadLidarsr532)
+  CALL bcast(Lclcalipso)
+  CALL bcast(Lclhcalipso)
+  CALL bcast(Lcllcalipso)
+  CALL bcast(Lclmcalipso)
+  CALL bcast(Lcltcalipso)
+  CALL bcast(LparasolRefl)
+  CALL bcast(Lclcalipsoliq)
+  CALL bcast(Lclcalipsoice)
+  CALL bcast(Lclcalipsoun)
+  CALL bcast(Lclcalipsotmp)
+  CALL bcast(Lclcalipsotmpliq)
+  CALL bcast(Lclcalipsotmpice)
+  CALL bcast(Lclcalipsotmpun)
+  CALL bcast(Lclhcalipsoliq)
+  CALL bcast(Lcllcalipsoliq)
+  CALL bcast(Lclmcalipsoliq)
+  CALL bcast(Lcltcalipsoliq)
+  CALL bcast(Lclhcalipsoice)
+  CALL bcast(Lcllcalipsoice)
+  CALL bcast(Lclmcalipsoice)
+  CALL bcast(Lcltcalipsoice)
+  CALL bcast(Lclhcalipsoun)
+  CALL bcast(Lcllcalipsoun)
+  CALL bcast(Lclmcalipsoun)
+  CALL bcast(Lcltcalipsoun)
+  CALL bcast(Lclopaquecalipso)
+  CALL bcast(Lclthincalipso)
+  CALL bcast(Lclzopaquecalipso)
+  CALL bcast(Lclcalipsoopaque)
+  CALL bcast(Lclcalipsothin)
+  CALL bcast(Lclcalipsozopaque)
+  CALL bcast(Lclcalipsoopacity)
+  CALL bcast(Lclopaquetemp)
+  CALL bcast(Lclthintemp)
+  CALL bcast(Lclzopaquetemp)
+  CALL bcast(Lclopaquemeanz)
+  CALL bcast(Lclthinmeanz)
+  CALL bcast(Lclthinemis)
+  CALL bcast(Lclopaquemeanzse)
+  CALL bcast(Lclthinmeanzse)
+  CALL bcast(Lclzopaquecalipsose)
+  CALL bcast(LlidarBetaMol532gr)
+  CALL bcast(LcfadLidarsr532gr)
+  CALL bcast(Latb532gr)
+  CALL bcast(LclgrLidar532)
+  CALL bcast(LclhgrLidar532)
+  CALL bcast(LcllgrLidar532)
+  CALL bcast(LclmgrLidar532)
+  CALL bcast(LcltgrLidar532)
+  CALL bcast(LlidarBetaMol355)
+  CALL bcast(LcfadLidarsr355)
+  CALL bcast(Latb355)
+  CALL bcast(Lclatlid)
+  CALL bcast(Lclhatlid)
+  CALL bcast(Lcllatlid)
+  CALL bcast(Lclmatlid)
+  CALL bcast(Lcltatlid)
+  CALL bcast(Lalbisccp)
+  CALL bcast(Lboxptopisccp)
+  CALL bcast(Lboxtauisccp)
+  CALL bcast(Lpctisccp)
+  CALL bcast(Lclisccp)
+  CALL bcast(Ltauisccp)
+  CALL bcast(Lcltisccp)
+  CALL bcast(Lmeantbisccp)
+  CALL bcast(Lmeantbclrisccp)
+  CALL bcast(LclMISR)
+  CALL bcast(Lclcalipso2)
+  CALL bcast(Lcltlidarradar)
+  CALL bcast(Lcloudsat_tcc)
+  CALL bcast(Lcloudsat_tcc2)
+  CALL bcast(Lfracout)
+  CALL bcast(LlidarBetaMol532)
+  CALL bcast(Lcltmodis)
+  CALL bcast(Lclwmodis)
+  CALL bcast(Lclimodis)
+  CALL bcast(Lclhmodis)
+  CALL bcast(Lclmmodis)
+  CALL bcast(Lcllmodis)
+  CALL bcast(Ltautmodis)
+  CALL bcast(Ltauwmodis)
+  CALL bcast(Ltauimodis)
+  CALL bcast(Ltautlogmodis)
+  CALL bcast(Ltauwlogmodis)
+  CALL bcast(Ltauilogmodis)
+  CALL bcast(Lreffclwmodis)
+  CALL bcast(Lreffclimodis)
+  CALL bcast(Lpctmodis)
+  CALL bcast(Llwpmodis)
+  CALL bcast(Liwpmodis)
+  CALL bcast(Lclmodis)
+  CALL bcast(Ltbrttov)
+  CALL bcast(Lptradarflag0)
+  CALL bcast(Lptradarflag1)
+  CALL bcast(Lptradarflag2)
+  CALL bcast(Lptradarflag3)
+  CALL bcast(Lptradarflag4)
+  CALL bcast(Lptradarflag5)
+  CALL bcast(Lptradarflag6)
+  CALL bcast(Lptradarflag7)
+  CALL bcast(Lptradarflag8)
+  CALL bcast(Lptradarflag9)
+  CALL bcast(Lradarpia)
+
+!$OMP BARRIER
+
+  ! Copy instrument flags to cfg structure
+  cfg%Lcloudsat = Lcloudsat
+  cfg%Lcalipso = Lcalipso
+  cfg%LgrLidar532 = LgrLidar532
+  cfg%Latlid = Latlid
+  cfg%Lisccp = Lisccp
+  cfg%Lmodis = Lmodis
+  cfg%Lmisr = Lmisr
+  cfg%Lrttov = Lrttov
+  cfg%Lparasol = Lparasol
+
+    print*,' cfg%Lcloudsat = ',cfg%Lcloudsat
+
+  ! Flag to control output to file
+  cfg%Lwrite_output = .false.
+  if (cfg%Lcloudsat .or. cfg%Lcalipso .or. cfg%LgrLidar532 .or. cfg%Latlid .or. cfg%Lisccp .or. cfg%Lmodis .or. cfg%Lmisr .or. cfg%Lrttov .or. cfg%Lparasol .or. Lfracout) then
+    cfg%Lwrite_output = .true.
+  endif
+
+  ! Output diagnostics
+  i = 1
+
+  if (Lcfaddbze94)        cfg%out_list(i) = 'cfaddbze94'
+  i = i+1
+  if (Ldbze94)        cfg%out_list(i) = 'dbze94'
+  i = i+1
+  if (Latb532)        cfg%out_list(i) = 'atb532'
+  i = i+1
+  if (LcfadLidarsr532)        cfg%out_list(i) = 'cfadLidarsr532'
+  i = i+1
+  if (Lclcalipso)        cfg%out_list(i) = 'clcalipso'
+  i = i+1
+  if (Lclhcalipso)        cfg%out_list(i) = 'clhcalipso'
+  i = i+1
+  if (Lcllcalipso)        cfg%out_list(i) = 'cllcalipso'
+  i = i+1
+  if (Lclmcalipso)        cfg%out_list(i) = 'clmcalipso'
+  i = i+1
+  if (Lcltcalipso)        cfg%out_list(i) = 'cltcalipso'
+  i = i+1
+  if (LparasolRefl)        cfg%out_list(i) = 'parasolRefl'
+  i = i+1
+  if (Lclcalipsoliq)        cfg%out_list(i) = 'clcalipsoliq'
+  i = i+1
+  if (Lclcalipsoice)        cfg%out_list(i) = 'clcalipsoice'
+  i = i+1
+  if (Lclcalipsoun)        cfg%out_list(i) = 'clcalipsoun'
+  i = i+1
+  if (Lclcalipsotmp)        cfg%out_list(i) = 'clcalipsotmp'
+  i = i+1
+  if (Lclcalipsotmpliq)        cfg%out_list(i) = 'clcalipsotmpliq'
+  i = i+1
+  if (Lclcalipsotmpice)        cfg%out_list(i) = 'clcalipsotmpice'
+  i = i+1
+  if (Lclcalipsotmpun)        cfg%out_list(i) = 'clcalipsotmpun'
+  i = i+1
+  if (Lclhcalipsoliq)        cfg%out_list(i) = 'clhcalipsoliq'
+  i = i+1
+  if (Lcllcalipsoliq)        cfg%out_list(i) = 'cllcalipsoliq'
+  i = i+1
+  if (Lclmcalipsoliq)        cfg%out_list(i) = 'clmcalipsoliq'
+  i = i+1
+  if (Lcltcalipsoliq)        cfg%out_list(i) = 'cltcalipsoliq'
+  i = i+1
+  if (Lclhcalipsoice)        cfg%out_list(i) = 'clhcalipsoice'
+  i = i+1
+  if (Lcllcalipsoice)        cfg%out_list(i) = 'cllcalipsoice'
+  i = i+1
+  if (Lclmcalipsoice)        cfg%out_list(i) = 'clmcalipsoice'
+  i = i+1
+  if (Lcltcalipsoice)        cfg%out_list(i) = 'cltcalipsoice'
+  i = i+1
+  if (Lclhcalipsoun)        cfg%out_list(i) = 'clhcalipsoun'
+  i = i+1
+  if (Lcllcalipsoun)        cfg%out_list(i) = 'cllcalipsoun'
+  i = i+1
+  if (Lclmcalipsoun)        cfg%out_list(i) = 'clmcalipsoun'
+  i = i+1
+  if (Lcltcalipsoun)        cfg%out_list(i) = 'cltcalipsoun'
+  i = i+1
+  if (Lclopaquecalipso)        cfg%out_list(i) = 'clopaquecalipso'
+  i = i+1
+  if (Lclthincalipso)        cfg%out_list(i) = 'clthincalipso'
+  i = i+1
+  if (Lclzopaquecalipso)        cfg%out_list(i) = 'clzopaquecalipso'
+  i = i+1
+  if (Lclcalipsoopaque)        cfg%out_list(i) = 'clcalipsoopaque'
+  i = i+1
+  if (Lclcalipsothin)        cfg%out_list(i) = 'clcalipsothin'
+  i = i+1
+  if (Lclcalipsozopaque)        cfg%out_list(i) = 'clcalipsozopaque'
+  i = i+1
+  if (Lclcalipsoopacity)        cfg%out_list(i) = 'clcalipsoopacity'
+  i = i+1
+  if (Lclopaquetemp)        cfg%out_list(i) = 'clopaquetemp'
+  i = i+1
+  if (Lclthintemp)        cfg%out_list(i) = 'clthintemp'
+  i = i+1
+  if (Lclzopaquetemp)        cfg%out_list(i) = 'clzopaquetemp'
+  i = i+1
+  if (Lclopaquemeanz)        cfg%out_list(i) = 'clopaquemeanz'
+  i = i+1
+  if (Lclthinmeanz)        cfg%out_list(i) = 'clthinmeanz'
+  i = i+1
+  if (Lclthinemis)        cfg%out_list(i) = 'clthinemis'
+  i = i+1
+  if (Lclopaquemeanzse)        cfg%out_list(i) = 'clopaquemeanzse'
+  i = i+1
+  if (Lclthinmeanzse)        cfg%out_list(i) = 'clthinmeanzse'
+  i = i+1
+  if (Lclzopaquecalipsose)        cfg%out_list(i) = 'clzopaquecalipsose'
+  i = i+1
+  if (LlidarBetaMol532gr)        cfg%out_list(i) = 'lidarBetaMol532gr'
+  i = i+1
+  if (LcfadLidarsr532gr)        cfg%out_list(i) = 'cfadLidarsr532gr'
+  i = i+1
+  if (Latb532gr)        cfg%out_list(i) = 'atb532gr'
+  i = i+1
+  if (LclgrLidar532)        cfg%out_list(i) = 'clgrLidar532'
+  i = i+1
+  if (LclhgrLidar532)        cfg%out_list(i) = 'clhgrLidar532'
+  i = i+1
+  if (LcllgrLidar532)        cfg%out_list(i) = 'cllgrLidar532'
+  i = i+1
+  if (LclmgrLidar532)        cfg%out_list(i) = 'clmgrLidar532'
+  i = i+1
+  if (LcltgrLidar532)        cfg%out_list(i) = 'cltgrLidar532'
+  i = i+1
+  if (LlidarBetaMol355)        cfg%out_list(i) = 'lidarBetaMol355'
+  i = i+1
+  if (LcfadLidarsr355)        cfg%out_list(i) = 'cfadLidarsr355'
+  i = i+1
+  if (Latb355)        cfg%out_list(i) = 'atb355'
+  i = i+1
+  if (Lclatlid)        cfg%out_list(i) = 'clatlid'
+  i = i+1
+  if (Lclhatlid)        cfg%out_list(i) = 'clhatlid'
+  i = i+1
+  if (Lcllatlid)        cfg%out_list(i) = 'cllatlid'
+  i = i+1
+  if (Lclmatlid)        cfg%out_list(i) = 'clmatlid'
+  i = i+1
+  if (Lcltatlid)        cfg%out_list(i) = 'cltatlid'
+  i = i+1
+  if (Lalbisccp)        cfg%out_list(i) = 'albisccp'
+  i = i+1
+  if (Lboxptopisccp)        cfg%out_list(i) = 'boxptopisccp'
+  i = i+1
+  if (Lboxtauisccp)        cfg%out_list(i) = 'boxtauisccp'
+  i = i+1
+  if (Lpctisccp)        cfg%out_list(i) = 'pctisccp'
+  i = i+1
+  if (Lclisccp)        cfg%out_list(i) = 'clisccp'
+  i = i+1
+  if (Ltauisccp)        cfg%out_list(i) = 'tauisccp'
+  i = i+1
+  if (Lcltisccp)        cfg%out_list(i) = 'cltisccp'
+  i = i+1
+  if (Lmeantbisccp)        cfg%out_list(i) = 'meantbisccp'
+  i = i+1
+  if (Lmeantbclrisccp)        cfg%out_list(i) = 'meantbclrisccp'
+  i = i+1
+  if (LclMISR)        cfg%out_list(i) = 'clMISR'
+  i = i+1
+  if (Lclcalipso2)        cfg%out_list(i) = 'clcalipso2'
+  i = i+1
+  if (Lcltlidarradar)        cfg%out_list(i) = 'cltlidarradar'
+  i = i+1
+  if (Lcloudsat_tcc)        cfg%out_list(i) = 'cloudsat_tcc'
+  i = i+1
+  if (Lcloudsat_tcc2)        cfg%out_list(i) = 'cloudsat_tcc2'
+  i = i+1
+  if (Lfracout)        cfg%out_list(i) = 'fracout'
+  i = i+1
+  if (LlidarBetaMol532)        cfg%out_list(i) = 'lidarBetaMol532'
+  i = i+1
+  if (Lcltmodis)        cfg%out_list(i) = 'cltmodis'
+  i = i+1
+  if (Lclwmodis)        cfg%out_list(i) = 'clwmodis'
+  i = i+1
+  if (Lclimodis)        cfg%out_list(i) = 'climodis'
+  i = i+1
+  if (Lclhmodis)        cfg%out_list(i) = 'clhmodis'
+  i = i+1
+  if (Lclmmodis)        cfg%out_list(i) = 'clmmodis'
+  i = i+1
+  if (Lcllmodis)        cfg%out_list(i) = 'cllmodis'
+  i = i+1
+  if (Ltautmodis)        cfg%out_list(i) = 'tautmodis'
+  i = i+1
+  if (Ltauwmodis)        cfg%out_list(i) = 'tauwmodis'
+  i = i+1
+  if (Ltauimodis)        cfg%out_list(i) = 'tauimodis'
+  i = i+1
+  if (Ltautlogmodis)        cfg%out_list(i) = 'tautlogmodis'
+  i = i+1
+  if (Ltauwlogmodis)        cfg%out_list(i) = 'tauwlogmodis'
+  i = i+1
+  if (Ltauilogmodis)        cfg%out_list(i) = 'tauilogmodis'
+  i = i+1
+  if (Lreffclwmodis)        cfg%out_list(i) = 'reffclwmodis'
+  i = i+1
+  if (Lreffclimodis)        cfg%out_list(i) = 'reffclimodis'
+  i = i+1
+  if (Lpctmodis)        cfg%out_list(i) = 'pctmodis'
+  i = i+1
+  if (Llwpmodis)        cfg%out_list(i) = 'lwpmodis'
+  i = i+1
+  if (Liwpmodis)        cfg%out_list(i) = 'iwpmodis'
+  i = i+1
+  if (Lclmodis)        cfg%out_list(i) = 'clmodis'
+  i = i+1
+  if (Ltbrttov)        cfg%out_list(i) = 'tbrttov'
+  i = i+1
+  if (Lptradarflag0)        cfg%out_list(i) = 'ptradarflag0'
+  i = i+1
+  if (Lptradarflag1)        cfg%out_list(i) = 'ptradarflag1'
+  i = i+1
+  if (Lptradarflag2)        cfg%out_list(i) = 'ptradarflag2'
+  i = i+1
+  if (Lptradarflag3)        cfg%out_list(i) = 'ptradarflag3'
+  i = i+1
+  if (Lptradarflag4)        cfg%out_list(i) = 'ptradarflag4'
+  i = i+1
+  if (Lptradarflag5)        cfg%out_list(i) = 'ptradarflag5'
+  i = i+1
+  if (Lptradarflag6)        cfg%out_list(i) = 'ptradarflag6'
+  i = i+1
+  if (Lptradarflag7)        cfg%out_list(i) = 'ptradarflag7'
+  i = i+1
+  if (Lptradarflag8)        cfg%out_list(i) = 'ptradarflag8'
+  i = i+1
+  if (Lptradarflag9)        cfg%out_list(i) = 'ptradarflag9'
+  i = i+1
+  if (Lradarpia)        cfg%out_list(i) = 'radarpia'
+!  i = i+1 !si on laisse, 108 au lieu de 107
+
+  if (i.gt.107) then
+     print *, 'COSP_IO: wrong number of output diagnostics'
+     print *, i,107
+     stop
+  endif
+
+
+  ! Copy diagnostic flags to cfg structure
+
+   cfg%Lpctisccp = Lpctisccp
+   cfg%Lclisccp = Lclisccp
+   cfg%Lboxptopisccp = Lboxptopisccp
+   cfg%Lboxtauisccp = Lboxtauisccp
+   cfg%Ltauisccp = Ltauisccp
+   cfg%Lcltisccp = Lcltisccp
+   cfg%Lmeantbisccp = Lmeantbisccp
+   cfg%Lmeantbclrisccp = Lmeantbclrisccp
+   cfg%Lalbisccp = Lalbisccp
+   cfg%LclMISR = LclMISR
+   cfg%Lcltmodis = Lcltmodis
+   cfg%Lclwmodis = Lclwmodis
+   cfg%Lclimodis = Lclimodis
+   cfg%Lclhmodis = Lclhmodis
+   cfg%Lclmmodis = Lclmmodis
+   cfg%Lcllmodis = Lcllmodis
+   cfg%Ltautmodis = Ltautmodis
+   cfg%Ltauwmodis = Ltauwmodis
+   cfg%Ltauimodis = Ltauimodis
+   cfg%Ltautlogmodis = Ltautlogmodis
+   cfg%Ltauwlogmodis = Ltauwlogmodis
+   cfg%Ltauilogmodis = Ltauilogmodis
+   cfg%Lreffclwmodis = Lreffclwmodis
+   cfg%Lreffclimodis = Lreffclimodis
+   cfg%Lpctmodis = Lpctmodis
+   cfg%Llwpmodis = Llwpmodis
+   cfg%Liwpmodis = Liwpmodis
+   cfg%Lclmodis = Lclmodis
+   cfg%Latb532 = Latb532
+   cfg%Latb532gr = Latb532gr
+   cfg%Latb355 = Latb355
+   cfg%LlidarBetaMol532 = LlidarBetaMol532
+   cfg%LlidarBetaMol532gr = LlidarBetaMol532gr
+   cfg%LlidarBetaMol355 = LlidarBetaMol355
+   cfg%LcfadLidarsr532 = LcfadLidarsr532
+   cfg%LcfadLidarsr532gr = LcfadLidarsr532gr
+   cfg%LcfadLidarsr355 = LcfadLidarsr355
+   cfg%Lclcalipso2 = Lclcalipso2
+   cfg%Lclcalipso = Lclcalipso
+   cfg%LclgrLidar532 = LclgrLidar532
+   cfg%Lclatlid = Lclatlid
+   cfg%Lclhcalipso = Lclhcalipso
+   cfg%Lcllcalipso = Lcllcalipso
+   cfg%Lclmcalipso = Lclmcalipso
+   cfg%Lcltcalipso = Lcltcalipso
+   cfg%LclhgrLidar532 = LclhgrLidar532
+   cfg%LcllgrLidar532 = LcllgrLidar532
+   cfg%LclmgrLidar532 = LclmgrLidar532
+   cfg%LcltgrLidar532 = LcltgrLidar532
+   cfg%Lclhatlid = Lclhatlid
+   cfg%Lcllatlid = Lcllatlid
+   cfg%Lclmatlid = Lclmatlid
+   cfg%Lcltatlid = Lcltatlid
+   cfg%Lcltlidarradar = Lcltlidarradar
+   cfg%Lcloudsat_tcc = Lcloudsat_tcc
+   cfg%Lcloudsat_tcc2 = Lcloudsat_tcc2
+   cfg%Lclcalipsoliq = Lclcalipsoliq
+   cfg%Lclcalipsoice = Lclcalipsoice
+   cfg%Lclcalipsoun = Lclcalipsoun
+   cfg%Lclcalipsotmp = Lclcalipsotmp
+   cfg%Lclcalipsotmpliq = Lclcalipsotmpliq
+   cfg%Lclcalipsotmpice = Lclcalipsotmpice
+   cfg%Lclcalipsotmpun = Lclcalipsotmpun
+   cfg%Lcltcalipsoliq = Lcltcalipsoliq
+   cfg%Lcltcalipsoice = Lcltcalipsoice
+   cfg%Lcltcalipsoun = Lcltcalipsoun
+   cfg%Lclhcalipsoliq = Lclhcalipsoliq
+   cfg%Lclhcalipsoice = Lclhcalipsoice
+   cfg%Lclhcalipsoun = Lclhcalipsoun
+   cfg%Lclmcalipsoliq = Lclmcalipsoliq
+   cfg%Lclmcalipsoice = Lclmcalipsoice
+   cfg%Lclmcalipsoun = Lclmcalipsoun
+   cfg%Lcllcalipsoliq = Lcllcalipsoliq
+   cfg%Lcllcalipsoice = Lcllcalipsoice
+   cfg%Lcllcalipsoun = Lcllcalipsoun
+   cfg%Lclopaquecalipso = Lclopaquecalipso
+   cfg%Lclthincalipso = Lclthincalipso
+   cfg%Lclzopaquecalipso = Lclzopaquecalipso
+   cfg%Lclcalipsoopaque = Lclcalipsoopaque
+   cfg%Lclcalipsothin = Lclcalipsothin
+   cfg%Lclcalipsozopaque = Lclcalipsozopaque
+   cfg%Lclcalipsoopacity = Lclcalipsoopacity
+   cfg%Lclopaquetemp = Lclopaquetemp
+   cfg%Lclthintemp = Lclthintemp
+   cfg%Lclzopaquetemp = Lclzopaquetemp
+   cfg%Lclopaquemeanz = Lclopaquemeanz
+   cfg%Lclthinmeanz = Lclthinmeanz
+   cfg%Lclthinemis = Lclthinemis
+   cfg%Lclopaquemeanzse = Lclopaquemeanzse
+   cfg%Lclthinmeanzse = Lclthinmeanzse
+   cfg%Lclzopaquecalipsose = Lclzopaquecalipsose
+   cfg%LcfadDbze94 = LcfadDbze94
+   cfg%Ldbze94 = Ldbze94
+   cfg%Lparasolrefl = Lparasolrefl
+   cfg%Ltbrttov = Ltbrttov
+   cfg%Lptradarflag0 = Lptradarflag0
+   cfg%Lptradarflag1 = Lptradarflag1
+   cfg%Lptradarflag2 = Lptradarflag2
+   cfg%Lptradarflag3 = Lptradarflag3
+   cfg%Lptradarflag4 = Lptradarflag4
+   cfg%Lptradarflag5 = Lptradarflag5
+   cfg%Lptradarflag6 = Lptradarflag6
+   cfg%Lptradarflag7 = Lptradarflag7
+   cfg%Lptradarflag8 = Lptradarflag8
+   cfg%Lptradarflag9 = Lptradarflag9
+   cfg%Lradarpia = Lradarpia
+   cfg%Lfracout = Lfracout
+  
+ END SUBROUTINE READ_COSP_OUTPUT_NL
+
+
+ SUBROUTINE read_xiosfieldactive(cfg)
+
+#ifdef CPP_XIOS
+    USE xios, ONLY: xios_field_is_active
+#endif
+  implicit none
+  type(cosp_config),intent(inout) :: cfg
+  integer :: i
+
+#ifdef CPP_XIOS
+
+!COSPv2 local variables
+  logical :: &
+       Lisccp      = .false., & ! Local on/off switch for simulators
+       Lmodis      = .false., & !
+       Lmisr       = .false., & !
+       Lcalipso    = .false., & !
+       LgrLidar532 = .false., & !
+       Latlid      = .false., & !
+       Lcloudsat   = .false., & !
+       Lrttov      = .false., & !
+       Lparasol    = .false., & !
+       Lwrite_output=.false.    ! ecrire un fichier de sortie COSP ! RG voir si on garde
+
+  logical :: Lcfaddbze94,Ldbze94,Latb532,LcfadLidarsr532,Lclcalipso,Lclhcalipso,         &
+             Lcllcalipso,Lclmcalipso,Lcltcalipso,LparasolRefl,Lclcalipsoliq,             &
+             Lclcalipsoice,Lclcalipsoun,Lclcalipsotmp,Lclcalipsotmpliq,Lclcalipsotmpice, &
+             Lclcalipsotmpun,Lclhcalipsoliq,Lcllcalipsoliq,Lclmcalipsoliq,Lcltcalipsoliq,& 
+             Lclhcalipsoice,Lcllcalipsoice,Lclmcalipsoice,Lcltcalipsoice,Lclhcalipsoun,  & 
+             Lcllcalipsoun,Lclmcalipsoun,Lcltcalipsoun,Lclopaquecalipso,Lclthincalipso,  & 
+             Lclzopaquecalipso,Lclcalipsoopaque,Lclcalipsothin,Lclcalipsozopaque,        & 
+             Lclcalipsoopacity,Lclopaquetemp,Lclthintemp,Lclzopaquetemp,Lclopaquemeanz,  &
+             Lclthinmeanz,Lclthinemis,Lclopaquemeanzse,Lclthinmeanzse,Lclzopaquecalipsose,&
+             LlidarBetaMol532gr,LcfadLidarsr532gr,Latb532gr,LclgrLidar532,LclhgrLidar532,&
+             LcllgrLidar532,LclmgrLidar532,LcltgrLidar532,LlidarBetaMol355,              &
+             LcfadLidarsr355,Latb355,Lclatlid,Lclhatlid,Lcllatlid,Lclmatlid,Lcltatlid,   &
+             Lalbisccp,Lboxptopisccp,Lboxtauisccp,Lpctisccp,Lclisccp,Ltauisccp,Lcltisccp,&
+             Lmeantbisccp,Lmeantbclrisccp,LclMISR,Lclcalipso2,Lcltlidarradar,            &
+             Lcloudsat_tcc, Lcloudsat_tcc2,Lfracout,   &
+             LlidarBetaMol532,Lcltmodis,Lclwmodis,Lclimodis,Lclhmodis,Lclmmodis,         &
+             Lcllmodis,Ltautmodis,Ltauwmodis,Ltauimodis,Ltautlogmodis,Ltauwlogmodis,     &
+             Ltauilogmodis,Lreffclwmodis,Lreffclimodis,Lpctmodis,Llwpmodis,Liwpmodis,    &
+             Lclmodis,Ltbrttov,Lptradarflag0,Lptradarflag1,Lptradarflag2,Lptradarflag3,  &
+             Lptradarflag4,Lptradarflag5,Lptradarflag6,Lptradarflag7,Lptradarflag8,      &
+             Lptradarflag9,Lradarpia
+
+        
+  character(len=32) :: out_list(107)
+
+  do i=1,107
+    cfg%out_list(i)=''
+  enddo
+
+! diagnostics
+   Lpctisccp=.false.
+   Lclisccp=.false.
+   Lboxptopisccp=.false.
+   Lboxtauisccp=.false.
+   Ltauisccp=.false.
+   Lcltisccp=.false.
+   Lmeantbisccp=.false.
+   Lmeantbclrisccp=.false.
+   Lalbisccp=.false.
+   LclMISR=.false.
+   Lcltmodis=.false.
+   Lclwmodis=.false.
+   Lclimodis=.false.
+   Lclhmodis=.false.
+   Lclmmodis=.false.
+   Lcllmodis=.false.
+   Ltautmodis=.false.
+   Ltauwmodis=.false.
+   Ltauimodis=.false.
+   Ltautlogmodis=.false.
+   Ltauwlogmodis=.false.
+   Ltauilogmodis=.false.
+   Lreffclwmodis=.false.
+   Lreffclimodis=.false.
+   Lpctmodis=.false.
+   Llwpmodis=.false.
+   Liwpmodis=.false.
+   Lclmodis=.false.
+   Latb532=.false.
+   Latb532gr=.false.
+   Latb355=.false.
+   LlidarBetaMol532=.false.
+   LlidarBetaMol532gr=.false.
+   LlidarBetaMol355=.false.
+   LcfadLidarsr532=.false.
+   LcfadLidarsr532gr=.false.
+   LcfadLidarsr355 =.false.
+   Lclcalipso2=.false.
+   Lclcalipso=.false.
+   LclgrLidar532=.false.
+   Lclatlid=.false.
+   Lclhcalipso=.false.
+   Lcllcalipso=.false.
+   Lclmcalipso=.false.
+   Lcltcalipso=.false.
+   LclhgrLidar532=.false.
+   LcllgrLidar532=.false.
+   LclmgrLidar532 =.false.
+   LcltgrLidar532=.false.
+   Lclhatlid=.false.
+   Lcllatlid=.false.
+   Lclmatlid=.false.
+   Lcltatlid=.false.
+   Lcltlidarradar=.false.
+   Lcloudsat_tcc=.false.
+   Lcloudsat_tcc2=.false.
+   Lclcalipsoliq=.false.
+   Lclcalipsoice=.false.
+   Lclcalipsoun=.false.
+   Lclcalipsotmp=.false.
+   Lclcalipsotmpliq=.false.
+   Lclcalipsotmpice=.false.
+   Lclcalipsotmpun=.false.
+   Lcltcalipsoliq=.false.
+   Lcltcalipsoice=.false.
+   Lcltcalipsoun=.false.
+   Lclhcalipsoliq=.false.
+   Lclhcalipsoice=.false.
+   Lclhcalipsoun=.false.
+   Lclmcalipsoliq=.false.
+   Lclmcalipsoice=.false.
+   Lclmcalipsoun=.false.
+   Lcllcalipsoliq=.false.
+   Lcllcalipsoice=.false.
+   Lcllcalipsoun =.false.
+   Lclopaquecalipso=.false.
+   Lclthincalipso=.false.
+   Lclzopaquecalipso=.false.
+   Lclcalipsoopaque=.false.
+   Lclcalipsothin=.false.
+   Lclcalipsozopaque=.false.
+   Lclcalipsoopacity=.false.
+   Lclopaquetemp=.false.
+   Lclthintemp=.false.
+   Lclzopaquetemp=.false.
+   Lclopaquemeanz=.false.
+   Lclthinmeanz=.false.
+   Lclthinemis=.false.
+   Lclopaquemeanzse=.false.
+   Lclthinmeanzse=.false.
+   Lclzopaquecalipsose=.false.
+   LcfadDbze94=.false.
+   Ldbze94=.false.
+   Lparasolrefl=.false.
+   Ltbrttov=.false.
+   Lptradarflag0=.false.
+   Lptradarflag1=.false.
+   Lptradarflag2=.false.
+   Lptradarflag3=.false.
+   Lptradarflag4=.false.
+   Lptradarflag5=.false.
+   Lptradarflag6=.false.
+   Lptradarflag7=.false.
+   Lptradarflag8=.false.
+   Lptradarflag9=.false.
+   Lradarpia=.false.
+   Lfracout=.false.
+
+
+  IF (is_master) THEN
+! VEREFIER LES CHAMPS DEMANDES DANS .XML
+! 2. Si champs active dans .xml alors mettre la cles de sortie en true
+ IF (xios_field_is_active("cllcalipso")) Lcllcalipso=.TRUE.
+ IF (xios_field_is_active("clmcalipso")) Lclmcalipso=.TRUE.
+ IF (xios_field_is_active("clhcalipso")) Lclhcalipso=.TRUE.
+ IF (xios_field_is_active("cltcalipso")) Lcltcalipso=.TRUE.
+ IF (xios_field_is_active("cllcalipsoice")) Lcllcalipsoice=.TRUE.
+ IF (xios_field_is_active("clmcalipsoice")) Lclmcalipsoice=.TRUE.
+ IF (xios_field_is_active("clhcalipsoice")) Lclhcalipsoice=.TRUE.
+ IF (xios_field_is_active("cltcalipsoice")) Lcltcalipsoice=.TRUE.
+ IF (xios_field_is_active("cllcalipsoliq")) Lcllcalipsoliq=.TRUE.
+ IF (xios_field_is_active("clmcalipsoliq")) Lclmcalipsoliq=.TRUE.
+ IF (xios_field_is_active("clhcalipsoliq")) Lclhcalipsoliq=.TRUE.
+ IF (xios_field_is_active("cltcalipsoliq")) Lcltcalipsoliq=.TRUE.
+ IF (xios_field_is_active("cllcalipsoun")) Lcllcalipsoun=.TRUE.
+ IF (xios_field_is_active("clmcalipsoun")) Lclmcalipsoun=.TRUE.
+ IF (xios_field_is_active("clhcalipsoun")) Lclhcalipsoun=.TRUE.
+ IF (xios_field_is_active("cltcalipsoun")) Lcltcalipsoun=.TRUE.
+ IF (xios_field_is_active("clcalipso")) Lclcalipso=.TRUE.
+ IF (xios_field_is_active("clcalipsoice")) Lclcalipsoice=.TRUE.
+ IF (xios_field_is_active("clcalipsoliq")) Lclcalipsoliq=.TRUE.
+ IF (xios_field_is_active("clcalipsoun")) Lclcalipsoun=.TRUE.
+ IF (xios_field_is_active("clcalipsotmp")) Lclcalipsotmp=.TRUE.
+ IF (xios_field_is_active("clcalipsotmpice")) Lclcalipsotmpice=.TRUE.
+ IF (xios_field_is_active("clcalipsotmpliq")) Lclcalipsotmpliq=.TRUE.
+ IF (xios_field_is_active("clcalipsotmpun")) Lclcalipsotmpun=.TRUE.
+! IF (xios_field_is_active("parasol_crefl")) cfg%LparasolRefl=.TRUE.
+! IF (xios_field_is_active("Ncrefl")) cfg%LparasolRefl=.TRUE.
+ IF (xios_field_is_active("cfadLidarsr532")) LcfadLidarsr532=.TRUE.
+ IF (xios_field_is_active("atb532")) Latb532=.TRUE.
+ IF (xios_field_is_active("lidarBetaMol532")) LlidarBetaMol532=.TRUE.
+ IF (xios_field_is_active("clopaquecalipso")) Lclopaquecalipso=.TRUE.
+ IF (xios_field_is_active("clthincalipso")) Lclthincalipso=.TRUE.
+ IF (xios_field_is_active("clzopaquecalipso")) Lclzopaquecalipso=.TRUE.
+ IF (xios_field_is_active("clcalipsoopaque")) Lclcalipsoopaque=.TRUE.
+ IF (xios_field_is_active("clcalipsothin")) Lclcalipsothin=.TRUE.
+ IF (xios_field_is_active("clcalipsozopaque")) Lclcalipsozopaque=.TRUE.
+ IF (xios_field_is_active("clcalipsoopacity")) Lclcalipsoopacity=.TRUE.
+ IF (xios_field_is_active("clopaquetemp")) Lclopaquetemp=.TRUE.
+ IF (xios_field_is_active("clthintemp")) Lclthintemp=.TRUE.
+ IF (xios_field_is_active("clzopaquetemp")) Lclzopaquetemp=.TRUE.
+ IF (xios_field_is_active("clopaquemeanz")) Lclopaquemeanz=.TRUE.
+ IF (xios_field_is_active("clthinmeanz")) Lclthinmeanz=.TRUE.
+ IF (xios_field_is_active("clthinemis")) Lclthinemis=.TRUE.
+ IF (xios_field_is_active("clopaquemeanzse")) Lclopaquemeanzse=.TRUE.
+ IF (xios_field_is_active("clthinmeanzse")) Lclthinmeanzse=.TRUE.
+ IF (xios_field_is_active("clzopaquecalipsose")) Lclzopaquecalipsose=.TRUE.
+!!!! 43 champs CALIPSO
+
+ IF (xios_field_is_active("parasolGrid_refl")) LparasolRefl=.TRUE.
+ IF (xios_field_is_active("parasolPix_refl")) LparasolRefl=.TRUE.
+!!!! 2 champs PARASOL controles par une seule clef logique
+
+ IF (xios_field_is_active("lidarBetaMol532gr")) LlidarBetaMol532gr=.TRUE.
+ IF (xios_field_is_active("cfadLidarsr532gr")) LcfadLidarsr532gr=.TRUE.
+ IF (xios_field_is_active("atb532gr")) Latb532gr=.TRUE.
+ IF (xios_field_is_active("clgrLidar532")) LclgrLidar532=.TRUE.
+ IF (xios_field_is_active("clhgrLidar532")) LclhgrLidar532=.TRUE.
+ IF (xios_field_is_active("cllgrLidar532")) LcllgrLidar532=.TRUE.
+ IF (xios_field_is_active("clmgrLidar532")) LclmgrLidar532=.TRUE.
+ IF (xios_field_is_active("cltgrLidar532")) LcltgrLidar532=.TRUE.
+!!!! 8 champs GROUND LIDAR 532 nm
+
+ IF (xios_field_is_active("lidarBetaMol355")) LlidarBetaMol355=.TRUE.
+ IF (xios_field_is_active("cfadLidarsr355")) LcfadLidarsr355=.TRUE.
+ IF (xios_field_is_active("atb355")) Latb355=.TRUE.
+ IF (xios_field_is_active("clatlid")) Lclatlid=.TRUE.
+ IF (xios_field_is_active("clhatlid")) Lclhatlid=.TRUE.
+ IF (xios_field_is_active("cllatlid")) Lcllatlid=.TRUE.
+ IF (xios_field_is_active("clmatlid")) Lclmatlid=.TRUE.
+ IF (xios_field_is_active("cltatlid")) Lcltatlid=.TRUE.
+!!!! 8 champs ATLID
+
+ IF (xios_field_is_active("cfadDbze94")) LcfadDbze94=.TRUE.
+ IF (xios_field_is_active("dbze94")) Ldbze94=.TRUE.
+ IF (xios_field_is_active("ptradarflag0")) Lptradarflag0=.TRUE.
+ IF (xios_field_is_active("ptradarflag1")) Lptradarflag1=.TRUE.
+ IF (xios_field_is_active("ptradarflag2")) Lptradarflag2=.TRUE.
+ IF (xios_field_is_active("ptradarflag3")) Lptradarflag3=.TRUE.
+ IF (xios_field_is_active("ptradarflag4")) Lptradarflag4=.TRUE.
+ IF (xios_field_is_active("ptradarflag5")) Lptradarflag5=.TRUE.
+ IF (xios_field_is_active("ptradarflag6")) Lptradarflag6=.TRUE.
+ IF (xios_field_is_active("ptradarflag7")) Lptradarflag7=.TRUE.
+ IF (xios_field_is_active("ptradarflag8")) Lptradarflag8=.TRUE.
+ IF (xios_field_is_active("ptradarflag9")) Lptradarflag9=.TRUE.
+ IF (xios_field_is_active("radarpia")) Lradarpia=.TRUE.
+!!! 13 champs CLOUDSAT
+
+ IF (xios_field_is_active("cltlidarradar")) Lcltlidarradar=.TRUE.
+ IF (xios_field_is_active("clcalipso2")) Lclcalipso2=.TRUE.
+ IF (xios_field_is_active("cloudsat_tcc")) Lcloudsat_tcc=.TRUE. !COSPv2
+ IF (xios_field_is_active("cloudsat_tcc2")) Lcloudsat_tcc2=.TRUE. !COSPv2
+!!! 4 champs CLOUDSAT et CALIPSO
+
+ IF (xios_field_is_active("clisccp")) Lclisccp=.TRUE.
+ IF (xios_field_is_active("boxtauisccp")) Lboxtauisccp=.TRUE.
+ IF (xios_field_is_active("boxptopisccp")) Lboxptopisccp=.TRUE.
+ IF (xios_field_is_active("cltisccp")) Lcltisccp=.TRUE.
+ IF (xios_field_is_active("pctisccp")) Lpctisccp=.TRUE.
+ IF (xios_field_is_active("tauisccp")) Ltauisccp=.TRUE.
+ IF (xios_field_is_active("albisccp")) Lalbisccp=.TRUE.
+ IF (xios_field_is_active("meantbisccp")) Lmeantbisccp=.TRUE.
+ IF (xios_field_is_active("meantbclrisccp")) Lmeantbclrisccp=.TRUE.
+!!! 9 champs ISCCP
+
+ IF (xios_field_is_active("misr_fq")) LclMISR=.TRUE.
+ IF (xios_field_is_active("misr_meanztop")) LclMISR=.TRUE.
+ IF (xios_field_is_active("misr_cldarea")) LclMISR=.TRUE.
+!!! 3 champs MISR controles par une seule clef logique
+
+ IF (xios_field_is_active("cllmodis")) Lcllmodis=.TRUE.
+ IF (xios_field_is_active("clmmodis")) Lclmmodis=.TRUE.
+ IF (xios_field_is_active("clhmodis")) Lclhmodis=.TRUE.
+ IF (xios_field_is_active("cltmodis")) Lcltmodis=.TRUE.
+ IF (xios_field_is_active("clwmodis")) Lclwmodis=.TRUE.
+ IF (xios_field_is_active("climodis")) Lclimodis=.TRUE.
+ IF (xios_field_is_active("tautmodis")) Ltautmodis=.TRUE.
+ IF (xios_field_is_active("tauwmodis")) Ltauwmodis=.TRUE.
+ IF (xios_field_is_active("tauimodis")) Ltauimodis=.TRUE.
+ IF (xios_field_is_active("tautlogmodis")) Ltautlogmodis=.TRUE.
+ IF (xios_field_is_active("tauilogmodis")) Ltauilogmodis=.TRUE.
+ IF (xios_field_is_active("tauwlogmodis")) Ltauwlogmodis=.TRUE.
+ IF (xios_field_is_active("reffclwmodis")) Lreffclwmodis=.TRUE.
+ IF (xios_field_is_active("reffclimodis")) Lreffclimodis=.TRUE.
+ IF (xios_field_is_active("pctmodis")) Lpctmodis=.TRUE.
+ IF (xios_field_is_active("lwpmodis")) Llwpmodis=.TRUE.
+ IF (xios_field_is_active("iwpmodis")) Liwpmodis=.TRUE.
+ IF (xios_field_is_active("modis_ot_vs_ctp")) Lclmodis=.TRUE.
+ IF (xios_field_is_active("modis_ot_vs_reffice")) Lclmodis=.TRUE.
+ IF (xios_field_is_active("modis_ot_vs_reffliq")) Lclmodis=.TRUE.
+! IF (xios_field_is_active("crimodis")) Lcrimodis=.TRUE. !COSPv2
+! IF (xios_field_is_active("crlmodis")) Lcrlmodis=.TRUE. !COSPv2
+!!! 20 champs MODIS dont 3 champs controles par la clef logique "clmodis"
+
+! IF (xios_field_is_active("tbrttov")) cfg%Ltbrttov=.TRUE.
+! IF (xios_field_is_active("fracout")) Lfracout=.TRUE.
+
+!!! 106 diagnostics en tout dans COSPv2 + fracout (107)
+
+
+! 2.  si champs demande alors activer le simulateur correspondant
+   IF (xios_field_is_active("cllcalipso").OR. &
+       xios_field_is_active("clmcalipso").OR. &
+       xios_field_is_active("clhcalipso").OR. &
+       xios_field_is_active("cltcalipso").OR. &
+       xios_field_is_active("cllcalipsoice").OR. &
+       xios_field_is_active("clmcalipsoice").OR. &
+       xios_field_is_active("clhcalipsoice").OR. &
+       xios_field_is_active("cltcalipsoice").OR. &
+       xios_field_is_active("cllcalipsoliq").OR. &
+       xios_field_is_active("clmcalipsoliq").OR. &
+       xios_field_is_active("clhcalipsoliq").OR. &
+       xios_field_is_active("cltcalipsoliq").OR. &
+       xios_field_is_active("cllcalipsoun").OR. &
+       xios_field_is_active("clmcalipsoun").OR. &
+       xios_field_is_active("clhcalipsoun").OR. &
+       xios_field_is_active("cltcalipsoun").OR. &
+       xios_field_is_active("clcalipso").OR. &
+       xios_field_is_active("clcalipsoice").OR. &
+       xios_field_is_active("clcalipsoliq").OR. &
+       xios_field_is_active("clcalipsoun").OR. &
+       xios_field_is_active("clcalipsotmp").OR. &
+       xios_field_is_active("clcalipsotmpice").OR. &
+       xios_field_is_active("clcalipsotmpliq").OR. &
+       xios_field_is_active("clcalipsotmpun").OR. &
+       xios_field_is_active("cfadLidarsr532").OR. &
+       xios_field_is_active("atb532").OR. &
+       xios_field_is_active("lidarBetaMol532").OR. &
+       xios_field_is_active("clopaquecalipso").OR. &
+       xios_field_is_active("clthincalipso").OR. &
+       xios_field_is_active("clzopaquecalipso").OR. &
+       xios_field_is_active("clcalipsoopaque").OR. &
+       xios_field_is_active("clcalipsothin").OR. &
+       xios_field_is_active("clcalipsozopaque").OR. &
+       xios_field_is_active("clcalipsoopacity").OR. &
+       xios_field_is_active("clopaquetemp").OR. &
+       xios_field_is_active("clthintemp").OR. &
+       xios_field_is_active("clzopaquetemp").OR. &
+       xios_field_is_active("clopaquemeanz").OR. &
+       xios_field_is_active("clthinmeanz").OR. &
+       xios_field_is_active("clthinemis").OR. &
+       xios_field_is_active("clopaquemeanzse").OR. &
+       xios_field_is_active("clthinmeanzse").OR. &
+       xios_field_is_active("clzopaquecalipsose"))  Lcalipso=.TRUE.
+
+    IF (xios_field_is_active("parasolGrid_refl").OR. &
+       xios_field_is_active("parasolPix_refl")) Lparasol=.TRUE.
+
+   IF (xios_field_is_active("lidarBetaMol532gr").OR. &
+       xios_field_is_active("cfadLidarsr532gr").OR. &
+       xios_field_is_active("atb532gr").OR. &
+       xios_field_is_active("clgrLidar532").OR. &
+       xios_field_is_active("clhgrLidar532").OR. &
+       xios_field_is_active("cllgrLidar532").OR. &
+       xios_field_is_active("clmgrLidar532").OR. &
+       xios_field_is_active("cltgrLidar532"))  LgrLidar532=.TRUE.
+
+   IF (xios_field_is_active("lidarBetaMol355").OR. &
+       xios_field_is_active("cfadLidarsr355").OR. &
+       xios_field_is_active("atb355").OR. &
+       xios_field_is_active("clatlid").OR. &
+       xios_field_is_active("clhatlid").OR. &
+       xios_field_is_active("cllatlid").OR. &
+       xios_field_is_active("clmatlid").OR. &
+       xios_field_is_active("cltatlid"))  Latlid=.TRUE.
+
+    IF (xios_field_is_active("cfadDbze94").OR. &
+      xios_field_is_active("dbze94").OR. &
+      xios_field_is_active("ptradarflag0").OR. &
+      xios_field_is_active("ptradarflag1").OR. &
+      xios_field_is_active("ptradarflag2").OR. &
+      xios_field_is_active("ptradarflag3").OR. &
+      xios_field_is_active("ptradarflag4").OR. &
+      xios_field_is_active("ptradarflag5").OR. &
+      xios_field_is_active("ptradarflag6").OR. &
+      xios_field_is_active("ptradarflag7").OR. &
+      xios_field_is_active("ptradarflag8").OR. &
+      xios_field_is_active("ptradarflag9").OR. &
+      xios_field_is_active("radarpia")) Lcloudsat=.TRUE.
+
+    IF (xios_field_is_active("cltlidarradar").OR. &
+      xios_field_is_active("clcalipso2").OR. &
+      xios_field_is_active("cloudsat_tcc").OR. &
+      xios_field_is_active("cloudsat_tcc2")) THEN
+               Lcloudsat=.TRUE.
+               Lcalipso=.TRUE.
+    ENDIF
+
+    IF (xios_field_is_active("clisccp").OR. &     !COSPv2 nouveau nom
+       xios_field_is_active("boxtauisccp").OR. &
+       xios_field_is_active("boxptopisccp").OR. &
+       xios_field_is_active("cltisccp").OR. &     !COSPv2 nouveau nom
+       xios_field_is_active("pctisccp").OR. &     !COSPv2 nouveau nom
+       xios_field_is_active("tauisccp").OR. &
+       xios_field_is_active("albisccp").OR. &
+       xios_field_is_active("meantbisccp").OR. &
+       xios_field_is_active("meantbclrisccp")) Lisccp=.TRUE.
+
+    IF (xios_field_is_active("misr_fq").OR. &
+       xios_field_is_active("misr_meanztop").OR. &
+       xios_field_is_active("misr_cldarea")) Lmisr=.TRUE.
+
+    IF (xios_field_is_active("cllmodis").OR. &
+       xios_field_is_active("clmmodis").OR. &
+       xios_field_is_active("clhmodis").OR. &
+       xios_field_is_active("cltmodis").OR. &
+       xios_field_is_active("clwmodis").OR. &
+       xios_field_is_active("climodis").OR. &
+       xios_field_is_active("tautmodis").OR. &
+       xios_field_is_active("tauwmodis").OR. &
+       xios_field_is_active("tauimodis").OR. &
+       xios_field_is_active("tautlogmodis").OR. &
+       xios_field_is_active("tauilogmodis").OR. &
+       xios_field_is_active("tauwlogmodis").OR. &
+       xios_field_is_active("reffclwmodis").OR. &
+       xios_field_is_active("reffclimodis").OR. &
+       xios_field_is_active("pctmodis").OR. &
+       xios_field_is_active("lwpmodis").OR. &
+       xios_field_is_active("iwpmodis").OR. &
+       xios_field_is_active("modis_ot_vs_ctp").OR. &
+       xios_field_is_active("modis_ot_vs_reffice").OR. &
+       xios_field_is_active("modis_ot_vs_reffliq")) Lmodis=.TRUE.
+!       xios_field_is_active("crimodis").OR. &              !COSPv2 n'existe plus
+!       xios_field_is_active("crlmodis")) Lmodis_sim=.TRUE. !COSPv2 n'existe plus
+
+  ENDIF !   (is_master) 
+
+!$OMP BARRIER
+
+  CALL bcast(Lcloudsat)
+  CALL bcast(Lcalipso)
+  CALL bcast(LgrLidar532)
+  CALL bcast(Latlid)
+  CALL bcast(Lisccp)
+  CALL bcast(Lmodis)
+  CALL bcast(Lmisr)
+  CALL bcast(Lparasol)
+  CALL bcast(Lrttov)
+
+  CALL bcast(Lcfaddbze94)
+  CALL bcast(Ldbze94)
+  CALL bcast(Latb532)
+  CALL bcast(LcfadLidarsr532)
+  CALL bcast(Lclcalipso)
+  CALL bcast(Lclhcalipso)
+  CALL bcast(Lcllcalipso)
+  CALL bcast(Lclmcalipso)
+  CALL bcast(Lcltcalipso)
+  CALL bcast(LparasolRefl)
+  CALL bcast(Lclcalipsoliq)
+  CALL bcast(Lclcalipsoice)
+  CALL bcast(Lclcalipsoun)
+  CALL bcast(Lclcalipsotmp)
+  CALL bcast(Lclcalipsotmpliq)
+  CALL bcast(Lclcalipsotmpice)
+  CALL bcast(Lclcalipsotmpun)
+  CALL bcast(Lclhcalipsoliq)
+  CALL bcast(Lcllcalipsoliq)
+  CALL bcast(Lclmcalipsoliq)
+  CALL bcast(Lcltcalipsoliq)
+  CALL bcast(Lclhcalipsoice)
+  CALL bcast(Lcllcalipsoice)
+  CALL bcast(Lclmcalipsoice)
+  CALL bcast(Lcltcalipsoice)
+  CALL bcast(Lclhcalipsoun)
+  CALL bcast(Lcllcalipsoun)
+  CALL bcast(Lclmcalipsoun)
+  CALL bcast(Lcltcalipsoun)
+  CALL bcast(Lclopaquecalipso)
+  CALL bcast(Lclthincalipso)
+  CALL bcast(Lclzopaquecalipso)
+  CALL bcast(Lclcalipsoopaque)
+  CALL bcast(Lclcalipsothin)
+  CALL bcast(Lclcalipsozopaque)
+  CALL bcast(Lclcalipsoopacity)
+  CALL bcast(Lclopaquetemp)
+  CALL bcast(Lclthintemp)
+  CALL bcast(Lclzopaquetemp)
+  CALL bcast(Lclopaquemeanz)
+  CALL bcast(Lclthinmeanz)
+  CALL bcast(Lclthinemis)
+  CALL bcast(Lclopaquemeanzse)
+  CALL bcast(Lclthinmeanzse)
+  CALL bcast(Lclzopaquecalipsose)
+  CALL bcast(LlidarBetaMol532gr)
+  CALL bcast(LcfadLidarsr532gr)
+  CALL bcast(Latb532gr)
+  CALL bcast(LclgrLidar532)
+  CALL bcast(LclhgrLidar532)
+  CALL bcast(LcllgrLidar532)
+  CALL bcast(LclmgrLidar532)
+  CALL bcast(LcltgrLidar532)
+  CALL bcast(LlidarBetaMol355)
+  CALL bcast(LcfadLidarsr355)
+  CALL bcast(Latb355)
+  CALL bcast(Lclatlid)
+  CALL bcast(Lclhatlid)
+  CALL bcast(Lcllatlid)
+  CALL bcast(Lclmatlid)
+  CALL bcast(Lcltatlid)
+  CALL bcast(Lalbisccp)
+  CALL bcast(Lboxptopisccp)
+  CALL bcast(Lboxtauisccp)
+  CALL bcast(Lpctisccp)
+  CALL bcast(Lclisccp)
+  CALL bcast(Ltauisccp)
+  CALL bcast(Lcltisccp)
+  CALL bcast(Lmeantbisccp)
+  CALL bcast(Lmeantbclrisccp)
+  CALL bcast(LclMISR)
+  CALL bcast(Lclcalipso2)
+  CALL bcast(Lcltlidarradar)
+  CALL bcast(Lcloudsat_tcc)
+  CALL bcast(Lcloudsat_tcc2)
+  CALL bcast(Lfracout)
+  CALL bcast(LlidarBetaMol532)
+  CALL bcast(Lcltmodis)
+  CALL bcast(Lclwmodis)
+  CALL bcast(Lclimodis)
+  CALL bcast(Lclhmodis)
+  CALL bcast(Lclmmodis)
+  CALL bcast(Lcllmodis)
+  CALL bcast(Ltautmodis)
+  CALL bcast(Ltauwmodis)
+  CALL bcast(Ltauimodis)
+  CALL bcast(Ltautlogmodis)
+  CALL bcast(Ltauwlogmodis)
+  CALL bcast(Ltauilogmodis)
+  CALL bcast(Lreffclwmodis)
+  CALL bcast(Lreffclimodis)
+  CALL bcast(Lpctmodis)
+  CALL bcast(Llwpmodis)
+  CALL bcast(Liwpmodis)
+  CALL bcast(Lclmodis)
+  CALL bcast(Ltbrttov)
+  CALL bcast(Lptradarflag0)
+  CALL bcast(Lptradarflag1)
+  CALL bcast(Lptradarflag2)
+  CALL bcast(Lptradarflag3)
+  CALL bcast(Lptradarflag4)
+  CALL bcast(Lptradarflag5)
+  CALL bcast(Lptradarflag6)
+  CALL bcast(Lptradarflag7)
+  CALL bcast(Lptradarflag8)
+  CALL bcast(Lptradarflag9)
+  CALL bcast(Lradarpia)
+
+!    IF (xios_field_is_active("tbrttov")) cfg%Lrttov_sim=.TRUE.
+
+
+  ! Copy diagnostic flags to cfg structure
+! ISCCP simulator  (9 diagnostics)
+   cfg%Lpctisccp = Lpctisccp
+   cfg%Lclisccp = Lclisccp
+   cfg%Lboxptopisccp = Lboxptopisccp
+   cfg%Lboxtauisccp = Lboxtauisccp
+   cfg%Ltauisccp = Ltauisccp
+   cfg%Lcltisccp = Lcltisccp
+   cfg%Lmeantbisccp = Lmeantbisccp
+   cfg%Lmeantbclrisccp = Lmeantbclrisccp
+   cfg%Lalbisccp = Lalbisccp
+
+! CloudSat simulator  (13 diagnostics) 
+   cfg%Ldbze94 = Ldbze94
+   cfg%LcfadDbze94 = LcfadDbze94
+   cfg%Lptradarflag0 = Lptradarflag0
+   cfg%Lptradarflag1 = Lptradarflag1
+   cfg%Lptradarflag2 = Lptradarflag2
+   cfg%Lptradarflag3 = Lptradarflag3
+   cfg%Lptradarflag4 = Lptradarflag4
+   cfg%Lptradarflag5 = Lptradarflag5
+   cfg%Lptradarflag6 = Lptradarflag6
+   cfg%Lptradarflag7 = Lptradarflag7
+   cfg%Lptradarflag8 = Lptradarflag8
+   cfg%Lptradarflag9 = Lptradarflag9
+   cfg%Lradarpia = Lradarpia
+
+! Cloudsat et Calipso  (4 diagnostics)
+   cfg%Lclcalipso2 = Lclcalipso2
+   cfg%Lcltlidarradar = Lcltlidarradar
+   cfg%Lcloudsat_tcc = Lcloudsat_tcc
+   cfg%Lcloudsat_tcc2 = Lcloudsat_tcc2
+
+! CALIPSO simulator  (43 diagnostics)
+   cfg%Latb532 = Latb532
+   cfg%LlidarBetaMol532 = LlidarBetaMol532
+   cfg%LcfadLidarsr532 = LcfadLidarsr532
+   cfg%Lclcalipso = Lclcalipso
+   cfg%Lclhcalipso = Lclhcalipso
+   cfg%Lcllcalipso = Lcllcalipso
+   cfg%Lclmcalipso = Lclmcalipso
+   cfg%Lcltcalipso = Lcltcalipso
+   cfg%Lclcalipsoliq = Lclcalipsoliq
+   cfg%Lclcalipsoice = Lclcalipsoice
+   cfg%Lclcalipsoun = Lclcalipsoun
+   cfg%Lclcalipsotmp = Lclcalipsotmp
+   cfg%Lclcalipsotmpliq = Lclcalipsotmpliq
+   cfg%Lclcalipsotmpice = Lclcalipsotmpice
+   cfg%Lclcalipsotmpun = Lclcalipsotmpun
+   cfg%Lcltcalipsoliq = Lcltcalipsoliq
+   cfg%Lcltcalipsoice = Lcltcalipsoice
+   cfg%Lcltcalipsoun = Lcltcalipsoun
+   cfg%Lclhcalipsoliq = Lclhcalipsoliq
+   cfg%Lclhcalipsoice = Lclhcalipsoice
+   cfg%Lclhcalipsoun = Lclhcalipsoun
+   cfg%Lclmcalipsoliq = Lclmcalipsoliq
+   cfg%Lclmcalipsoice = Lclmcalipsoice
+   cfg%Lclmcalipsoun = Lclmcalipsoun
+   cfg%Lcllcalipsoliq = Lcllcalipsoliq
+   cfg%Lcllcalipsoice = Lcllcalipsoice
+   cfg%Lcllcalipsoun = Lcllcalipsoun
+   cfg%Lclopaquecalipso = Lclopaquecalipso
+   cfg%Lclthincalipso = Lclthincalipso
+   cfg%Lclzopaquecalipso = Lclzopaquecalipso
+   cfg%Lclcalipsoopaque = Lclcalipsoopaque
+   cfg%Lclcalipsothin = Lclcalipsothin
+   cfg%Lclcalipsozopaque = Lclcalipsozopaque
+   cfg%Lclcalipsoopacity = Lclcalipsoopacity
+   cfg%Lclopaquetemp = Lclopaquetemp
+   cfg%Lclthintemp = Lclthintemp
+   cfg%Lclzopaquetemp = Lclzopaquetemp
+   cfg%Lclopaquemeanz = Lclopaquemeanz
+   cfg%Lclthinmeanz = Lclthinmeanz
+   cfg%Lclthinemis = Lclthinemis
+   cfg%Lclopaquemeanzse = Lclopaquemeanzse
+   cfg%Lclthinmeanzse = Lclthinmeanzse
+   cfg%Lclzopaquecalipsose = Lclzopaquecalipsose
+
+! PARASOL simulator  (2 diagnostics, 1 clef)
+   cfg%Lparasolrefl = Lparasolrefl
+
+! GROUND LIDAR 532 nm simulator  (8 diagnostics)
+   cfg%Latb532gr = Latb532gr
+   cfg%LlidarBetaMol532gr = LlidarBetaMol532gr
+   cfg%LcfadLidarsr532gr = LcfadLidarsr532gr
+   cfg%LclgrLidar532 = LclgrLidar532
+   cfg%LclhgrLidar532 = LclhgrLidar532
+   cfg%LcllgrLidar532 = LcllgrLidar532
+   cfg%LclmgrLidar532 = LclmgrLidar532
+   cfg%LcltgrLidar532 = LcltgrLidar532
+
+! ATLID simulator  (8 diagnostics)
+   cfg%Latb355 = Latb355
+   cfg%LlidarBetaMol355 = LlidarBetaMol355
+   cfg%LcfadLidarsr355 = LcfadLidarsr355
+   cfg%Lclatlid = Lclatlid
+   cfg%Lclhatlid = Lclhatlid
+   cfg%Lcllatlid = Lcllatlid
+   cfg%Lclmatlid = Lclmatlid
+   cfg%Lcltatlid = Lcltatlid
+
+! MISR simulator   (3 diagnostics, 1 clef)
+  cfg%LclMISR = LclMISR
+
+! RTTOV  (1 diagnostic)
+  cfg%Ltbrttov = Ltbrttov
+
+! MODIS simulator   (20 diagnostics, 18 clefs)
+  cfg%Lcltmodis=Lcltmodis
+  cfg%Lclwmodis=Lclwmodis
+  cfg%Lclimodis=Lclimodis
+  cfg%Lclhmodis=Lclhmodis
+  cfg%Lclmmodis=Lclmmodis
+  cfg%Lcllmodis=Lcllmodis
+  cfg%Ltautmodis=Ltautmodis
+  cfg%Ltauwmodis=Ltauwmodis
+  cfg%Ltauimodis=Ltauimodis
+  cfg%Ltautlogmodis=Ltautlogmodis
+  cfg%Ltauwlogmodis=Ltauwlogmodis
+  cfg%Ltauilogmodis=Ltauilogmodis
+  cfg%Lreffclwmodis=Lreffclwmodis
+  cfg%Lreffclimodis=Lreffclimodis
+  cfg%Lpctmodis=Lpctmodis
+  cfg%Llwpmodis=Llwpmodis
+  cfg%Liwpmodis=Liwpmodis
+  cfg%Lclmodis=Lclmodis
+
+! Others
+  cfg%Lfracout=Lfracout
+
+! Copy instrument flags to cfg structure
+  cfg%Lcloudsat = Lcloudsat
+  cfg%Lcalipso = Lcalipso
+  cfg%LgrLidar532 = LgrLidar532
+  cfg%Latlid = Latlid
+  cfg%Lparasol = Lparasol
+  cfg%Lisccp = Lisccp
+  cfg%Lmodis = Lmodis
+  cfg%Lmisr = Lmisr
+  cfg%Lrttov = Lrttov
+  if (cfg%Lcloudsat .or. cfg%Lcalipso .or. cfg%LgrLidar532 .or. cfg%Latlid .or. cfg%Lisccp .or. cfg%Lmodis .or. cfg%Lmisr .or. cfg%Lrttov .or. cfg%Lparasol .or. cfg%Lfracout) then
+   cfg%Lwrite_output=.TRUE.
+ endif 
+
+#endif
+
+  END SUBROUTINE read_xiosfieldactive
+
+END MODULE lmdz_cosp_read_outputkeys
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_subsample_and_optics_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_subsample_and_optics_mod.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/lmdz_cosp_subsample_and_optics_mod.F90	(revision 3605)
@@ -0,0 +1,456 @@
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!
+! Module pour remplir la variable "cospIN", calculs des proprietes optiques subcolumn
+! pour les differents simulateurs
+!
+!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+MODULE LMDZ_COSP_SUBSAMPLE_AND_OPTICS_MOD
+
+use cosp_kinds,                only: wp                         
+USE MOD_COSP_CONFIG
+USE mod_quickbeam_optics,      only: size_distribution,quickbeam_optics,gases
+use quickbeam,                 only: radar_cfg
+use MOD_COSP,                  only: cosp_optical_inputs,cosp_column_inputs
+USE mod_rng,                   ONLY: rng_state, init_rng
+USE mod_scops,                 ONLY: scops
+USE mod_prec_scops,            ONLY: prec_scops
+USE MOD_COSP_UTILS,            ONLY: cosp_precip_mxratio
+use cosp_optics,               ONLY: cosp_simulator_optics,lidar_optics,modis_optics,   &
+                                     modis_optics_partition
+use mod_cosp_stats,            ONLY: COSP_CHANGE_VERTICAL_GRID
+use lmdz_cosp_read_outputkeys, ONLY: cosp_config
+
+
+  implicit none
+
+  ! Indices to address arrays of LS and CONV hydrometeors
+  integer,parameter :: &
+       I_LSCLIQ = 1, & ! Large-scale (stratiform) liquid
+       I_LSCICE = 2, & ! Large-scale (stratiform) ice
+       I_LSRAIN = 3, & ! Large-scale (stratiform) rain
+       I_LSSNOW = 4, & ! Large-scale (stratiform) snow
+       I_CVCLIQ = 5, & ! Convective liquid
+       I_CVCICE = 6, & ! Convective ice
+       I_CVRAIN = 7, & ! Convective rain
+       I_CVSNOW = 8, & ! Convective snow
+       I_LSGRPL = 9    ! Large-scale (stratiform) groupel
+  
+  ! Stratiform and convective clouds in frac_out.
+  integer, parameter :: &
+       I_LSC = 1, & ! Large-scale clouds
+       I_CVC = 2    ! Convective clouds      
+  
+  ! Microphysical settings for the precipitation flux to mixing ratio conversion
+  real(wp),parameter,dimension(N_HYDRO) :: &
+                 ! LSL   LSI      LSR       LSS   CVL  CVI      CVR       CVS       LSG
+       N_ax    = (/-1., -1.,     8.e6,     3.e6, -1., -1.,     8.e6,     3.e6,     4.e6/),&
+       N_bx    = (/-1., -1.,      0.0,      0.0, -1., -1.,      0.0,      0.0,      0.0/),&
+       alpha_x = (/-1., -1.,      0.0,      0.0, -1., -1.,      0.0,      0.0,      0.0/),&
+       c_x     = (/-1., -1.,    842.0,     4.84, -1., -1.,    842.0,     4.84,     94.5/),&
+       d_x     = (/-1., -1.,      0.8,     0.25, -1., -1.,      0.8,     0.25,      0.5/),&
+       g_x     = (/-1., -1.,      0.5,      0.5, -1., -1.,      0.5,      0.5,      0.5/),&
+       a_x     = (/-1., -1.,    524.0,    52.36, -1., -1.,    524.0,    52.36,   209.44/),&
+       b_x     = (/-1., -1.,      3.0,      3.0, -1., -1.,      3.0,      3.0,      3.0/),&
+       gamma_1 = (/-1., -1., 17.83725, 8.284701, -1., -1., 17.83725, 8.284701, 11.63230/),&
+       gamma_2 = (/-1., -1.,      6.0,      6.0, -1., -1.,      6.0,      6.0,      6.0/),&
+       gamma_3 = (/-1., -1.,      2.0,      2.0, -1., -1.,      2.0,      2.0,      2.0/),&
+       gamma_4 = (/-1., -1.,      6.0,      6.0, -1., -1.,      6.0,      6.0,      6.0/)
+
+
+contains
+
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
+  ! SUBROUTINE subsample_and_optics
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
+  subroutine subsample_and_optics(cfg, nPoints, nLevels, nColumns, nHydro, overlap, &
+       use_precipitation_fluxes, lidar_ice_type, sd, tca, cca, fl_lsrainIN, fl_lssnowIN,    &
+       fl_lsgrplIN, fl_ccrainIN, fl_ccsnowIN, mr_lsliq, mr_lsice, mr_ccliq, mr_ccice,       &
+       reffIN, dtau_c, dtau_s, dem_c, dem_s, cospstateIN, cospIN)
+    ! Inputs
+    integer,intent(in) :: nPoints, nLevels, nColumns, nHydro, overlap, lidar_ice_type
+    real(wp),intent(in),dimension(nPoints,nLevels) :: tca,cca,mr_lsliq,mr_lsice,mr_ccliq,   &
+         mr_ccice,dtau_c,dtau_s,dem_c,dem_s,fl_lsrainIN,fl_lssnowIN,fl_lsgrplIN,fl_ccrainIN,&
+         fl_ccsnowIN
+    real(wp),intent(in),dimension(nPoints,nLevels,nHydro) :: reffIN
+    logical,intent(in) :: use_precipitation_fluxes
+    type(size_distribution),intent(inout) :: sd
+    type(cosp_config),intent(in) :: cfg   ! Configuration options
+    
+    ! Outputs
+    type(cosp_optical_inputs),intent(inout) :: cospIN
+    type(cosp_column_inputs),intent(inout)  :: cospstateIN
+
+    type(rng_state),allocatable,dimension(:) :: rngs  ! Seeds for random number generator
+    integer,dimension(:),allocatable :: seed
+    integer,dimension(:),allocatable :: cloudsat_preclvl_index !PREC_BUG
+    integer :: i,j,k
+    real(wp),dimension(:,:), allocatable :: &
+         ls_p_rate, cv_p_rate, frac_ls, frac_cv, prec_ls, prec_cv,g_vol
+    real(wp),dimension(:,:,:),  allocatable :: &
+         frac_prec, MODIS_cloudWater, MODIS_cloudIce, fracPrecipIce, fracPrecipIce_statGrid,&
+         MODIS_watersize,MODIS_iceSize, MODIS_opticalThicknessLiq,MODIS_opticalThicknessIce
+    real(wp),dimension(:,:,:,:),allocatable :: &
+         mr_hydro, Reff, Np
+    real(wp),dimension(nPoints,nLevels) :: &
+         column_frac_out, column_prec_out, fl_lsrain, fl_lssnow, fl_lsgrpl, fl_ccrain, fl_ccsnow
+!    real(wp),dimension(nPoints,nColumns,Nlvgrid_local) :: tempOut
+    logical :: cmpGases=.true.
+
+    if (Ncolumns .gt. 1) then
+       !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+       ! Generate subcolumns for clouds (SCOPS) and precipitation type (PREC_SCOPS)
+       !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+       ! RNG used for subcolumn generation
+       allocate(rngs(nPoints),seed(nPoints))
+       seed(:)=0
+       seed = int(cospstateIN%phalf(:,Nlevels+1))  ! In case of NPoints=1
+       ! *NOTE* Chunking will change the seed
+       if (NPoints .gt. 1) seed=int((cospstateIN%phalf(:,Nlevels+1)-minval(cospstateIN%phalf(:,Nlevels+1)))/      &
+            (maxval(cospstateIN%phalf(:,Nlevels+1))-minval(cospstateIN%phalf(:,Nlevels+1)))*100000) + 1
+       call init_rng(rngs, seed)
+      
+       ! Call scops
+       call scops(NPoints,Nlevels,Ncolumns,rngs,tca,cca,overlap,cospIN%frac_out,0)
+       deallocate(seed,rngs)
+       
+       ! Sum up precipitation rates
+       allocate(ls_p_rate(nPoints,nLevels),cv_p_rate(nPoints,Nlevels))
+       if(use_precipitation_fluxes) then
+          ls_p_rate(:,1:nLevels) = fl_lsrainIN + fl_lssnowIN + fl_lsgrplIN
+          cv_p_rate(:,1:nLevels) = fl_ccrainIN + fl_ccsnowIN
+       else
+          ls_p_rate(:,1:nLevels) = 0 ! mixing_ratio(rain) + mixing_ratio(snow) + mixing_ratio (groupel)
+          cv_p_rate(:,1:nLevels) = 0 ! mixing_ratio(rain) + mixing_ratio(snow)
+       endif
+       
+       ! Call PREC_SCOPS
+       allocate(frac_prec(nPoints,nColumns,nLevels))
+       call prec_scops(nPoints,nLevels,nColumns,ls_p_rate,cv_p_rate,cospIN%frac_out,frac_prec)
+       deallocate(ls_p_rate,cv_p_rate)
+       
+       !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+       ! Compute fraction in each gridbox for precipitation  and cloud type.
+       !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+       ! Allocate
+       allocate(frac_ls(nPoints,nLevels),prec_ls(nPoints,nLevels),                       &
+                frac_cv(nPoints,nLevels),prec_cv(nPoints,nLevels))
+       
+       ! Initialize
+       frac_ls(1:nPoints,1:nLevels) = 0._wp
+       prec_ls(1:nPoints,1:nLevels) = 0._wp
+       frac_cv(1:nPoints,1:nLevels) = 0._wp
+       prec_cv(1:nPoints,1:nLevels) = 0._wp
+       do j=1,nPoints
+          do k=1,nLevels
+             do i=1,nColumns
+                if (cospIN%frac_out(j,i,k)  .eq. 1)  frac_ls(j,k) = frac_ls(j,k)+1._wp
+                if (cospIN%frac_out(j,i,k)  .eq. 2)  frac_cv(j,k) = frac_cv(j,k)+1._wp
+                if (frac_prec(j,i,k) .eq. 1)  prec_ls(j,k) = prec_ls(j,k)+1._wp
+                if (frac_prec(j,i,k) .eq. 2)  prec_cv(j,k) = prec_cv(j,k)+1._wp
+                if (frac_prec(j,i,k) .eq. 3)  prec_cv(j,k) = prec_cv(j,k)+1._wp
+                if (frac_prec(j,i,k) .eq. 3)  prec_ls(j,k) = prec_ls(j,k)+1._wp
+             enddo
+             frac_ls(j,k)=frac_ls(j,k)/nColumns
+             frac_cv(j,k)=frac_cv(j,k)/nColumns
+             prec_ls(j,k)=prec_ls(j,k)/nColumns
+             prec_cv(j,k)=prec_cv(j,k)/nColumns
+          enddo
+       enddo       
+
+       !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+       ! Assign gridmean mixing-ratios (mr_XXXXX), effective radius (ReffIN) and number
+       ! concentration (not defined) to appropriate sub-column. Here we are using scops. 
+       !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+       allocate(mr_hydro(nPoints,nColumns,nLevels,nHydro),                               &
+                Reff(nPoints,nColumns,nLevels,nHydro),                                   &
+                Np(nPoints,nColumns,nLevels,nHydro))
+
+       ! Initialize
+       mr_hydro(:,:,:,:) = 0._wp
+       Reff(:,:,:,:)     = 0._wp
+       Np(:,:,:,:)       = 0._wp
+       do k=1,nColumns
+          ! Subcolumn cloud fraction
+          column_frac_out = cospIN%frac_out(:,k,:)
+               
+          ! LS clouds
+          where (column_frac_out == I_LSC)
+             mr_hydro(:,k,:,I_LSCLIQ) = mr_lsliq
+             mr_hydro(:,k,:,I_LSCICE) = mr_lsice
+             Reff(:,k,:,I_LSCLIQ)     = ReffIN(:,:,I_LSCLIQ)
+             Reff(:,k,:,I_LSCICE)     = ReffIN(:,:,I_LSCICE)
+          ! CONV clouds   
+          elsewhere (column_frac_out == I_CVC)
+             mr_hydro(:,k,:,I_CVCLIQ) = mr_ccliq
+             mr_hydro(:,k,:,I_CVCICE) = mr_ccice
+             Reff(:,k,:,I_CVCLIQ)     = ReffIN(:,:,I_CVCLIQ)
+             Reff(:,k,:,I_CVCICE)     = ReffIN(:,:,I_CVCICE)
+          end where
+          
+          ! Subcolumn precipitation
+          column_prec_out = frac_prec(:,k,:)
+
+          ! LS Precipitation
+          where ((column_prec_out == 1) .or. (column_prec_out == 3) )
+             Reff(:,k,:,I_LSRAIN) = ReffIN(:,:,I_LSRAIN)
+             Reff(:,k,:,I_LSSNOW) = ReffIN(:,:,I_LSSNOW)
+             Reff(:,k,:,I_LSGRPL) = ReffIN(:,:,I_LSGRPL)
+             ! CONV precipitation   
+          elsewhere ((column_prec_out == 2) .or. (column_prec_out == 3))
+             Reff(:,k,:,I_CVRAIN) = ReffIN(:,:,I_CVRAIN)
+             Reff(:,k,:,I_CVSNOW) = ReffIN(:,:,I_CVSNOW)
+          end where
+       enddo
+       
+       !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+       ! Convert the subcolumn mixing ratio and precipitation fluxes from gridbox mean
+       ! values to fraction-based values. 
+       !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+       ! Initialize
+       fl_lsrain(:,:) = 0._wp
+       fl_lssnow(:,:) = 0._wp
+       fl_lsgrpl(:,:) = 0._wp
+       fl_ccrain(:,:) = 0._wp
+       fl_ccsnow(:,:) = 0._wp
+       do k=1,nLevels
+          do j=1,nPoints
+             ! In-cloud mixing ratios.
+             if (frac_ls(j,k) .ne. 0.) then
+                mr_hydro(j,:,k,I_LSCLIQ) = mr_hydro(j,:,k,I_LSCLIQ)/frac_ls(j,k)
+                mr_hydro(j,:,k,I_LSCICE) = mr_hydro(j,:,k,I_LSCICE)/frac_ls(j,k)
+             endif
+             if (frac_cv(j,k) .ne. 0.) then
+                mr_hydro(j,:,k,I_CVCLIQ) = mr_hydro(j,:,k,I_CVCLIQ)/frac_cv(j,k)
+                mr_hydro(j,:,k,I_CVCICE) = mr_hydro(j,:,k,I_CVCICE)/frac_cv(j,k)
+             endif
+             ! Precipitation
+             if (use_precipitation_fluxes) then
+                if (prec_ls(j,k) .ne. 0.) then
+                   fl_lsrain(j,k) = fl_lsrainIN(j,k)/prec_ls(j,k)
+                   fl_lssnow(j,k) = fl_lssnowIN(j,k)/prec_ls(j,k)
+                   fl_lsgrpl(j,k) = fl_lsgrplIN(j,k)/prec_ls(j,k)
+                endif
+                if (prec_cv(j,k) .ne. 0.) then
+                   fl_ccrain(j,k) = fl_ccrainIN(j,k)/prec_cv(j,k)
+                   fl_ccsnow(j,k) = fl_ccsnowIN(j,k)/prec_cv(j,k)
+                endif
+             else
+                if (prec_ls(j,k) .ne. 0.) then
+                   mr_hydro(j,:,k,I_LSRAIN) = mr_hydro(j,:,k,I_LSRAIN)/prec_ls(j,k)
+                   mr_hydro(j,:,k,I_LSSNOW) = mr_hydro(j,:,k,I_LSSNOW)/prec_ls(j,k)
+                   mr_hydro(j,:,k,I_LSGRPL) = mr_hydro(j,:,k,I_LSGRPL)/prec_ls(j,k)
+                endif
+                if (prec_cv(j,k) .ne. 0.) then
+                   mr_hydro(j,:,k,I_CVRAIN) = mr_hydro(j,:,k,I_CVRAIN)/prec_cv(j,k)
+                   mr_hydro(j,:,k,I_CVSNOW) = mr_hydro(j,:,k,I_CVSNOW)/prec_cv(j,k)
+                endif
+             endif
+          enddo
+       enddo
+
+       deallocate(frac_ls,prec_ls,frac_cv,prec_cv)
+
+       !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+       ! Convert precipitation fluxes to mixing ratios
+       !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+       if (use_precipitation_fluxes) then
+          ! LS rain
+          call cosp_precip_mxratio(nPoints, nLevels, nColumns, cospstateIN%pfull,        &
+               cospstateIN%at, frac_prec, 1._wp, n_ax(I_LSRAIN), n_bx(I_LSRAIN),         &
+               alpha_x(I_LSRAIN), c_x(I_LSRAIN),   d_x(I_LSRAIN),   g_x(I_LSRAIN),       &
+               a_x(I_LSRAIN),   b_x(I_LSRAIN),   gamma_1(I_LSRAIN), gamma_2(I_LSRAIN),   &
+               gamma_3(I_LSRAIN), gamma_4(I_LSRAIN), fl_lsrain,                          &
+               mr_hydro(:,:,:,I_LSRAIN), Reff(:,:,:,I_LSRAIN))
+          ! LS snow
+          call cosp_precip_mxratio(nPoints, nLevels, nColumns, cospstateIN%pfull,        &
+               cospstateIN%at, frac_prec, 1._wp,  n_ax(I_LSSNOW),  n_bx(I_LSSNOW),       &
+               alpha_x(I_LSSNOW), c_x(I_LSSNOW),  d_x(I_LSSNOW),  g_x(I_LSSNOW),         &
+               a_x(I_LSSNOW),   b_x(I_LSSNOW),   gamma_1(I_LSSNOW),  gamma_2(I_LSSNOW),  &
+               gamma_3(I_LSSNOW), gamma_4(I_LSSNOW), fl_lssnow,                          &
+               mr_hydro(:,:,:,I_LSSNOW), Reff(:,:,:,I_LSSNOW))
+          ! CV rain
+          call cosp_precip_mxratio(nPoints, nLevels, nColumns, cospstateIN%pfull,        &
+               cospstateIN%at, frac_prec, 2._wp, n_ax(I_CVRAIN),  n_bx(I_CVRAIN),        &
+               alpha_x(I_CVRAIN), c_x(I_CVRAIN),   d_x(I_CVRAIN),   g_x(I_CVRAIN),       &
+               a_x(I_CVRAIN),   b_x(I_CVRAIN),   gamma_1(I_CVRAIN), gamma_2(I_CVRAIN),   &
+               gamma_3(I_CVRAIN), gamma_4(I_CVRAIN), fl_ccrain,                          &
+               mr_hydro(:,:,:,I_CVRAIN), Reff(:,:,:,I_CVRAIN))
+          ! CV snow
+          call cosp_precip_mxratio(nPoints, nLevels, nColumns, cospstateIN%pfull,        &
+               cospstateIN%at, frac_prec, 2._wp, n_ax(I_CVSNOW),  n_bx(I_CVSNOW),        &
+               alpha_x(I_CVSNOW),  c_x(I_CVSNOW),   d_x(I_CVSNOW),   g_x(I_CVSNOW),      &
+               a_x(I_CVSNOW),   b_x(I_CVSNOW),   gamma_1(I_CVSNOW), gamma_2(I_CVSNOW),   &
+               gamma_3(I_CVSNOW), gamma_4(I_CVSNOW), fl_ccsnow,                          &
+               mr_hydro(:,:,:,I_CVSNOW), Reff(:,:,:,I_CVSNOW))
+          ! LS groupel.
+          call cosp_precip_mxratio(nPoints, nLevels, nColumns, cospstateIN%pfull,        &
+               cospstateIN%at, frac_prec, 1._wp, n_ax(I_LSGRPL),  n_bx(I_LSGRPL),        &
+               alpha_x(I_LSGRPL), c_x(I_LSGRPL),   d_x(I_LSGRPL),   g_x(I_LSGRPL),       &
+               a_x(I_LSGRPL),   b_x(I_LSGRPL),   gamma_1(I_LSGRPL),  gamma_2(I_LSGRPL),  &
+               gamma_3(I_LSGRPL), gamma_4(I_LSGRPL), fl_lsgrpl,                          &
+               mr_hydro(:,:,:,I_LSGRPL), Reff(:,:,:,I_LSGRPL))
+          deallocate(frac_prec)
+       endif
+
+    else
+       cospIN%frac_out(:,:,:) = 1  
+       allocate(mr_hydro(nPoints,1,nLevels,nHydro),Reff(nPoints,1,nLevels,nHydro),       &
+                Np(nPoints,1,nLevels,nHydro))
+       mr_hydro(:,1,:,I_LSCLIQ) = mr_lsliq
+       mr_hydro(:,1,:,I_LSCICE) = mr_lsice
+       mr_hydro(:,1,:,I_CVCLIQ) = mr_ccliq
+       mr_hydro(:,1,:,I_CVCICE) = mr_ccice
+       Reff(:,1,:,:)            = ReffIN
+    endif
+    
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! 11 micron emissivity
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if (cfg%Lisccp) then
+       call cosp_simulator_optics(nPoints,nColumns,nLevels,cospIN%frac_out,dem_c,dem_s,    &
+                                  cospIN%emiss_11)
+    endif
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! 0.67 micron optical depth
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if (cfg%Lisccp .or. cfg%Lmisr .or. cfg%Lmodis) then
+       call cosp_simulator_optics(nPoints,nColumns,nLevels,cospIN%frac_out,dtau_c,dtau_s,  &
+                                  cospIN%tau_067)
+    endif
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! LIDAR Polarized optics
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if (cfg%Lcalipso) then
+       call lidar_optics(nPoints, nColumns, nLevels, 4, lidar_ice_type, 532, .false.,      &
+            mr_hydro(:,:,:,I_LSCLIQ),  mr_hydro(:,:,:,I_LSCICE), mr_hydro(:,:,:,I_CVCLIQ), &
+            mr_hydro(:,:,:,I_CVCICE), ReffIN(:,:,I_LSCLIQ), ReffIN(:,:,I_LSCICE),          &
+            ReffIN(:,:,I_CVCLIQ), ReffIN(:,:,I_CVCICE), cospstateIN%pfull,                 &
+            cospstateIN%phalf, cospstateIN%at, cospIN%beta_mol_calipso,                    &
+            cospIN%betatot_calipso, cospIN%tau_mol_calipso, cospIN%tautot_calipso,         &
+            cospIN%tautot_S_liq, cospIN%tautot_S_ice, cospIN%betatot_ice_calipso,          &
+            cospIN%betatot_liq_calipso, cospIN%tautot_ice_calipso, cospIN%tautot_liq_calipso)
+    endif
+
+    if (cfg%LgrLidar532) then
+       call lidar_optics(nPoints, nColumns, nLevels, 4, lidar_ice_type, 532, .true.,       &
+            mr_hydro(:,:,:,I_LSCLIQ),  mr_hydro(:,:,:,I_LSCICE), mr_hydro(:,:,:,I_CVCLIQ), &
+            mr_hydro(:,:,:,I_CVCICE), ReffIN(:,:,I_LSCLIQ), ReffIN(:,:,I_LSCICE),          &
+            ReffIN(:,:,I_CVCLIQ), ReffIN(:,:,I_CVCICE), cospstateIN%pfull,                 &
+            cospstateIN%phalf, cospstateIN%at, cospIN%beta_mol_grLidar532,                 &
+            cospIN%betatot_grLidar532, cospIN%tau_mol_grLidar532, cospIN%tautot_grLidar532)
+    endif
+    
+    if (cfg%Latlid) then
+       call lidar_optics(nPoints, nColumns, nLevels, 4, lidar_ice_type, 355, .false.,      &
+            mr_hydro(:,:,:,I_LSCLIQ),  mr_hydro(:,:,:,I_LSCICE), mr_hydro(:,:,:,I_CVCLIQ), &
+            mr_hydro(:,:,:,I_CVCICE), ReffIN(:,:,I_LSCLIQ), ReffIN(:,:,I_LSCICE),          &
+            ReffIN(:,:,I_CVCLIQ), ReffIN(:,:,I_CVCICE), cospstateIN%pfull,                 &
+            cospstateIN%phalf, cospstateIN%at, cospIN%beta_mol_atlid, cospIN%betatot_atlid,&
+            cospIN%tau_mol_atlid, cospIN%tautot_atlid)
+    endif
+    
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! CLOUDSAT RADAR OPTICS
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if (cfg%Lcloudsat) then
+
+       ! Compute gaseous absorption (assume identical for each subcolun)
+       allocate(g_vol(nPoints,nLevels))
+       g_vol(:,:)=0._wp
+       do i=1,nPoints
+          do j=1,nLevels
+             if (cospIN%rcfg_cloudsat%use_gas_abs == 1 .or. (cospIN%rcfg_cloudsat%use_gas_abs == 2 .and. j .eq. 1)) then
+                g_vol(i,j) = gases(cospstateIN%pfull(i,j), cospstateIN%at(i,j),cospstateIN%qv(i,j),cospIN%rcfg_cloudsat%freq)
+             endif
+             cospIN%g_vol_cloudsat(i,:,j)=g_vol(i,j)
+          end do
+       end do
+       
+       ! Loop over all subcolumns
+       allocate(fracPrecipIce(nPoints,nColumns,nLevels))
+       fracPrecipIce(:,:,:) = 0._wp
+       do k=1,nColumns
+          call quickbeam_optics(sd, cospIN%rcfg_cloudsat, nPoints, nLevels, R_UNDEF,  &
+               mr_hydro(:,k,:,1:nHydro)*1000._wp, Reff(:,k,:,1:nHydro)*1.e6_wp,&
+               Np(:,k,:,1:nHydro), cospstateIN%pfull, cospstateIN%at,          &
+               cospstateIN%qv, cospIN%z_vol_cloudsat(1:nPoints,k,:),           &
+               cospIN%kr_vol_cloudsat(1:nPoints,k,:))
+          
+          ! At each model level, what fraction of the precipitation is frozen?
+          where(mr_hydro(:,k,:,I_LSRAIN) .gt. 0 .or. mr_hydro(:,k,:,I_LSSNOW) .gt. 0 .or. &
+                mr_hydro(:,k,:,I_CVRAIN) .gt. 0 .or. mr_hydro(:,k,:,I_CVSNOW) .gt. 0 .or. &
+                mr_hydro(:,k,:,I_LSGRPL) .gt. 0)
+             fracPrecipIce(:,k,:) = (mr_hydro(:,k,:,I_LSSNOW) + mr_hydro(:,k,:,I_CVSNOW) + &
+                  mr_hydro(:,k,:,I_LSGRPL)) / &
+                  (mr_hydro(:,k,:,I_LSSNOW) + mr_hydro(:,k,:,I_CVSNOW) + mr_hydro(:,k,:,I_LSGRPL) + &
+                  mr_hydro(:,k,:,I_LSRAIN)  + mr_hydro(:,k,:,I_CVRAIN))
+          elsewhere
+             fracPrecipIce(:,k,:) = 0._wp
+          endwhere
+       enddo
+
+       ! Regrid frozen fraction to Cloudsat/Calipso statistical grid
+       allocate(fracPrecipIce_statGrid(nPoints,nColumns,Nlvgrid))
+       fracPrecipIce_statGrid(:,:,:) = 0._wp
+       call cosp_change_vertical_grid(Npoints, Ncolumns, Nlevels, cospstateIN%hgt_matrix(:,Nlevels:1:-1), &
+            cospstateIN%hgt_matrix_half(:,Nlevels:1:-1), fracPrecipIce(:,:,Nlevels:1:-1), Nlvgrid,  &
+!            vgrid_zl(Nlvgrid:1:-1),  vgrid_zu(Nlvgrid:1:-1), fracPrecipIce_statGrid)  !!! ORIGINAL
+            vgrid_zl(Nlvgrid:1:-1),  vgrid_zu(Nlvgrid:1:-1), fracPrecipIce_statGrid(:,:,Nlvgrid:1:-1)) !DEBUG fracPrecipIce_statGrid
+
+       ! Find proper layer to compute precip flags in Cloudsat/Calipso statistical grid     !PREC_BUG
+       allocate(cloudsat_preclvl_index(nPoints))                                            !PREC_BUG
+       cloudsat_preclvl_index(:) = 0._wp                                                    !PREC_BUG
+       ! Computing altitude index for precip flags calculation (2nd layer above surfelev)   !PREC_BUG
+       cloudsat_preclvl_index(:) = 39 - floor( cospstateIN%surfelev(:)/480. )               !PREC_BUG
+
+       ! For near-surface diagnostics, we only need the frozen fraction at one layer.
+       do i=1,nPoints                                                                       !PREC_BUG
+	  cospIN%fracPrecipIce(i,:) = fracPrecipIce_statGrid(i,:,cloudsat_preclvl_index(i)) !PREC_BUG
+       enddo                                                                                !PREC_BUG
+!       cospIN%fracPrecipIce(:,:) = fracPrecipIce_statGrid(:,:,cloudsat_preclvl)      !!! ORIGINAL
+!       cospIN%fracPrecipIce(:,:) = fracPrecipIce_statGrid(:,:,2)                      !!! TEST ARTEM
+       
+    endif
+   
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ! MODIS optics
+    !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if (cfg%Lmodis) then
+       allocate(MODIS_cloudWater(nPoints,nColumns,nLevels),                                &
+                MODIS_cloudIce(nPoints,nColumns,nLevels),                                  &
+                MODIS_waterSize(nPoints,nColumns,nLevels),                                 &
+                MODIS_iceSize(nPoints,nColumns,nLevels),                                   &
+                MODIS_opticalThicknessLiq(nPoints,nColumns,nLevels),                       &
+                MODIS_opticalThicknessIce(nPoints,nColumns,nLevels))
+       ! Cloud water
+       call cosp_simulator_optics(nPoints,nColumns,nLevels,cospIN%frac_out,                &
+            mr_hydro(:,:,:,I_CVCLIQ),mr_hydro(:,:,:,I_LSCLIQ),MODIS_cloudWater)
+       ! Cloud ice
+       call cosp_simulator_optics(nPoints,nColumns,nLevels,cospIN%frac_out,                &
+            mr_hydro(:,:,:,I_CVCICE),mr_hydro(:,:,:,I_LSCICE),MODIS_cloudIce)  
+       ! Water droplet size
+       call cosp_simulator_optics(nPoints,nColumns,nLevels,cospIN%frac_out,                &
+            Reff(:,:,:,I_CVCLIQ),Reff(:,:,:,I_LSCLIQ),MODIS_waterSize)
+       ! Ice crystal size
+       call cosp_simulator_optics(nPoints,nColumns,nLevels,cospIN%frac_out,                &
+            Reff(:,:,:,I_CVCICE),Reff(:,:,:,I_LSCICE),MODIS_iceSize)
+       
+       ! Partition optical thickness into liquid and ice parts
+       call modis_optics_partition(nPoints, nLevels, nColumns, MODIS_cloudWater,           &
+            MODIS_cloudIce, MODIS_waterSize, MODIS_iceSize, cospIN%tau_067,                &
+            MODIS_opticalThicknessLiq, MODIS_opticalThicknessIce)
+       
+       ! Compute assymetry parameter and single scattering albedo 
+       call modis_optics(nPoints, nLevels, nColumns, MODIS_opticalThicknessLiq,            &
+            MODIS_waterSize*1.0e6_wp, MODIS_opticalThicknessIce,                           &
+            MODIS_iceSize*1.0e6_wp, cospIN%fracLiq, cospIN%asym, cospIN%ss_alb)
+       
+       ! Deallocate memory
+       deallocate(MODIS_cloudWater,MODIS_cloudIce,MODIS_WaterSize,MODIS_iceSize,           &
+            MODIS_opticalThicknessLiq,MODIS_opticalThicknessIce,mr_hydro,                  &
+            Np,Reff)
+    endif
+  end subroutine subsample_and_optics
+
+END MODULE LMDZ_COSP_SUBSAMPLE_AND_OPTICS_MOD
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/math_lib.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/math_lib.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/math_lib.F90	(revision 3605)
@@ -0,0 +1,404 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History:
+! July 2006: John Haynes      - Initial version
+! May 2015:  Dustin Swales    - Modified for COSPv2.0
+! 
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+module math_lib
+  USE COSP_KINDS,     ONLY: wp
+  use mod_cosp_error, ONLY: errorMessage
+  implicit none
+
+contains
+  ! ##########################################################################  
+  !                           function PATH_INTEGRAL 
+  ! ##########################################################################  
+  function path_integral(f,s,i1,i2)
+    use m_mrgrnk
+    use array_lib
+    implicit none
+    ! ########################################################################
+    ! Purpose:
+    !   evalues the integral (f ds) between f(index=i1) and f(index=i2)
+    !   using the AVINT procedure
+    !
+    ! Inputs:
+    !   [f]    functional values
+    !   [s]    abscissa values
+    !   [i1]   index of lower limit
+    !   [i2]   index of upper limit
+    !
+    ! Returns:
+    !   result of path integral
+    !
+    ! Notes:
+    !   [s] may be in forward or reverse numerical order
+    !
+    ! Requires:
+    !   mrgrnk package
+    !
+    ! Created:
+    !   02/02/06  John Haynes (haynes@atmos.colostate.edu)
+    ! ########################################################################
+
+    ! INPUTS
+    real(wp),intent(in), dimension(:) :: &
+         f,  & ! Functional values
+         s     ! Abscissa values  
+    integer, intent(in) :: &
+         i1, & ! Index of lower limit
+         i2    ! Index of upper limit
+
+    ! OUTPUTS
+    real(wp) :: path_integral  
+  
+    ! Internal variables
+    real(wp) :: sumo, deltah, val
+    integer :: nelm, j
+    integer, dimension(i2-i1+1) :: idx
+    real(wp), dimension(i2-i1+1) :: f_rev, s_rev
+
+    nelm = i2-i1+1
+    if (nelm > 3) then
+       call mrgrnk(s(i1:i2),idx)
+       s_rev = s(idx)
+       f_rev = f(idx)
+       call avint(f_rev(i1:i2),s_rev(i1:i2),(i2-i1+1), &
+            s_rev(i1),s_rev(i2), val)
+       path_integral = val
+    else
+       sumo = 0._wp
+       do j=i1,i2
+          deltah = abs(s(i1+1)-s(i1))
+          sumo = sumo + f(j)*deltah
+       enddo
+       path_integral = sumo
+    endif
+    
+    return
+  end function path_integral
+  
+  ! ##########################################################################
+  !                            subroutine AVINT
+  ! ##########################################################################
+  subroutine avint ( ftab, xtab, ntab, a_in, b_in, result )
+    implicit none
+    ! ########################################################################  
+    ! Purpose:
+    !   estimate the integral of unevenly spaced data
+    !
+    ! Inputs:
+    !   [ftab]     functional values
+    !   [xtab]     abscissa values
+    !   [ntab]     number of elements of [ftab] and [xtab]
+    !   [a]        lower limit of integration
+    !   [b]        upper limit of integration
+    !
+    ! Outputs:
+    !   [result]   approximate value of integral
+    !
+    ! Reference:
+    !   From SLATEC libraries, in public domain
+    !
+    !***********************************************************************
+    !
+    !  AVINT estimates the integral of unevenly spaced data.
+    !
+    !  Discussion:
+    !
+    !    The method uses overlapping parabolas and smoothing.
+    !
+    !  Modified:
+    !
+    !    30 October 2000
+    !    4 January 2008, A. Bodas-Salcedo. Error control for XTAB taken out of
+    !                    loop to allow vectorization.
+    !
+    !  Reference:
+    !
+    !    Philip Davis and Philip Rabinowitz,
+    !    Methods of Numerical Integration,
+    !    Blaisdell Publishing, 1967.
+    !
+    !    P E Hennion,
+    !    Algorithm 77,
+    !    Interpolation, Differentiation and Integration,
+    !    Communications of the Association for Computing Machinery,
+    !    Volume 5, page 96, 1962.
+    !
+    !  Parameters:
+    !
+    !    Input, real ( kind = 8 ) FTAB(NTAB), the function values,
+    !    FTAB(I) = F(XTAB(I)).
+    !
+    !    Input, real ( kind = 8 ) XTAB(NTAB), the abscissas at which the
+    !    function values are given.  The XTAB's must be distinct
+    !    and in ascending order.
+    !
+    !    Input, integer NTAB, the number of entries in FTAB and
+    !    XTAB.  NTAB must be at least 3.
+    !
+    !    Input, real ( kind = 8 ) A, the lower limit of integration.  A should
+    !    be, but need not be, near one endpoint of the interval
+    !    (X(1), X(NTAB)).
+    !
+    !    Input, real ( kind = 8 ) B, the upper limit of integration.  B should
+    !    be, but need not be, near one endpoint of the interval
+    !    (X(1), X(NTAB)).
+    !
+    !    Output, real ( kind = 8 ) RESULT, the approximate value of the integral.
+    ! ##########################################################################  
+
+    ! INPUTS
+    integer,intent(in) :: &
+         ntab    ! Number of elements of [ftab] and [xtab]
+    real(wp),intent(in) :: &
+         a_in, & ! Lower limit of integration
+         b_in    ! Upper limit of integration
+    real(wp),intent(in),dimension(ntab) :: &
+         ftab, & ! Functional values
+         xtab    ! Abscissa value
+    
+    ! OUTPUTS
+    real(wp),intent(out) :: result  ! Approximate value of integral
+
+    ! Internal varaibles
+    real(wp) :: a, atemp, b, btemp,ca,cb,cc,ctemp,sum1,syl,term1,term2,term3,x1,x2,x3
+    integer  :: i,ihi,ilo,ind
+    logical  :: lerror
+  
+    lerror = .false.
+    a = a_in
+    b = b_in  
+  
+    if ( ntab < 3 ) then
+       call errorMessage('FATAL ERROR(optics/math_lib.f90:AVINT): Ntab is less than 3.')
+       return
+    end if
+    
+    do i = 2, ntab
+       if ( xtab(i) <= xtab(i-1) ) then
+          lerror = .true.
+          exit
+       end if
+    end do
+    
+    if (lerror) then
+       call errorMessage('FATAL ERROR(optics/math_lib.f90:AVINT): Xtab(i) is not greater than Xtab(i-1).')
+       return
+    end if
+    
+!ds    result = 0.0D+00
+    result = 0._wp
+    
+    if ( a == b ) then
+       call errorMessage('WARNING(optics/math_lib.f90:AVINT): A=B => integral=0')
+       return
+    end if
+    
+    !  If B < A, temporarily switch A and B, and store sign.
+    if ( b < a ) then
+       syl = b
+       b = a
+       a = syl
+       ind = -1
+    else
+       syl = a
+       ind = 1
+    end if
+    
+    !  Bracket A and B between XTAB(ILO) and XTAB(IHI).
+    ilo = 1
+    ihi = ntab
+    
+    do i = 1, ntab
+       if ( a <= xtab(i) ) then
+          exit
+       end if
+       ilo = ilo + 1
+    end do
+    
+    ilo = max ( 2, ilo )
+    ilo = min ( ilo, ntab - 1 )
+    
+    do i = 1, ntab
+       if ( xtab(i) <= b ) then
+          exit
+       end if
+       ihi = ihi - 1
+    end do
+    
+    ihi = min ( ihi, ntab - 1 )
+    ihi = max ( ilo, ihi - 1 )
+    
+    !  Carry out approximate integration from XTAB(ILO) to XTAB(IHI).
+    sum1 = 0._wp
+!ds    sum1 = 0.0D+00
+    
+    do i = ilo, ihi
+       
+       x1 = xtab(i-1)
+       x2 = xtab(i)
+       x3 = xtab(i+1)
+       
+       term1 = ftab(i-1) / ( ( x1 - x2 ) * ( x1 - x3 ) )
+       term2 = ftab(i)   / ( ( x2 - x1 ) * ( x2 - x3 ) )
+       term3 = ftab(i+1) / ( ( x3 - x1 ) * ( x3 - x2 ) )
+       
+       atemp = term1 + term2 + term3
+       
+       btemp = - ( x2 + x3 ) * term1 &
+            - ( x1 + x3 ) * term2 &
+            - ( x1 + x2 ) * term3
+       
+       ctemp = x2 * x3 * term1 + x1 * x3 * term2 + x1 * x2 * term3
+       
+       if ( i <= ilo ) then
+          ca = atemp
+          cb = btemp
+          cc = ctemp
+       else
+          ca = 0.5_wp * ( atemp + ca )
+          cb = 0.5_wp * ( btemp + cb )
+          cc = 0.5_wp * ( ctemp + cc )
+!ds          ca = 0.5D+00 * ( atemp + ca )
+!ds          cb = 0.5D+00 * ( btemp + cb )
+!ds          cc = 0.5D+00 * ( ctemp + cc )
+       end if
+       
+       sum1 = sum1 + ca * ( x2**3 - syl**3 ) / 3._wp &
+            + cb * 0.5_wp * ( x2**2 - syl**2 ) + cc * ( x2 - syl )
+!ds       sum1 = sum1 + ca * ( x2**3 - syl**3 ) / 3.0D+00 &
+!ds            + cb * 0.5D+00 * ( x2**2 - syl**2 ) + cc * ( x2 - syl )
+       
+       ca = atemp
+       cb = btemp
+       cc = ctemp
+       
+       syl = x2
+       
+    end do
+
+    result = sum1 + ca * ( b**3 - syl**3 ) / 3._wp &
+         + cb * 0.5_wp * ( b**2 - syl**2 ) + cc * ( b - syl )
+!ds    result = sum1 + ca * ( b**3 - syl**3 ) / 3.0D+00 &
+!ds         + cb * 0.5D+00 * ( b**2 - syl**2 ) + cc * ( b - syl )
+
+    !  Restore original values of A and B, reverse sign of integral
+    !  because of earlier switch.
+    if ( ind /= 1 ) then
+       ind = 1
+       syl = b
+       b = a
+       a = syl
+       result = -result
+    end if
+    
+    return
+  end subroutine avint
+  ! ######################################################################################
+  ! SUBROUTINE gamma
+  ! Purpose:
+  !   Returns the gamma function
+  !
+  ! Input:
+  !   [x]   value to compute gamma function of
+  !
+  ! Returns:
+  !   gamma(x)
+  !
+  ! Coded:
+  !   02/02/06  John Haynes (haynes@atmos.colostate.edu)
+  !   (original code of unknown origin)
+  ! ######################################################################################
+  function gamma(x)
+    ! Inputs 
+    real(wp), intent(in) :: x
+
+    ! Outputs
+    real(wp) :: gamma
+    
+    ! Local variables
+    real(wp) :: pi,ga,z,r,gr
+    integer  :: k,m1,m  
+    
+    ! Parameters
+    real(wp),dimension(26),parameter :: &
+         g = (/1.0,0.5772156649015329, -0.6558780715202538, -0.420026350340952e-1,     &
+               0.1665386113822915,-0.421977345555443e-1,-0.96219715278770e-2,              &
+               0.72189432466630e-2,-0.11651675918591e-2, -0.2152416741149e-3,                &
+               0.1280502823882e-3, -0.201348547807e-4, -0.12504934821e-5, 0.11330272320e-5,  &
+               -0.2056338417e-6, 0.61160950e-8,0.50020075e-8, -0.11812746e-8, 0.1043427e-9,   &
+               0.77823e-11, -0.36968e-11, 0.51e-12, -0.206e-13, -0.54e-14, 0.14e-14, 0.1e-15/)  
+!ds    real(wp),dimension(26),parameter :: &
+!ds         g = (/1.0d0,0.5772156649015329d0, -0.6558780715202538d0, -0.420026350340952d-1,     &
+!ds               0.1665386113822915d0,-0.421977345555443d-1,-0.96219715278770d-2,              &
+!ds               0.72189432466630d-2,-0.11651675918591d-2, -0.2152416741149d-3,                &
+!ds               0.1280502823882d-3, -0.201348547807d-4, -0.12504934821d-5, 0.11330272320d-5,  &
+!ds               -0.2056338417d-6, 0.61160950d-8,0.50020075d-8, -0.11812746d-8, 0.1043427d-9,   &
+!ds               0.77823d-11, -0.36968d-11, 0.51d-12, -0.206d-13, -0.54d-14, 0.14d-14, 0.1d-15/)  
+    
+    pi = acos(-1._wp)    
+    if (x ==int(x)) then
+       if (x > 0.0) then
+          ga=1._wp
+          m1=x-1
+          do k=2,m1
+             ga=ga*k
+          enddo
+       else
+          ga=1._wp+300
+       endif
+    else
+       if (abs(x) > 1.0) then
+          z=abs(x)
+          m=int(z)
+          r=1._wp
+          do k=1,m
+             r=r*(z-k)
+          enddo
+          z=z-m
+       else
+          z=x
+       endif
+       gr=g(26)
+       do k=25,1,-1
+          gr=gr*z+g(k)
+       enddo
+       ga=1._wp/(gr*z)
+       if (abs(x) > 1.0) then
+          ga=ga*r
+          if (x < 0.0) ga=-pi/(x*ga*sin(pi*x))
+       endif
+    endif
+    gamma = ga
+    return
+  end function gamma
+end module math_lib
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/mo_rng.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/mo_rng.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/mo_rng.F90	(revision 3605)
@@ -0,0 +1,138 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History:
+! May 2015- D. Swales - Original version
+! 
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MODULE mod_rng
+  USE cosp_kinds, ONLY: dp, sp, wp 
+  IMPLICIT NONE 
+
+  INTEGER, parameter :: ki9    = selected_int_kind(R=9)
+  integer :: testInt
+  
+  TYPE rng_state
+     INTEGER(ki9) :: seed ! 32 bit integer
+  END TYPE rng_state
+  
+  INTERFACE init_rng
+     MODULE PROCEDURE init_rng_1, init_rng_n
+  END INTERFACE init_rng
+  
+  INTERFACE get_rng
+     MODULE PROCEDURE get_rng_1, get_rng_n, get_rng_v
+  END INTERFACE get_rng
+  
+CONTAINS 
+  
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! Set single seed
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  SUBROUTINE init_rng_1(s, seed_in)
+    TYPE(rng_state), INTENT(INOUT) :: s
+    INTEGER,         INTENT(IN   ) :: seed_in
+    s%seed = seed_in     
+  END SUBROUTINE init_rng_1
+  
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! Set vector of seeds
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  SUBROUTINE init_rng_n(s, seed_in)
+    TYPE(rng_state), DIMENSION(:), INTENT(INOUT) :: s
+    INTEGER,         DIMENSION(:), INTENT(IN   ) :: seed_in
+    
+    INTEGER :: i 
+    DO i = 1, SIZE(seed_in)
+       s(i)%seed = seed_in(i) 
+    END DO
+  END SUBROUTINE init_rng_n
+  
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! Create single random number from seed
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  FUNCTION get_rng_1(s)  
+    TYPE(rng_state), INTENT(INOUT) :: s
+    REAL(WP)                       :: get_rng_1
+    REAL(SP)                       :: r
+
+    ! Return the next random numbers     
+    ! Marsaglia CONG algorithm
+    s%seed=69069*s%seed+1234567
+    ! mod 32 bit overflow
+    s%seed=mod(s%seed,2_ki9**30_ki9)   
+    r = s%seed*0.931322574615479E-09
+
+    ! convert to range 0-1 (32 bit only)
+    ! DJS2016: What is being done here is an intentional integer overflow and a test to
+    !          see if this occured. Some compilers check for integer overflows during
+    !          compilation (ie. gfortan), while others do not (ie. pgi and ifort). When
+    !          using gfortran, you cannot use the overflow and test for overflow method,
+    !          so we use sizeof(someInt) to determine wheter it is on 32 bit.
+    !if ( i2_16*i2_16 .le. huge32 ) then
+    if (digits(testInt) .le. 31) then
+    !if (sizeof(testInt) .eq. 4) then
+       r=r+1
+       r=r-int(r)
+    endif
+    get_rng_1 = REAL(r, KIND = WP) 
+    
+  END FUNCTION get_rng_1
+  
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! Create single random number N times
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  FUNCTION get_rng_n(s, n) RESULT (r) 
+    integer,intent(inout) :: n
+    TYPE(rng_state),INTENT(INOUT) :: s
+    ! Return the next N random numbers 
+    REAL(WP), DIMENSION (n)        :: r
+    
+    INTEGER :: i 
+    
+    DO i = 1, N
+       r(i) = get_rng_1(s)
+    END DO
+  END FUNCTION get_rng_n
+  
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  ! Create a vector of random numbers from a vector of input seeds
+  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  FUNCTION get_rng_v(s) RESULT (r) 
+    ! Return the next N random numbers 
+    TYPE(rng_state), DIMENSION(:), INTENT(INOUT) :: s
+    REAL(WP),        DIMENSION (SIZE(S))         :: r
+    
+    INTEGER :: i
+    
+    DO i = 1, size(s)
+       r(i) = get_rng_1(s(i))
+    END DO
+  END FUNCTION get_rng_v
+  
+END MODULE mod_rng
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/modis_simulator.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/modis_simulator.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/modis_simulator.F90	(revision 3605)
@@ -0,0 +1,906 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History
+! May 2009:      Robert Pincus - Initial version
+! June 2009:     Steve Platnick and Robert Pincus - Simple radiative transfer for size 
+!                retrievals
+! August 2009:   Robert Pincus - Consistency and bug fixes suggested by Rick Hemler (GFDL) 
+! November 2009: Robert Pincus - Bux fixes and speed-ups after experience with Rick Hemler 
+!                using AM2 (GFDL) 
+! January 2010:  Robert Pincus - Added high, middle, low cloud fractions
+! May 2015:      Dustin Swales - Modified for COSPv2.0
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+!
+! Notes on using the MODIS simulator: 
+!  *) You may provide either layer-by-layer values of optical thickness at 0.67 and 2.1
+!     microns, or optical thickness at 0.67 microns and ice- and liquid-water contents 
+!     (in consistent units of your choosing)
+!  *) Required input also includes the optical thickness and cloud top pressure 
+!     derived from the ISCCP simulator run with parameter top_height = 1. 
+!  *) Cloud particle sizes are specified as radii, measured in meters, though within the 
+!     module we use units of microns. Where particle sizes are outside the bounds used in 
+!     the MODIS retrieval libraries (parameters re_water_min, re_ice_min, etc.) the 
+!     simulator returns missing values (re_fill)
+!
+! When error conditions are encountered this code calls the function complain_and_die, 
+! supplied at the bottom of this module. Users probably want to replace this with 
+! something more graceful. 
+!
+module mod_modis_sim
+  USE MOD_COSP_CONFIG, only: R_UNDEF,modis_histTau,modis_histPres,numMODISTauBins,       &
+                             numMODISPresBins,numMODISReffIceBins,numMODISReffLiqBins,   &
+                             modis_histReffIce,modis_histReffLiq
+  USE COSP_KINDS,      ONLY: wp
+  use MOD_COSP_STATS,  ONLY: hist2D
+
+  implicit none
+  ! ##########################################################################
+  ! Retrieval parameters
+   integer, parameter :: &
+        num_trial_res = 15              ! Increase to make the linear pseudo-retrieval of size more accurate
+   
+   real(wp) :: &
+       min_OpticalThickness,          & ! Minimum detectable optical thickness
+       CO2Slicing_PressureLimit,      & ! Cloud with higher pressures use thermal methods, units Pa
+       CO2Slicing_TauLimit,           & ! How deep into the cloud does CO2 slicing see? 
+       phase_TauLimit,                & ! How deep into the cloud does the phase detection see?
+       size_TauLimit,                 & ! Depth of the re retreivals
+       phaseDiscrimination_Threshold, & ! What fraction of total extincton needs to be in a single
+                                        ! category to make phase discrim. work? 
+       re_fill,                       & !
+       re_water_min,                  & ! Minimum effective radius (liquid)
+       re_water_max,                  & ! Maximum effective radius (liquid)
+       re_ice_min,                    & ! Minimum effective radius (ice)
+       re_ice_max,                    & ! Minimum effective radius (ice)
+       highCloudPressureLimit,        & ! High cloud pressure limit (Pa)
+       lowCloudPressureLimit            ! Low cloud pressure limit (Pa)
+  integer :: &
+       phaseIsNone,                   & !
+       phaseIsLiquid,                 & !
+       phaseIsIce,                    & !
+       phaseIsUndetermined              !
+ 
+  real(wp),dimension(num_trial_res) :: &
+       trial_re_w, & ! Near-IR optical params vs size for retrieval scheme (liquid)
+       trial_re_i    ! Near-IR optical params vs size for retrieval scheme (ice)
+  real(wp),dimension(num_trial_res) :: &
+       g_w,        & ! Assymettry parameter for size retrieval (liquid)
+       g_i,        & ! Assymettry parameter for size retrieval (ice)
+       w0_w,       & ! Single-scattering albedo for size retrieval (liquid)
+       w0_i          ! Single-scattering albedo for size retrieval (ice)
+  ! Algorithmic parameters
+  real(wp),parameter :: &
+     ice_density = 0.93_wp ! Liquid density is 1. 
+      
+contains
+  ! ########################################################################################
+  ! MODIS simulator using specified liquid and ice optical thickness in each layer 
+  !
+  ! Note: this simulator operates on all points; to match MODIS itself night-time 
+  !       points should be excluded
+  !
+  ! Note: the simulator requires as input the optical thickness and cloud top pressure 
+  !       derived from the ISCCP simulator run with parameter top_height = 1. 
+  !       If cloud top pressure is higher than about 700 mb, MODIS can't use CO2 slicing 
+  !       and reverts to a thermal algorithm much like ISCCP's. Rather than replicate that 
+  !       alogrithm in this simulator we simply report the values from the ISCCP simulator. 
+  ! ########################################################################################
+  subroutine modis_subcolumn(nSubCols, nLevels, pressureLevels, optical_thickness,       & 
+                         tauLiquidFraction, g, w0,isccpCloudTopPressure,                 &
+                         retrievedPhase, retrievedCloudTopPressure,                      &
+                         retrievedTau,   retrievedSize)
+
+    ! INPUTS
+    integer,intent(in) :: &
+         nSubCols,                  & ! Number of subcolumns
+         nLevels                      ! Number of levels         
+    real(wp),dimension(nLevels+1),intent(in) :: &
+         pressureLevels               ! Gridmean pressure at layer edges (Pa)                  
+    real(wp),dimension(nSubCols,nLevels),intent(in) :: &
+         optical_thickness,         & ! Subcolumn optical thickness @ 0.67 microns.
+         tauLiquidFraction,         & ! Liquid water fraction
+         g,                         & ! Subcolumn assymetry parameter  
+         w0                           ! Subcolumn single-scattering albedo 
+    real(wp),dimension(nSubCols),intent(in) :: &
+         isccpCloudTopPressure        ! ISCCP retrieved cloud top pressure (Pa)
+
+    ! OUTPUTS
+    integer, dimension(nSubCols), intent(inout) :: &
+         retrievedPhase               ! MODIS retrieved phase (liquid/ice/other)              
+    real(wp),dimension(nSubCols), intent(inout) :: &
+         retrievedCloudTopPressure, & ! MODIS retrieved CTP (Pa)
+         retrievedTau,              & ! MODIS retrieved optical depth (unitless)              
+         retrievedSize                ! MODIS retrieved particle size (microns)              
+
+    ! LOCAL VARIABLES
+    logical, dimension(nSubCols)      :: &
+         cloudMask
+    real(wp)                          :: &
+         integratedLiquidFraction,       &
+         obs_Refl_nir
+    real(wp),dimension(num_trial_res) :: &
+         predicted_Refl_nir
+    integer                           :: &
+         i
+
+    ! ########################################################################################
+    !                           Optical depth retrieval 
+    ! This is simply a sum over the optical thickness in each layer. 
+    ! It should agree with the ISCCP values after min values have been excluded.
+    ! ########################################################################################
+    retrievedTau(1:nSubCols) = sum(optical_thickness(1:nSubCols,1:nLevels), dim = 2)
+
+    ! ########################################################################################
+    !                                 Cloud detection
+    ! does optical thickness exceed detection threshold? 
+    ! ########################################################################################
+    cloudMask = retrievedTau(1:nSubCols) >= min_OpticalThickness
+    
+    do i = 1, nSubCols
+       if(cloudMask(i)) then 
+          ! ##################################################################################
+          !                       Cloud top pressure determination 
+          ! MODIS uses CO2 slicing for clouds with tops above about 700 mb and thermal 
+          ! methods for clouds lower than that. For CO2 slicing we report the optical-depth
+          ! weighted pressure, integrating to a specified optical depth.
+          ! This assumes linear variation in p between levels. Linear in ln(p) is probably 
+          ! better, though we'd need to deal with the lowest pressure gracefully. 
+          ! ##################################################################################
+          retrievedCloudTopPressure(i) = cloud_top_pressure(nLevels,(/ 0._wp, optical_thickness(i,1:nLevels) /), &
+                                                            pressureLevels(1:nLevels),CO2Slicing_TauLimit)  
+        
+          ! ##################################################################################
+          !                               Phase determination 
+          ! Determine fraction of total tau that's liquid when ice and water contribute about 
+          ! equally to the extinction we can't tell what the phase is.
+          ! ##################################################################################
+          integratedLiquidFraction = weight_by_extinction(nLevels,optical_thickness(i,1:nLevels),       &
+                                                          tauLiquidFraction(i, 1:nLevels), &
+                                                          phase_TauLimit)
+          if(integratedLiquidFraction >= phaseDiscrimination_Threshold) then 
+             retrievedPhase(i) = phaseIsLiquid
+          else if (integratedLiquidFraction <= 1._wp- phaseDiscrimination_Threshold) then 
+             retrievedPhase(i) = phaseIsIce
+          else 
+             retrievedPhase(i) = phaseIsUndetermined
+          end if
+        
+          ! ##################################################################################
+          !                                 Size determination 
+          ! ##################################################################################
+          
+          ! Compute observed reflectance
+          obs_Refl_nir = compute_toa_reflectace(nLevels,optical_thickness(i,1:nLevels), g(i,1:nLevels), w0(i,1:nLevels))
+
+          ! Compute predicted reflectance
+          if(any(retrievedPhase(i) == (/ phaseIsLiquid, phaseIsUndetermined, phaseIsIce /))) then 
+             if (retrievedPhase(i) == phaseIsLiquid .OR. retrievedPhase(i) == phaseIsUndetermined) then
+                predicted_Refl_nir(1:num_trial_res) = two_stream_reflectance(retrievedTau(i), &
+                     g_w(1:num_trial_res), w0_w(1:num_trial_res))
+                retrievedSize(i) = 1.0e-06_wp*interpolate_to_min(trial_re_w(1:num_trial_res), &
+                     predicted_Refl_nir(1:num_trial_res), obs_Refl_nir)
+             else
+                predicted_Refl_nir(1:num_trial_res) = two_stream_reflectance(retrievedTau(i), &
+                     g_i(1:num_trial_res), w0_i(1:num_trial_res))
+                retrievedSize(i) = 1.0e-06_wp*interpolate_to_min(trial_re_i(1:num_trial_res), &
+                     predicted_Refl_nir(1:num_trial_res), obs_Refl_nir)
+             endif
+          else 
+             retrievedSize(i) = re_fill
+          endif
+       else   
+          ! Values when we don't think there's a cloud. 
+          retrievedCloudTopPressure(i) = R_UNDEF 
+          retrievedPhase(i)            = phaseIsNone
+          retrievedSize(i)             = R_UNDEF 
+          retrievedTau(i)              = R_UNDEF 
+       end if
+    end do
+    where((retrievedSize(1:nSubCols) < 0.).and.(retrievedSize(1:nSubCols) /= R_UNDEF)) &
+         retrievedSize(1:nSubCols) = 1.0e-06_wp*re_fill
+
+    ! We use the ISCCP-derived CTP for low clouds, since the ISCCP simulator ICARUS 
+    ! mimics what MODIS does to first order. 
+    ! Of course, ISCCP cloud top pressures are in mb.   
+    where(cloudMask(1:nSubCols) .and. retrievedCloudTopPressure(1:nSubCols) > CO2Slicing_PressureLimit) &
+         retrievedCloudTopPressure(1:nSubCols) = isccpCloudTopPressure! * 100._wp
+    
+  end subroutine modis_subcolumn
+
+  ! ########################################################################################
+  subroutine modis_column(nPoints,nSubCols,phase, cloud_top_pressure, optical_thickness, particle_size,     &
+       Cloud_Fraction_Total_Mean,         Cloud_Fraction_Water_Mean,         Cloud_Fraction_Ice_Mean,        &
+       Cloud_Fraction_High_Mean,          Cloud_Fraction_Mid_Mean,           Cloud_Fraction_Low_Mean,        &
+       Optical_Thickness_Total_Mean,      Optical_Thickness_Water_Mean,      Optical_Thickness_Ice_Mean,     &
+       Optical_Thickness_Total_MeanLog10, Optical_Thickness_Water_MeanLog10, Optical_Thickness_Ice_MeanLog10,&
+       Cloud_Particle_Size_Water_Mean,    Cloud_Particle_Size_Ice_Mean,      Cloud_Top_Pressure_Total_Mean,  &
+       Liquid_Water_Path_Mean,            Ice_Water_Path_Mean,                                               &    
+       Optical_Thickness_vs_Cloud_Top_Pressure,Optical_Thickness_vs_ReffIce,Optical_Thickness_vs_ReffLiq)
+    
+    ! INPUTS
+    integer,intent(in) :: &
+         nPoints,                           & ! Number of horizontal gridpoints
+         nSubCols                             ! Number of subcolumns
+    integer,intent(in), dimension(nPoints, nSubCols) ::  &
+         phase                             
+    real(wp),intent(in),dimension(nPoints, nSubCols) ::  &
+         cloud_top_pressure,                &
+         optical_thickness,                 &
+         particle_size
+ 
+    ! OUTPUTS 
+    real(wp),intent(inout),dimension(nPoints)  ::   & !
+         Cloud_Fraction_Total_Mean,         & !
+         Cloud_Fraction_Water_Mean,         & !
+         Cloud_Fraction_Ice_Mean,           & !
+         Cloud_Fraction_High_Mean,          & !
+         Cloud_Fraction_Mid_Mean,           & !
+         Cloud_Fraction_Low_Mean,           & !
+         Optical_Thickness_Total_Mean,      & !
+         Optical_Thickness_Water_Mean,      & !
+         Optical_Thickness_Ice_Mean,        & !
+         Optical_Thickness_Total_MeanLog10, & !
+         Optical_Thickness_Water_MeanLog10, & !
+         Optical_Thickness_Ice_MeanLog10,   & !
+         Cloud_Particle_Size_Water_Mean,    & !
+         Cloud_Particle_Size_Ice_Mean,      & !
+         Cloud_Top_Pressure_Total_Mean,     & !
+         Liquid_Water_Path_Mean,            & !
+         Ice_Water_Path_Mean                  !
+    real(wp),intent(inout),dimension(nPoints,numMODISTauBins,numMODISPresBins) :: &
+         Optical_Thickness_vs_Cloud_Top_Pressure
+    real(wp),intent(inout),dimension(nPoints,numMODISTauBins,numMODISReffIceBins) :: &    
+         Optical_Thickness_vs_ReffIce
+    real(wp),intent(inout),dimension(nPoints,numMODISTauBins,numMODISReffLiqBins) :: &    
+         Optical_Thickness_vs_ReffLiq         
+
+    ! LOCAL VARIABLES
+    real(wp), parameter :: &
+         LWP_conversion = 2._wp/3._wp * 1000._wp ! MKS units  
+    integer :: j
+    logical, dimension(nPoints,nSubCols) :: &
+         cloudMask,      &
+         waterCloudMask, &
+         iceCloudMask,   &
+         validRetrievalMask
+    real(wp),dimension(nPoints,nSubCols) :: &
+         tauWRK,ctpWRK,reffIceWRK,reffLiqWRK
+
+    ! ########################################################################################
+    ! Include only those pixels with successful retrievals in the statistics 
+    ! ########################################################################################
+    validRetrievalMask(1:nPoints,1:nSubCols) = particle_size(1:nPoints,1:nSubCols) > 0.
+    cloudMask(1:nPoints,1:nSubCols) = phase(1:nPoints,1:nSubCols) /= phaseIsNone .and.       &
+         validRetrievalMask(1:nPoints,1:nSubCols)
+    waterCloudMask(1:nPoints,1:nSubCols) = phase(1:nPoints,1:nSubCols) == phaseIsLiquid .and. &
+         validRetrievalMask(1:nPoints,1:nSubCols)
+    iceCloudMask(1:nPoints,1:nSubCols)   = phase(1:nPoints,1:nSubCols) == phaseIsIce .and.    &
+         validRetrievalMask(1:nPoints,1:nSubCols)
+    
+    ! ########################################################################################
+    ! Use these as pixel counts at first 
+    ! ########################################################################################
+    Cloud_Fraction_Total_Mean(1:nPoints) = real(count(cloudMask,      dim = 2))
+    Cloud_Fraction_Water_Mean(1:nPoints) = real(count(waterCloudMask, dim = 2))
+    Cloud_Fraction_Ice_Mean(1:nPoints)   = real(count(iceCloudMask,   dim = 2))
+    Cloud_Fraction_High_Mean(1:nPoints)  = real(count(cloudMask .and. cloud_top_pressure <=          &
+                                           highCloudPressureLimit, dim = 2)) 
+    Cloud_Fraction_Low_Mean(1:nPoints)   = real(count(cloudMask .and. cloud_top_pressure >           &
+                                           lowCloudPressureLimit,  dim = 2)) 
+    Cloud_Fraction_Mid_Mean(1:nPoints)   = Cloud_Fraction_Total_Mean(1:nPoints) - Cloud_Fraction_High_Mean(1:nPoints)&
+                                           - Cloud_Fraction_Low_Mean(1:nPoints)
+
+    ! ########################################################################################
+    ! Compute column amounts.
+    ! ########################################################################################
+    where(Cloud_Fraction_Total_Mean(1:nPoints) > 0)
+       Optical_Thickness_Total_Mean(1:nPoints) = sum(optical_thickness, mask = cloudMask,      dim = 2) / &
+            Cloud_Fraction_Total_Mean(1:nPoints)
+       Optical_Thickness_Total_MeanLog10(1:nPoints) = sum(log10(abs(optical_thickness)), mask = cloudMask, &
+            dim = 2) / Cloud_Fraction_Total_Mean(1:nPoints)
+    elsewhere
+       Optical_Thickness_Total_Mean      = R_UNDEF
+       Optical_Thickness_Total_MeanLog10 = R_UNDEF
+    endwhere
+    where(Cloud_Fraction_Water_Mean(1:nPoints) > 0)
+       Optical_Thickness_Water_Mean(1:nPoints) = sum(optical_thickness, mask = waterCloudMask, dim = 2) / &
+            Cloud_Fraction_Water_Mean(1:nPoints)
+       Liquid_Water_Path_Mean(1:nPoints) = LWP_conversion*sum(particle_size*optical_thickness, &
+            mask=waterCloudMask,dim=2)/Cloud_Fraction_Water_Mean(1:nPoints)
+       Optical_Thickness_Water_MeanLog10(1:nPoints) = sum(log10(abs(optical_thickness)), mask = waterCloudMask,&
+            dim = 2) / Cloud_Fraction_Water_Mean(1:nPoints)
+       Cloud_Particle_Size_Water_Mean(1:nPoints) = sum(particle_size, mask = waterCloudMask, dim = 2) / &
+            Cloud_Fraction_Water_Mean(1:nPoints)
+    elsewhere
+       Optical_Thickness_Water_Mean      = R_UNDEF
+       Optical_Thickness_Water_MeanLog10 = R_UNDEF
+       Cloud_Particle_Size_Water_Mean    = R_UNDEF
+       Liquid_Water_Path_Mean            = R_UNDEF
+    endwhere
+    where(Cloud_Fraction_Ice_Mean(1:nPoints) > 0)
+       Optical_Thickness_Ice_Mean(1:nPoints)   = sum(optical_thickness, mask = iceCloudMask,   dim = 2) / &
+            Cloud_Fraction_Ice_Mean(1:nPoints)
+       Ice_Water_Path_Mean(1:nPoints) = LWP_conversion * ice_density*sum(particle_size*optical_thickness,&
+            mask=iceCloudMask,dim = 2) /Cloud_Fraction_Ice_Mean(1:nPoints) 
+       Optical_Thickness_Ice_MeanLog10(1:nPoints) = sum(log10(abs(optical_thickness)), mask = iceCloudMask,&
+            dim = 2) / Cloud_Fraction_Ice_Mean(1:nPoints)
+       Cloud_Particle_Size_Ice_Mean(1:nPoints) = sum(particle_size, mask = iceCloudMask,   dim = 2) / &
+            Cloud_Fraction_Ice_Mean(1:nPoints)    
+    elsewhere
+       Optical_Thickness_Ice_Mean        = R_UNDEF
+       Optical_Thickness_Ice_MeanLog10   = R_UNDEF
+       Cloud_Particle_Size_Ice_Mean      = R_UNDEF
+       Ice_Water_Path_Mean               = R_UNDEF
+    endwhere
+    Cloud_Top_Pressure_Total_Mean  = sum(cloud_top_pressure, mask = cloudMask, dim = 2) / &
+                                     max(1, count(cloudMask, dim = 2))
+
+    ! ########################################################################################
+    ! Normalize pixel counts to fraction. 
+    ! ########################################################################################
+    Cloud_Fraction_High_Mean(1:nPoints)  = Cloud_Fraction_High_Mean(1:nPoints)  /nSubcols
+    Cloud_Fraction_Mid_Mean(1:nPoints)   = Cloud_Fraction_Mid_Mean(1:nPoints)   /nSubcols
+    Cloud_Fraction_Low_Mean(1:nPoints)   = Cloud_Fraction_Low_Mean(1:nPoints)   /nSubcols
+    Cloud_Fraction_Total_Mean(1:nPoints) = Cloud_Fraction_Total_Mean(1:nPoints) /nSubcols
+    Cloud_Fraction_Ice_Mean(1:nPoints)   = Cloud_Fraction_Ice_Mean(1:nPoints)   /nSubcols
+    Cloud_Fraction_Water_Mean(1:nPoints) = Cloud_Fraction_Water_Mean(1:nPoints) /nSubcols
+    
+    ! ########################################################################################
+    ! Joint histograms
+    ! ########################################################################################
+    ! Loop over all points
+    tauWRK(1:nPoints,1:nSubCols)     = optical_thickness(1:nPoints,1:nSubCols)
+    ctpWRK(1:nPoints,1:nSubCols)     = cloud_top_pressure(1:nPoints,1:nSubCols)
+    reffIceWRK(1:nPoints,1:nSubCols) = merge(particle_size,R_UNDEF,iceCloudMask)
+    reffLiqWRK(1:nPoints,1:nSubCols) = merge(particle_size,R_UNDEF,waterCloudMask)
+    do j=1,nPoints
+
+       ! Fill clear and optically thin subcolumns with fill
+       where(.not. cloudMask(j,1:nSubCols)) 
+          tauWRK(j,1:nSubCols) = -999._wp
+          ctpWRK(j,1:nSubCols) = -999._wp
+       endwhere
+       ! Joint histogram of tau/CTP
+       call hist2D(tauWRK(j,1:nSubCols),ctpWRK(j,1:nSubCols),nSubCols,&
+                   modis_histTau,numMODISTauBins,&
+                   modis_histPres,numMODISPresBins,&
+                   Optical_Thickness_vs_Cloud_Top_Pressure(j,1:numMODISTauBins,1:numMODISPresBins))
+       ! Joint histogram of tau/ReffICE
+       call hist2D(tauWRK(j,1:nSubCols),reffIceWrk(j,1:nSubCols),nSubCols,               &
+                   modis_histTau,numMODISTauBins,modis_histReffIce,         &
+                   numMODISReffIceBins, Optical_Thickness_vs_ReffIce(j,1:numMODISTauBins,1:numMODISReffIceBins))
+       ! Joint histogram of tau/ReffLIQ
+       call hist2D(tauWRK(j,1:nSubCols),reffLiqWrk(j,1:nSubCols),nSubCols,               &
+                   modis_histTau,numMODISTauBins,modis_histReffLiq,         &
+                   numMODISReffLiqBins, Optical_Thickness_vs_ReffLiq(j,1:numMODISTauBins,1:numMODISReffLiqBins))                   
+
+    enddo   
+    Optical_Thickness_vs_Cloud_Top_Pressure(1:nPoints,1:numMODISTauBins,1:numMODISPresBins) = &
+         Optical_Thickness_vs_Cloud_Top_Pressure(1:nPoints,1:numMODISTauBins,1:numMODISPresBins)/nSubCols
+    Optical_Thickness_vs_ReffIce(1:nPoints,1:numMODISTauBins,1:numMODISReffIceBins) = &
+         Optical_Thickness_vs_ReffIce(1:nPoints,1:numMODISTauBins,1:numMODISReffIceBins)/nSubCols
+    Optical_Thickness_vs_ReffLiq(1:nPoints,1:numMODISTauBins,1:numMODISReffLiqBins) = &
+         Optical_Thickness_vs_ReffLiq(1:nPoints,1:numMODISTauBins,1:numMODISReffLiqBins)/nSubCols 
+                 
+
+    ! Unit conversion
+    where(Optical_Thickness_vs_Cloud_Top_Pressure /= R_UNDEF) &
+      Optical_Thickness_vs_Cloud_Top_Pressure = Optical_Thickness_vs_Cloud_Top_Pressure*100._wp
+    where(Optical_Thickness_vs_ReffIce /= R_UNDEF) Optical_Thickness_vs_ReffIce = Optical_Thickness_vs_ReffIce*100._wp
+    where(Optical_Thickness_vs_ReffLiq /= R_UNDEF) Optical_Thickness_vs_ReffLiq = Optical_Thickness_vs_ReffLiq*100._wp
+    where(Cloud_Fraction_Total_Mean /= R_UNDEF) Cloud_Fraction_Total_Mean = Cloud_Fraction_Total_Mean*100._wp
+    where(Cloud_Fraction_Water_Mean /= R_UNDEF) Cloud_Fraction_Water_Mean = Cloud_Fraction_Water_Mean*100._wp
+    where(Cloud_Fraction_Ice_Mean /= R_UNDEF)   Cloud_Fraction_Ice_Mean = Cloud_Fraction_Ice_Mean*100._wp
+    where(Cloud_Fraction_High_Mean /= R_UNDEF)  Cloud_Fraction_High_Mean = Cloud_Fraction_High_Mean*100._wp
+    where(Cloud_Fraction_Mid_Mean /= R_UNDEF)   Cloud_Fraction_Mid_Mean = Cloud_Fraction_Mid_Mean*100._wp
+    where(Cloud_Fraction_Low_Mean /= R_UNDEF)   Cloud_Fraction_Low_Mean = Cloud_Fraction_Low_Mean*100._wp
+
+  end subroutine modis_column
+
+  ! ########################################################################################
+  function cloud_top_pressure(nLevels,tauIncrement, pressure, tauLimit) 
+    ! INPUTS
+    integer, intent(in)                    :: nLevels
+    real(wp),intent(in),dimension(nLevels) :: tauIncrement, pressure
+    real(wp),intent(in)                    :: tauLimit
+    ! OUTPUTS
+    real(wp)                               :: cloud_top_pressure
+    ! LOCAL VARIABLES
+    real(wp)                               :: deltaX, totalTau, totalProduct
+    integer                                :: i 
+    
+    ! Find the extinction-weighted pressure. Assume that pressure varies linearly between 
+    !   layers and use the trapezoidal rule.
+    totalTau = 0._wp; totalProduct = 0._wp
+    do i = 2, size(tauIncrement)
+      if(totalTau + tauIncrement(i) > tauLimit) then 
+        deltaX = tauLimit - totalTau
+        totalTau = totalTau + deltaX
+        !
+        ! Result for trapezoidal rule when you take less than a full step
+        !   tauIncrement is a layer-integrated value
+        !
+        totalProduct = totalProduct           &
+                     + pressure(i-1) * deltaX &
+                     + (pressure(i) - pressure(i-1)) * deltaX**2/(2._wp * tauIncrement(i)) 
+      else
+        totalTau =     totalTau     + tauIncrement(i) 
+        totalProduct = totalProduct + tauIncrement(i) * (pressure(i) + pressure(i-1)) / 2._wp
+      end if 
+      if(totalTau >= tauLimit) exit
+    end do 
+
+    if (totalTau > 0._wp) then
+       cloud_top_pressure = totalProduct/totalTau
+    else
+       cloud_top_pressure = 0._wp
+    endif
+    
+  end function cloud_top_pressure
+
+  ! ########################################################################################
+  function weight_by_extinction(nLevels,tauIncrement, f, tauLimit) 
+    ! INPUTS
+    integer, intent(in)                    :: nLevels
+    real(wp),intent(in),dimension(nLevels) :: tauIncrement, f
+    real(wp),intent(in)                    :: tauLimit
+    ! OUTPUTS
+    real(wp)                               :: weight_by_extinction
+    ! LOCAL VARIABLES
+    real(wp)                               :: deltaX, totalTau, totalProduct
+    integer                                :: i 
+    
+    ! Find the extinction-weighted value of f(tau), assuming constant f within each layer
+    totalTau = 0._wp; totalProduct = 0._wp
+    do i = 1, size(tauIncrement)
+      if(totalTau + tauIncrement(i) > tauLimit) then 
+        deltaX       = tauLimit - totalTau
+        totalTau     = totalTau     + deltaX
+        totalProduct = totalProduct + deltaX * f(i) 
+      else
+        totalTau     = totalTau     + tauIncrement(i) 
+        totalProduct = totalProduct + tauIncrement(i) * f(i) 
+      end if 
+      if(totalTau >= tauLimit) exit
+    end do 
+
+    if (totalTau > 0._wp) then
+       weight_by_extinction = totalProduct/totalTau
+    else
+       weight_by_extinction = 0._wp
+    endif
+    
+  end function weight_by_extinction
+
+  ! ########################################################################################
+  pure function interpolate_to_min(x, y, yobs)
+    ! INPUTS
+    real(wp),intent(in),dimension(num_trial_res) :: x, y 
+    real(wp),intent(in)                          :: yobs
+    ! OUTPUTS
+    real(wp)                                     :: interpolate_to_min
+    ! LOCAL VARIABLES
+    real(wp), dimension(num_trial_res)           :: diff
+    integer                                      :: nPoints, minDiffLoc, lowerBound, upperBound
+    
+    ! Given a set of values of y as y(x), find the value of x that minimizes abs(y - yobs)
+    !   y must be monotonic in x
+ 
+    nPoints = size(y)
+    diff(1:num_trial_res) = y(1:num_trial_res) - yobs
+    minDiffLoc = minloc(abs(diff), dim = 1) 
+    
+    if(minDiffLoc == 1) then 
+      lowerBound = minDiffLoc
+      upperBound = minDiffLoc + 1
+    else if(minDiffLoc == nPoints) then
+      lowerBound = minDiffLoc - 1
+      upperBound = minDiffLoc
+    else
+      if(diff(minDiffLoc-1) * diff(minDiffLoc) < 0) then
+        lowerBound = minDiffLoc-1
+        upperBound = minDiffLoc
+      else 
+        lowerBound = minDiffLoc
+        upperBound = minDiffLoc + 1
+      end if 
+    end if 
+    
+    if(diff(lowerBound) * diff(upperBound) < 0) then     
+      !
+      ! Interpolate the root position linearly if we bracket the root
+      !
+      interpolate_to_min = x(upperBound) - & 
+                           diff(upperBound) * (x(upperBound) - x(lowerBound)) / (diff(upperBound) - diff(lowerBound))
+    else 
+      interpolate_to_min = re_fill
+    end if 
+    
+
+  end function interpolate_to_min
+
+  ! ########################################################################################
+  ! Optical properties
+  ! ########################################################################################
+  elemental function get_g_nir_old (phase, re)
+    ! Polynomial fit for asummetry parameter g in MODIS band 7 (near IR) as a function 
+    !   of size for ice and water
+    ! Fits from Steve Platnick
+
+    ! INPUTS
+    integer, intent(in) :: phase
+    real(wp),intent(in) :: re
+    ! OUTPUTS
+    real(wp)            :: get_g_nir_old 
+    ! LOCAL VARIABLES(parameters)
+    real(wp), dimension(3), parameter :: &
+         ice_coefficients         = (/ 0.7432,  4.5563e-3, -2.8697e-5 /), & 
+         small_water_coefficients = (/ 0.8027, -1.0496e-2,  1.7071e-3 /), & 
+         big_water_coefficients   = (/ 0.7931,  5.3087e-3, -7.4995e-5 /) 
+   
+    ! approx. fits from MODIS Collection 5 LUT scattering calculations
+    if(phase == phaseIsLiquid) then
+      if(re < 8.) then 
+        get_g_nir_old = fit_to_quadratic(re, small_water_coefficients)
+        if(re < re_water_min) get_g_nir_old = fit_to_quadratic(re_water_min, small_water_coefficients)
+      else
+        get_g_nir_old = fit_to_quadratic(re,   big_water_coefficients)
+        if(re > re_water_max) get_g_nir_old = fit_to_quadratic(re_water_max, big_water_coefficients)
+      end if 
+    else
+      get_g_nir_old = fit_to_quadratic(re, ice_coefficients)
+      if(re < re_ice_min) get_g_nir_old = fit_to_quadratic(re_ice_min, ice_coefficients)
+      if(re > re_ice_max) get_g_nir_old = fit_to_quadratic(re_ice_max, ice_coefficients)
+    end if 
+    
+  end function get_g_nir_old
+
+  ! ########################################################################################
+  elemental function get_ssa_nir_old (phase, re)
+    ! Polynomial fit for single scattering albedo in MODIS band 7 (near IR) as a function 
+    !   of size for ice and water
+    ! Fits from Steve Platnick
+    
+    ! INPUTS
+    integer, intent(in) :: phase
+    real(wp),intent(in) :: re
+    ! OUTPUTS
+    real(wp)            :: get_ssa_nir_old
+    ! LOCAL VARIABLES (parameters)
+    real(wp), dimension(4), parameter :: ice_coefficients   = (/ 0.9994, -4.5199e-3, 3.9370e-5, -1.5235e-7 /)
+    real(wp), dimension(3), parameter :: water_coefficients = (/ 1.0008, -2.5626e-3, 1.6024e-5 /) 
+    
+    ! approx. fits from MODIS Collection 5 LUT scattering calculations
+    if(phase == phaseIsLiquid) then
+       get_ssa_nir_old = fit_to_quadratic(re, water_coefficients)
+       if(re < re_water_min) get_ssa_nir_old = fit_to_quadratic(re_water_min, water_coefficients)
+       if(re > re_water_max) get_ssa_nir_old = fit_to_quadratic(re_water_max, water_coefficients)
+    else
+       get_ssa_nir_old = fit_to_cubic(re, ice_coefficients)
+       if(re < re_ice_min) get_ssa_nir_old = fit_to_cubic(re_ice_min, ice_coefficients)
+       if(re > re_ice_max) get_ssa_nir_old = fit_to_cubic(re_ice_max, ice_coefficients)
+    end if
+    
+  end function get_ssa_nir_old
+  
+  elemental function get_g_nir (phase, re)
+    !
+    ! Polynomial fit for asummetry parameter g in MODIS band 7 (near IR) as a function 
+    !   of size for ice and water
+    ! Fits from Steve Platnick
+    !
+
+    integer, intent(in) :: phase
+    real(wp),    intent(in) :: re
+    real(wp) :: get_g_nir 
+
+    real(wp), dimension(3), parameter :: ice_coefficients         = (/ 0.7490, 6.5153e-3, -5.4136e-5 /), &
+                                         small_water_coefficients = (/ 1.0364, -8.8800e-2, 7.0000e-3 /)
+    real(wp), dimension(4), parameter :: big_water_coefficients   = (/ 0.6035, 2.8993e-2, -1.1051e-3, 1.5134e-5 /)
+
+    ! approx. fits from MODIS Collection 6 LUT scattering calculations for 3.7 µm channel size retrievals
+    if(phase == phaseIsLiquid) then 
+       if(re < 7.) then
+          get_g_nir = fit_to_quadratic(re, small_water_coefficients)
+          if(re < re_water_min) get_g_nir = fit_to_quadratic(re_water_min, small_water_coefficients)
+       else
+          get_g_nir = fit_to_cubic(re, big_water_coefficients)
+          if(re > re_water_max) get_g_nir = fit_to_cubic(re_water_max, big_water_coefficients)
+       end if
+    else
+       get_g_nir = fit_to_quadratic(re, ice_coefficients)
+      if(re < re_ice_min) get_g_nir = fit_to_quadratic(re_ice_min, ice_coefficients)
+      if(re > re_ice_max) get_g_nir = fit_to_quadratic(re_ice_max, ice_coefficients)
+    end if 
+    
+  end function get_g_nir
+
+  ! --------------------------------------------
+    elemental function get_ssa_nir (phase, re)
+        integer, intent(in) :: phase
+        real(wp),    intent(in) :: re
+        real(wp)                :: get_ssa_nir
+        !
+        ! Polynomial fit for single scattering albedo in MODIS band 7 (near IR) as a function 
+        !   of size for ice and water
+        ! Fits from Steve Platnick
+        !
+        real(wp), dimension(4), parameter :: ice_coefficients   = (/ 0.9625, -1.8069e-2, 3.3281e-4,-2.2865e-6/)
+        real(wp), dimension(3), parameter :: water_coefficients = (/ 1.0044, -1.1397e-2, 1.3300e-4 /)
+        
+        ! approx. fits from MODIS Collection 6 LUT scattering calculations
+        if(phase == phaseIsLiquid) then
+          get_ssa_nir = fit_to_quadratic(re, water_coefficients)
+          if(re < re_water_min) get_ssa_nir = fit_to_quadratic(re_water_min, water_coefficients)
+          if(re > re_water_max) get_ssa_nir = fit_to_quadratic(re_water_max, water_coefficients)
+        else
+          get_ssa_nir = fit_to_cubic(re, ice_coefficients)
+          if(re < re_ice_min) get_ssa_nir = fit_to_cubic(re_ice_min, ice_coefficients)
+          if(re > re_ice_max) get_ssa_nir = fit_to_cubic(re_ice_max, ice_coefficients)
+        end if 
+
+    end function get_ssa_nir
+
+  
+
+  ! ########################################################################################
+  pure function fit_to_cubic(x, coefficients) 
+    ! INPUTS
+    real(wp),               intent(in) :: x
+    real(wp), dimension(4), intent(in) :: coefficients
+    ! OUTPUTS
+    real(wp)                           :: fit_to_cubic  
+    
+    fit_to_cubic = coefficients(1) + x * (coefficients(2) + x * (coefficients(3) + x * coefficients(4)))
+  end function fit_to_cubic
+    
+  ! ########################################################################################
+  pure function fit_to_quadratic(x, coefficients) 
+    ! INPUTS
+    real(wp),               intent(in) :: x
+    real(wp), dimension(3), intent(in) :: coefficients
+    ! OUTPUTS
+    real(wp)                           :: fit_to_quadratic
+    
+    fit_to_quadratic = coefficients(1) + x * (coefficients(2) + x * (coefficients(3)))
+  end function fit_to_quadratic
+
+  ! ########################################################################################
+  ! Radiative transfer
+  ! ########################################################################################
+  pure function compute_toa_reflectace(nLevels,tau, g, w0)
+    ! This wrapper reports reflectance only and strips out non-cloudy elements from the 
+    ! calculation
+    
+    ! INPUTS
+    integer,intent(in)                     :: nLevels
+    real(wp),intent(in),dimension(nLevels) :: tau, g, w0
+    ! OUTPUTS
+    real(wp)                               :: compute_toa_reflectace
+    ! LOCAL VARIABLES
+    logical, dimension(nLevels)                   :: cloudMask
+    integer, dimension(count(tau(1:nLevels) > 0)) :: cloudIndicies
+    real(wp),dimension(count(tau(1:nLevels) > 0)) :: Refl,Trans
+    real(wp)                                      :: Refl_tot, Trans_tot
+    integer                                       :: i
+
+    cloudMask(1:nLevels) = tau(1:nLevels) > 0. 
+    cloudIndicies = pack((/ (i, i = 1, nLevels) /), mask = cloudMask) 
+    do i = 1, size(cloudIndicies)
+       call two_stream(tau(cloudIndicies(i)), g(cloudIndicies(i)), w0(cloudIndicies(i)), Refl(i), Trans(i))
+    end do
+    
+    call adding_doubling(count(tau(1:nLevels) > 0),Refl(:), Trans(:), Refl_tot, Trans_tot)  
+    
+    compute_toa_reflectace = Refl_tot
+    
+  end function compute_toa_reflectace
+ 
+  ! ########################################################################################
+  pure subroutine two_stream(tauint, gint, w0int, ref, tra) 
+    ! Compute reflectance in a single layer using the two stream approximation 
+    !   The code itself is from Lazaros Oreopoulos via Steve Platnick 
+    ! INPUTS
+    real(wp), intent(in)  :: tauint, gint, w0int
+    ! OUTPUTS
+    real(wp), intent(out) :: ref, tra
+    ! LOCAL VARIABLES
+    !   for delta Eddington code
+    !   xmu, gamma3, and gamma4 only used for collimated beam approximation (i.e., beam=1)
+    integer, parameter :: beam = 2
+    real(wp),parameter :: xmu = 0.866, minConservativeW0 = 0.9999999
+    real(wp) :: tau, w0, g, f, gamma1, gamma2, gamma3, gamma4, &
+         rh, a1, a2, rk, r1, r2, r3, r4, r5, t1, t2, t3, t4, t5, beta, e1, e2, ef1, ef2, den, th
+    
+    ! Compute reflectance and transmittance in a single layer using the two stream approximation 
+    !   The code itself is from Lazaros Oreopoulos via Steve Platnick 
+    f   = gint**2
+    tau = (1._wp - w0int * f) * tauint
+    w0  = (1._wp - f) * w0int / (1._wp - w0int * f)
+    g   = (gint - f) / (1._wp - f)
+
+    ! delta-Eddington (Joseph et al. 1976)
+    gamma1 =  (7._wp - w0* (4._wp + 3._wp * g)) / 4._wp
+    gamma2 = -(1._wp - w0* (4._wp - 3._wp * g)) / 4._wp
+    gamma3 =  (2._wp - 3._wp*g*xmu) / 4._wp
+    gamma4 =   1._wp - gamma3
+
+    if (w0int > minConservativeW0) then
+      ! Conservative scattering
+      if (beam == 1) then
+          rh = (gamma1*tau+(gamma3-gamma1*xmu)*(1-exp(-tau/xmu)))
+  
+          ref = rh / (1._wp + gamma1 * tau)
+          tra = 1._wp - ref       
+      else if(beam == 2) then
+          ref = gamma1*tau/(1._wp + gamma1*tau)
+          tra = 1._wp - ref
+      endif
+    else
+      ! Non-conservative scattering
+      a1 = gamma1 * gamma4 + gamma2 * gamma3
+      a2 = gamma1 * gamma3 + gamma2 * gamma4
+
+      rk = sqrt(gamma1**2 - gamma2**2)
+      
+      r1 = (1._wp - rk * xmu) * (a2 + rk * gamma3)
+      r2 = (1._wp + rk * xmu) * (a2 - rk * gamma3)
+      r3 = 2._wp * rk *(gamma3 - a2 * xmu)
+      r4 = (1._wp - (rk * xmu)**2) * (rk + gamma1)
+      r5 = (1._wp - (rk * xmu)**2) * (rk - gamma1)
+      
+      t1 = (1._wp + rk * xmu) * (a1 + rk * gamma4)
+      t2 = (1._wp - rk * xmu) * (a1 - rk * gamma4)
+      t3 = 2._wp * rk * (gamma4 + a1 * xmu)
+      t4 = r4
+      t5 = r5
+
+      beta = -r5 / r4         
+  
+      e1 = min(rk * tau, 500._wp) 
+      e2 = min(tau / xmu, 500._wp) 
+      
+      if (beam == 1) then
+         den = r4 * exp(e1) + r5 * exp(-e1)
+         ref  = w0*(r1*exp(e1)-r2*exp(-e1)-r3*exp(-e2))/den
+         den = t4 * exp(e1) + t5 * exp(-e1)
+         th  = exp(-e2)
+         tra = th-th*w0*(t1*exp(e1)-t2*exp(-e1)-t3*exp(e2))/den
+      elseif (beam == 2) then
+         ef1 = exp(-e1)
+         ef2 = exp(-2*e1)
+         ref = (gamma2*(1._wp-ef2))/((rk+gamma1)*(1._wp-beta*ef2))
+         tra = (2._wp*rk*ef1)/((rk+gamma1)*(1._wp-beta*ef2))
+      endif
+    end if
+  end subroutine two_stream
+
+  ! ########################################################################################
+  elemental function two_stream_reflectance(tauint, gint, w0int)
+    ! Compute reflectance in a single layer using the two stream approximation 
+    !   The code itself is from Lazaros Oreopoulos via Steve Platnick 
+    
+    ! INPUTS
+    real(wp), intent(in) :: tauint, gint, w0int
+    ! OUTPUTS
+    real(wp)             :: two_stream_reflectance
+    ! LOCAL VARIABLES
+    !   for delta Eddington code
+    !   xmu, gamma3, and gamma4 only used for collimated beam approximation (i.e., beam=1)
+    integer, parameter :: beam = 2
+    real(wp),parameter :: xmu = 0.866, minConservativeW0 = 0.9999999
+    real(wp) :: tau, w0, g, f, gamma1, gamma2, gamma3, gamma4, &
+         rh, a1, a2, rk, r1, r2, r3, r4, r5, t1, t2, t3, t4, t5, beta, e1, e2, ef1, ef2, den
+
+    f   = gint**2
+    tau = (1._wp - w0int * f) * tauint
+    w0  = (1._wp - f) * w0int / (1._wp - w0int * f)
+    g   = (gint - f) / (1._wp - f)
+
+    ! delta-Eddington (Joseph et al. 1976)
+    gamma1 =  (7._wp - w0* (4._wp + 3._wp * g)) / 4._wp
+    gamma2 = -(1._wp - w0* (4._wp - 3._wp * g)) / 4._wp
+    gamma3 =  (2._wp - 3._wp*g*xmu) / 4._wp
+    gamma4 =   1._wp - gamma3
+
+    if (w0int > minConservativeW0) then
+      ! Conservative scattering
+      if (beam == 1) then
+          rh = (gamma1*tau+(gamma3-gamma1*xmu)*(1-exp(-tau/xmu)))
+          two_stream_reflectance = rh / (1._wp + gamma1 * tau)
+      elseif (beam == 2) then
+          two_stream_reflectance = gamma1*tau/(1._wp + gamma1*tau)
+      endif
+        
+    else    !
+
+        ! Non-conservative scattering
+         a1 = gamma1 * gamma4 + gamma2 * gamma3
+         a2 = gamma1 * gamma3 + gamma2 * gamma4
+
+         rk = sqrt(gamma1**2 - gamma2**2)
+         
+         r1 = (1._wp - rk * xmu) * (a2 + rk * gamma3)
+         r2 = (1._wp + rk * xmu) * (a2 - rk * gamma3)
+         r3 = 2._wp * rk *(gamma3 - a2 * xmu)
+         r4 = (1._wp - (rk * xmu)**2) * (rk + gamma1)
+         r5 = (1._wp - (rk * xmu)**2) * (rk - gamma1)
+         
+         t1 = (1._wp + rk * xmu) * (a1 + rk * gamma4)
+         t2 = (1._wp - rk * xmu) * (a1 - rk * gamma4)
+         t3 = 2._wp * rk * (gamma4 + a1 * xmu)
+         t4 = r4
+         t5 = r5
+
+         beta = -r5 / r4         
+         
+         e1 = min(rk * tau, 500._wp) 
+         e2 = min(tau / xmu, 500._wp) 
+         
+         if (beam == 1) then
+           den = r4 * exp(e1) + r5 * exp(-e1)
+           two_stream_reflectance  = w0*(r1*exp(e1)-r2*exp(-e1)-r3*exp(-e2))/den
+         elseif (beam == 2) then
+           ef1 = exp(-e1)
+           ef2 = exp(-2*e1)
+           two_stream_reflectance = (gamma2*(1._wp-ef2))/((rk+gamma1)*(1._wp-beta*ef2))
+         endif
+           
+      end if
+  end function two_stream_reflectance 
+
+  ! ########################################################################################
+  pure subroutine adding_doubling (npts,Refl, Tran, Refl_tot, Tran_tot)      
+    ! Use adding/doubling formulas to compute total reflectance and transmittance from 
+    ! layer values
+    
+    ! INPUTS
+    integer,intent(in)                  :: npts
+    real(wp),intent(in),dimension(npts) :: Refl,Tran
+    ! OUTPUTS
+    real(wp),intent(out)                :: Refl_tot, Tran_tot
+    ! LOCAL VARIABLES
+    integer :: i
+    real(wp), dimension(npts) :: Refl_cumulative, Tran_cumulative
+    
+    Refl_cumulative(1) = Refl(1)
+    Tran_cumulative(1) = Tran(1)    
+    
+    do i=2, npts
+       ! place (add) previous combined layer(s) reflectance on top of layer i, w/black surface (or ignoring surface):
+       Refl_cumulative(i) = Refl_cumulative(i-1) + Refl(i)*(Tran_cumulative(i-1)**2)/(1._wp - Refl_cumulative(i-1) * Refl(i))
+       Tran_cumulative(i) = (Tran_cumulative(i-1)*Tran(i)) / (1._wp - Refl_cumulative(i-1) * Refl(i))
+    end do
+    
+    Refl_tot = Refl_cumulative(size(Refl))
+    Tran_tot = Tran_cumulative(size(Refl))
+    
+  end subroutine adding_doubling
+
+end module mod_modis_sim
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/mrgrnk.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/mrgrnk.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/mrgrnk.F90	(revision 3605)
@@ -0,0 +1,645 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History:
+! May 2015:  Dustin Swales    - Modified for COSPv2.0
+! 
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+Module m_mrgrnk
+  USE COSP_KINDS,          ONLY: wp
+  Integer, Parameter :: kdp = selected_real_kind(15)
+  public :: mrgrnk
+  private :: kdp
+  private :: R_mrgrnk, I_mrgrnk, D_mrgrnk
+
+  interface mrgrnk
+!     module procedure D_mrgrnk, R_mrgrnk, I_mrgrnk
+     module procedure R_mrgrnk, I_mrgrnk
+     
+  end interface
+contains
+  
+  Subroutine D_mrgrnk (XDONT, IRNGT)
+    ! __________________________________________________________
+    ! MRGRNK = Merge-sort ranking of an array
+    ! For performance reasons, the first 2 passes are taken
+    ! out of the standard loop, and use dedicated coding.
+    ! __________________________________________________________
+    ! __________________________________________________________
+    Real (wp), Dimension (:), Intent (In) :: XDONT
+    Integer, Dimension (:), Intent (Out) :: IRNGT
+    ! __________________________________________________________
+    Real (wp) :: XVALA, XVALB
+    !
+    Integer, Dimension (SIZE(IRNGT)) :: JWRKT
+    Integer :: LMTNA, LMTNC, IRNG1, IRNG2
+    Integer :: NVAL, IIND, IWRKD, IWRK, IWRKF, JINDA, IINDA, IINDB
+    !
+    NVAL = Min (SIZE(XDONT), SIZE(IRNGT))
+    Select Case (NVAL)
+    Case (:0)
+       Return
+    Case (1)
+       IRNGT (1) = 1
+       Return
+    Case Default
+       Continue
+    End Select
+    !
+    ! Fill-in the index array, creating ordered couples
+    !
+    Do IIND = 2, NVAL, 2
+       If (XDONT(IIND-1) <= XDONT(IIND)) Then
+          IRNGT (IIND-1) = IIND - 1
+          IRNGT (IIND) = IIND
+       Else
+          IRNGT (IIND-1) = IIND
+          IRNGT (IIND) = IIND - 1
+       End If
+    End Do
+    If (Modulo(NVAL, 2) /= 0) Then
+       IRNGT (NVAL) = NVAL
+    End If
+    !
+    ! We will now have ordered subsets A - B - A - B - ...
+    ! and merge A and B couples into C - C - ...
+    !
+    LMTNA = 2
+    LMTNC = 4
+    !
+    ! First iteration. The length of the ordered subsets goes from 2 to 4
+    !
+    Do
+       If (NVAL <= 2) Exit
+       !
+       ! Loop on merges of A and B into C
+       !
+       Do IWRKD = 0, NVAL - 1, 4
+          If ((IWRKD+4) > NVAL) Then
+             If ((IWRKD+2) >= NVAL) Exit
+             !
+             ! 1 2 3
+             !
+             If (XDONT(IRNGT(IWRKD+2)) <= XDONT(IRNGT(IWRKD+3))) Exit
+             !
+             ! 1 3 2
+             !
+             If (XDONT(IRNGT(IWRKD+1)) <= XDONT(IRNGT(IWRKD+3))) Then
+                IRNG2 = IRNGT (IWRKD+2)
+                IRNGT (IWRKD+2) = IRNGT (IWRKD+3)
+                IRNGT (IWRKD+3) = IRNG2
+                !
+                ! 3 1 2
+                !
+             Else
+                IRNG1 = IRNGT (IWRKD+1)
+                IRNGT (IWRKD+1) = IRNGT (IWRKD+3)
+                IRNGT (IWRKD+3) = IRNGT (IWRKD+2)
+                IRNGT (IWRKD+2) = IRNG1
+             End If
+             Exit
+          End If
+          !
+          ! 1 2 3 4
+          !
+          If (XDONT(IRNGT(IWRKD+2)) <= XDONT(IRNGT(IWRKD+3))) Cycle
+          !
+          ! 1 3 x x
+          !
+          If (XDONT(IRNGT(IWRKD+1)) <= XDONT(IRNGT(IWRKD+3))) Then
+             IRNG2 = IRNGT (IWRKD+2)
+             IRNGT (IWRKD+2) = IRNGT (IWRKD+3)
+             If (XDONT(IRNG2) <= XDONT(IRNGT(IWRKD+4))) Then
+                ! 1 3 2 4
+                IRNGT (IWRKD+3) = IRNG2
+             Else
+                ! 1 3 4 2
+                IRNGT (IWRKD+3) = IRNGT (IWRKD+4)
+                IRNGT (IWRKD+4) = IRNG2
+             End If
+             !
+             ! 3 x x x
+             !
+          Else
+             IRNG1 = IRNGT (IWRKD+1)
+             IRNG2 = IRNGT (IWRKD+2)
+             IRNGT (IWRKD+1) = IRNGT (IWRKD+3)
+             If (XDONT(IRNG1) <= XDONT(IRNGT(IWRKD+4))) Then
+                IRNGT (IWRKD+2) = IRNG1
+                If (XDONT(IRNG2) <= XDONT(IRNGT(IWRKD+4))) Then
+                   ! 3 1 2 4
+                   IRNGT (IWRKD+3) = IRNG2
+                Else
+                   ! 3 1 4 2
+                   IRNGT (IWRKD+3) = IRNGT (IWRKD+4)
+                   IRNGT (IWRKD+4) = IRNG2
+                End If
+             Else
+                ! 3 4 1 2
+                IRNGT (IWRKD+2) = IRNGT (IWRKD+4)
+                IRNGT (IWRKD+3) = IRNG1
+                IRNGT (IWRKD+4) = IRNG2
+             End If
+          End If
+       End Do
+       !
+       ! The Cs become As and Bs
+       !
+       LMTNA = 4
+       Exit
+    End Do
+    !
+    ! Iteration loop. Each time, the length of the ordered subsets
+    ! is doubled.
+    !
+    Do
+       If (LMTNA >= NVAL) Exit
+       IWRKF = 0
+       LMTNC = 2 * LMTNC
+       !
+       ! Loop on merges of A and B into C
+       !
+       Do
+          IWRK = IWRKF
+          IWRKD = IWRKF + 1
+          JINDA = IWRKF + LMTNA
+          IWRKF = IWRKF + LMTNC
+          If (IWRKF >= NVAL) Then
+             If (JINDA >= NVAL) Exit
+             IWRKF = NVAL
+          End If
+          IINDA = 1
+          IINDB = JINDA + 1
+          !
+          ! Shortcut for the case when the max of A is smaller
+          ! than the min of B. This line may be activated when the
+          ! initial set is already close to sorted.
+          !
+          ! IF (XDONT(IRNGT(JINDA)) <= XDONT(IRNGT(IINDB))) CYCLE
+          !
+          ! One steps in the C subset, that we build in the final rank array
+          !
+          ! Make a copy of the rank array for the merge iteration
+          !
+          JWRKT (1:LMTNA) = IRNGT (IWRKD:JINDA)
+          !
+          XVALA = XDONT (JWRKT(IINDA))
+          XVALB = XDONT (IRNGT(IINDB))
+          !
+          Do
+             IWRK = IWRK + 1
+             !
+             ! We still have unprocessed values in both A and B
+             !
+             If (XVALA > XVALB) Then
+                IRNGT (IWRK) = IRNGT (IINDB)
+                IINDB = IINDB + 1
+                If (IINDB > IWRKF) Then
+                   ! Only A still with unprocessed values
+                   IRNGT (IWRK+1:IWRKF) = JWRKT (IINDA:LMTNA)
+                   Exit
+                End If
+                XVALB = XDONT (IRNGT(IINDB))
+             Else
+                IRNGT (IWRK) = JWRKT (IINDA)
+                IINDA = IINDA + 1
+                If (IINDA > LMTNA) Exit! Only B still with unprocessed values
+                XVALA = XDONT (JWRKT(IINDA))
+             End If
+             !
+          End Do
+       End Do
+       !
+       ! The Cs become As and Bs
+       !
+       LMTNA = 2 * LMTNA
+    End Do
+    !
+    Return
+    !
+  End Subroutine D_mrgrnk
+  
+  Subroutine R_mrgrnk (XDONT, IRNGT)
+    ! __________________________________________________________
+    ! MRGRNK = Merge-sort ranking of an array
+    ! For performance reasons, the first 2 passes are taken
+    ! out of the standard loop, and use dedicated coding.
+    ! __________________________________________________________
+    ! _________________________________________________________
+    Real(wp), Dimension (:), Intent (In) :: XDONT
+    Integer, Dimension (:), Intent (Out) :: IRNGT
+    ! __________________________________________________________
+    Real(wp) :: XVALA, XVALB
+    !
+    Integer, Dimension (SIZE(IRNGT)) :: JWRKT
+    Integer :: LMTNA, LMTNC, IRNG1, IRNG2
+    Integer :: NVAL, IIND, IWRKD, IWRK, IWRKF, JINDA, IINDA, IINDB
+    !
+    NVAL = Min (SIZE(XDONT), SIZE(IRNGT))
+    Select Case (NVAL)
+    Case (:0)
+       Return
+    Case (1)
+       IRNGT (1) = 1
+       Return
+    Case Default
+       Continue
+    End Select
+    !
+    ! Fill-in the index array, creating ordered couples
+    !
+    Do IIND = 2, NVAL, 2
+       If (XDONT(IIND-1) <= XDONT(IIND)) Then
+          IRNGT (IIND-1) = IIND - 1
+          IRNGT (IIND) = IIND
+       Else
+          IRNGT (IIND-1) = IIND
+          IRNGT (IIND) = IIND - 1
+       End If
+    End Do
+    If (Modulo(NVAL, 2) /= 0) Then
+       IRNGT (NVAL) = NVAL
+    End If
+    !
+    ! We will now have ordered subsets A - B - A - B - ...
+    ! and merge A and B couples into C - C - ...
+    !
+    LMTNA = 2
+    LMTNC = 4
+    !
+    ! First iteration. The length of the ordered subsets goes from 2 to 4
+    !
+    Do
+       If (NVAL <= 2) Exit
+       !
+       ! Loop on merges of A and B into C
+       !
+       Do IWRKD = 0, NVAL - 1, 4
+          If ((IWRKD+4) > NVAL) Then
+             If ((IWRKD+2) >= NVAL) Exit
+             !
+             ! 1 2 3
+             !
+             If (XDONT(IRNGT(IWRKD+2)) <= XDONT(IRNGT(IWRKD+3))) Exit
+             !
+             ! 1 3 2
+             !
+             If (XDONT(IRNGT(IWRKD+1)) <= XDONT(IRNGT(IWRKD+3))) Then
+                IRNG2 = IRNGT (IWRKD+2)
+                IRNGT (IWRKD+2) = IRNGT (IWRKD+3)
+                IRNGT (IWRKD+3) = IRNG2
+                !
+                ! 3 1 2
+                !
+             Else
+                IRNG1 = IRNGT (IWRKD+1)
+                IRNGT (IWRKD+1) = IRNGT (IWRKD+3)
+                IRNGT (IWRKD+3) = IRNGT (IWRKD+2)
+                IRNGT (IWRKD+2) = IRNG1
+             End If
+             Exit
+          End If
+          !
+          ! 1 2 3 4
+          !
+          If (XDONT(IRNGT(IWRKD+2)) <= XDONT(IRNGT(IWRKD+3))) Cycle
+          !
+          ! 1 3 x x
+          !
+          If (XDONT(IRNGT(IWRKD+1)) <= XDONT(IRNGT(IWRKD+3))) Then
+             IRNG2 = IRNGT (IWRKD+2)
+             IRNGT (IWRKD+2) = IRNGT (IWRKD+3)
+             If (XDONT(IRNG2) <= XDONT(IRNGT(IWRKD+4))) Then
+                ! 1 3 2 4
+                IRNGT (IWRKD+3) = IRNG2
+             Else
+                ! 1 3 4 2
+                IRNGT (IWRKD+3) = IRNGT (IWRKD+4)
+                IRNGT (IWRKD+4) = IRNG2
+             End If
+             !
+             ! 3 x x x
+             !
+          Else
+             IRNG1 = IRNGT (IWRKD+1)
+             IRNG2 = IRNGT (IWRKD+2)
+             IRNGT (IWRKD+1) = IRNGT (IWRKD+3)
+             If (XDONT(IRNG1) <= XDONT(IRNGT(IWRKD+4))) Then
+                IRNGT (IWRKD+2) = IRNG1
+                If (XDONT(IRNG2) <= XDONT(IRNGT(IWRKD+4))) Then
+                   ! 3 1 2 4
+                   IRNGT (IWRKD+3) = IRNG2
+                Else
+                   ! 3 1 4 2
+                   IRNGT (IWRKD+3) = IRNGT (IWRKD+4)
+                   IRNGT (IWRKD+4) = IRNG2
+                End If
+             Else
+                ! 3 4 1 2
+                IRNGT (IWRKD+2) = IRNGT (IWRKD+4)
+                IRNGT (IWRKD+3) = IRNG1
+                IRNGT (IWRKD+4) = IRNG2
+             End If
+          End If
+       End Do
+       !
+       ! The Cs become As and Bs
+       !
+       LMTNA = 4
+       Exit
+    End Do
+    !
+    ! Iteration loop. Each time, the length of the ordered subsets
+    ! is doubled.
+    !
+    Do
+       If (LMTNA >= NVAL) Exit
+       IWRKF = 0
+       LMTNC = 2 * LMTNC
+       !
+       ! Loop on merges of A and B into C
+       !
+       Do
+          IWRK = IWRKF
+          IWRKD = IWRKF + 1
+          JINDA = IWRKF + LMTNA
+          IWRKF = IWRKF + LMTNC
+          If (IWRKF >= NVAL) Then
+             If (JINDA >= NVAL) Exit
+             IWRKF = NVAL
+          End If
+          IINDA = 1
+          IINDB = JINDA + 1
+          !
+          ! Shortcut for the case when the max of A is smaller
+          ! than the min of B. This line may be activated when the
+          ! initial set is already close to sorted.
+          !
+          ! IF (XDONT(IRNGT(JINDA)) <= XDONT(IRNGT(IINDB))) CYCLE
+          !
+          ! One steps in the C subset, that we build in the final rank array
+          !
+          ! Make a copy of the rank array for the merge iteration
+          !
+          JWRKT (1:LMTNA) = IRNGT (IWRKD:JINDA)
+          !
+          XVALA = XDONT (JWRKT(IINDA))
+          XVALB = XDONT (IRNGT(IINDB))
+          !
+          Do
+             IWRK = IWRK + 1
+             !
+             ! We still have unprocessed values in both A and B
+             !
+             If (XVALA > XVALB) Then
+                IRNGT (IWRK) = IRNGT (IINDB)
+                IINDB = IINDB + 1
+                If (IINDB > IWRKF) Then
+                   ! Only A still with unprocessed values
+                   IRNGT (IWRK+1:IWRKF) = JWRKT (IINDA:LMTNA)
+                   Exit
+                End If
+                XVALB = XDONT (IRNGT(IINDB))
+             Else
+                IRNGT (IWRK) = JWRKT (IINDA)
+                IINDA = IINDA + 1
+                If (IINDA > LMTNA) Exit! Only B still with unprocessed values
+                XVALA = XDONT (JWRKT(IINDA))
+             End If
+             !
+          End Do
+       End Do
+       !
+       ! The Cs become As and Bs
+       !
+       LMTNA = 2 * LMTNA
+    End Do
+    !
+    Return
+    !
+  End Subroutine R_mrgrnk
+  Subroutine I_mrgrnk (XDONT, IRNGT)
+    ! __________________________________________________________
+    ! MRGRNK = Merge-sort ranking of an array
+    ! For performance reasons, the first 2 passes are taken
+    ! out of the standard loop, and use dedicated coding.
+    ! __________________________________________________________
+    ! __________________________________________________________
+    Integer, Dimension (:), Intent (In) :: XDONT
+    Integer, Dimension (:), Intent (Out) :: IRNGT
+    ! __________________________________________________________
+    Integer :: XVALA, XVALB
+    !
+    Integer, Dimension (SIZE(IRNGT)) :: JWRKT
+    Integer :: LMTNA, LMTNC, IRNG1, IRNG2
+    Integer :: NVAL, IIND, IWRKD, IWRK, IWRKF, JINDA, IINDA, IINDB
+    !
+    NVAL = Min (SIZE(XDONT), SIZE(IRNGT))
+    Select Case (NVAL)
+    Case (:0)
+       Return
+    Case (1)
+       IRNGT (1) = 1
+       Return
+    Case Default
+       Continue
+    End Select
+    !
+    ! Fill-in the index array, creating ordered couples
+    !
+    Do IIND = 2, NVAL, 2
+       If (XDONT(IIND-1) <= XDONT(IIND)) Then
+          IRNGT (IIND-1) = IIND - 1
+          IRNGT (IIND) = IIND
+       Else
+          IRNGT (IIND-1) = IIND
+          IRNGT (IIND) = IIND - 1
+       End If
+    End Do
+    If (Modulo(NVAL, 2) /= 0) Then
+       IRNGT (NVAL) = NVAL
+    End If
+    !
+    ! We will now have ordered subsets A - B - A - B - ...
+    ! and merge A and B couples into C - C - ...
+    !
+    LMTNA = 2
+    LMTNC = 4
+    !
+    ! First iteration. The length of the ordered subsets goes from 2 to 4
+    !
+    Do
+       If (NVAL <= 2) Exit
+       !
+       ! Loop on merges of A and B into C
+       !
+       Do IWRKD = 0, NVAL - 1, 4
+          If ((IWRKD+4) > NVAL) Then
+             If ((IWRKD+2) >= NVAL) Exit
+             !
+             ! 1 2 3
+             !
+             If (XDONT(IRNGT(IWRKD+2)) <= XDONT(IRNGT(IWRKD+3))) Exit
+             !
+             ! 1 3 2
+             !
+             If (XDONT(IRNGT(IWRKD+1)) <= XDONT(IRNGT(IWRKD+3))) Then
+                IRNG2 = IRNGT (IWRKD+2)
+                IRNGT (IWRKD+2) = IRNGT (IWRKD+3)
+                IRNGT (IWRKD+3) = IRNG2
+                !
+                ! 3 1 2
+                !
+             Else
+                IRNG1 = IRNGT (IWRKD+1)
+                IRNGT (IWRKD+1) = IRNGT (IWRKD+3)
+                IRNGT (IWRKD+3) = IRNGT (IWRKD+2)
+                IRNGT (IWRKD+2) = IRNG1
+             End If
+             Exit
+          End If
+          !
+          ! 1 2 3 4
+          !
+          If (XDONT(IRNGT(IWRKD+2)) <= XDONT(IRNGT(IWRKD+3))) Cycle
+          !
+          ! 1 3 x x
+          !
+          If (XDONT(IRNGT(IWRKD+1)) <= XDONT(IRNGT(IWRKD+3))) Then
+             IRNG2 = IRNGT (IWRKD+2)
+             IRNGT (IWRKD+2) = IRNGT (IWRKD+3)
+             If (XDONT(IRNG2) <= XDONT(IRNGT(IWRKD+4))) Then
+                ! 1 3 2 4
+                IRNGT (IWRKD+3) = IRNG2
+             Else
+                ! 1 3 4 2
+                IRNGT (IWRKD+3) = IRNGT (IWRKD+4)
+                IRNGT (IWRKD+4) = IRNG2
+             End If
+             !
+             ! 3 x x x
+             !
+          Else
+             IRNG1 = IRNGT (IWRKD+1)
+             IRNG2 = IRNGT (IWRKD+2)
+             IRNGT (IWRKD+1) = IRNGT (IWRKD+3)
+             If (XDONT(IRNG1) <= XDONT(IRNGT(IWRKD+4))) Then
+                IRNGT (IWRKD+2) = IRNG1
+                If (XDONT(IRNG2) <= XDONT(IRNGT(IWRKD+4))) Then
+                   ! 3 1 2 4
+                   IRNGT (IWRKD+3) = IRNG2
+                Else
+                   ! 3 1 4 2
+                   IRNGT (IWRKD+3) = IRNGT (IWRKD+4)
+                   IRNGT (IWRKD+4) = IRNG2
+                End If
+             Else
+                ! 3 4 1 2
+                IRNGT (IWRKD+2) = IRNGT (IWRKD+4)
+                IRNGT (IWRKD+3) = IRNG1
+                IRNGT (IWRKD+4) = IRNG2
+             End If
+          End If
+       End Do
+       !
+       ! The Cs become As and Bs
+       !
+       LMTNA = 4
+       Exit
+    End Do
+    !
+    ! Iteration loop. Each time, the length of the ordered subsets
+    ! is doubled.
+    !
+    Do
+       If (LMTNA >= NVAL) Exit
+       IWRKF = 0
+       LMTNC = 2 * LMTNC
+       !
+       ! Loop on merges of A and B into C
+       !
+       Do
+          IWRK = IWRKF
+          IWRKD = IWRKF + 1
+          JINDA = IWRKF + LMTNA
+          IWRKF = IWRKF + LMTNC
+          If (IWRKF >= NVAL) Then
+             If (JINDA >= NVAL) Exit
+             IWRKF = NVAL
+          End If
+          IINDA = 1
+          IINDB = JINDA + 1
+          !
+          ! Shortcut for the case when the max of A is smaller
+          ! than the min of B. This line may be activated when the
+          ! initial set is already close to sorted.
+          !
+          ! IF (XDONT(IRNGT(JINDA)) <= XDONT(IRNGT(IINDB))) CYCLE
+          !
+          ! One steps in the C subset, that we build in the final rank array
+          !
+          ! Make a copy of the rank array for the merge iteration
+          !
+          JWRKT (1:LMTNA) = IRNGT (IWRKD:JINDA)
+          !
+          XVALA = XDONT (JWRKT(IINDA))
+          XVALB = XDONT (IRNGT(IINDB))
+          !
+          Do
+             IWRK = IWRK + 1
+             !
+             ! We still have unprocessed values in both A and B
+             !
+             If (XVALA > XVALB) Then
+                IRNGT (IWRK) = IRNGT (IINDB)
+                IINDB = IINDB + 1
+                If (IINDB > IWRKF) Then
+                   ! Only A still with unprocessed values
+                   IRNGT (IWRK+1:IWRKF) = JWRKT (IINDA:LMTNA)
+                   Exit
+                End If
+                XVALB = XDONT (IRNGT(IINDB))
+             Else
+                IRNGT (IWRK) = JWRKT (IINDA)
+                IINDA = IINDA + 1
+                If (IINDA > LMTNA) Exit! Only B still with unprocessed values
+                XVALA = XDONT (JWRKT(IINDA))
+             End If
+             !
+          End Do
+       End Do
+       !
+       ! The Cs become As and Bs
+       !
+       LMTNA = 2 * LMTNA
+    End Do
+    !
+    Return
+    !
+  End Subroutine I_mrgrnk
+end module m_mrgrnk
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/optics_lib.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/optics_lib.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/optics_lib.F90	(revision 3605)
@@ -0,0 +1,771 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History:
+! July 2006: John Haynes      - Initial version
+! May 2015:  Dustin Swales    - Modified for COSPv2.0
+! 
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+module optics_lib
+  USE COSP_KINDS,     ONLY: wp
+  use mod_cosp_error, ONLY: errorMessage
+  implicit none
+
+contains
+
+  ! ##############################################################################
+  !                           subroutine M_WAT
+  ! ##############################################################################
+  subroutine m_wat(freq, tk, n_r, n_i)
+    ! ############################################################################
+    !  
+    ! Purpose:
+    !   compute complex index of refraction of liquid water
+    !
+    ! Inputs:
+    !   [freq]    frequency (GHz)
+    !   [tk]       temperature (K)
+    !
+    ! Outputs:
+    !   [n_r]     real part index of refraction
+    !   [n_i]     imaginary part index of refraction
+    !
+    ! Reference:
+    !   Based on the work of Ray (1972)
+    !
+    ! Coded:
+    !   03/22/05  John Haynes (haynes@atmos.colostate.edu)
+    ! ############################################################################
+
+    ! INPUTS
+    real(wp), intent(in) :: &
+         freq, & ! Frequency (GHz)
+         tk      ! Temperature (K)
+  
+    ! OUTPUTS
+    real(wp), intent(out) :: &
+         n_r,  & ! Real part of index of refraction
+         n_i     ! Imaginary part of index of refraction
+
+    ! Internal variables
+    real(wp) :: ld,es,ei,a,ls,sg,tm1,cos1,sin1,e_r,e_i,pi,tc
+    complex(wp) :: e_comp, sq
+
+    tc = tk - 273.15_wp
+
+    ld = 100._wp*2.99792458E8_wp/(freq*1E9_wp)
+    es = 78.54_wp*(1-(4.579E-3_wp*(tc-25._wp)+1.19E-5_wp*(tc-25._wp)**2 &
+         -2.8E-8_wp*(tc-25._wp)**3))
+    ei = 5.27137_wp+0.021647_wp*tc-0.00131198_wp*tc**2
+    a = -(16.8129_wp/(tc+273._wp))+0.0609265_wp
+    ls = 0.00033836_wp*exp(2513.98_wp/(tc+273._wp))
+    sg = 12.5664E8_wp
+    
+    tm1 = (ls/ld)**(1-a)
+    pi = acos(-1._wp)
+    cos1 = cos(0.5_wp*a*pi)
+    sin1 = sin(0.5_wp*a*pi)
+    
+    e_r = ei + (((es-ei)*(1.+tm1*sin1))/(1._wp+2*tm1*sin1+tm1**2))
+    e_i = (((es-ei)*tm1*cos1)/(1._wp+2*tm1*sin1+tm1**2)) &
+         +((sg*ld)/1.885E11_wp)
+    
+!ds    e_comp = cmplx(e_r,e_i,Kind=Kind(0d0))
+    e_comp = cmplx(e_r,e_i,Kind=wp)
+    sq = sqrt(e_comp)
+    
+    n_r = real(sq)
+    n_i = aimag(sq)      
+    
+    return
+  end subroutine m_wat
+
+  ! ############################################################################
+  !                           subroutine M_ICE
+  ! ############################################################################
+  subroutine m_ice(freq,t,n_r,n_i)
+    ! ##########################################################################
+    !
+    ! Purpose:
+    !   compute complex index of refraction of ice
+    !
+    ! Inputs:
+    !   [freq]    frequency (GHz)
+    !   [t]       temperature (K)
+    !
+    ! Outputs:
+    !   [n_r]     real part index of refraction
+    !   [n_i]     imaginary part index of refraction
+    !
+    ! Reference:
+    !    Fortran 90 port from IDL of REFICE by Stephen G. Warren
+    !
+    ! Modified:
+    !   05/31/05  John Haynes (haynes@atmos.colostate.edu)
+    ! ##########################################################################
+
+    ! INPUTS
+    real(wp), intent(in) :: &
+         freq, & ! Frequency (GHz)
+         t       ! Temperature (K)
+  
+    ! OUTPUTS
+    real(wp), intent(out) :: &
+         n_r,  & ! Real part of index of refraction
+         n_i     ! Imaginary part of index of refraction
+
+    ! Internal variables
+    integer  :: i,lt1,lt2
+    real(wp) :: alam,pi,t1,t2, &
+         x,x1,x2,y,y1,y2,ylo,yhi,tk
+
+
+    ! Parameters:
+    integer,parameter :: &
+         nwl  = 468,      & !
+         nwlt = 62          !
+    real(wp),parameter,dimension(4) :: &
+         temref = [272.16,268.16,253.16,213.16]
+    real(wp),parameter :: & !
+         wlmin  = 0.045,  & !
+         wlmax  = 8.6e6,  & !
+         cutice = 167.0
+    real(wp),parameter,dimension(nwlt) :: &
+         wlt = &
+         [0.1670e+03, 0.1778e+03, 0.1884e+03, 0.1995e+03, 0.2113e+03, 0.2239e+03, &
+          0.2371e+03, 0.2512e+03, 0.2661e+03, 0.2818e+03, 0.2985e+03, 0.3162e+03, &
+          0.3548e+03, 0.3981e+03, 0.4467e+03, 0.5012e+03, 0.5623e+03, 0.6310e+03, &
+          0.7943e+03, 0.1000e+04, 0.1259e+04, 0.2500e+04, 0.5000e+04, 0.1000e+05, &
+          0.2000e+05, 0.3200e+05, 0.3500e+05, 0.4000e+05, 0.4500e+05, 0.5000e+05, &
+          0.6000e+05, 0.7000e+05, 0.9000e+05, 0.1110e+06, 0.1200e+06, 0.1300e+06, &
+          0.1400e+06, 0.1500e+06, 0.1600e+06, 0.1700e+06, 0.1800e+06, 0.2000e+06, &
+          0.2500e+06, 0.2900e+06, 0.3200e+06, 0.3500e+06, 0.3800e+06, 0.4000e+06, &
+          0.4500e+06, 0.5000e+06, 0.6000e+06, 0.6400e+06, 0.6800e+06, 0.7200e+06, &
+          0.7600e+06, 0.8000e+06, 0.8400e+06, 0.9000e+06, 0.1000e+07, 0.2000e+07, &
+          0.5000e+07,0.8600e+07]
+    real(wp),parameter,dimension(nwl) :: &
+         tabim = &
+         [0.1640e+00, 0.1730e+00, 0.1830e+00, 0.1950e+00, 0.2080e+00, 0.2230e+00, &
+          0.2400e+00, 0.2500e+00, 0.2590e+00, 0.2680e+00, 0.2790e+00, 0.2970e+00, &
+          0.3190e+00, 0.3400e+00, 0.3660e+00, 0.3920e+00, 0.4160e+00, 0.4400e+00, &
+          0.4640e+00, 0.4920e+00, 0.5170e+00, 0.5280e+00, 0.5330e+00, 0.5340e+00, &
+          0.5310e+00, 0.5240e+00, 0.5100e+00, 0.5000e+00, 0.4990e+00, 0.4680e+00, &
+          0.3800e+00, 0.3600e+00, 0.3390e+00, 0.3180e+00, 0.2910e+00, 0.2510e+00, &
+          0.2440e+00, 0.2390e+00, 0.2390e+00, 0.2440e+00, 0.2470e+00, 0.2240e+00, &
+          0.1950e+00, 0.1740e+00, 0.1720e+00, 0.1800e+00, 0.1940e+00, 0.2130e+00, &
+          0.2430e+00, 0.2710e+00, 0.2890e+00, 0.3340e+00, 0.3440e+00, 0.3820e+00, &
+          0.4010e+00, 0.4065e+00, 0.4050e+00, 0.3890e+00, 0.3770e+00, 0.3450e+00, &
+          0.3320e+00, 0.3150e+00, 0.2980e+00, 0.2740e+00, 0.2280e+00, 0.1980e+00, &
+          0.1720e+00, 0.1560e+00, 0.1100e+00, 0.8300e-01, 0.5800e-01, 0.2200e-01, &
+          0.1000e-01, 0.3000e-02, 0.1000e-02, 0.3000e-03, 0.1000e-03, 0.3000e-04, &
+          0.1000e-04, 0.3000e-05, 0.1000e-05, 0.7000e-06, 0.4000e-06, 0.2000e-06, &
+          0.1000e-06, 0.6377e-07, 0.3750e-07, 0.2800e-07, 0.2400e-07, 0.2200e-07, &
+          0.1900e-07, 0.1750e-07, 0.1640e-07, 0.1590e-07, 0.1325e-07, 0.8623e-08, &
+          0.5504e-08, 0.3765e-08, 0.2710e-08, 0.2510e-08, 0.2260e-08, 0.2080e-08, &
+          0.1910e-08, 0.1540e-08, 0.1530e-08, 0.1550e-08, 0.1640e-08, 0.1780e-08, &
+          0.1910e-08, 0.2140e-08, 0.2260e-08, 0.2540e-08, 0.2930e-08, 0.3110e-08, &
+          0.3290e-08, 0.3520e-08, 0.4040e-08, 0.4880e-08, 0.5730e-08, 0.6890e-08, &
+          0.8580e-08, 0.1040e-07, 0.1220e-07, 0.1430e-07, 0.1660e-07, 0.1890e-07, &
+          0.2090e-07, 0.2400e-07, 0.2900e-07, 0.3440e-07, 0.4030e-07, 0.4300e-07, &
+          0.4920e-07, 0.5870e-07, 0.7080e-07, 0.8580e-07, 0.1020e-06, 0.1180e-06, &
+          0.1340e-06, 0.1400e-06, 0.1430e-06, 0.1450e-06, 0.1510e-06, 0.1830e-06, &
+          0.2150e-06, 0.2650e-06, 0.3350e-06, 0.3920e-06, 0.4200e-06, 0.4440e-06, &
+          0.4740e-06, 0.5110e-06, 0.5530e-06, 0.6020e-06, 0.7550e-06, 0.9260e-06, &
+          0.1120e-05, 0.1330e-05, 0.1620e-05, 0.2000e-05, 0.2250e-05, 0.2330e-05, &
+          0.2330e-05, 0.2170e-05, 0.1960e-05, 0.1810e-05, 0.1740e-05, 0.1730e-05, &
+          0.1700e-05, 0.1760e-05, 0.1820e-05, 0.2040e-05, 0.2250e-05, 0.2290e-05, &
+          0.3040e-05, 0.3840e-05, 0.4770e-05, 0.5760e-05, 0.6710e-05, 0.8660e-05, &
+          0.1020e-04, 0.1130e-04, 0.1220e-04, 0.1290e-04, 0.1320e-04, 0.1350e-04, &
+          0.1330e-04, 0.1320e-04, 0.1320e-04, 0.1310e-04, 0.1320e-04, 0.1320e-04, &
+          0.1340e-04, 0.1390e-04, 0.1420e-04, 0.1480e-04, 0.1580e-04, 0.1740e-04, &
+          0.1980e-04, 0.2500e-04, 0.5400e-04, 0.1040e-03, 0.2030e-03, 0.2708e-03, &
+          0.3511e-03, 0.4299e-03, 0.5181e-03, 0.5855e-03, 0.5899e-03, 0.5635e-03, &
+          0.5480e-03, 0.5266e-03, 0.4394e-03, 0.3701e-03, 0.3372e-03, 0.2410e-03, &
+          0.1890e-03, 0.1660e-03, 0.1450e-03, 0.1280e-03, 0.1030e-03, 0.8600e-04, &
+          0.8220e-04, 0.8030e-04, 0.8500e-04, 0.9900e-04, 0.1500e-03, 0.2950e-03, &
+          0.4687e-03, 0.7615e-03, 0.1010e-02, 0.1313e-02, 0.1539e-02, 0.1588e-02, &
+          0.1540e-02, 0.1412e-02, 0.1244e-02, 0.1068e-02, 0.8414e-03, 0.5650e-03, &
+          0.4320e-03, 0.3500e-03, 0.2870e-03, 0.2210e-03, 0.2030e-03, 0.2010e-03, &
+          0.2030e-03, 0.2140e-03, 0.2320e-03, 0.2890e-03, 0.3810e-03, 0.4620e-03, &
+          0.5480e-03, 0.6180e-03, 0.6800e-03, 0.7300e-03, 0.7820e-03, 0.8480e-03, &
+          0.9250e-03, 0.9200e-03, 0.8920e-03, 0.8700e-03, 0.8900e-03, 0.9300e-03, &
+          0.1010e-02, 0.1350e-02, 0.3420e-02, 0.7920e-02, 0.2000e-01, 0.3800e-01, &
+          0.5200e-01, 0.6800e-01, 0.9230e-01, 0.1270e+00, 0.1690e+00, 0.2210e+00, &
+          0.2760e+00, 0.3120e+00, 0.3470e+00, 0.3880e+00, 0.4380e+00, 0.4930e+00, &
+          0.5540e+00, 0.6120e+00, 0.6250e+00, 0.5930e+00, 0.5390e+00, 0.4910e+00, &
+          0.4380e+00, 0.3720e+00, 0.3000e+00, 0.2380e+00, 0.1930e+00, 0.1580e+00, &
+          0.1210e+00, 0.1030e+00, 0.8360e-01, 0.6680e-01, 0.5400e-01, 0.4220e-01, &
+          0.3420e-01, 0.2740e-01, 0.2200e-01, 0.1860e-01, 0.1520e-01, 0.1260e-01, &
+          0.1060e-01, 0.8020e-02, 0.6850e-02, 0.6600e-02, 0.6960e-02, 0.9160e-02, &
+          0.1110e-01, 0.1450e-01, 0.2000e-01, 0.2300e-01, 0.2600e-01, 0.2900e-01, &
+          0.2930e-01, 0.3000e-01, 0.2850e-01, 0.1730e-01, 0.1290e-01, 0.1200e-01, &
+          0.1250e-01, 0.1340e-01, 0.1400e-01, 0.1750e-01, 0.2400e-01, 0.3500e-01, &
+          0.3800e-01, 0.4200e-01, 0.4600e-01, 0.5200e-01, 0.5700e-01, 0.6900e-01, &
+          0.7000e-01, 0.6700e-01, 0.6500e-01, 0.6400e-01, 0.6200e-01, 0.5900e-01, &
+          0.5700e-01, 0.5600e-01, 0.5500e-01, 0.5700e-01, 0.5800e-01, 0.5700e-01, &
+          0.5500e-01, 0.5500e-01, 0.5400e-01, 0.5200e-01, 0.5200e-01, 0.5200e-01, &
+          0.5200e-01, 0.5000e-01, 0.4700e-01, 0.4300e-01, 0.3900e-01, 0.3700e-01, &
+          0.3900e-01, 0.4000e-01, 0.4200e-01, 0.4400e-01, 0.4500e-01, 0.4600e-01, &
+          0.4700e-01, 0.5100e-01, 0.6500e-01, 0.7500e-01, 0.8800e-01, 0.1080e+00, &
+          0.1340e+00, 0.1680e+00, 0.2040e+00, 0.2480e+00, 0.2800e+00, 0.3410e+00, &
+          0.3790e+00, 0.4090e+00, 0.4220e+00, 0.4220e+00, 0.4030e+00, 0.3890e+00, &
+          0.3740e+00, 0.3540e+00, 0.3350e+00, 0.3150e+00, 0.2940e+00, 0.2710e+00, &
+          0.2460e+00, 0.1980e+00, 0.1640e+00, 0.1520e+00, 0.1420e+00, 0.1280e+00, &
+          0.1250e+00, 0.1230e+00, 0.1160e+00, 0.1070e+00, 0.7900e-01, 0.7200e-01, &
+          0.7600e-01, 0.7500e-01, 0.6700e-01, 0.5500e-01, 0.4500e-01, 0.2900e-01, &
+          0.2750e-01, 0.2700e-01, 0.2730e-01, 0.2890e-01, 0.3000e-01, 0.3400e-01, &
+          0.5300e-01, 0.7550e-01, 0.1060e+00, 0.1350e+00, 0.1761e+00, 0.2229e+00, &
+          0.2746e+00, 0.3280e+00, 0.3906e+00, 0.4642e+00, 0.5247e+00, 0.5731e+00, &
+          0.6362e+00, 0.6839e+00, 0.7091e+00, 0.6790e+00, 0.6250e+00, 0.5654e+00, &
+          0.5433e+00, 0.5292e+00, 0.5070e+00, 0.4883e+00, 0.4707e+00, 0.4203e+00, &
+          0.3771e+00, 0.3376e+00, 0.3056e+00, 0.2835e+00, 0.3170e+00, 0.3517e+00, &
+          0.3902e+00, 0.4509e+00, 0.4671e+00, 0.4779e+00, 0.4890e+00, 0.4899e+00, &
+          0.4873e+00, 0.4766e+00, 0.4508e+00, 0.4193e+00, 0.3880e+00, 0.3433e+00, &
+          0.3118e+00, 0.2935e+00, 0.2350e+00, 0.1981e+00, 0.1865e+00, 0.1771e+00, &
+          0.1620e+00, 0.1490e+00, 0.1390e+00, 0.1200e+00, 0.9620e-01, 0.8300e-01]
+    real(wp),parameter,dimension(nwl) :: &
+         wl = &
+         [0.4430e-01, 0.4510e-01, 0.4590e-01, 0.4680e-01, 0.4770e-01, 0.4860e-01, &
+          0.4960e-01, 0.5060e-01, 0.5170e-01, 0.5280e-01, 0.5390e-01, 0.5510e-01, &
+          0.5640e-01, 0.5770e-01, 0.5900e-01, 0.6050e-01, 0.6200e-01, 0.6360e-01, &
+          0.6530e-01, 0.6700e-01, 0.6890e-01, 0.7080e-01, 0.7290e-01, 0.7380e-01, &
+          0.7510e-01, 0.7750e-01, 0.8000e-01, 0.8270e-01, 0.8550e-01, 0.8860e-01, &
+          0.9180e-01, 0.9300e-01, 0.9540e-01, 0.9920e-01, 0.1033e+00, 0.1078e+00, &
+          0.1100e+00, 0.1127e+00, 0.1140e+00, 0.1181e+00, 0.1210e+00, 0.1240e+00, &
+          0.1272e+00, 0.1295e+00, 0.1305e+00, 0.1319e+00, 0.1333e+00, 0.1348e+00, &
+          0.1362e+00, 0.1370e+00, 0.1378e+00, 0.1387e+00, 0.1393e+00, 0.1409e+00, &
+          0.1425e+00, 0.1435e+00, 0.1442e+00, 0.1450e+00, 0.1459e+00, 0.1468e+00, &
+          0.1476e+00, 0.1480e+00, 0.1485e+00, 0.1494e+00, 0.1512e+00, 0.1531e+00, &
+          0.1540e+00, 0.1550e+00, 0.1569e+00, 0.1580e+00, 0.1589e+00, 0.1610e+00, &
+          0.1625e+00, 0.1648e+00, 0.1669e+00, 0.1692e+00, 0.1713e+00, 0.1737e+00, &
+          0.1757e+00, 0.1779e+00, 0.1802e+00, 0.1809e+00, 0.1821e+00, 0.1833e+00, &
+          0.1843e+00, 0.1850e+00, 0.1860e+00, 0.1870e+00, 0.1880e+00, 0.1890e+00, &
+          0.1900e+00, 0.1910e+00, 0.1930e+00, 0.1950e+00, 0.2100e+00, 0.2500e+00, &
+          0.3000e+00, 0.3500e+00, 0.4000e+00, 0.4100e+00, 0.4200e+00, 0.4300e+00, &
+          0.4400e+00, 0.4500e+00, 0.4600e+00, 0.4700e+00, 0.4800e+00, 0.4900e+00, &
+          0.5000e+00, 0.5100e+00, 0.5200e+00, 0.5300e+00, 0.5400e+00, 0.5500e+00, &
+          0.5600e+00, 0.5700e+00, 0.5800e+00, 0.5900e+00, 0.6000e+00, 0.6100e+00, &
+          0.6200e+00, 0.6300e+00, 0.6400e+00, 0.6500e+00, 0.6600e+00, 0.6700e+00, &
+          0.6800e+00, 0.6900e+00, 0.7000e+00, 0.7100e+00, 0.7200e+00, 0.7300e+00, &
+          0.7400e+00, 0.7500e+00, 0.7600e+00, 0.7700e+00, 0.7800e+00, 0.7900e+00, &
+          0.8000e+00, 0.8100e+00, 0.8200e+00, 0.8300e+00, 0.8400e+00, 0.8500e+00, &
+          0.8600e+00, 0.8700e+00, 0.8800e+00, 0.8900e+00, 0.9000e+00, 0.9100e+00, &
+          0.9200e+00, 0.9300e+00, 0.9400e+00, 0.9500e+00, 0.9600e+00, 0.9700e+00, &
+          0.9800e+00, 0.9900e+00, 0.1000e+01, 0.1010e+01, 0.1020e+01, 0.1030e+01, &
+          0.1040e+01, 0.1050e+01, 0.1060e+01, 0.1070e+01, 0.1080e+01, 0.1090e+01, &
+          0.1100e+01, 0.1110e+01, 0.1120e+01, 0.1130e+01, 0.1140e+01, 0.1150e+01, &
+          0.1160e+01, 0.1170e+01, 0.1180e+01, 0.1190e+01, 0.1200e+01, 0.1210e+01, &
+          0.1220e+01, 0.1230e+01, 0.1240e+01, 0.1250e+01, 0.1260e+01, 0.1270e+01, &
+          0.1280e+01, 0.1290e+01, 0.1300e+01, 0.1310e+01, 0.1320e+01, 0.1330e+01, &
+          0.1340e+01, 0.1350e+01, 0.1360e+01, 0.1370e+01, 0.1380e+01, 0.1390e+01, &
+          0.1400e+01, 0.1410e+01, 0.1420e+01, 0.1430e+01, 0.1440e+01, 0.1449e+01, &
+          0.1460e+01, 0.1471e+01, 0.1481e+01, 0.1493e+01, 0.1504e+01, 0.1515e+01, &
+          0.1527e+01, 0.1538e+01, 0.1563e+01, 0.1587e+01, 0.1613e+01, 0.1650e+01, &
+          0.1680e+01, 0.1700e+01, 0.1730e+01, 0.1760e+01, 0.1800e+01, 0.1830e+01, &
+          0.1840e+01, 0.1850e+01, 0.1855e+01, 0.1860e+01, 0.1870e+01, 0.1890e+01, &
+          0.1905e+01, 0.1923e+01, 0.1942e+01, 0.1961e+01, 0.1980e+01, 0.2000e+01, &
+          0.2020e+01, 0.2041e+01, 0.2062e+01, 0.2083e+01, 0.2105e+01, 0.2130e+01, &
+          0.2150e+01, 0.2170e+01, 0.2190e+01, 0.2220e+01, 0.2240e+01, 0.2245e+01, &
+          0.2250e+01, 0.2260e+01, 0.2270e+01, 0.2290e+01, 0.2310e+01, 0.2330e+01, &
+          0.2350e+01, 0.2370e+01, 0.2390e+01, 0.2410e+01, 0.2430e+01, 0.2460e+01, &
+          0.2500e+01, 0.2520e+01, 0.2550e+01, 0.2565e+01, 0.2580e+01, 0.2590e+01, &
+          0.2600e+01, 0.2620e+01, 0.2675e+01, 0.2725e+01, 0.2778e+01, 0.2817e+01, &
+          0.2833e+01, 0.2849e+01, 0.2865e+01, 0.2882e+01, 0.2899e+01, 0.2915e+01, &
+          0.2933e+01, 0.2950e+01, 0.2967e+01, 0.2985e+01, 0.3003e+01, 0.3021e+01, &
+          0.3040e+01, 0.3058e+01, 0.3077e+01, 0.3096e+01, 0.3115e+01, 0.3135e+01, &
+          0.3155e+01, 0.3175e+01, 0.3195e+01, 0.3215e+01, 0.3236e+01, 0.3257e+01, &
+          0.3279e+01, 0.3300e+01, 0.3322e+01, 0.3345e+01, 0.3367e+01, 0.3390e+01, &
+          0.3413e+01, 0.3436e+01, 0.3460e+01, 0.3484e+01, 0.3509e+01, 0.3534e+01, &
+          0.3559e+01, 0.3624e+01, 0.3732e+01, 0.3775e+01, 0.3847e+01, 0.3969e+01, &
+          0.4099e+01, 0.4239e+01, 0.4348e+01, 0.4387e+01, 0.4444e+01, 0.4505e+01, &
+          0.4547e+01, 0.4560e+01, 0.4580e+01, 0.4719e+01, 0.4904e+01, 0.5000e+01, &
+          0.5100e+01, 0.5200e+01, 0.5263e+01, 0.5400e+01, 0.5556e+01, 0.5714e+01, &
+          0.5747e+01, 0.5780e+01, 0.5814e+01, 0.5848e+01, 0.5882e+01, 0.6061e+01, &
+          0.6135e+01, 0.6250e+01, 0.6289e+01, 0.6329e+01, 0.6369e+01, 0.6410e+01, &
+          0.6452e+01, 0.6494e+01, 0.6579e+01, 0.6667e+01, 0.6757e+01, 0.6897e+01, &
+          0.7042e+01, 0.7143e+01, 0.7246e+01, 0.7353e+01, 0.7463e+01, 0.7576e+01, &
+          0.7692e+01, 0.7812e+01, 0.7937e+01, 0.8065e+01, 0.8197e+01, 0.8333e+01, &
+          0.8475e+01, 0.8696e+01, 0.8929e+01, 0.9091e+01, 0.9259e+01, 0.9524e+01, &
+          0.9804e+01, 0.1000e+02, 0.1020e+02, 0.1031e+02, 0.1042e+02, 0.1053e+02, &
+          0.1064e+02, 0.1075e+02, 0.1087e+02, 0.1100e+02, 0.1111e+02, 0.1136e+02, &
+          0.1163e+02, 0.1190e+02, 0.1220e+02, 0.1250e+02, 0.1282e+02, 0.1299e+02, &
+          0.1316e+02, 0.1333e+02, 0.1351e+02, 0.1370e+02, 0.1389e+02, 0.1408e+02, &
+          0.1429e+02, 0.1471e+02, 0.1515e+02, 0.1538e+02, 0.1563e+02, 0.1613e+02, &
+          0.1639e+02, 0.1667e+02, 0.1695e+02, 0.1724e+02, 0.1818e+02, 0.1887e+02, &
+          0.1923e+02, 0.1961e+02, 0.2000e+02, 0.2041e+02, 0.2083e+02, 0.2222e+02, &
+          0.2260e+02, 0.2305e+02, 0.2360e+02, 0.2460e+02, 0.2500e+02, 0.2600e+02, &
+          0.2857e+02, 0.3100e+02, 0.3333e+02, 0.3448e+02, 0.3564e+02, 0.3700e+02, &
+          0.3824e+02, 0.3960e+02, 0.4114e+02, 0.4276e+02, 0.4358e+02, 0.4458e+02, &
+          0.4550e+02, 0.4615e+02, 0.4671e+02, 0.4736e+02, 0.4800e+02, 0.4878e+02, &
+          0.5003e+02, 0.5128e+02, 0.5275e+02, 0.5350e+02, 0.5424e+02, 0.5500e+02, &
+          0.5574e+02, 0.5640e+02, 0.5700e+02, 0.5746e+02, 0.5840e+02, 0.5929e+02, &
+          0.6000e+02, 0.6100e+02, 0.6125e+02, 0.6250e+02, 0.6378e+02, 0.6467e+02, &
+          0.6558e+02, 0.6655e+02, 0.6760e+02, 0.6900e+02, 0.7053e+02, 0.7300e+02, &
+          0.7500e+02, 0.7629e+02, 0.8000e+02, 0.8297e+02, 0.8500e+02, 0.8680e+02, &
+          0.9080e+02, 0.9517e+02, 0.1000e+03, 0.1200e+03, 0.1500e+03, 0.1670e+03]
+    real(wp),parameter,dimension(nwlt,4) :: &
+         tabimt = reshape(source= &
+        (/0.8300e-01, 0.6900e-01, 0.5700e-01, 0.4560e-01, 0.3790e-01, 0.3140e-01, &
+          0.2620e-01, 0.2240e-01, 0.1960e-01, 0.1760e-01, 0.1665e-01, 0.1620e-01, &
+          0.1550e-01, 0.1470e-01, 0.1390e-01, 0.1320e-01, 0.1250e-01, 0.1180e-01, & 
+          0.1060e-01, 0.9540e-02, 0.8560e-02, 0.6210e-02, 0.4490e-02, 0.3240e-02, &
+          0.2340e-02, 0.1880e-02, 0.1740e-02, 0.1500e-02, 0.1320e-02, 0.1160e-02, &
+          0.8800e-03, 0.6950e-03, 0.4640e-03, 0.3400e-03, 0.3110e-03, 0.2940e-03, &
+          0.2790e-03, 0.2700e-03, 0.2640e-03, 0.2580e-03, 0.2520e-03, 0.2490e-03, &
+          0.2540e-03, 0.2640e-03, 0.2740e-03, 0.2890e-03, 0.3050e-03, 0.3150e-03, &
+          0.3460e-03, 0.3820e-03, 0.4620e-03, 0.5000e-03, 0.5500e-03, 0.5950e-03, &
+          0.6470e-03, 0.6920e-03, 0.7420e-03, 0.8200e-03, 0.9700e-03, 0.1950e-02, &
+          0.5780e-02, 0.9700e-02, 0.8300e-01, 0.6900e-01, 0.5700e-01, 0.4560e-01, &
+          0.3790e-01, 0.3140e-01, 0.2620e-01, 0.2240e-01, 0.1960e-01, 0.1760e-01, &
+          0.1665e-01, 0.1600e-01, 0.1500e-01, 0.1400e-01, 0.1310e-01, 0.1230e-01, &
+          0.1150e-01, 0.1080e-01, 0.9460e-02, 0.8290e-02, 0.7270e-02, 0.4910e-02, &
+          0.3300e-02, 0.2220e-02, 0.1490e-02, 0.1140e-02, 0.1060e-02, 0.9480e-03, &
+          0.8500e-03, 0.7660e-03, 0.6300e-03, 0.5200e-03, 0.3840e-03, 0.2960e-03, &
+          0.2700e-03, 0.2520e-03, 0.2440e-03, 0.2360e-03, 0.2300e-03, 0.2280e-03, &
+          0.2250e-03, 0.2200e-03, 0.2160e-03, 0.2170e-03, 0.2200e-03, 0.2250e-03, &
+          0.2320e-03, 0.2390e-03, 0.2600e-03, 0.2860e-03, 0.3560e-03, 0.3830e-03, &
+          0.4150e-03, 0.4450e-03, 0.4760e-03, 0.5080e-03, 0.5400e-03, 0.5860e-03, &
+          0.6780e-03, 0.1280e-02, 0.3550e-02, 0.5600e-02, 0.8300e-01, 0.6900e-01, &
+          0.5700e-01, 0.4560e-01, 0.3790e-01, 0.3140e-01, 0.2620e-01, 0.2190e-01, &
+          0.1880e-01, 0.1660e-01, 0.1540e-01, 0.1470e-01, 0.1350e-01, 0.1250e-01, &
+          0.1150e-01, 0.1060e-01, 0.9770e-02, 0.9010e-02, 0.7660e-02, 0.6520e-02, &
+          0.5540e-02, 0.3420e-02, 0.2100e-02, 0.1290e-02, 0.7930e-03, 0.5700e-03, &
+          0.5350e-03, 0.4820e-03, 0.4380e-03, 0.4080e-03, 0.3500e-03, 0.3200e-03, &
+          0.2550e-03, 0.2120e-03, 0.2000e-03, 0.1860e-03, 0.1750e-03, 0.1660e-03, &
+          0.1560e-03, 0.1490e-03, 0.1440e-03, 0.1350e-03, 0.1210e-03, 0.1160e-03, &
+          0.1160e-03, 0.1170e-03, 0.1200e-03, 0.1230e-03, 0.1320e-03, 0.1440e-03, &
+          0.1680e-03, 0.1800e-03, 0.1900e-03, 0.2090e-03, 0.2160e-03, 0.2290e-03, &
+          0.2400e-03, 0.2600e-03, 0.2920e-03, 0.6100e-03, 0.1020e-02, 0.1810e-02, &
+          0.8300e-01, 0.6900e-01, 0.5700e-01, 0.4450e-01, 0.3550e-01, 0.2910e-01, &
+          0.2440e-01, 0.1970e-01, 0.1670e-01, 0.1400e-01, 0.1235e-01, 0.1080e-01, &
+          0.8900e-02, 0.7340e-02, 0.6400e-02, 0.5600e-02, 0.5000e-02, 0.4520e-02, &
+          0.3680e-02, 0.2990e-02, 0.2490e-02, 0.1550e-02, 0.9610e-03, 0.5950e-03, &
+          0.3690e-03, 0.2670e-03, 0.2510e-03, 0.2290e-03, 0.2110e-03, 0.1960e-03, &
+          0.1730e-03, 0.1550e-03, 0.1310e-03, 0.1130e-03, 0.1060e-03, 0.9900e-04, &
+          0.9300e-04, 0.8730e-04, 0.8300e-04, 0.7870e-04, 0.7500e-04, 0.6830e-04, &
+          0.5600e-04, 0.4960e-04, 0.4550e-04, 0.4210e-04, 0.3910e-04, 0.3760e-04, &
+          0.3400e-04, 0.3100e-04, 0.2640e-04, 0.2510e-04, 0.2430e-04, 0.2390e-04, &
+          0.2370e-04, 0.2380e-04, 0.2400e-04, 0.2460e-04, 0.2660e-04, 0.4450e-04, &
+          0.8700e-04, 0.1320e-03/),shape=(/nwlt,4/))
+
+    real(wp),parameter,dimension(nwl) :: &
+         tabre = &
+         [0.83441,   0.83676,   0.83729,   0.83771,   0.83827,   0.84038, &
+          0.84719,   0.85522,   0.86047,   0.86248,   0.86157,   0.86093, &
+          0.86419,   0.86916,   0.87764,   0.89296,   0.91041,   0.93089, &
+          0.95373,   0.98188,   1.02334,   1.06735,   1.11197,   1.13134, &
+          1.15747,   1.20045,   1.23840,   1.27325,   1.32157,   1.38958, &
+          1.41644,   1.40906,   1.40063,   1.40169,   1.40934,   1.40221, &
+          1.39240,   1.38424,   1.38075,   1.38186,   1.39634,   1.40918, &
+          1.40256,   1.38013,   1.36303,   1.34144,   1.32377,   1.30605, &
+          1.29054,   1.28890,   1.28931,   1.30190,   1.32025,   1.36302, &
+          1.41872,   1.45834,   1.49028,   1.52128,   1.55376,   1.57782, &
+          1.59636,   1.60652,   1.61172,   1.61919,   1.62522,   1.63404, &
+          1.63689,   1.63833,   1.63720,   1.63233,   1.62222,   1.58269, &
+          1.55635,   1.52453,   1.50320,   1.48498,   1.47226,   1.45991, &
+          1.45115,   1.44272,   1.43498,   1.43280,   1.42924,   1.42602, &
+          1.42323,   1.42143,   1.41897,   1.41660,   1.41434,   1.41216, &
+          1.41006,   1.40805,   1.40423,   1.40067,   1.38004,   1.35085, &
+          1.33394,   1.32492,   1.31940,   1.31854,   1.31775,   1.31702, &
+          1.31633,   1.31569,   1.31509,   1.31452,   1.31399,   1.31349, &
+          1.31302,   1.31257,   1.31215,   1.31175,   1.31136,   1.31099, &
+          1.31064,   1.31031,   1.30999,   1.30968,   1.30938,   1.30909, &
+          1.30882,   1.30855,   1.30829,   1.30804,   1.30780,   1.30756, &
+          1.30733,   1.30710,   1.30688,   1.30667,   1.30646,   1.30625, &
+          1.30605,   1.30585,   1.30566,   1.30547,   1.30528,   1.30509, &
+          1.30491,   1.30473,   1.30455,   1.30437,   1.30419,   1.30402, &
+          1.30385,   1.30367,   1.30350,   1.30333,   1.30316,   1.30299, &
+          1.30283,   1.30266,   1.30249,   1.30232,   1.30216,   1.30199, &
+          1.30182,   1.30166,   1.30149,   1.30132,   1.30116,   1.30099, &
+          1.30082,   1.30065,   1.30048,   1.30031,   1.30014,   1.29997, &
+          1.29979,   1.29962,   1.29945,   1.29927,   1.29909,   1.29891, &
+          1.29873,   1.29855,   1.29837,   1.29818,   1.29800,   1.29781, &
+          1.29762,   1.29743,   1.29724,   1.29705,   1.29686,   1.29666, &
+          1.29646,   1.29626,   1.29605,   1.29584,   1.29563,   1.29542, &
+          1.29521,   1.29499,   1.29476,   1.29453,   1.29430,   1.29406, &
+          1.29381,   1.29355,   1.29327,   1.29299,   1.29272,   1.29252, &
+          1.29228,   1.29205,   1.29186,   1.29167,   1.29150,   1.29130, &
+          1.29106,   1.29083,   1.29025,   1.28962,   1.28891,   1.28784, &
+          1.28689,   1.28623,   1.28521,   1.28413,   1.28261,   1.28137, &
+          1.28093,   1.28047,   1.28022,   1.27998,   1.27948,   1.27849, &
+          1.27774,   1.27691,   1.27610,   1.27535,   1.27471,   1.27404, &
+          1.27329,   1.27240,   1.27139,   1.27029,   1.26901,   1.26736, &
+          1.26591,   1.26441,   1.26284,   1.26036,   1.25860,   1.25815, &
+          1.25768,   1.25675,   1.25579,   1.25383,   1.25179,   1.24967, &
+          1.24745,   1.24512,   1.24266,   1.24004,   1.23725,   1.23270, &
+          1.22583,   1.22198,   1.21548,   1.21184,   1.20790,   1.20507, &
+          1.20209,   1.19566,   1.17411,   1.14734,   1.10766,   1.06739, &
+          1.04762,   1.02650,   1.00357,   0.98197,   0.96503,   0.95962, &
+          0.97269,   0.99172,   1.00668,   1.02186,   1.04270,   1.07597, &
+          1.12954,   1.21267,   1.32509,   1.42599,   1.49656,   1.55095, &
+          1.59988,   1.63631,   1.65024,   1.64278,   1.62691,   1.61284, &
+          1.59245,   1.57329,   1.55770,   1.54129,   1.52654,   1.51139, &
+          1.49725,   1.48453,   1.47209,   1.46125,   1.45132,   1.44215, &
+          1.43366,   1.41553,   1.39417,   1.38732,   1.37735,   1.36448, &
+          1.35414,   1.34456,   1.33882,   1.33807,   1.33847,   1.34053, &
+          1.34287,   1.34418,   1.34634,   1.34422,   1.33453,   1.32897, &
+          1.32333,   1.31800,   1.31432,   1.30623,   1.29722,   1.28898, &
+          1.28730,   1.28603,   1.28509,   1.28535,   1.28813,   1.30156, &
+          1.30901,   1.31720,   1.31893,   1.32039,   1.32201,   1.32239, &
+          1.32149,   1.32036,   1.31814,   1.31705,   1.31807,   1.31953, &
+          1.31933,   1.31896,   1.31909,   1.31796,   1.31631,   1.31542, &
+          1.31540,   1.31552,   1.31455,   1.31193,   1.30677,   1.29934, &
+          1.29253,   1.28389,   1.27401,   1.26724,   1.25990,   1.24510, &
+          1.22241,   1.19913,   1.17150,   1.15528,   1.13700,   1.11808, &
+          1.10134,   1.09083,   1.08734,   1.09254,   1.10654,   1.14779, &
+          1.20202,   1.25825,   1.32305,   1.38574,   1.44478,   1.47170, &
+          1.49619,   1.51652,   1.53328,   1.54900,   1.56276,   1.57317, &
+          1.58028,   1.57918,   1.56672,   1.55869,   1.55081,   1.53807, &
+          1.53296,   1.53220,   1.53340,   1.53289,   1.51705,   1.50097, &
+          1.49681,   1.49928,   1.50153,   1.49856,   1.49053,   1.46070, &
+          1.45182,   1.44223,   1.43158,   1.41385,   1.40676,   1.38955, &
+          1.34894,   1.31039,   1.26420,   1.23656,   1.21663,   1.20233, &
+          1.19640,   1.19969,   1.20860,   1.22173,   1.24166,   1.28175, &
+          1.32784,   1.38657,   1.46486,   1.55323,   1.60379,   1.61877, &
+          1.62963,   1.65712,   1.69810,   1.72065,   1.74865,   1.76736, &
+          1.76476,   1.75011,   1.72327,   1.68490,   1.62398,   1.59596, &
+          1.58514,   1.59917,   1.61405,   1.66625,   1.70663,   1.73713, &
+          1.76860,   1.80343,   1.83296,   1.85682,   1.87411,   1.89110, &
+          1.89918,   1.90432,   1.90329,   1.88744,   1.87499,   1.86702, &
+          1.85361,   1.84250,   1.83225,   1.81914,   1.82268,   1.82961]
+    real(wp),parameter,dimension(nwlt,4) :: &
+         tabret = reshape( &
+           source =(/1.82961,   1.83258,   1.83149, &
+          1.82748,   1.82224,   1.81718,   1.81204,   1.80704,   1.80250, &
+          1.79834,   1.79482,   1.79214,   1.78843,   1.78601,   1.78434, &
+          1.78322,   1.78248,   1.78201,   1.78170,   1.78160,   1.78190, &
+          1.78300,   1.78430,   1.78520,   1.78620,   1.78660,   1.78680, &
+          1.78690,   1.78700,   1.78700,   1.78710,   1.78710,   1.78720, &
+          1.78720,   1.78720,   1.78720,   1.78720,   1.78720,   1.78720, &
+          1.78720,   1.78720,   1.78720,   1.78720,   1.78720,   1.78720, &
+          1.78720,   1.78720,   1.78720,   1.78720,   1.78720,   1.78720, &
+          1.78720,   1.78720,   1.78720,   1.78720,   1.78720,   1.78720, &
+          1.78720,   1.78720,   1.78720,   1.78720,   1.78800,            &
+          1.82961,   1.83258,   1.83149,   1.82748,                       &
+          1.82224,   1.81718,   1.81204,   1.80704,   1.80250,   1.79834, &
+          1.79482,   1.79214,   1.78843,   1.78601,   1.78434,   1.78322, &
+          1.78248,   1.78201,   1.78170,   1.78160,   1.78190,   1.78300, &
+          1.78430,   1.78520,   1.78610,   1.78630,   1.78640,   1.78650, &
+          1.78650,   1.78650,   1.78650,   1.78650,   1.78650,   1.78650, &
+          1.78650,   1.78650,   1.78650,   1.78650,   1.78650,   1.78650, &
+          1.78650,   1.78650,   1.78650,   1.78650,   1.78650,   1.78650, &
+          1.78650,   1.78650,   1.78650,   1.78650,   1.78650,   1.78650, &
+          1.78650,   1.78650,   1.78650,   1.78650,   1.78650,   1.78650, &
+          1.78650,   1.78650,   1.78650,   1.78720,                       &
+          1.82961,   1.83258,   1.83149,   1.82748,   1.82224,            &
+          1.81718,   1.81204,   1.80704,   1.80250,   1.79834,   1.79482, &
+          1.79214,   1.78843,   1.78601,   1.78434,   1.78322,   1.78248, &
+          1.78201,   1.78160,   1.78140,   1.78160,   1.78220,   1.78310, &
+          1.78380,   1.78390,   1.78400,   1.78400,   1.78400,   1.78400, &
+          1.78400,   1.78390,   1.78380,   1.78370,   1.78370,   1.78370, &
+          1.78370,   1.78370,   1.78370,   1.78370,   1.78370,   1.78370, &
+          1.78370,   1.78370,   1.78370,   1.78370,   1.78370,   1.78370, &
+          1.78370,   1.78370,   1.78370,   1.78370,   1.78370,   1.78370, &
+          1.78370,   1.78370,   1.78370,   1.78370,   1.78370,   1.78370, &
+          1.78370,   1.78400,   1.78450,                                  &
+          1.82961,   1.83258,   1.83149,   1.82748,   1.82224,   1.81718, &
+          1.81204,   1.80704,   1.80250,   1.79834,   1.79482,   1.79214, &
+          1.78843,   1.78601,   1.78434,   1.78322,   1.78248,   1.78201, &
+          1.78150,   1.78070,   1.78010,   1.77890,   1.77790,   1.77730, &
+          1.77720,   1.77720,   1.77720,   1.77720,   1.77720,   1.77720, &
+          1.77720,   1.77720,   1.77720,   1.77720,   1.77720,   1.77720, &
+          1.77720,   1.77720,   1.77720,   1.77720,   1.77720,   1.77720, &
+          1.77720,   1.77720,   1.77720,   1.77720,   1.77720,   1.77720, &
+          1.77720,   1.77720,   1.77720,   1.77720,   1.77720,   1.77720, &
+          1.77720,   1.77720,   1.77720,   1.77720,   1.77720,   1.77720, &
+          1.77720,   1.77800/),shape=(/nwlt,4/))
+
+    ! #####################################################################
+    ! Defines wavelength dependent complex index of refraction for ice.
+    ! Allowable wavelength range extends from 0.045 microns to 8.6 meter
+    ! temperature dependence only considered beyond 167 microns.
+    ! 
+    ! interpolation is done     n_r  vs. log(xlam)
+    !                           n_r  vs.        t
+    !                       log(n_i) vs. log(xlam)
+    !                       log(n_i) vs.        t
+    !
+    ! Stephen G. Warren - 1983
+    ! Dept. of Atmospheric Sciences
+    ! University of Washington
+    ! Seattle, Wa  98195
+    !
+    ! Based on
+    !
+    !    Warren,S.G.,1984.
+    !    Optical constants of ice from the ultraviolet to the microwave.
+    !    Applied Optics,23,1206-1225
+    !
+    ! Reference temperatures are -1.0,-5.0,-20.0, and -60.0 deg C
+    ! #####################################################################
+
+    pi  = acos(-1._wp)
+    n_r = 0._wp
+    n_i = 0._wp
+    tk  = t
+    
+    ! Convert frequency to wavelength (um)
+    alam=3E5_wp/freq
+    if((alam < wlmin) .or. (alam > wlmax)) then
+       call errorMessage('FATAL ERROR(optics/optics_lib.f90:m_ice): wavelength out of bounds')
+       return
+    endif
+    
+    if (alam < cutice) then
+       ! Region from 0.045 microns to 167.0 microns - no temperature depend
+       do i=2,nwl
+          if(alam < wl(i)) continue
+       enddo
+       x1  = log(wl(i-1))
+       x2  = log(wl(i))
+       y1  = tabre(i-1)
+       y2  = tabre(i)
+       x   = log(alam)
+       y   = ((x-x1)*(y2-y1)/(x2-x1))+y1
+       n_r = y
+       y1  = log(abs(tabim(i-1)))
+       y2  = log(abs(tabim(i)))
+       y   = ((x-x1)*(y2-y1)/(x2-x1))+y1
+       n_i = exp(y)    
+    else
+       ! Region from 167.0 microns to 8.6 meters - temperature dependence
+       if(tk > temref(1)) tk=temref(1)
+       if(tk < temref(4)) tk=temref(4)
+       do i=2,4
+          if(tk.ge.temref(i)) go to 12
+       enddo
+12     lt1 = i
+       lt2 = i-1
+       do i=2,nwlt
+          if(alam.le.wlt(i)) go to 14
+       enddo
+14     x1  = log(wlt(i-1))
+       x2  = log(wlt(i))
+       y1  = tabret(i-1,lt1)
+       y2  = tabret(i,lt1)
+       x   = log(alam)
+       ylo = ((x-x1)*(y2-y1)/(x2-x1))+y1
+       y1  = tabret(i-1,lt2)
+       y2  = tabret(i,lt2)
+       yhi = ((x-x1)*(y2-y1)/(x2-x1))+y1
+       t1  = temref(lt1)
+       t2  = temref(lt2)
+       y   = ((tk-t1)*(yhi-ylo)/(t2-t1))+ylo
+       n_r = y
+       y1  = log(abs(tabimt(i-1,lt1)))
+       y2  = log(abs(tabimt(i,lt1)))
+       ylo = ((x-x1)*(y2-y1)/(x2-x1))+y1
+       y1  = log(abs(tabimt(i-1,lt2)))
+       y2  = log(abs(tabimt(i,lt2)))
+       yhi = ((x-x1)*(y2-y1)/(x2-x1))+y1
+       y   = ((tk-t1)*(yhi-ylo)/(t2-t1))+ylo
+       n_i = exp(y)
+    endif
+  end subroutine m_ice
+
+  ! ############################################################################
+  ! subroutine MIEINT
+  ! ############################################################################
+  Subroutine MieInt(Dx, SCm, Inp, Dqv, Dqxt, Dqsc, Dbsc, Dg, Xs1, Xs2, DPh, Error)
+    ! ##########################################################################
+    !
+    !     General purpose Mie scattering routine for single particles
+    !     Author: R Grainger 1990
+    !     History:
+    !     G Thomas, March 2005: Added calculation of Phase function and
+    !     code to ensure correct calculation of backscatter coeficient
+    !     Options/Extend_Source
+    !
+    ! ##########################################################################
+    ! INPUTS
+    integer, intent(in) :: &
+         Inp
+    real(wp),intent(in) :: &
+         Dx !
+    real(wp),intent(in),dimension(Inp) :: &
+         Dqv
+    Complex(wp),intent(in) :: &
+         SCm!
+
+    ! OUTPUTS
+    Complex(wp),intent(out),dimension(InP) :: &
+         Xs1,  & !
+         Xs2     !
+    real(wp),intent(out) :: &
+         Dqxt, & !
+         Dqsc, & !
+         Dg,   & !
+         Dbsc    !
+    real(wp),intent(out),dimension(InP) :: &
+         DPh
+    integer :: &
+         Error   !!
+
+    ! PARAMETERS
+    Integer,parameter :: &
+         Imaxx   = 12000, & !
+         Itermax = 30000, & ! Must be large enough to cope with the
+                            ! largest possible nmx = x * abs(scm) + 15
+                            ! or nmx =  Dx + 4.05*Dx**(1./3.) + 2.0
+         Imaxnp = 10000     ! Change this as required
+    Real(wp),parameter :: &
+         RIMax=2.5,       & ! Largest real part of refractive index
+         IRIMax = -2        ! Largest imaginary part of refractive index
+
+    ! Internal variables
+    Integer :: I, NStop, NmX, N, Inp2
+    Real(wp)  :: Chi,Chi0,Chi1,APsi,APsi0,APsi1,Psi,Psi0,Psi1
+    Real(wp),dimension(Imaxnp) :: Pi0,Pi1,Taun
+    Complex(wp) :: Ir,Cm,A,ANM1,APB,B,BNM1,AMB,Xi,Xi0,Xi1,Y
+    Complex(wp),dimension(Itermax) :: D
+    Complex(wp),dimension(Imaxnp) :: Sp,Sm!
+
+    ! ACCELERATOR VARIABLES
+    Integer :: Tnp1,Tnm1
+    Real(wp) :: Dn, Rnx,Turbo,A2
+    real(wp),dimension(Imaxnp) :: S,T
+    Complex(wp) :: A1
+    
+    If ((Dx.Gt.Imaxx) .Or. (InP.Gt.ImaxNP)) Then
+       Error = 1
+       Return
+    EndIf
+    Cm = SCm
+    Ir = 1 / Cm
+    Y =  Dx * Cm
+    If (Dx.Lt.0.02) Then
+       NStop = 2
+    Else
+       If (Dx.Le.8.0) Then
+          NStop = Dx + 4.00*Dx**(1./3.) + 2.0
+       Else
+          If (Dx.Lt. 4200.0) Then
+             NStop = Dx + 4.05*Dx**(1./3.) + 2.0
+          Else
+             NStop = Dx + 4.00*Dx**(1./3.) + 2.0
+          End If
+       End If
+    End If
+    NmX = Max(Real(NStop),Real(Abs(Y))) + 15.
+    If (Nmx .gt. Itermax) then
+       Error = 1
+       Return
+    End If
+    Inp2 = Inp+1
+!ds    D(NmX) = cmplx(0,0,Kind=Kind(0d0))
+    D(NmX) = cmplx(0,0,Kind=wp)
+    Do N = Nmx-1,1,-1
+       A1 = (N+1) / Y
+       D(N) = A1 - 1/(A1+D(N+1))
+    End Do
+    Do I =1,Inp2
+       Sm(I) = cmplx(0,0,Kind=wp)
+!ds       Sm(I) = cmplx(0,0,Kind=Kind(0d0))
+       Sp(I) = cmplx(0,0,Kind=wp)
+!ds       Sp(I) = cmplx(0,0,Kind=Kind(0d0))
+       Pi0(I) = 0
+       Pi1(I) = 1
+    End Do
+    Psi0 = Cos(Dx)
+    Psi1 = Sin(Dx)
+    Chi0 =-Sin(Dx)
+    Chi1 = Cos(Dx)
+    APsi0 = Psi0
+    APsi1 = Psi1
+    Xi0 = cmplx(APsi0,Chi0,Kind=wp)
+!ds    Xi0 = cmplx(APsi0,Chi0,Kind=Kind(0d0))
+    Xi1 = cmplx(APsi1,Chi1,Kind=wp)
+!ds    Xi1 = cmplx(APsi1,Chi1,Kind=Kind(0d0))
+    Dg = 0
+    Dqsc = 0
+    Dqxt = 0
+    Tnp1 = 1
+    Do N = 1,Nstop
+       DN = N
+       Tnp1 = Tnp1 + 2
+       Tnm1 = Tnp1 - 2
+       A2 = Tnp1 / (DN*(DN+1._wp))
+!ds       A2 = Tnp1 / (DN*(DN+1D0))
+       Turbo = (DN+1._wp) / DN
+!ds       Turbo = (DN+1D0) / DN
+       Rnx = DN/Dx
+       Psi = Tnm1*Psi1/Dx - Psi0
+!ds       Psi = Dble(Tnm1)*Psi1/Dx - Psi0
+       APsi = Psi
+       Chi = Tnm1*Chi1/Dx       - Chi0
+       Xi = cmplx(APsi,Chi,Kind=wp)
+!ds       Xi = cmplx(APsi,Chi,Kind=Kind(0d0))
+       A = ((D(N)*Ir+Rnx)*APsi-APsi1) / ((D(N)*Ir+Rnx)*  Xi-  Xi1)
+       B = ((D(N)*Cm+Rnx)*APsi-APsi1) / ((D(N)*Cm+Rnx)*  Xi-  Xi1)
+       Dqxt = Tnp1*(A + B)+ Dqxt
+!ds       Dqxt = Tnp1 *      Dble(A + B)          + Dqxt
+       Dqsc = Tnp1 * (A*Conjg(A) + B*Conjg(B)) + Dqsc
+       If (N.Gt.1) then
+          Dg = Dg + (dN*dN - 1) * (ANM1*Conjg(A) + BNM1 * Conjg(B)) / dN + TNM1 *(ANM1*Conjg(BNM1)) / (dN*dN - dN)
+!ds          Dg = Dg + (dN*dN - 1) * Dble(ANM1*Conjg(A) + BNM1 * Conjg(B)) / dN + TNM1 * Dble(ANM1*Conjg(BNM1)) / (dN*dN - dN)
+       End If
+       Anm1 = A
+       Bnm1 = B
+       APB = A2 * (A + B)
+       AMB = A2 * (A - B)
+       Do I = 1,Inp2
+          If (I.GT.Inp) Then
+             S(I) = -Pi1(I)
+          Else
+             S(I) = Dqv(I) * Pi1(I)
+          End If
+          T(I) = S(I) - Pi0(I)
+          Taun(I) = N*T(I) - Pi0(I)
+          Sp(I) = APB * (Pi1(I) + Taun(I)) + Sp(I)
+          Sm(I) = AMB * (Pi1(I) - Taun(I)) + Sm(I)
+          Pi0(I) = Pi1(I)
+          Pi1(I) = S(I) + T(I)*Turbo
+       End Do
+       Psi0 = Psi1
+       Psi1 = Psi
+       Apsi1 = Psi1
+       Chi0 = Chi1
+       Chi1 = Chi
+       Xi1 = cmplx(APsi1,Chi1,Kind=wp)
+!ds       Xi1 = cmplx(APsi1,Chi1,Kind=Kind(0d0))
+    End Do
+
+    If (Dg .GT.0) Dg = 2 * Dg / Dqsc
+    Dqsc =  2 * Dqsc / Dx**2
+    Dqxt =  2 * Dqxt / Dx**2
+    Do I = 1,Inp
+       Xs1(I) = (Sp(I)+Sm(I)) / 2
+       Xs2(I) = (Sp(I)-Sm(I)) / 2
+       Dph(I) = 2 * (Xs1(I)*Conjg(Xs1(I)) + Xs2(I)*Conjg(Xs2(I))) / (Dx**2 * Dqsc)
+!ds       Dph(I) = 2 * Dble(Xs1(I)*Conjg(Xs1(I)) + Xs2(I)*Conjg(Xs2(I))) / (Dx**2 * Dqsc)
+    End Do
+    Dbsc = 4 * Abs(( (Sp(Inp2)+Sm(Inp2))/2 )**2) / Dx**2
+    Error = 0
+    Return
+  End subroutine MieInt
+end module optics_lib
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/parasol.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/parasol.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/parasol.F90	(revision 3605)
@@ -0,0 +1,176 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2009, Centre National de la Recherche Scientifique
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History
+! December 2008, S. Bony,  H. Chepfer and J-L. Dufresne : 
+! - optimization for vectorization
+! Version 2.0 (October 2008)
+! Version 2.1 (December 2008)
+! May 2015 - D. Swales - Modified for COSPv2.0
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+module mod_parasol
+  USE COSP_KINDS,          ONLY: wp
+  USE COSP_MATH_CONSTANTS, ONLY: pi
+  use mod_cosp_config,     ONLY: R_UNDEF,PARASOL_NREFL,PARASOL_NTAU,PARASOL_TAU,PARASOL_SZA,rlumA,rlumB
+  implicit none
+
+contains
+  SUBROUTINE parasol_subcolumn(npoints,nrefl,tautot_S_liq,tautot_S_ice,refl)
+    ! ##########################################################################
+    ! Purpose: To compute Parasol reflectance signal from model-simulated profiles 
+    !          of cloud water and cloud fraction in each sub-column of each model 
+    !          gridbox.
+    !
+    !
+    ! December 2008, S. Bony,  H. Chepfer and J-L. Dufresne : 
+    ! - optimization for vectorization
+    !
+    ! Version 2.0 (October 2008)
+    ! Version 2.1 (December 2008)
+    ! ##########################################################################
+    
+    ! INPUTS
+    INTEGER,intent(in) :: &
+         npoints,              & ! Number of horizontal gridpoints
+         nrefl                   ! Number of angles for which the reflectance is computed
+    REAL(WP),intent(inout),dimension(npoints) :: &
+         tautot_S_liq,         & ! Liquid water optical thickness, from TOA to SFC
+         tautot_S_ice            ! Ice water optical thickness, from TOA to SFC
+    ! OUTPUTS
+    REAL(WP),intent(inout),dimension(npoints,nrefl) :: &
+         refl                    ! Parasol reflectances
+    
+    ! LOCAL VARIABLES
+    REAL(WP),dimension(npoints) :: &
+         tautot_S,             & ! Cloud optical thickness, from TOA to surface
+         frac_taucol_liq,      & !
+         frac_taucol_ice         !
+    
+    ! Look up table variables:
+    INTEGER                            :: ny,it 
+    REAL(WP),dimension(PARASOL_NREFL)         :: r_norm
+    REAL(WP),dimension(PARASOL_NREFL,PARASOL_NTAU-1) :: aa,ab,ba,bb
+    REAL(WP),dimension(npoints,5)      :: rlumA_mod,rlumB_mod
+    
+    !--------------------------------------------------------------------------------
+    ! Lum_norm=f(PARASOL_SZA,tau_cloud) derived from adding-doubling calculations
+    !        valid ONLY ABOVE OCEAN (albedo_sfce=5%)
+    !        valid only in one viewing direction (theta_v=30�, phi_s-phi_v=320�)
+    !        based on adding-doubling radiative transfer computation
+    !        for PARASOL_TAU values (0 to 100) and for PARASOL_SZA values (0 to 80)
+    !        for 2 scattering phase functions: liquid spherical, ice non spherical
+    
+    ! Initialize
+    rlumA_mod(1:npoints,1:5) = 0._wp
+    rlumB_mod(1:npoints,1:5) = 0._wp
+
+    r_norm(1:PARASOL_NREFL)=1._wp/ cos(pi/180._wp*PARASOL_SZA(1:PARASOL_NREFL))
+    
+    tautot_S_liq(1:npoints) = max(tautot_S_liq(1:npoints),PARASOL_TAU(1))
+    tautot_S_ice(1:npoints) = max(tautot_S_ice(1:npoints),PARASOL_TAU(1))
+    tautot_S(1:npoints)     = tautot_S_ice(1:npoints) + tautot_S_liq(1:npoints)
+
+    ! Relative fraction of the opt. thick due to liquid or ice clouds
+    WHERE (tautot_S(1:npoints) .gt. 0.)
+       frac_taucol_liq(1:npoints) = tautot_S_liq(1:npoints) / tautot_S(1:npoints)
+       frac_taucol_ice(1:npoints) = tautot_S_ice(1:npoints) / tautot_S(1:npoints)
+    ELSEWHERE
+       frac_taucol_liq(1:npoints) = 1._wp
+       frac_taucol_ice(1:npoints) = 0._wp
+    END WHERE
+    tautot_S(1:npoints)=MIN(tautot_S(1:npoints),PARASOL_TAU(PARASOL_NTAU))
+    
+    ! Linear interpolation    
+    DO ny=1,PARASOL_NTAU-1
+       ! Microphysics A (liquid clouds) 
+       aA(1:PARASOL_NREFL,ny) = (rlumA(1:PARASOL_NREFL,ny+1)-rlumA(1:PARASOL_NREFL,ny))/(PARASOL_TAU(ny+1)-PARASOL_TAU(ny))
+       bA(1:PARASOL_NREFL,ny) = rlumA(1:PARASOL_NREFL,ny) - aA(1:PARASOL_NREFL,ny)*PARASOL_TAU(ny)
+       ! Microphysics B (ice clouds)
+       aB(1:PARASOL_NREFL,ny) = (rlumB(1:PARASOL_NREFL,ny+1)-rlumB(1:PARASOL_NREFL,ny))/(PARASOL_TAU(ny+1)-PARASOL_TAU(ny))
+       bB(1:PARASOL_NREFL,ny) = rlumB(1:PARASOL_NREFL,ny) - aB(1:PARASOL_NREFL,ny)*PARASOL_TAU(ny)
+    ENDDO
+    
+    DO it=1,PARASOL_NREFL
+       DO ny=1,PARASOL_NTAU-1
+          WHERE (tautot_S(1:npoints) .ge. PARASOL_TAU(ny).and. &
+                 tautot_S(1:npoints) .le. PARASOL_TAU(ny+1))
+             rlumA_mod(1:npoints,it) = aA(it,ny)*tautot_S(1:npoints) + bA(it,ny)
+             rlumB_mod(1:npoints,it) = aB(it,ny)*tautot_S(1:npoints) + bB(it,ny)
+          END WHERE
+       END DO
+    END DO
+    
+    DO it=1,PARASOL_NREFL
+       refl(1:npoints,it) = frac_taucol_liq(1:npoints) * rlumA_mod(1:npoints,it) &
+            + frac_taucol_ice(1:npoints) * rlumB_mod(1:npoints,it)
+       ! Normalized radiance -> reflectance: 
+       refl(1:npoints,it) = refl(1:npoints,it) * r_norm(it)
+    ENDDO
+    
+    RETURN
+  END SUBROUTINE parasol_subcolumn
+  ! ######################################################################################
+  ! SUBROUTINE parasol_gridbox
+  ! ######################################################################################
+  subroutine parasol_column(npoints,nrefl,ncol,land,refl,parasolrefl)
+
+    ! Inputs
+    integer,intent(in) :: &
+         npoints, & ! Number of horizontal grid points
+         ncol,    & ! Number of subcolumns
+         nrefl      ! Number of solar zenith angles for parasol reflectances
+    real(wp),intent(in),dimension(npoints) :: &
+         land       ! Landmask [0 - Ocean, 1 - Land]
+    real(wp),intent(in),dimension(npoints,ncol,nrefl) :: &
+         refl       ! Subgrid parasol reflectance ! parasol
+
+    ! Outputs
+    real(wp),intent(out),dimension(npoints,nrefl) :: &
+         parasolrefl   ! Grid-averaged parasol reflectance
+
+    ! Local variables
+    integer :: k,ic
+
+    ! Compute grid-box averaged Parasol reflectances
+    parasolrefl(:,:) = 0._wp
+    do k = 1, nrefl
+       do ic = 1, ncol
+          parasolrefl(:,k) = parasolrefl(:,k) + refl(:,ic,k)
+       enddo
+    enddo
+    
+    do k = 1, nrefl
+       parasolrefl(:,k) = parasolrefl(:,k) / float(ncol)
+       ! if land=1 -> parasolrefl=R_UNDEF
+       ! if land=0 -> parasolrefl=parasolrefl
+       parasolrefl(:,k) = parasolrefl(:,k) * MAX(1._wp-land(:),0.0) &
+            + (1._wp - MAX(1._wp-land(:),0.0))*R_UNDEF
+    enddo
+  end subroutine parasol_column
+
+end module mod_parasol
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/prec_scops.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/prec_scops.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/prec_scops.F90	(revision 3605)
@@ -0,0 +1,277 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2008, Lawrence Livermore National Security Limited Liability Corporation
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History:
+! May 2015- D. Swales - Modified for COSPv2.0
+! 
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+module mod_prec_scops
+   implicit none
+contains
+      
+      subroutine prec_scops(npoints,nlev,ncol,ls_p_rate,cv_p_rate,frac_out,prec_frac)
+
+        USE COSP_KINDS, ONLY: wp
+        use mod_cosp_config, ONLY: scops_ccfrac
+
+      INTEGER npoints       !  number of model points in the horizontal
+      INTEGER nlev          !  number of model levels in column
+      INTEGER ncol          !  number of subcolumns
+
+      INTEGER j,ilev,ibox,cv_col
+      
+      REAL(WP) ls_p_rate(npoints,nlev),cv_p_rate(npoints,nlev)
+
+      REAL(WP) frac_out(npoints,ncol,nlev) ! boxes gridbox divided up into
+                              ! Equivalent of BOX in original version, but
+                              ! indexed by column then row, rather than
+                              ! by row then column
+                              !TOA to SURFACE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+      REAL(WP) prec_frac(npoints,ncol,nlev) ! 0 -> clear sky
+                                        ! 1 -> LS precipitation
+                                        ! 2 -> CONV precipitation
+                    ! 3 -> both
+                                        !TOA to SURFACE!!!!!!!!!!!!!!!!!!
+                    
+      INTEGER flag_ls, flag_cv
+      INTEGER frac_out_ls(npoints,ncol),frac_out_cv(npoints,ncol) !flag variables for 
+                       ! stratiform cloud and convective cloud in the vertical column
+
+      cv_col = scops_ccfrac*ncol
+      if (cv_col .eq. 0) cv_col=1
+ 
+      do ilev=1,nlev
+        do ibox=1,ncol
+          do j=1,npoints 
+            prec_frac(j,ibox,ilev) = 0
+          enddo
+        enddo
+      enddo
+      
+      do j=1,npoints
+       do ibox=1,ncol
+        frac_out_ls(j,ibox)=0
+        frac_out_cv(j,ibox)=0
+        flag_ls=0
+        flag_cv=0
+        do ilev=1,nlev
+          if (frac_out(j,ibox,ilev) .eq. 1) then 
+            flag_ls=1
+          endif
+          if (frac_out(j,ibox,ilev) .eq. 2) then 
+            flag_cv=1
+          endif
+        enddo !loop over nlev
+        if (flag_ls .eq. 1) then
+           frac_out_ls(j,ibox)=1
+        endif
+        if (flag_cv .eq. 1) then
+           frac_out_cv(j,ibox)=1
+        endif
+       enddo  ! loop over ncol
+      enddo ! loop over npoints
+
+!      initialize the top layer      
+       do j=1,npoints
+        flag_ls=0
+        flag_cv=0
+    
+        if (ls_p_rate(j,1) .gt. 0.) then 
+            do ibox=1,ncol ! possibility ONE
+                if (frac_out(j,ibox,1) .eq. 1) then 
+                    prec_frac(j,ibox,1) = 1
+                    flag_ls=1
+                endif
+            enddo ! loop over ncol
+            if (flag_ls .eq. 0) then ! possibility THREE
+                do ibox=1,ncol
+                    if (frac_out(j,ibox,2) .eq. 1) then 
+                        prec_frac(j,ibox,1) = 1
+                        flag_ls=1
+                    endif
+                enddo ! loop over ncol
+            endif
+        if (flag_ls .eq. 0) then ! possibility Four
+        do ibox=1,ncol
+        if (frac_out_ls(j,ibox) .eq. 1) then 
+            prec_frac(j,ibox,1) = 1
+            flag_ls=1
+        endif
+        enddo ! loop over ncol
+        endif
+        if (flag_ls .eq. 0) then ! possibility Five
+        do ibox=1,ncol
+    !     prec_frac(j,1:ncol,1) = 1
+        prec_frac(j,ibox,1) = 1
+        enddo ! loop over ncol
+            endif
+        endif
+       ! There is large scale precipitation
+     
+        if (cv_p_rate(j,1) .gt. 0.) then 
+         do ibox=1,ncol ! possibility ONE
+          if (frac_out(j,ibox,1) .eq. 2) then 
+           if (prec_frac(j,ibox,1) .eq. 0) then
+        prec_frac(j,ibox,1) = 2
+       else
+        prec_frac(j,ibox,1) = 3
+       endif
+       flag_cv=1
+      endif
+        enddo ! loop over ncol
+        if (flag_cv .eq. 0) then ! possibility THREE
+        do ibox=1,ncol
+        if (frac_out(j,ibox,2) .eq. 2) then 
+                if (prec_frac(j,ibox,1) .eq. 0) then
+            prec_frac(j,ibox,1) = 2
+            else
+            prec_frac(j,ibox,1) = 3
+            endif
+            flag_cv=1
+        endif
+        enddo ! loop over ncol
+        endif
+        if (flag_cv .eq. 0) then ! possibility Four
+        do ibox=1,ncol
+        if (frac_out_cv(j,ibox) .eq. 1) then 
+                if (prec_frac(j,ibox,1) .eq. 0) then
+            prec_frac(j,ibox,1) = 2
+            else
+            prec_frac(j,ibox,1) = 3
+            endif
+            flag_cv=1
+        endif
+        enddo ! loop over ncol
+        endif
+        if (flag_cv .eq. 0) then  ! possibility Five
+        do ibox=1,cv_col
+                if (prec_frac(j,ibox,1) .eq. 0) then
+            prec_frac(j,ibox,1) = 2
+            else
+            prec_frac(j,ibox,1) = 3
+            endif 
+        enddo !loop over cv_col
+            endif 
+        endif 
+        ! There is convective precipitation
+        
+        enddo ! loop over npoints
+!      end of initializing the top layer
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+!     working on the levels from top to surface
+      do ilev=2,nlev
+       do j=1,npoints
+        flag_ls=0
+        flag_cv=0
+    
+        if (ls_p_rate(j,ilev) .gt. 0.) then 
+         do ibox=1,ncol ! possibility ONE&TWO
+          if ((frac_out(j,ibox,ilev) .eq. 1) .or. ((prec_frac(j,ibox,ilev-1) .eq. 1)     &
+            .or. (prec_frac(j,ibox,ilev-1) .eq. 3))) then 
+           prec_frac(j,ibox,ilev) = 1
+           flag_ls=1
+          endif
+        enddo ! loop over ncol
+        if ((flag_ls .eq. 0) .and. (ilev .lt. nlev)) then ! possibility THREE
+        do ibox=1,ncol
+        if (frac_out(j,ibox,ilev+1) .eq. 1) then 
+            prec_frac(j,ibox,ilev) = 1
+            flag_ls=1
+        endif
+        enddo ! loop over ncol
+        endif
+        if (flag_ls .eq. 0) then ! possibility Four
+        do ibox=1,ncol
+        if (frac_out_ls(j,ibox) .eq. 1) then 
+            prec_frac(j,ibox,ilev) = 1
+            flag_ls=1
+        endif
+        enddo ! loop over ncol
+        endif
+        if (flag_ls .eq. 0) then ! possibility Five
+        do ibox=1,ncol
+!     prec_frac(j,1:ncol,ilev) = 1
+        prec_frac(j,ibox,ilev) = 1
+        enddo ! loop over ncol
+         endif
+      endif ! There is large scale precipitation
+    
+        if (cv_p_rate(j,ilev) .gt. 0.) then 
+         do ibox=1,ncol ! possibility ONE&TWO
+          if ((frac_out(j,ibox,ilev) .eq. 2) .or. ((prec_frac(j,ibox,ilev-1) .eq. 2)     &
+            .or. (prec_frac(j,ibox,ilev-1) .eq. 3))) then 
+            if (prec_frac(j,ibox,ilev) .eq. 0) then
+         prec_frac(j,ibox,ilev) = 2
+        else
+         prec_frac(j,ibox,ilev) = 3
+        endif 
+        flag_cv=1
+        endif
+       enddo ! loop over ncol
+        if ((flag_cv .eq. 0) .and. (ilev .lt. nlev)) then ! possibility THREE
+        do ibox=1,ncol
+        if (frac_out(j,ibox,ilev+1) .eq. 2) then 
+                if (prec_frac(j,ibox,ilev) .eq. 0) then
+            prec_frac(j,ibox,ilev) = 2
+            else
+            prec_frac(j,ibox,ilev) = 3
+            endif
+            flag_cv=1
+        endif
+        enddo ! loop over ncol
+        endif
+        if (flag_cv .eq. 0) then ! possibility Four
+        do ibox=1,ncol
+        if (frac_out_cv(j,ibox) .eq. 1) then 
+                if (prec_frac(j,ibox,ilev) .eq. 0) then
+            prec_frac(j,ibox,ilev) = 2
+            else
+            prec_frac(j,ibox,ilev) = 3
+            endif
+            flag_cv=1
+        endif
+        enddo ! loop over ncol
+        endif
+        if (flag_cv .eq. 0) then  ! possibility Five 
+        do ibox=1,cv_col
+                if (prec_frac(j,ibox,ilev) .eq. 0) then
+            prec_frac(j,ibox,ilev) = 2
+            else
+            prec_frac(j,ibox,ilev) = 3
+            endif 
+        enddo !loop over cv_col 
+            endif 
+        endif ! There is convective precipitation
+    
+        enddo ! loop over npoints
+        enddo ! loop over nlev
+
+      end subroutine prec_scops
+end module mod_prec_scops
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/quickbeam.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/quickbeam.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/quickbeam.F90	(revision 3605)
@@ -0,0 +1,643 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History
+! 11/2005: John Haynes - Created
+! 09/2006  placed into subroutine form (Roger Marchand,JMH)
+! 08/2007  added equivalent volume spheres, Z and N scalling most distrubtion types (Roger Marchand)
+! 01/2008  'Do while' to determine if hydrometeor(s) present in volume
+!           changed for vectorization purposes (A. Bodas-Salcedo)
+!
+! 07/2010  V3.0 ... Modified to load or save scale factors to disk as a Look-Up Table (LUT)
+!  ... All hydrometeor and radar simulator properties now included in hp structure
+!  ... hp structure should be initialized by call to radar_simulator_init prior 
+!  ... to calling this subroutine.  
+!     Also ... Support of Morrison 2-moment style microphyscis (Np_matrix) added 
+!  ... Changes implement by Roj Marchand following work by Laura Fowler
+!
+!   10/2011  Modified ngate loop to go in either direction depending on flag 
+!     hp%radar_at_layer_one.  This affects the direction in which attenuation is summed.
+!
+!     Also removed called to AVINT for gas and hydrometeor attenuation and replaced with simple
+!     summation. (Roger Marchand)
+! May 2015 - D. Swales - Modified for COSPv2.0
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+module quickbeam
+  USE COSP_KINDS,           ONLY: wp
+  USE MOD_COSP_CONFIG,      ONLY: R_UNDEF,cloudsat_histRef,use_vgrid,vgrid_zl,vgrid_zu,&
+                                  pClass_noPrecip, pClass_Rain1, pClass_Rain2, pClass_Rain3,&
+                                  pClass_Snow1, pClass_Snow2, pClass_Mixed1, pClass_Mixed2, &
+                                  pClass_Rain4, pClass_default, Zenonbinval, Zbinvallnd,    &
+                                  N_HYDRO,nCloudsatPrecipClass !,cloudsat_preclvl !PREC_BUG
+  USE MOD_COSP_STATS,       ONLY: COSP_LIDAR_ONLY_CLOUD,hist1D,COSP_CHANGE_VERTICAL_GRID
+  implicit none
+
+  integer,parameter :: &
+       maxhclass     = 20,  & ! Qucikbeam maximum number of hydrometeor classes.
+       nRe_types     = 550, & ! Quickbeam maximum number or Re size bins allowed in N and Z_scaled look up table.
+       nd            = 85,  & ! Qucikbeam number of discrete particles used in construction DSDs.
+       mt_ntt        = 39,  & ! Quickbeam number of temperatures in mie LUT.
+       Re_BIN_LENGTH = 10,  & ! Quickbeam minimum Re interval in scale LUTs  
+       Re_MAX_BIN    = 250    ! Quickbeam maximum Re interval in scale LUTs
+  real(wp),parameter :: &
+       dmin          = 0.1, & ! Quickbeam minimum size of discrete particle
+       dmax          = 10000. ! Quickbeam maximum size of discrete particle
+  
+  !djs logical :: radar_at_layer_one   ! If true radar is assume to be at the edge 
+                                  ! of the first layer, if the first layer is the
+                                  ! surface than a ground-based radar.   If the
+                                  ! first layer is the top-of-atmosphere, then
+                                  ! a space borne radar.
+
+  ! ##############################################################################################
+  type radar_cfg
+     ! Radar properties
+     real(wp) :: freq,k2
+     integer  :: nhclass               ! Number of hydrometeor classes in use
+     integer  :: use_gas_abs, do_ray
+     logical  :: radar_at_layer_one    ! If true radar is assume to be at the edge 
+                                       ! of the first layer, if the first layer is the
+                                       ! surface than a ground-based radar.   If the
+                                       ! first layer is the top-of-atmosphere, then
+                                       ! a space borne radar.
+     
+     ! Variables used to store Z scale factors
+     character(len=240)                             :: scale_LUT_file_name
+     logical                                        :: load_scale_LUTs, update_scale_LUTs
+     logical, dimension(maxhclass,nRe_types)        :: N_scale_flag
+     logical, dimension(maxhclass,mt_ntt,nRe_types) :: Z_scale_flag,Z_scale_added_flag
+     real(wp),dimension(maxhclass,mt_ntt,nRe_types) :: Ze_scaled,Zr_scaled,kr_scaled
+     real(wp),dimension(maxhclass,nd,nRe_types)     :: fc, rho_eff
+     real(wp),dimension(Re_MAX_BIN)                 :: base_list,step_list
+
+  end type radar_cfg
+
+contains
+  ! ######################################################################################
+  ! SUBROUTINE quickbeam_subcolumn
+  ! ######################################################################################
+  subroutine quickbeam_subcolumn(rcfg,nprof,ngate,hgt_matrix,z_vol,kr_vol,g_vol,dBZe,Ze_non)
+
+    ! INPUTS
+    type(radar_cfg),intent(inout) :: &
+         rcfg             ! Derived type for radar simulator setup
+    integer,intent(in) :: &
+         nprof,         & ! Number of hydrometeor profiles
+         ngate            ! Number of vertical layers
+    real(wp),intent(in),dimension(nprof,ngate) :: &
+         hgt_matrix,    & ! Height of hydrometeors (km)
+         z_vol,         & ! Effective reflectivity factor (mm^6/m^3)
+         kr_vol,        & ! Attenuation coefficient hydro (dB/km)
+         g_vol            ! Attenuation coefficient gases (dB/km)
+    
+    ! OUTPUTS
+    real(wp), intent(out),dimension(nprof,ngate) :: &
+         Ze_non,        & ! Radar reflectivity without attenuation (dBZ)
+         dBZe             ! Effective radar reflectivity factor (dBZ)
+
+    ! LOCAL VARIABLES
+    integer :: k,pr,start_gate,end_gate,d_gate
+    real(wp),dimension(nprof,ngate) :: &
+         Ze_ray,        & ! Rayleigh reflectivity (dBZ)
+         g_to_vol,      & ! Gaseous atteunation, radar to vol (dB)
+         a_to_vol,      & ! Hydromets attenuation, radar to vol (dB) 
+         z_ray            ! Reflectivity factor, Rayleigh only (mm^6/m^3)
+
+    ! Load scaling matricies from disk -- but only the first time this subroutine is called
+    if(rcfg%load_scale_LUTs) then
+       call load_scale_LUTs(rcfg)
+       rcfg%load_scale_LUTs=.false.
+       rcfg%Z_scale_added_flag = .false. ! will be set true if scaling Look Up Tables are modified during run
+    endif
+
+    ! Initialization
+    g_to_vol = 0._wp
+    a_to_vol = 0._wp
+
+    ! Loop over each range gate (ngate) ... starting with layer closest to the radar !
+    if(rcfg%radar_at_layer_one) then
+       start_gate = 1
+       end_gate   = ngate
+       d_gate     = 1
+    else
+       start_gate = ngate
+       end_gate   = 1
+       d_gate     = -1
+    endif
+    do k=start_gate,end_gate,d_gate
+       ! Loop over each profile (nprof)
+       do pr=1,nprof
+          ! Attenuation due to hydrometeors between radar and volume
+          
+          ! NOTE old scheme integrates attenuation only for the layers ABOVE
+          ! the current layer ... i.e. 1 to k-1 rather than 1 to k ...
+          ! which may be a problem.   ROJ
+          ! in the new scheme I assign half the attenuation to the current layer
+          if(d_gate==1) then
+             ! dheight calcuations assumes hgt_matrix points are the cell mid-points.
+             if (k>2) then
+                ! add to previous value to half of above layer + half of current layer
+                a_to_vol(pr,k)=  a_to_vol(pr,k-1) + &
+                     (kr_vol(pr,k-1)+kr_vol(pr,k))*(hgt_matrix(pr,k-1)-hgt_matrix(pr,k))
+             else
+                a_to_vol(pr,k)=  kr_vol(pr,k)*(hgt_matrix(pr,k)-hgt_matrix(pr,k+1))
+             endif
+          else   ! d_gate==-1
+             if(k<ngate) then
+                ! Add to previous value half of above layer + half of current layer
+                a_to_vol(pr,k) = a_to_vol(pr,k+1) + &
+                     (kr_vol(pr,k+1)+kr_vol(pr,k))*(hgt_matrix(pr,k+1)-hgt_matrix(pr,k))
+             else
+                a_to_vol(pr,k)= kr_vol(pr,k)*(hgt_matrix(pr,k)-hgt_matrix(pr,k-1))
+             endif
+          endif
+          
+          ! Attenuation due to gaseous absorption between radar and volume
+          if ((rcfg%use_gas_abs == 1) .or. (rcfg%use_gas_abs == 2 .and. pr .eq. 1)) then
+             if (d_gate==1) then
+                if (k>1) then
+                   ! Add to previous value to half of above layer + half of current layer
+                   g_to_vol(pr,k) =  g_to_vol(pr,k-1) + &
+                        0.5*(g_vol(pr,k-1)+g_vol(pr,k))*(hgt_matrix(pr,k-1)-hgt_matrix(pr,k))
+                else
+                   g_to_vol(pr,k)=  0.5_wp*g_vol(pr,k)*(hgt_matrix(pr,k)-hgt_matrix(pr,k+1))
+                endif
+             else   ! d_gate==-1
+                if (k<ngate) then
+                   ! Add to previous value to half of above layer + half of current layer
+                   g_to_vol(pr,k) = g_to_vol(pr,k+1) + &
+                        0.5_wp*(g_vol(pr,k+1)+g_vol(pr,k))*(hgt_matrix(pr,k+1)-hgt_matrix(pr,k))
+                else
+                   g_to_vol(pr,k)= 0.5_wp*g_vol(pr,k)*(hgt_matrix(pr,k)-hgt_matrix(pr,k-1))
+                endif
+             endif
+          elseif(rcfg%use_gas_abs == 2) then
+             ! Using value calculated for the first column
+             g_to_vol(pr,k) = g_to_vol(1,k)
+          elseif (rcfg%use_gas_abs == 0) then
+             g_to_vol(pr,k) = 0._wp
+          endif
+       enddo   ! End loop over pr (profile)
+    enddo ! End loop of k (range gate)
+    
+    ! Compute Rayleigh reflectivity, and full, attenuated reflectivity
+    if(rcfg%do_ray == 1) then
+       where(z_ray(1:nprof,1:ngate) > 0._wp)
+          Ze_ray(1:nprof,1:ngate) = 10._wp*log10(z_ray(1:nprof,1:ngate))
+       elsewhere
+          Ze_Ray(1:nprof,1:ngate) = 0._wp
+       endwhere
+    else 
+      Ze_ray(1:nprof,1:ngate) = R_UNDEF
+    end if
+
+    where(z_vol(1:nprof,1:ngate) > 0._wp) 
+      Ze_non(1:nprof,1:ngate) = 10._wp*log10(z_vol(1:nprof,1:ngate))
+      dBZe(1:nprof,1:ngate) = Ze_non(1:nprof,1:ngate)-a_to_vol(1:nprof,1:ngate)-g_to_vol(1:nprof,1:ngate)
+    elsewhere
+      dBZe(1:nprof,1:ngate) = R_UNDEF
+      Ze_non(1:nprof,1:ngate) = R_UNDEF
+    end where 
+
+    ! Save any updates made 
+    if (rcfg%update_scale_LUTs) call save_scale_LUTs(rcfg)
+ 
+  end subroutine quickbeam_subcolumn
+  ! ######################################################################################
+  ! SUBROUTINE quickbeam_column
+  ! ######################################################################################
+  subroutine quickbeam_column(npoints, ncolumns, nlevels, llm, DBZE_BINS, platform,      &
+       Ze_tot, Ze_tot_non, land, surfelev, t2m, fracPrecipIce, zlev, zlev_half, cfad_ze, & !PREC_BUG
+       cloudsat_precip_cover, cloudsat_pia)
+    ! Inputs
+    integer,intent(in) :: &
+         npoints,    & ! Number of horizontal grid points
+         ncolumns,   & ! Number of subcolumns
+         nlevels,    & ! Number of vertical layers in OLD grid
+         llm,        & ! Number of vertical layers in NEW grid
+         DBZE_BINS     ! Number of bins for cfad.
+    character(len=*),intent(in) :: &
+         platform      ! Name of platform (e.g. cloudsat)
+    real(wp),dimension(Npoints),intent(in) :: &
+         land,               & ! Land/Sea mask. (1/0)
+         surfelev,           & ! Surface Elevation (m) !PREC_BUG
+         t2m                   ! Near-surface temperature
+    real(wp),dimension(Npoints,Ncolumns),intent(in) :: &
+         fracPrecipIce         ! Fraction of precipitation which is frozen.     (1)
+    real(wp),intent(in),dimension(npoints,ncolumns,Nlevels) :: &
+         Ze_tot,     & ! Effective reflectivity factor                 (dBZ)
+         Ze_tot_non    ! Effective reflectivity factor w/o attenuation (dBZ)
+    real(wp),intent(in),dimension(npoints,Nlevels) :: &
+         zlev          ! Model full levels
+    real(wp),intent(in),dimension(npoints,Nlevels+1) :: &
+         zlev_half     ! Model half levels
+         
+    ! Outputs
+    real(wp),intent(inout),dimension(npoints,DBZE_BINS,llm) :: &
+         cfad_ze    !
+    real(wp),dimension(Npoints,nCloudsatPrecipClass),intent(out) :: &
+         cloudsat_precip_cover ! Model precip rate in by CloudSat precip flag
+    real(wp),dimension(Npoints),intent(out) :: &
+         cloudsat_pia          ! Cloudsat path integrated attenuation
+    
+    ! Local variables
+    integer :: i,j
+    real(wp),dimension(npoints,ncolumns,llm) :: ze_toti,ze_noni
+    logical :: lcloudsat = .false.
+
+    ! Which platforms to create diagnostics for?
+    if (platform .eq. 'cloudsat') lcloudsat=.true.
+
+    ! Create Cloudsat diagnostics.
+    if (lcloudsat) then
+       if (use_vgrid) then
+          ! Regrid in the vertical (*NOTE* This routine requires SFC-2-TOA ordering, so flip
+          ! inputs and outputs to maintain TOA-2-SFC ordering convention in COSP2.)
+          call cosp_change_vertical_grid(Npoints,Ncolumns,Nlevels,zlev(:,nlevels:1:-1),&
+               zlev_half(:,nlevels:1:-1),Ze_tot(:,:,nlevels:1:-1),llm,vgrid_zl(llm:1:-1),&
+               vgrid_zu(llm:1:-1),Ze_toti(:,:,llm:1:-1),log_units=.true.)
+          
+          ! Effective reflectivity histogram
+          do i=1,Npoints
+             do j=1,llm
+                cfad_ze(i,:,j) = hist1D(Ncolumns,Ze_toti(i,:,j),DBZE_BINS,cloudsat_histRef)
+             enddo
+          enddo
+          where(cfad_ze .ne. R_UNDEF) cfad_ze = cfad_ze/Ncolumns
+
+          ! Compute cloudsat near-surface precipitation diagnostics
+          ! First, regrid in the vertical Ze_tot_non.
+          call cosp_change_vertical_grid(Npoints,Ncolumns,Nlevels,zlev(:,nlevels:1:-1),&
+               zlev_half(:,nlevels:1:-1),Ze_tot_non(:,:,nlevels:1:-1),llm,vgrid_zl(llm:1:-1),&
+               vgrid_zu(llm:1:-1),Ze_noni(:,:,llm:1:-1),log_units=.true.)
+          ! Not call routine to generate diagnostics.
+          call cloudsat_precipOccurence(Npoints, Ncolumns, llm, N_HYDRO, Ze_toti, Ze_noni, &
+               land, surfelev, t2m, fracPrecipIce, cloudsat_precip_cover, cloudsat_pia) !PREC_BUG
+       else
+          ! Effective reflectivity histogram
+          do i=1,Npoints
+             do j=1,llm
+                cfad_ze(i,:,j) = hist1D(Ncolumns,Ze_tot(i,:,j),DBZE_BINS,cloudsat_histRef)
+             enddo
+          enddo
+          where(cfad_ze .ne. R_UNDEF) cfad_ze = cfad_ze/Ncolumns
+       endif
+    endif
+
+  end subroutine quickbeam_column
+  ! ##############################################################################################
+  ! ##############################################################################################
+  ! ######################################################################################
+  ! SUBROUTINE cloudsat_precipOccurence
+  !
+  ! Notes from July 2016: Add precip flag also looped over subcolumns
+  ! Modified by Tristan L'Ecuyer (TSL) to add precipitation flagging
+  ! based on CloudSat's 2C-PRECIP-COLUMN algorithm (Haynes et al, JGR, 2009).
+  ! To mimic the satellite algorithm, this code applies thresholds to non-attenuated
+  ! reflectivities, Ze_non, consistent with those outlined in Haynes et al, JGR (2009).
+  !
+  ! Procedures/Notes:
+  !
+  ! (1) If the 2-way attenuation exceeds 40 dB, the pixel will be flagged as 'heavy rain'
+  ! consistent with the multiple-scattering analysis of Battaglia et al, JGR (2008).
+  ! (2) Rain, snow, and mixed precipitation scenes are separated according to the fraction
+  ! of the total precipitation hydrometeor mixing ratio that exists as ice.
+  ! (3) The entire analysis is applied to the range gate from 480-960 m to be consistent with
+  ! CloudSat's 720 m ground-clutter.
+  ! (4) Only a single flag is assigned to each model grid since there is no variation in
+  ! hydrometeor contents across a single model level.  Unlike CFADs, whose variation enters
+  ! due to differening attenuation corrections from hydrometeors aloft, the non-attenuated
+  ! reflectivities used in the computation of this flag cannot vary across sub-columns.
+  !
+  ! radar_prec_flag = 1-Rain possible 2-Rain probable 3-Rain certain 
+  !                   4-Snow possible 5-Snow certain 
+  !                   6-Mixed possible 7-Mixed certain 
+  !                   8-Heavy Rain
+  !                   9- default value
+  !
+  ! Modified by Dustin Swales (University of Colorado) for use with COSP2.
+  ! *NOTE* All inputs (Ze_out, Ze_non_out, fracPrecipIce) are at a single level from the
+  !        statistical output grid used by Cloudsat. This level is controlled by the
+  !        parameter cloudsat_preclvl, defined in src/cosp_config.F90
+  ! ######################################################################################
+  subroutine cloudsat_precipOccurence(Npoints, Ncolumns, llm, Nhydro, Ze_out, Ze_non_out, &
+       land, surfelev, t2m, fracPrecipIce,  cloudsat_precip_cover, cloudsat_pia) !PREC_BUG
+ 
+    ! Inputs
+    integer,intent(in) :: &
+         Npoints,            & ! Number of columns
+         Ncolumns,           & ! Numner of subcolumns
+         Nhydro,             & ! Number of hydrometeor types
+         llm                   ! Number of levels
+    real(wp),dimension(Npoints),intent(in) :: &
+         land,               & ! Land/Sea mask. (1/0)
+         surfelev,           & ! Surface Elevation (m) !PREC_BUG
+         t2m                   ! Near-surface temperature
+    real(wp),dimension(Npoints,Ncolumns,llm),intent(in) :: &
+         Ze_out,             & ! Effective reflectivity factor                  (dBZ)
+         Ze_non_out            ! Effective reflectivity factor, w/o attenuation (dBZ)
+    real(wp),dimension(Npoints,Ncolumns),intent(in) :: &
+         fracPrecipIce         ! Fraction of precipitation which is frozen.     (1)
+
+    ! Outputs 
+    real(wp),dimension(Npoints,nCloudsatPrecipClass),intent(out) :: &
+         cloudsat_precip_cover ! Model precip rate in by CloudSat precip flag
+    real(wp),dimension(Npoints),intent(out) :: &
+         cloudsat_pia          ! Cloudsat path integrated attenuation
+    
+    ! Local variables 
+    integer,dimension(Npoints,Ncolumns) :: &
+         cloudsat_pflag,      & ! Subcolumn precipitation flag
+         cloudsat_precip_pia    ! Subcolumn path integrated attenutation.
+    integer,dimension(Npoints) :: &                                           !PREC_BUG
+         cloudsat_preclvl_index ! Altitude index for precip flags calculation !PREC_BUG
+                                ! in 40-level grid (2nd layer above surfelev) !PREC_BUG
+    integer :: pr,i,k,m,j,cloudsat_preclvl                                    !PREC_BUG
+    real(wp) :: Zmax
+    
+    ! Initialize 
+    cloudsat_pflag(:,:)        = pClass_default
+    cloudsat_precip_pia(:,:)   = 0._wp
+    cloudsat_precip_cover(:,:) = 0._wp
+    cloudsat_pia(:)            = 0._wp
+    cloudsat_preclvl_index(:)  = 0._wp !PREC_BUG
+
+
+!!! Computing altitude index for precip flags calculation  !PREC_BUG
+cloudsat_preclvl_index(:) = 39 - floor( surfelev(:)/480. ) !PREC_BUG
+
+    ! ######################################################################################
+    ! SUBCOLUMN processing
+    ! ######################################################################################
+    do i=1, Npoints
+
+       cloudsat_preclvl = cloudsat_preclvl_index(i) !PREC_BUG
+!       print*, 'i, surfelev(i), cloudsat_preclvl : ', i, surfelev(i), cloudsat_preclvl !PREC_BUG
+
+       do pr=1,Ncolumns
+          ! 1) Compute the PIA in all profiles containing hydrometeors
+          if ( (Ze_non_out(i,pr,cloudsat_preclvl).gt.-100) .and. (Ze_out(i,pr,cloudsat_preclvl).gt.-100) ) then
+             if ( (Ze_non_out(i,pr,cloudsat_preclvl).lt.100) .and. (Ze_out(i,pr,cloudsat_preclvl).lt.100) ) then
+                cloudsat_precip_pia(i,pr) = Ze_non_out(i,pr,cloudsat_preclvl) - Ze_out(i,pr,cloudsat_preclvl)
+             endif
+          endif
+          
+          ! 2) Compute precipitation flag
+          ! ################################################################################
+          ! 2a) Oceanic points.
+          ! ################################################################################
+          if (land(i) .eq. 0) then
+!             print*, 'aaa i, pr, fracPrecipIce(i,pr) : ', i, pr, fracPrecipIce(i,pr) !Artem
+             ! Snow
+             if(fracPrecipIce(i,pr).gt.0.9) then
+                if(Ze_non_out(i,pr,cloudsat_preclvl).gt.Zenonbinval(2)) then
+                   cloudsat_pflag(i,pr) = pClass_Snow2                   ! TSL: Snow certain
+                endif
+                if(Ze_non_out(i,pr,cloudsat_preclvl).gt.Zenonbinval(4).and. &
+                     Ze_non_out(i,pr,cloudsat_preclvl).le.Zenonbinval(2)) then
+                   cloudsat_pflag(i,pr) = pClass_Snow1                   ! TSL: Snow possible
+                endif
+             endif
+             
+             ! Mixed
+             if(fracPrecipIce(i,pr).gt.0.1.and.fracPrecipIce(i,pr).le.0.9) then
+                if(Ze_non_out(i,pr,cloudsat_preclvl).gt.Zenonbinval(2)) then
+                   cloudsat_pflag(i,pr) = pClass_Mixed2                  ! TSL: Mixed certain
+                endif
+                if(Ze_non_out(i,pr,cloudsat_preclvl).gt.Zenonbinval(4).and. &
+                     Ze_non_out(i,pr,cloudsat_preclvl).le.Zenonbinval(2)) then
+                   cloudsat_pflag(i,pr) = pClass_Mixed1                  ! TSL: Mixed possible
+                endif
+             endif
+             
+             ! Rain
+             if(fracPrecipIce(i,pr).le.0.1) then
+                if(Ze_non_out(i,pr,cloudsat_preclvl).gt.Zenonbinval(1)) then
+                   cloudsat_pflag(i,pr) = pClass_Rain3                   ! TSL: Rain certain
+                endif
+                if(Ze_non_out(i,pr,cloudsat_preclvl).gt.Zenonbinval(3).and. &
+                     Ze_non_out(i,pr,cloudsat_preclvl).le.Zenonbinval(1)) then
+                   cloudsat_pflag(i,pr) = pClass_Rain2                   ! TSL: Rain probable
+                endif
+                if(Ze_non_out(i,pr,cloudsat_preclvl).gt.Zenonbinval(4).and. &
+                     Ze_non_out(i,pr,cloudsat_preclvl).le.Zenonbinval(3)) then
+                   cloudsat_pflag(i,pr) = pClass_Rain1                   ! TSL: Rain possible
+                endif
+                if(cloudsat_precip_pia(i,pr).gt.40) then
+                   cloudsat_pflag(i,pr) = pClass_Rain4                   ! TSL: Heavy Rain
+                endif
+             endif
+             
+             ! No precipitation
+             if(Ze_non_out(i,pr,cloudsat_preclvl).le.-15) then
+                cloudsat_pflag(i,pr) = pClass_noPrecip                   ! TSL: Not Raining
+             endif
+          endif ! Ocean points
+          
+          ! ################################################################################
+          ! 2b) Land points.
+          ! ################################################################################
+          if (land(i) .eq. 1) then
+             ! Find Zmax, the maximum reflectivity value in the attenuated profile (Ze_out);
+             Zmax=maxval(Ze_out(i,pr,:))
+
+             ! Snow (T<273)
+             if(t2m(i) .lt. 273._wp) then
+                if(Ze_out(i,pr,cloudsat_preclvl) .gt. Zbinvallnd(5)) then
+                   cloudsat_pflag(i,pr) = pClass_Snow2                      ! JEK: Snow certain
+                endif
+                if(Ze_out(i,pr,cloudsat_preclvl) .gt. Zbinvallnd(6) .and. &
+                     Ze_out(i,pr,cloudsat_preclvl).le.Zbinvallnd(5)) then
+                   cloudsat_pflag(i,pr) = pClass_Snow1                      ! JEK: Snow possible
+                endif
+             endif
+             
+             ! Mized phase (273<T<275)
+             if(t2m(i) .ge. 273._wp .and. t2m(i) .le. 275._wp) then
+                if ((Zmax .gt. Zbinvallnd(1) .and. cloudsat_precip_pia(i,pr).gt.30) .or. &
+                     (Ze_out(i,pr,cloudsat_preclvl) .gt. Zbinvallnd(4))) then
+                   cloudsat_pflag(i,pr) = pClass_Mixed2                     ! JEK: Mixed certain
+                endif
+                if ((Ze_out(i,pr,cloudsat_preclvl) .gt. Zbinvallnd(6)  .and. &
+                     Ze_out(i,pr,cloudsat_preclvl) .le. Zbinvallnd(4)) .and. &
+                     (Zmax .gt. Zbinvallnd(5)) ) then
+                   cloudsat_pflag(i,pr) = pClass_Mixed1                     ! JEK: Mixed possible
+                endif
+             endif
+
+             ! Rain (T>275)
+             if(t2m(i) .gt. 275) then
+                if ((Zmax .gt. Zbinvallnd(1) .and. cloudsat_precip_pia(i,pr).gt.30) .or. &
+                     (Ze_out(i,pr,cloudsat_preclvl) .gt. Zbinvallnd(2))) then
+                   cloudsat_pflag(i,pr) = pClass_Rain3                      ! JEK: Rain certain
+                endif
+                if((Ze_out(i,pr,cloudsat_preclvl) .gt. Zbinvallnd(6)) .and. &
+                     (Zmax .gt. Zbinvallnd(3))) then
+                   cloudsat_pflag(i,pr) = pClass_Rain2                      ! JEK: Rain probable
+                endif
+                if((Ze_out(i,pr,cloudsat_preclvl) .gt. Zbinvallnd(6)) .and. &
+                     (Zmax.lt.Zbinvallnd(3))) then
+                   cloudsat_pflag(i,pr) = pClass_Rain1                      ! JEK: Rain possible
+                endif
+                if(cloudsat_precip_pia(i,pr).gt.40) then
+                   cloudsat_pflag(i,pr) = pClass_Rain4                      ! JEK: Heavy Rain
+                endif
+             endif
+             
+             ! No precipitation
+             if(Ze_out(i,pr,cloudsat_preclvl).le.-15) then
+                cloudsat_pflag(i,pr) =  pClass_noPrecip                     ! JEK: Not Precipitating
+             endif         
+          endif ! Land points
+       enddo ! Sub-columns
+    enddo    ! Gridpoints
+
+    ! ######################################################################################
+    ! COLUMN processing
+    ! ######################################################################################
+
+    ! Aggregate subcolumns
+    do i=1,Npoints
+       ! Gridmean precipitation fraction for each precipitation type
+       do k=1,nCloudsatPrecipClass
+          if (any(cloudsat_pflag(i,:) .eq. k-1)) then
+             cloudsat_precip_cover(i,k) = count(cloudsat_pflag(i,:) .eq. k-1)
+          endif
+       enddo
+
+       ! Gridmean path integrated attenuation (pia)
+       cloudsat_pia(i)=sum(cloudsat_precip_pia(i,:))
+    enddo
+  
+    ! Normalize by number of subcolumns
+    where ((cloudsat_precip_cover /= R_UNDEF).and.(cloudsat_precip_cover /= 0.0)) &
+         cloudsat_precip_cover = cloudsat_precip_cover / Ncolumns
+    where ((cloudsat_pia/= R_UNDEF).and.(cloudsat_pia/= 0.0)) &
+         cloudsat_pia = cloudsat_pia / Ncolumns 
+
+  end subroutine cloudsat_precipOccurence
+  
+  ! ##############################################################################################
+  ! ##############################################################################################
+  subroutine load_scale_LUTs(rcfg)
+    
+    type(radar_cfg), intent(inout) :: rcfg
+    logical                        :: LUT_file_exists
+    integer                        :: i,j,k,ind
+    
+    ! Load scale LUT from file 
+    inquire(file=trim(rcfg%scale_LUT_file_name) // '_radar_Z_scale_LUT.dat', &
+         exist=LUT_file_exists)
+    
+    if(.not.LUT_file_exists) then  
+       write(*,*) '*************************************************'
+       write(*,*) 'Warning: Could NOT FIND radar LUT file: ', &
+            trim(rcfg%scale_LUT_file_name) // '_radar_Z_scale_LUT.dat'        
+       write(*,*) 'Will calculated LUT values as needed'
+       write(*,*) '*************************************************'
+       return
+    else
+       OPEN(unit=12,file=trim(rcfg%scale_LUT_file_name) // '_radar_Z_scale_LUT.dat',&
+            form='unformatted', &
+            err= 89, &
+            access='DIRECT',&
+            recl=28)
+       write(*,*) 'Loading radar LUT file: ', &
+            trim(rcfg%scale_LUT_file_name) // '_radar_Z_scale_LUT.dat'
+       
+       do i=1,maxhclass
+          do j=1,mt_ntt
+             do k=1,nRe_types
+                ind = i+(j-1)*maxhclass+(k-1)*(nRe_types*mt_ntt)
+                read(12,rec=ind) rcfg%Z_scale_flag(i,j,k), &
+                     rcfg%Ze_scaled(i,j,k), &
+                     rcfg%Zr_scaled(i,j,k), &
+                     rcfg%kr_scaled(i,j,k)
+             enddo
+          enddo
+       enddo
+       close(unit=12)
+       return 
+    endif
+    
+89  write(*,*) 'Error: Found but could NOT READ radar LUT file: ', &
+         trim(rcfg%scale_LUT_file_name) // '_radar_Z_scale_LUT.dat'
+    
+  end subroutine load_scale_LUTs
+  
+  ! ##############################################################################################
+  ! ##############################################################################################
+  subroutine save_scale_LUTs(rcfg)
+    type(radar_cfg), intent(inout) :: rcfg
+    logical                        :: LUT_file_exists
+    integer                        :: i,j,k,ind
+    
+    inquire(file=trim(rcfg%scale_LUT_file_name) // '_radar_Z_scale_LUT.dat', &
+         exist=LUT_file_exists)
+    
+    OPEN(unit=12,file=trim(rcfg%scale_LUT_file_name) // '_radar_Z_scale_LUT.dat',&
+         form='unformatted',err= 99,access='DIRECT',recl=28)
+    
+    write(*,*) 'Creating or Updating radar LUT file: ', &
+         trim(rcfg%scale_LUT_file_name) // '_radar_Z_scale_LUT.dat'
+    
+    do i=1,maxhclass
+       do j=1,mt_ntt
+          do k=1,nRe_types
+             ind = i+(j-1)*maxhclass+(k-1)*(nRe_types*mt_ntt)
+             if(.not.LUT_file_exists .or. rcfg%Z_scale_added_flag(i,j,k)) then
+                rcfg%Z_scale_added_flag(i,j,k)=.false.
+                write(12,rec=ind) rcfg%Z_scale_flag(i,j,k), &
+                     rcfg%Ze_scaled(i,j,k), &
+                     rcfg%Zr_scaled(i,j,k), &
+                     rcfg%kr_scaled(i,j,k)
+             endif
+          enddo
+       enddo
+    enddo
+    close(unit=12)
+    return 
+    
+99  write(*,*) 'Error: Unable to create/update radar LUT file: ', &
+         trim(rcfg%scale_LUT_file_name) // '_radar_Z_scale_LUT.dat'
+    return  
+    
+  end subroutine save_scale_LUTs
+  ! ##############################################################################################
+  ! ##############################################################################################
+  subroutine quickbeam_init()
+
+    
+  end subroutine quickBeam_init
+  ! ##############################################################################################
+  ! ##############################################################################################
+
+
+end module quickbeam
+
+
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/quickbeam_optics.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/quickbeam_optics.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/quickbeam_optics.F90	(revision 3605)
@@ -0,0 +1,1380 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2015, Regents of the University of Colorado
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History:
+! May 2015:  Dustin Swales - Initial version
+! 
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+module mod_quickbeam_optics
+  USE COSP_KINDS,          ONLY: wp,dp
+  USE array_lib,           ONLY: infind
+  USE math_lib,            ONLY: path_integral,avint,gamma
+  USE optics_lib,          ONLY: m_wat,m_ice,MieInt
+  USE cosp_math_constants, ONLY: pi
+  USE cosp_phys_constants, ONLY: rhoice  
+  use quickbeam,           ONLY: radar_cfg,dmin,dmax,Re_BIN_LENGTH,  &
+                                 Re_MAX_BIN,nRe_types,nd,maxhclass
+  use mod_cosp_config,     ONLY: N_HYDRO
+  use mod_cosp_error,      ONLY: errorMessage
+  implicit none
+
+  ! Derived type for particle size distribution
+  TYPE size_distribution
+     real(wp),dimension(maxhclass) :: p1,p2,p3,dmin,dmax,apm,bpm,rho
+     integer, dimension(maxhclass) :: dtype,phase
+  END TYPE size_distribution
+  
+  ! Parameters
+  integer,parameter ::   & !
+       cnt_liq       = 19, & ! Liquid temperature count
+       cnt_ice       = 20    ! Lce temperature count
+  
+  ! Initialization variables
+  real(wp),dimension(cnt_ice) :: mt_tti 
+  real(wp),dimension(cnt_liq) :: mt_ttl
+  real(wp),dimension(nd)      :: D
+  !logical :: lQuickbeamInit
+  
+contains
+  ! ######################################################################################
+  ! SUBROUTINE quickbeam_optics_init
+  ! ######################################################################################
+  subroutine quickbeam_optics_init()
+    integer :: j
+    
+    mt_tti = (/ ((j-1)*5-90 + 273.15, j = 1, cnt_ice) /) 
+    mt_ttl = (/ ((j-1)*5-60 + 273.15, j = 1, cnt_liq) /)
+    D(1) = dmin
+    do j=2,nd
+       D(j) = D(j-1)*exp((log(dmax)-log(dmin))/(nd-1))
+    enddo
+    !lQuickbeamInit = .true.
+  end subroutine quickbeam_optics_init
+  
+  ! ######################################################################################
+  ! SUBROUTINE QUICKBEAM_OPTICS
+  ! ######################################################################################
+  subroutine quickbeam_optics(sd, rcfg, nprof, ngate, undef, hm_matrix, re_matrix,       &
+       Np_matrix, p_matrix, t_matrix, sh_matrix,z_vol,kr_vol)
+    
+    ! INPUTS
+    type(size_distribution),intent(inout) :: &
+         sd               !
+    type(radar_cfg),intent(inout) :: &
+         rcfg             !
+    integer,intent(in) :: &
+         nprof,         & ! Number of hydrometeor profiles
+         ngate            ! Number of vertical layers
+    real(wp),intent(in) :: &
+         undef            ! Missing data value
+    real(wp),intent(in),dimension(nprof,ngate) :: &
+         p_matrix,      & ! Pressure profile (hPa)
+         t_matrix,      & ! Temperature profile (K)
+         sh_matrix        ! Specific humidity profile (%) -- only needed if gaseous aborption calculated.
+    real(wp),intent(in),dimension(nprof,ngate,rcfg%nhclass) :: &
+         re_matrix,     & ! Table of hydrometeor effective radii.       0 ==> use defaults. (units=microns)
+         hm_matrix        ! Table of hydrometeor mixing ratios (g/kg)
+    real(wp),intent(inout),dimension(nprof,ngate,rcfg%nhclass) :: &
+         Np_matrix        ! Table of hydrometeor number concentration.  0 ==> use defaults. (units = 1/kg)
+
+    ! OUTPUTS
+    real(wp),intent(out), dimension(nprof, ngate) :: &
+         z_vol,         & ! Effective reflectivity factor (mm^6/m^3)
+         kr_vol           ! Attenuation coefficient hydro (dB/km)
+
+    ! INTERNAL VARIABLES   
+    integer :: &
+         phase, ns,tp,j,k,pr,itt,iRe_type,n 
+    logical :: &
+         hydro
+    real(wp) :: &
+         t_kelvin,Re_internal
+    real(wp) :: &
+         rho_a,kr,ze,zr,scale_factor,Re,Np,base,step 
+
+    real(wp),dimension(:),allocatable :: &
+         Deq,     & ! Discrete drop sizes (um)
+         Ni,      & ! Discrete concentrations (cm^-3 um^-1)
+         rhoi,    & ! Discrete densities (kg m^-3)
+         xxa,     & !
+         Di         ! Discrete drop sizes (um)
+    
+    real(wp), dimension(nprof, ngate) :: &
+         z_ray      ! Reflectivity factor, Rayleigh only (mm^6/m^3)
+    
+    ! PARAMETERS    
+    logical, parameter ::       & !
+         DO_LUT_TEST = .false., & !
+         DO_NP_TEST  = .false.    !
+    real(wp), parameter :: &
+         one_third   = 1._wp/3._wp    !
+
+    ! Initialization
+    z_vol    = 0._wp
+    z_ray    = 0._wp
+    kr_vol   = 0._wp
+
+    do k=1,ngate       ! Loop over each profile (nprof)
+       do pr=1,nprof
+          ! Determine if hydrometeor(s) present in volume
+          hydro = .false.
+          do j=1,rcfg%nhclass
+             if ((hm_matrix(pr,k,j) > 1E-12) .and. (sd%dtype(j) > 0)) then
+                hydro = .true.
+                exit
+             endif
+          enddo
+
+          t_kelvin = t_matrix(pr,k)
+          ! If there is hydrometeor in the volume
+          if (hydro) then
+             rho_a = (p_matrix(pr,k))/(287._wp*(t_kelvin))
+             
+             ! Loop over hydrometeor type
+             do tp=1,rcfg%nhclass
+                Re_internal = re_matrix(pr,k,tp)
+
+                if (hm_matrix(pr,k,tp) <= 1E-12) cycle
+                
+                ! Index into temperature dimension of scaling tables
+                !   These tables have regular steps -- exploit this and abandon infind
+                phase = sd%phase(tp)
+                if (phase==0) then
+                   itt = infind(mt_ttl,t_kelvin)
+                else
+                   itt = infind(mt_tti,t_kelvin) 
+                endif
+                
+                ! Compute effective radius from number concentration and distribution parameters
+                if (Re_internal .eq. 0) then
+                   call calc_Re(hm_matrix(pr,k,tp),Np_matrix(pr,k,tp),rho_a, &
+                        sd%dtype(tp),sd%apm(tp),sd%bpm(tp),sd%rho(tp),sd%p1(tp),sd%p2(tp),sd%p3(tp),Re)
+                   Re_internal=Re
+                   !re_matrix(pr,k,tp)=Re
+                else
+                   if (Np_matrix(pr,k,tp) > 0) then
+                      call errorMessage('WARNING(optics/quickbeam_optics.f90): Re and Np set for the same volume & hydrometeor type.  Np is being ignored.')
+                   endif
+                   Re = Re_internal
+                   !Re = re_matrix(pr,k,tp)
+                endif
+                
+                ! Index into particle size dimension of scaling tables 
+                iRe_type=1
+                if(Re.gt.0) then
+                   ! Determine index in to scale LUT
+                   ! Distance between Re points (defined by "base" and "step") for
+                   ! each interval of size Re_BIN_LENGTH
+                   ! Integer asignment, avoids calling floor intrinsic
+                   n=Re/Re_BIN_LENGTH
+                   if (n>=Re_MAX_BIN) n=Re_MAX_BIN-1
+                   step = rcfg%step_list(n+1)
+                   base = rcfg%base_list(n+1)
+                   iRe_type=Re/step
+                   if (iRe_type.lt.1) iRe_type=1
+                   Re=step*(iRe_type+0.5_wp)    ! set value of Re to closest value allowed in LUT.
+                   iRe_type=iRe_type+base-int(n*Re_BIN_LENGTH/step)
+                   
+                   ! Make sure iRe_type is within bounds
+                   if (iRe_type.ge.nRe_types) then
+                      !write(*,*) 'Warning: size of Re exceed value permitted ', &
+                      !            'in Look-Up Table (LUT).  Will calculate. '
+                      ! No scaling allowed
+                      iRe_type=nRe_types
+                      rcfg%Z_scale_flag(tp,itt,iRe_type)=.false.
+                   else
+                      ! Set value in re_matrix to closest values in LUT
+                      if (.not. DO_LUT_TEST) re_internal=Re
+                      !if (.not. DO_LUT_TEST) re_matrix(pr,k,tp)=Re
+                   endif
+                endif
+                
+                ! Use Ze_scaled, Zr_scaled, and kr_scaled ... if know them
+                ! if not we will calculate Ze, Zr, and Kr from the distribution parameters
+!                if( rcfg%Z_scale_flag(tp,itt,iRe_type) .and. .not. DO_LUT_TEST)  then
+!                   ! can use z scaling
+!                   scale_factor=rho_a*hm_matrix(pr,k,tp)
+!                   zr = rcfg%Zr_scaled(tp,itt,iRe_type) * scale_factor
+!                   ze = rcfg%Ze_scaled(tp,itt,iRe_type) * scale_factor
+!                   kr = rcfg%kr_scaled(tp,itt,iRe_type) * scale_factor
+!                else
+                if( (.not. rcfg%Z_scale_flag(tp,itt,iRe_type)) .or. DO_LUT_TEST)  then
+                   ! Create a discrete distribution of hydrometeors within volume
+                   select case(sd%dtype(tp))
+                   case(4)
+                      ns = 1
+                      allocate(Di(ns),Ni(ns),rhoi(ns),xxa(ns),Deq(ns))
+                      Di = sd%p1(tp)
+                      Ni = 0._wp
+                   case default
+                      ns = nd   ! constant defined in simulator/quickbeam.f90
+                      allocate(Di(ns),Ni(ns),rhoi(ns),xxa(ns),Deq(ns))
+                      Di = D
+                      Ni = 0._wp
+                   end select
+                   call dsd(hm_matrix(pr,k,tp),re_internal,Np_matrix(pr,k,tp), &
+                        Di,Ni,ns,sd%dtype(tp),rho_a,t_kelvin, &
+                        sd%dmin(tp),sd%dmax(tp),sd%apm(tp),sd%bpm(tp), &
+                        sd%rho(tp),sd%p1(tp),sd%p2(tp),sd%p3(tp))
+                   
+                   ! Calculate particle density
+                   if (phase == 1) then
+                      if (sd%rho(tp) < 0) then
+                         ! Use equivalent volume spheres.
+                         rcfg%rho_eff(tp,1:ns,iRe_type) = rhoice ! solid ice == equivalent volume approach
+                         Deq = ( ( 6/pi*sd%apm(tp)/rhoice) ** one_third ) * ( (Di*1E-6) ** (sd%bpm(tp)/3._wp) )  * 1E6
+                         ! alternative is to comment out above two lines and use the following block
+                         ! MG Mie approach - adjust density of sphere with D = D_characteristic to match particle density
+                         !
+                         ! rcfg%rho_eff(tp,1:ns,iRe_type) = (6/pi)*sd%apm(tp)*(Di*1E-6)**(sd%bpm(tp)-3)   !MG Mie approach
+                         
+                         ! as the particle size gets small it is possible that the mass to size relationship of 
+                         ! (given by power law in hclass.data) can produce impossible results 
+                         ! where the mass is larger than a solid sphere of ice.  
+                         ! This loop ensures that no ice particle can have more mass/density larger than an ice sphere.
+                         ! do i=1,ns
+                         ! if(rcfg%rho_eff(tp,i,iRe_type) > 917 ) then
+                         ! rcfg%rho_eff(tp,i,iRe_type) = 917
+                         ! endif
+                         ! enddo
+                      else
+                         ! Equivalent volume sphere (solid ice rhoice=917 kg/m^3).
+                         rcfg%rho_eff(tp,1:ns,iRe_type) = rhoice
+                         Deq=Di * ((sd%rho(tp)/rhoice)**one_third)
+                         ! alternative ... coment out above two lines and use the following for MG-Mie
+                         ! rcfg%rho_eff(tp,1:ns,iRe_type) = sd%rho(tp)   !MG Mie approach
+                      endif
+                   else
+                      ! I assume here that water phase droplets are spheres.
+                      ! sd%rho should be ~ 1000  or sd%apm=524 .and. sd%bpm=3
+                      Deq = Di
+                   endif
+
+                   ! Calculate effective reflectivity factor of volume
+                   ! xxa are unused (Mie scattering and extinction efficiencies)
+                   xxa(1:ns) = -9.9_wp
+                   rhoi = rcfg%rho_eff(tp,1:ns,iRe_type)
+                   call zeff(rcfg%freq,Deq,Ni,ns,rcfg%k2,t_kelvin,phase,rcfg%do_ray, &
+                        ze,zr,kr,xxa,xxa,rhoi)
+
+                   ! Test compares total number concentration with sum of discrete samples 
+                   ! The second test, below, compares ab initio and "scaled" computations 
+                   !    of reflectivity
+                   !  These should get broken out as a unit test that gets called on 
+                   !    data. That routine could write to std out. 
+                   
+                   ! Test code ... compare Np value input to routine with sum of DSD
+                   ! NOTE: if .not. DO_LUT_TEST, then you are checking the LUT approximation 
+                   ! not just the DSD representation given by Ni
+                   if(Np_matrix(pr,k,tp)>0 .and. DO_NP_TEST ) then
+                      Np = path_integral(Ni,Di,1,ns-1)/rho_a*1.E6_wp
+                      ! Note: Representation is not great or small Re < 2 
+                      if( (Np_matrix(pr,k,tp)-Np)/Np_matrix(pr,k,tp)>0.1 ) then
+                         call errorMessage('ERROR(optics/quickbeam_optics.f90): Error: Np input does not match sum(N)')
+                      endif
+                   endif
+
+                   ! Clean up space
+                   deallocate(Di,Ni,rhoi,xxa,Deq)
+
+                   ! LUT test code
+                   ! This segment of code compares full calculation to scaling result
+                   if ( rcfg%Z_scale_flag(tp,itt,iRe_type) .and. DO_LUT_TEST )  then
+                      scale_factor=rho_a*hm_matrix(pr,k,tp)
+                      ! if more than 2 dBZe difference print error message/parameters.
+                      if ( abs(10*log10(ze) - 10*log10(rcfg%Ze_scaled(tp,itt,iRe_type) * &
+                           scale_factor)) > 2 ) then
+                         call errorMessage('ERROR(optics/quickbeam_optics.f90): ERROR: Roj Error?')
+                      endif
+                   endif
+                else
+                   ! Use z scaling
+                   scale_factor=rho_a*hm_matrix(pr,k,tp)
+                   zr = rcfg%Zr_scaled(tp,itt,iRe_type) * scale_factor
+                   ze = rcfg%Ze_scaled(tp,itt,iRe_type) * scale_factor
+                   kr = rcfg%kr_scaled(tp,itt,iRe_type) * scale_factor
+                endif  ! end z_scaling
+                
+                kr_vol(pr,k) = kr_vol(pr,k) + kr
+                z_vol(pr,k)  = z_vol(pr,k)  + ze
+                z_ray(pr,k)  = z_ray(pr,k)  + zr
+                
+                ! Construct Ze_scaled, Zr_scaled, and kr_scaled ... if we can
+                if ( .not. rcfg%Z_scale_flag(tp,itt,iRe_type) ) then
+                   if (iRe_type>1) then
+                      scale_factor=rho_a*hm_matrix(pr,k,tp)
+                      rcfg%Ze_scaled(tp,itt,iRe_type) = ze/ scale_factor
+                      rcfg%Zr_scaled(tp,itt,iRe_type) = zr/ scale_factor
+                      rcfg%kr_scaled(tp,itt,iRe_type) = kr/ scale_factor
+                      rcfg%Z_scale_flag(tp,itt,iRe_type) = .true.
+                      rcfg%Z_scale_added_flag(tp,itt,iRe_type)=.true.
+                   endif
+                endif
+             enddo   ! end loop of tp (hydrometeor type)
+          endif
+       enddo
+    enddo
+    
+    where(kr_vol(:,:) <= EPSILON(kr_vol)) 
+       ! Volume is hydrometeor-free	
+       !z_vol(:,:)  = undef
+       z_ray(:,:)  = undef
+    end where
+
+  end subroutine quickbeam_optics
+  ! ##############################################################################################
+  ! ##############################################################################################
+  subroutine calc_Re(Q,Np,rho_a,dtype,apm,bpm,rho_c,p1,p2,p3,Re)  
+    ! ##############################################################################################
+    ! Purpose:
+    !   Calculates Effective Radius (1/2 distribution 3rd moment / 2nd moment). 
+    !
+    !   For some distribution types, the total number concentration (per kg), Np
+    !   may be optionally specified.   Should be set to zero, otherwise.
+    !
+    !   Roj Marchand July 2010
+    !
+    ! Inputs:
+    !
+    !   [Q]        hydrometeor mixing ratio (g/kg)  ! not needed for some distribution types
+    !   [Np]       Optional Total number concentration (per kg).  0 = use defaults (p1, p2, p3)
+    !   [rho_a]    ambient air density (kg m^-3)   
+    !
+    !   Distribution parameters as per quickbeam documentation.
+    !   [dtype]    distribution type
+    !   [apm]      a parameter for mass (kg m^[-bpm])
+    !   [bmp]      b params for mass 
+    !   [p1],[p2],[p3]  distribution parameters
+    !
+    ! Outputs:
+    !   [Re]       Effective radius, 1/2 the 3rd moment/2nd moment (um)
+    !
+    ! Created:
+    !   July 2010  Roj Marchand
+    ! Modified:
+    !   12/18/14  Dustin Swales: Define type REALs as double precision (dustin.swales@noaa.gov)
+    !
+    ! ##############################################################################################
+    ! ##############################################################################################
+    
+    ! Inputs
+    real(wp), intent(in)    :: Q,Np,rho_a,rho_c,p1,p2,p3
+    integer,  intent(in)    :: dtype
+    real(wp), intent(inout) :: apm,bpm  
+    
+    ! Outputs
+    real(wp), intent(out) :: Re
+    
+    ! Internal
+    integer  :: local_dtype
+    real(wp) :: local_p3,local_Np,tmp1,tmp2
+    real(wp) :: N0,D0,vu,dm,ld,rg,log_sigma_g        ! gamma, exponential variables
+    
+    
+    ! If density is constant, set equivalent values for apm and bpm
+    if ((rho_c > 0) .and. (apm < 0)) then
+       apm = (pi/6)*rho_c
+       bpm = 3._wp
+    endif
+    
+    ! Exponential is same as modified gamma with vu =1
+    ! if Np is specified then we will just treat as modified gamma
+    if(dtype .eq. 2 .and. Np .gt. 0) then
+       local_dtype = 1
+       local_p3    = 1
+    else
+       local_dtype = dtype
+       local_p3    = p3
+    endif
+    select case(local_dtype)
+       
+       ! ---------------------------------------------------------!
+       ! Modified gamma                                           !
+       ! Np = total number concentration (1/kg) = Nt / rho_a      !
+       ! D0 = characteristic diameter (um)                        !
+       ! dm = mean diameter (um) - first moment over zeroth moment!
+       ! vu = distribution width parameter                        !
+       ! ---------------------------------------------------------!
+    case(1)  
+       
+       if( abs(local_p3+2) < 1E-8) then
+          if(Np>1E-30) then
+             ! Morrison scheme with Martin 1994 shape parameter (NOTE: vu = pc +1)
+             ! fixed Roj. Dec. 2010 -- after comment by S. Mcfarlane
+             vu = (1/(0.2714_wp + 0.00057145_wp*Np*rho_a*1E-6))**2 ! units of Nt = Np*rhoa = #/cm^3
+          else
+             call errorMessage('FATAL ERROR(optics/quickbeam_optics.f90:Calc_Re): Must specify a value for Np in each volume with Morrison/Martin Scheme.')
+             return
+          endif
+       elseif (abs(local_p3+1) > 1E-8) then
+          ! vu is fixed in hp structure  
+          vu = local_p3 
+       else
+          ! vu isn't specified
+          call errorMessage('FATAL ERROR(optics/quickbeam_optics.f90:Calc_Re): Must specify a value for vu for Modified Gamma distribution')
+          return
+       endif
+       
+       if( Np.eq.0 .and. p2+1 > 1E-8) then     ! use default value for MEAN diameter as first default  
+          dm = p2             ! by definition, should have units of microns
+          D0 = gamma(vu)/gamma(vu+1)*dm
+       else   ! use value of Np
+          if(Np.eq.0) then
+             if( abs(p1+1) > 1E-8 ) then  !   use default number concentration   
+                local_Np = p1 ! total number concentration / pa --- units kg^-1
+             else
+                call errorMessage('FATAL ERROR(optics/quickbeam_optics.f90:Calc_Re): Must specify Np or default value (p1=Dm [um] or p2=Np [1/kg]) for Modified Gamma distribution')
+                return
+             endif
+          else
+             local_Np=Np;    
+          endif
+          D0 = 1E6 * ( Q*1E-3*gamma(vu)/(apm*local_Np*gamma(vu+bpm)) )**(1/bpm)  ! units = microns
+       endif
+       Re = 0.5_wp*D0*gamma(vu+3)/gamma(vu+2)
+       
+       ! ---------------------------------------------------------!
+       ! Exponential                                              !
+       ! N0 = intercept parameter (m^-4)                          !
+       ! ld = slope parameter (um)                                !
+       ! ---------------------------------------------------------!
+    case(2)
+       
+       ! Np not specified (see if statement above) 
+       if((abs(p1+1) > 1E-8) ) then   ! N0 has been specified, determine ld
+          N0   = p1
+          tmp1 = 1._wp/(1._wp+bpm)
+          ld   = ((apm*gamma(1.+bpm)*N0)/(rho_a*Q*1E-3))**tmp1
+          ld   = ld/1E6                     ! set units to microns^-1
+       elseif (abs(p2+1) > 1E-8) then  ! lambda=ld has been specified as default
+          ld = p2     ! should have units of microns^-1 
+       else
+          call errorMessage('FATAL ERROR(optics/quickbeam_optics.f90:Calc_Re): Must specify Np or default value (p1=No or p2=lambda) for Exponential distribution')
+          return
+       endif
+       Re = 1.5_wp/ld 
+       
+       ! ---------------------------------------------------------!
+       ! Power law                                                !
+       ! ahp = Ar parameter (m^-4 mm^-bhp)                        !
+       ! bhp = br parameter                                       !
+       ! dmin_mm = lower bound (mm)                               !
+       ! dmax_mm = upper bound (mm)                               !
+       ! ---------------------------------------------------------!
+    case(3)
+       
+       Re=0._wp  ! Not supporting LUT approach for power-law ...
+       if(Np>0) then
+          call errorMessage('FATAL ERROR(optics/quickbeam_optics.f90:Calc_Re): Variable Np not supported for Power Law distribution')
+          return
+       endif
+       
+       ! ---------------------------------------------------------!
+       ! Monodisperse                                             !
+       ! D0 = particle diameter (um) == Re                        !
+       ! ---------------------------------------------------------!
+    case(4)
+       
+       Re = p1
+       if(Np>0) then
+          call errorMessage('FATAL ERROR(optics/quickbeam_optics.f90:Calc_Re): Variable Np not supported for Monodispersed distribution')
+          return
+       endif
+       
+       ! ---------------------------------------------------------!
+       ! Lognormal                                                !
+       ! N0 = total number concentration (m^-3)                   !
+       ! np = fixed number concentration (kg^-1)                  !
+       ! rg = mean radius (um)                                    !
+       ! log_sigma_g = ln(geometric standard deviation)           !
+       ! ---------------------------------------------------------!
+    case(5)
+       
+       if( abs(local_p3+1) > 1E-8 ) then
+          !set natural log width
+          log_sigma_g = local_p3 
+       else
+          call errorMessage('FATAL ERROR(optics/quickbeam_optics.f90:Calc_Re): Must specify a value for sigma_g when using a Log-Normal distribution')
+          return
+       endif
+       
+       ! get rg ... 
+       if( Np.eq.0 .and. (abs(p2+1) > 1E-8) ) then ! use default value of rg
+          rg = p2     
+       else
+          if(Np>0) then
+             local_Np=Np;  
+          elseif(abs(p2+1) < 1E-8) then
+             local_Np=p1
+          else
+             call errorMessage('ERROR(optics/quickbeam_optics.f90:Calc_Re): Must specify Np or default value (p2=Rg or p1=Np) for Log-Normal distribution')
+          endif
+          log_sigma_g = p3
+          tmp1        = (Q*1E-3)/(2._wp**bpm*apm*local_Np)
+          tmp2        = exp(0.5_wp*bpm*bpm*(log_sigma_g))*exp(0.5_wp*bpm*bpm*(log_sigma_g))    
+          rg          = ((tmp1/tmp2)**(1._wp/bpm))*1E6
+       endif
+       Re = rg*exp(2.5_wp*(log_sigma_g*log_sigma_g))    
+    end select
+  end subroutine calc_Re
+  ! ##############################################################################################
+  ! ##############################################################################################
+  subroutine dsd(Q,Re,Np,D,N,nsizes,dtype,rho_a,tk,dmin,dmax,apm,bpm,rho_c,p1,p2,p3)
+    ! ##############################################################################################
+    ! Purpose:
+    !   Create a discrete drop size distribution
+    !
+    !   Starting with Quickbeam V3, this routine now allows input of 
+    !   both effective radius (Re) and total number concentration (Nt)
+    !   Roj Marchand July 2010
+    !
+    !   The version in Quickbeam v.104 was modified to allow Re but not Nt 
+    !   This is a significantly modified form for the version      
+    !
+    !   Originally Part of QuickBeam v1.03 by John Haynes
+    !   http://reef.atmos.colostate.edu/haynes/radarsim
+    !
+    ! Inputs:
+    !
+    !   [Q]        hydrometeor mixing ratio (g/kg)
+    !   [Re]       Optional Effective Radius (microns).  0 = use defaults (p1, p2, p3)
+    !
+    !   [D]        array of discrete drop sizes (um) where we desire to know the number concentraiton n(D).
+    !   [nsizes]   number of elements of [D]
+    !
+    !   [dtype]    distribution type
+    !   [rho_a]    ambient air density (kg m^-3)
+    !   [tk]       temperature (K)
+    !   [dmin]     minimum size cutoff (um)
+    !   [dmax]     maximum size cutoff (um)
+    !   [rho_c]    alternate constant density (kg m^-3)
+    !   [p1],[p2],[p3]  distribution parameters
+    !
+    ! Input/Output:
+    !   [apm]      a parameter for mass (kg m^[-bpm])
+    !   [bmp]      b params for mass
+    !
+    ! Outputs:
+    !   [N]        discrete concentrations (cm^-3 um^-1)
+    !              or, for monodisperse, a constant (1/cm^3)
+    !
+    ! Requires:
+    !   function infind
+    !
+    ! Created:
+    !   11/28/05  John Haynes (haynes@atmos.colostate.edu)
+    ! Modified:
+    !   01/31/06  Port from IDL to Fortran 90
+    !   07/07/06  Rewritten for variable DSD's
+    !   10/02/06  Rewritten using scaling factors (Roger Marchand and JMH), Re added V1.04
+    !   July 2020 "N Scale factors" (variable fc) removed (Roj Marchand).
+    !   12/18/14  Define type REALs as double precision (dustin.swales@noaa.gov)
+    ! ##############################################################################################
+    
+    ! Inputs
+    integer, intent(in)                   :: &
+         nsizes,& ! Number of elements of [D]
+         dtype    !  distribution type
+    real(wp),intent(in),dimension(nsizes) :: &
+         D        ! Array of discrete drop sizes (um) where we desire to know the number concentraiton n(D).
+    real(wp),intent(in) :: &
+         Q,     & ! Hydrometeor mixing ratio (g/kg)
+         Np,    & !
+         rho_a, & ! Ambient air density (kg m^-3)
+         tk,    & ! Temperature (K)
+         dmin,  & ! Minimum size cutoff (um)
+         dmax,  & ! Maximum size cutoff (um)
+         rho_c, & ! Alternate constant density (kg m^-3)
+         p1,    & ! Distribution parameter 1
+         p2,    & ! Distribution parameter 2
+         p3       ! Distribution parameter 3
+    real(wp),intent(inout) :: &
+         apm,   & ! a parameter for mass (kg m^[-bpm])
+         bpm,   & ! b params for mass
+         Re       ! Optional Effective Radius (microns)
+    
+    ! Outputs
+    real(wp),intent(out),dimension(nsizes) :: &
+         N        ! Discrete concentrations (cm^-3 um^-1)
+                  ! or, for monodisperse, a constant (1/cm^3)
+    
+    ! Internal Variables
+    real(wp),dimension(nsizes) :: &
+         fc
+    real(wp)                   :: &
+         N0,D0,vu,local_np,dm,ld, & ! gamma, exponential variables
+         dmin_mm,dmax_mm,ahp,bhp, & ! power law variables
+         rg,log_sigma_g,          & ! lognormal variables
+         rho_e,                   & ! particle density (kg m^-3)
+         tmp1,tmp2,tc
+    integer :: &
+         k,lidx,uidx
+    
+    ! Convert temperature from Kelvin to Celsius
+    tc = tk - 273.15_wp
+    
+    ! If density is constant, store equivalent values for apm and bpm
+    if ((rho_c > 0) .and. (apm < 0)) then
+       apm = (pi/6)*rho_c
+       bpm = 3._wp
+    endif
+    
+    ! Will preferentially use Re input over Np.
+    ! if only Np given then calculate Re
+    ! if neigher than use other defaults (p1,p2,p3) following quickbeam documentation
+    if(Re==0 .and. Np>0) then
+       call calc_Re(Q,Np,rho_a,dtype,apm,bpm,rho_c,p1,p2,p3,Re)
+    endif
+    select case(dtype)
+       
+       ! ---------------------------------------------------------!
+       ! Modified gamma                                           !
+       ! np = total number concentration                          !
+       ! D0 = characteristic diameter (um)                        !
+       ! dm = mean diameter (um) - first moment over zeroth moment!
+       ! vu = distribution width parameter                        !
+       ! ---------------------------------------------------------!
+    case(1)  
+       
+       if( abs(p3+2) < 1E-8) then
+          if( Np>1E-30) then
+             ! Morrison scheme with Martin 1994 shape parameter (NOTE: vu = pc +1)
+             ! fixed Roj. Dec. 2010 -- after comment by S. Mcfarlane
+             vu = (1/(0.2714_wp + 0.00057145_wp*Np*rho_a*1E-6))**2._wp ! units of Nt = Np*rhoa = #/cm^3
+          else
+             call errorMessage('FATAL ERROR(optics/quickbeam_optics.f90:dsd): Must specify a value for Np in each volume with Morrison/Martin Scheme.')
+             return
+          endif
+       elseif (abs(p3+1) > 1E-8) then
+          ! vu is fixed in hp structure  
+          vu = p3 
+       else
+          ! vu isn't specified
+          call errorMessage('FATAL ERROR(optics/quickbeam_optics.f90:dsd): Must specify a value for vu for Modified Gamma distribution')
+          return
+       endif
+       
+       if(Re>0) then
+          D0 = 2._wp*Re*gamma(vu+2)/gamma(vu+3)
+          fc = (((D*1E-6)**(vu-1)*exp(-1*D/D0)) / &
+               (apm*((D0*1E-6)**(vu+bpm))*gamma(vu+bpm))) * 1E-12
+          N  = fc*rho_a*(Q*1E-3)
+       elseif( p2+1 > 1E-8) then     ! use default value for MEAN diameter
+          dm = p2
+          D0 = gamma(vu)/gamma(vu+1)*dm
+          fc = (((D*1E-6)**(vu-1)*exp(-1*D/D0)) / &
+               (apm*((D0*1E-6)**(vu+bpm))*gamma(vu+bpm))) * 1E-12
+          N  = fc*rho_a*(Q*1E-3)
+       elseif(abs(p3+1) > 1E-8)  then! use default number concentration
+          local_np = p1 ! total number concentration / pa check
+          tmp1     = (Q*1E-3)**(1./bpm)
+          fc       = (D*1E-6 / (gamma(vu)/(apm*local_np*gamma(vu+bpm)))**(1._wp/bpm))**vu
+          N        = ((rho_a*local_np*fc*(D*1E-6)**(-1._wp))/(gamma(vu)*tmp1**vu) * &
+               exp(-1._wp*fc**(1._wp/vu)/tmp1)) * 1E-12
+       else
+          call errorMessage('FATAL ERROR(optics/quickbeam_optics.f90:dsd): No default value for Dm or Np provided!')
+          return
+       endif
+       
+       ! ---------------------------------------------------------!
+       ! Exponential                                              !
+       ! N0 = intercept parameter (m^-4)                          !
+       ! ld = slope parameter (um)                                !
+       ! ---------------------------------------------------------!
+    case(2)
+       
+       if(Re>0) then
+          ld = 1.5_wp/Re   ! units 1/um
+          fc = (ld*1E6)**(1.+bpm)/(apm*gamma(1+bpm))*exp(-1._wp*(ld*1E6)*(D*1E-6))*1E-12
+          N  = fc*rho_a*(Q*1E-3)
+       elseif (abs(p1+1) > 1E-8) then
+          ! Use N0 default value
+          N0   = p1
+          tmp1 = 1._wp/(1._wp+bpm)
+          fc   = ((apm*gamma(1.+bpm)*N0)**tmp1)*(D*1E-6)
+          N    = (N0*exp(-1._wp*fc*(1._wp/(rho_a*Q*1E-3))**tmp1)) * 1E-12
+       elseif (abs(p2+1) > 1E-8) then
+          ! Use default value for lambda 
+          ld = p2
+          fc = (ld*1E6)**(1._wp+bpm)/(apm*gamma(1+bpm))*exp(-1._wp*(ld*1E6)*(D*1E-6))*1E-12
+          N  = fc*rho_a*(Q*1E-3)
+       else
+          ! ld "parameterized" from temperature (carry over from original Quickbeam).
+          ld = 1220._wp*10._wp**(-0.0245_wp*tc)*1E-6
+          N0 = ((ld*1E6)**(1._wp+bpm)*Q*1E-3*rho_a)/(apm*gamma(1+bpm))
+          N  = (N0*exp(-ld*D)) * 1E-12
+       endif
+       
+       ! ---------------------------------------------------------!
+       ! Power law                                                !
+       ! ahp = Ar parameter (m^-4 mm^-bhp)                        !
+       ! bhp = br parameter                                       !
+       ! dmin_mm = lower bound (mm)                               !
+       ! dmax_mm = upper bound (mm)                               !
+       ! ---------------------------------------------------------!
+    case(3)
+       
+       if(Re>0) then
+          call errorMessage('FATAL ERROR(optics/quickbeam_optics.f90:dsd): Variable Re not supported for Power-Law distribution')
+          return
+       elseif(Np>0) then
+          call errorMessage('FATAL ERROR(optics/quickbeam_optics.f90:dsd): Variable Np not supported for Power-Law distribution')
+          return
+       endif
+       
+       ! br parameter
+       if (abs(p1+2) < 1E-8) then
+          ! if p1=-2, bhp is parameterized according to Ryan (2000),
+          ! applicatable to cirrus clouds
+          if (tc < -30) then
+             bhp = -1.75_wp+0.09_wp*((tc+273._wp)-243.16_wp)
+          elseif ((tc >= -30) .and. (tc < -9)) then
+             bhp = -3.25_wp-0.06_wp*((tc+273._wp)-265.66_wp)
+          else
+             bhp = -2.15_wp
+          endif
+       elseif (abs(p1+3) < 1E-8) then      
+          ! if p1=-3, bhp is parameterized according to Ryan (2000),
+          ! applicable to frontal clouds
+          if (tc < -35) then
+             bhp = -1.75_wp+0.09_wp*((tc+273._wp)-243.16_wp)
+          elseif ((tc >= -35) .and. (tc < -17.5)) then
+             bhp = -2.65_wp+0.09_wp*((tc+273._wp)-255.66_wp)
+          elseif ((tc >= -17.5) .and. (tc < -9)) then
+             bhp = -3.25_wp-0.06_wp*((tc+273._wp)-265.66_wp)
+          else
+             bhp = -2.15_wp
+          endif
+       else
+          ! Otherwise the specified value is used
+          bhp = p1
+       endif
+       
+       ! Ar parameter
+       dmin_mm = dmin*1E-3
+       dmax_mm = dmax*1E-3
+       
+       ! Commented lines are original method with constant density
+       ! rc = 500.       ! (kg/m^3)
+       ! tmp1 = 6*rho_a*(bhp+4)
+       ! tmp2 = pi*rc*(dmax_mm**(bhp+4))*(1-(dmin_mm/dmax_mm)**(bhp+4))
+       ! ahp = (Q*1E-3)*1E12*tmp1/tmp2
+       
+       ! New method is more consistent with the rest of the distributions
+       ! and allows density to vary with particle size
+       tmp1 = rho_a*(Q*1E-3)*(bhp+bpm+1)
+       tmp2 = apm*(dmax_mm**bhp*dmax**(bpm+1)-dmin_mm**bhp*dmin**(bpm+1))
+       ahp  = tmp1/tmp2 * 1E24
+       ! ahp = tmp1/tmp2 
+       lidx = infind(D,dmin)
+       uidx = infind(D,dmax)    
+       do k=lidx,uidx
+          N(k) = (ahp*(D(k)*1E-3)**bhp) * 1E-12    
+       enddo
+       
+       ! ---------------------------------------------------------!
+       ! Monodisperse                                             !
+       ! D0 = particle diameter (um)                              !
+       ! ---------------------------------------------------------!
+    case(4)
+       
+       if (Re>0) then
+          D0 = Re
+       else
+          D0 = p1
+       endif
+       
+       rho_e = (6._wp/pi)*apm*(D0*1E-6)**(bpm-3)
+       fc(1) = (6._wp/(pi*D0*D0*D0*rho_e))*1E12
+       N(1)  = fc(1)*rho_a*(Q*1E-3)
+       
+       ! ---------------------------------------------------------!
+       ! Lognormal                                                !
+       ! N0 = total number concentration (m^-3)                   !
+       ! np = fixed number concentration (kg^-1)                  !
+       ! rg = mean radius (um)                                    !
+       ! og_sigma_g = ln(geometric standard deviation)            !
+       ! ---------------------------------------------------------!
+    case(5)
+       if (abs(p1+1) < 1E-8 .or. Re>0 ) then
+          ! rg, log_sigma_g are given
+          log_sigma_g = p3
+          tmp2 = (bpm*log_sigma_g)*(bpm*log_sigma_g)
+          if(Re.le.0) then 
+             rg = p2
+          else
+             !rg = Re*exp(-2.5*(log_sigma_g*log_sigma_g))
+             rg =Re*exp(-2.5_wp*(log_sigma_g**2))
+             
+          endif
+          
+          fc = 0.5_wp*((1._wp/((2._wp*rg*1E-6)**(bpm)*apm*(2._wp*pi)**(0.5_wp) * &
+               log_sigma_g*D*0.5_wp*1E-6))*exp(-0.5_wp*((log(0.5_wp*D/rg)/log_sigma_g)**2._wp+tmp2)))*1E-12
+          N = fc*rho_a*(Q*1E-3)
+          
+       elseif (abs(p2+1) < 1E-8 .or. Np>0) then
+          ! Np, log_sigma_g are given    
+          if(Np>0) then
+             local_Np = Np
+          else
+             local_Np = p1
+          endif
+          
+          log_sigma_g = p3
+          N0   = local_np*rho_a
+          tmp1 = (rho_a*(Q*1E-3))/(2._wp**bpm*apm*N0)
+          tmp2 = exp(0.5_wp*bpm*bpm*(log_sigma_g))*exp(0.5_wp*bpm*bpm*(log_sigma_g))
+          rg   = ((tmp1/tmp2)**(1/bpm))*1E6
+          
+          N = 0.5_wp*(N0 / ((2._wp*pi)**(0.5_wp)*log_sigma_g*D*0.5_wp*1E-6) * &
+               exp((-0.5_wp*(log(0.5_wp*D/rg)/log_sigma_g)**2._wp)))*1E-12      
+       else
+          call errorMessage('FATAL ERROR(optics/quickbeam_optics.f90:dsd): Must specify a value for sigma_g')
+          return
+       endif
+    end select
+  end subroutine dsd
+  ! ##############################################################################################
+  ! ##############################################################################################
+  subroutine zeff(freq,D,N,nsizes,k2,tt,ice,xr,z_eff,z_ray,kr,qe,qs,rho_e)
+    ! ##############################################################################################
+    ! Purpose:
+    !   Simulates radar return of a volume given DSD of spheres
+    !   Part of QuickBeam v1.03 by John Haynes
+    !   http://reef.atmos.colostate.edu/haynes/radarsim
+    !
+    ! Inputs:
+    !   [freq]      radar frequency (GHz)
+    !   [D]         discrete drop sizes (um)
+    !   [N]         discrete concentrations (cm^-3 um^-1)
+    !   [nsizes]    number of discrete drop sizes
+    !   [k2]        |K|^2, -1=use frequency dependent default 
+    !   [tt]        hydrometeor temperature (K)
+    !   [ice]       indicates volume consists of ice
+    !   [xr]        perform Rayleigh calculations?
+    !   [qe]        if using a mie table, these contain ext/sca ...
+    !   [qs]        ... efficiencies; otherwise set to -1
+    !   [rho_e]     medium effective density (kg m^-3) (-1 = pure)
+    !
+    ! Outputs:
+    !   [z_eff]     unattenuated effective reflectivity factor (mm^6/m^3)
+    !   [z_ray]     reflectivity factor, Rayleigh only (mm^6/m^3)
+    !   [kr]        attenuation coefficient (db km^-1)
+    !
+    ! Created:
+    !   11/28/05  John Haynes (haynes@atmos.colostate.edu)
+    ! Modified:
+    !   12/18/14  Dustin Swales: Define type REALs as double precision (dustin.swales@noaa.gov)
+    ! ##############################################################################################
+    ! Inputs
+    integer,  intent(in) :: &
+         ice,        & ! Indicates volume consists of ice
+         xr,         & ! Perform Rayleigh calculations?
+         nsizes        ! Number of discrete drop sizes
+    real(wp), intent(in),dimension(nsizes) :: &
+         D,     & ! Discrete drop sizes (um)
+         N,     & ! Discrete concentrations (cm^-3 um^-1)
+         rho_e, & ! Medium effective density (kg m^-3) (-1 = pure)
+         qe,    & ! Extinction efficiency, when using Mie tables
+         qs       ! Scatering efficiency, when using Mie tables
+    real(wp),intent(in) :: &
+         freq,  & ! Radar frequency (GHz)
+         tt       ! Hydrometeor temperature (K)
+    real(wp), intent(inout) :: &
+         k2            ! |K|^2, -1=use frequency dependent default 
+    
+    ! Outputs
+    real(wp), intent(out) :: &
+         z_eff,      & ! Unattenuated effective reflectivity factor (mm^6/m^3)
+         z_ray,      & ! Reflectivity factor, Rayleigh only (mm^6/m^3)
+         kr            ! Attenuation coefficient (db km^-1)
+    
+    ! Internal Variables
+    integer                     :: correct_for_rho ! Correct for density flag
+    real(wp), dimension(nsizes) :: &
+         D0,        &    ! D in (m)
+         N0,        &    ! N in m^-3 m^-1
+         sizep,     &    ! Size parameter
+         qext,      &    ! Extinction efficiency
+         qbsca,     &    ! Backscatter efficiency
+         f,         &    ! Ice fraction
+         xtemp           !
+    real(wp) :: &
+         wl, cr,eta_sum,eta_mie,const,z0_eff,z0_ray,k_sum,n_r,n_i,dqv(1),dqsc,dg,dph(1)
+    complex(wp)         :: &
+         m,                  &    ! Complex index of refraction of bulk form
+         Xs1(1), Xs2(1)           !
+    integer          :: &
+         i, err                   !
+    integer, parameter :: &
+         one=1                    !
+    real(wp),parameter :: &
+         conv_d  = 1e-6,     &    ! Conversion factor for drop sizes (to m)
+         conv_n  = 1e12,     &    ! Conversion factor for drop concentrations (to m^-3)
+         conv_f  = 0.299792458    ! Conversion for radar frequency (to m)
+    complex(wp),dimension(nsizes) ::&
+         m0             ! Complex index of refraction
+    
+    ! Initialize
+    z0_ray = 0._wp
+    
+    ! Conversions
+    D0 = d*conv_d
+    N0 = n*conv_n
+    wl = conv_f/freq
+    
+    ! // dielectric constant |k^2| defaults
+    if (k2 < 0) then
+       k2 = 0.933_wp
+       if (abs(94.-freq) < 3.) k2=0.75_wp
+       if (abs(35.-freq) < 3.) k2=0.88_wp
+       if (abs(13.8-freq) < 3.) k2=0.925_wp
+    endif
+    
+    if (qe(1) < -9) then
+       
+       ! Get the refractive index of the bulk hydrometeors
+       if (ice == 0) then
+          call m_wat(freq,tt,n_r,n_i)
+       else
+          call m_ice(freq,tt,n_r,n_i)
+       endif
+       m = cmplx(n_r,-n_i)
+       m0(1:nsizes) = m
+       
+       correct_for_rho = 0
+       if ((ice == 1) .and. (minval(rho_e) >= 0)) correct_for_rho = 1
+       
+       ! Correct refractive index for ice density if needed
+       if (correct_for_rho == 1) then
+          f  = rho_e/rhoice
+          m0 = sqrt((2+(m0*m0)+2*f*((m0*m0)-1))/(2+(m0*m0)+f*(1-(m0*m0))))
+       endif
+       
+       ! Mie calculations
+       sizep = (pi*D0)/wl
+       dqv(1) = 0._wp
+       do i=1,nsizes
+          call mieint(sizep(i), m0(i), one, dqv, qext(i), dqsc, qbsca(i), &
+               dg, xs1, xs2, dph, err)
+       end do
+
+    else
+       ! Mie table used
+       qext  = qe
+       qbsca = qs
+    endif
+    
+    ! eta_mie = 0.25*sum[qbsca*pi*D^2*N(D)*deltaD]
+    ! <--------- eta_sum --------->
+    ! z0_eff = (wl^4/!pi^5)*(1./k2)*eta_mie
+    eta_sum = 0._wp
+    if (size(D0) == 1) then
+       eta_sum = qbsca(1)*(n(1)*1E6)*D0(1)*D0(1)
+    else
+       xtemp = qbsca*N0*D0*D0
+       call avint(xtemp,D0,nsizes,D0(1),D0(size(D0,1)),eta_sum)
+    endif
+    
+    eta_mie = eta_sum*0.25_wp*pi
+    const   = ((wl*wl*wl*wl)/(pi*pi*pi*pi*pi))*(1._wp/k2)
+    
+    z0_eff  = const*eta_mie
+    
+    ! kr = 0.25*cr*sum[qext*pi*D^2*N(D)*deltaD]
+    ! <---------- k_sum --------->  
+    k_sum = 0._wp
+    if (size(D0) == 1) then
+       k_sum = qext(1)*(n(1)*1E6)*D0(1)*D0(1)
+    else
+       xtemp = qext*N0*D0*D0
+       call avint(xtemp,D0,nsizes,D0(1),D0(size(D0,1)),k_sum)
+    endif
+    ! DS2014 START: Making this calculation in double precision results in a small 
+    !               amount of very small errors in the COSP output field,dBZE94,
+    !               so it will be left as is.
+    !cr = 10._wp/log(10._wp)
+    cr = 10./log(10.)
+    ! DS2014 STOP
+    kr = k_sum*0.25_wp*pi*(1000._wp*cr)
+    
+    ! z_ray = sum[D^6*N(D)*deltaD]
+    if (xr == 1) then
+       z0_ray = 0._wp
+       if (size(D0) == 1) then
+          z0_ray = (n(1)*1E6)*D0(1)*D0(1)*D0(1)*D0(1)*D0(1)*D0(1)
+       else
+          xtemp = N0*D0*D0*D0*D0*D0*D0
+          call avint(xtemp,D0,nsizes,D0(1),D0(size(D0)),z0_ray)
+       endif
+    endif
+    
+    ! Convert to mm^6/m^3
+    z_eff = z0_eff*1E18 !  10.*alog10(z0_eff*1E18)
+    z_ray = z0_ray*1E18 !  10.*alog10(z0_ray*1E18)
+    
+  end subroutine zeff
+  ! ##############################################################################################
+  ! ##############################################################################################
+  function gases(PRES_mb,T,SH,f)
+    ! ##############################################################################################
+    ! Purpose:
+    !   Compute 2-way gaseous attenuation through a volume in microwave
+    !
+    ! Inputs:
+    !   [PRES_mb]   pressure (mb) (hPa)
+    !   [T]         temperature (K)
+    !   [RH]        relative humidity (%)
+    !   [f]         frequency (GHz), < 300 GHz
+    !
+    ! Returns:
+    !   2-way gaseous attenuation (dB/km)
+    !
+    ! Reference:
+    !   Uses method of Liebe (1985)
+    !
+    ! Created:
+    !   12/09/05  John Haynes (haynes@atmos.colostate.edu)
+    ! Modified:
+    !   01/31/06  Port from IDL to Fortran 90
+    !   12/19/14  Dustin Swales: Define type REALs as double precision (dustin.swales@noaa.gov)
+    ! ##############################################################################################
+    
+    ! INPUTS
+    real(wp), intent(in) :: & !
+         PRES_mb,           & ! Pressure (mb) (hPa)
+         T,                 & ! Temperature (K)
+         SH,                & ! Specific humidity
+         f                    ! Frequency (GHz), < 300 GHz
+    
+    ! PARAMETERS
+    integer, parameter   :: & !
+         nbands_o2  = 48,   & ! Number of O2 bands
+         nbands_h2o = 30      ! Number of h2o bands
+    ! LOCAL VARIABLES
+    real(wp) :: &
+         gases, th, e, p, sumo, gm0, a0, ap, term1,    &
+         term2, term3, bf, be, term4, npp,e_th,one_th, &
+         pth3,eth35,aux1,aux2,aux3, aux4,gm,delt,x,y,  &
+         gm2,fpp_o2,fpp_h2o,s_o2,s_h2o
+    integer :: i
+
+    ! Table1 parameters  v0, a1, a2, a3, a4, a5, a6  
+    real(wp),dimension(nbands_o2),parameter ::                                          &
+         v0 = (/49.4523790,49.9622570,50.4742380,50.9877480,51.5033500,                 &
+                52.0214090,52.5423930,53.0669060,53.5957480,54.1299999,54.6711570,      &
+                55.2213650,55.7838000,56.2647770,56.3378700,56.9681000,57.6124810,      &
+                58.3238740,58.4465890,59.1642040,59.5909820,60.3060570,60.4347750,      &
+                61.1505580,61.8001520,62.4112120,62.4862530,62.9979740,63.5685150,      &
+                64.1277640,64.6789000,65.2240670,65.7647690,66.3020880,66.8368270,      &
+                67.3695950,67.9008620,68.4310010,68.9603060,69.4890210,70.0173420,      &
+                118.7503410,368.4983500,424.7631200,487.2493700,715.3931500,            &
+                773.8387300, 834.1453300/),                                             &
+         a1 = (/0.0000001,0.0000003,0.0000009,0.0000025,0.0000061,0.0000141,            &
+                0.0000310,0.0000641,0.0001247,0.0002280,0.0003918,0.0006316,0.0009535,  &
+                0.0005489,0.0013440,0.0017630,0.0000213,0.0000239,0.0000146,0.0000240,  &
+                0.0000211,0.0000212,0.0000246,0.0000250,0.0000230,0.0000193,0.0000152,  &
+                0.0000150,0.0000109,0.0007335,0.0004635,0.0002748,0.0001530,0.0000801,  &
+                0.0000395,0.0000183,0.0000080,0.0000033,0.0000013,0.0000005,0.0000002,  &
+                0.0000094,0.0000679,0.0006380,0.0002350,0.0000996,0.0006710,0.0001800/),&
+         a2 = (/11.8300000,10.7200000,9.6900000,8.8900000,7.7400000,6.8400000,          &
+                6.0000000,5.2200000,4.4800000,3.8100000,3.1900000,2.6200000,2.1150000,  &
+                0.0100000,1.6550000,1.2550000,0.9100000,0.6210000,0.0790000,0.3860000,  &
+                0.2070000,0.2070000,0.3860000,0.6210000,0.9100000,1.2550000,0.0780000,  &
+                1.6600000,2.1100000,2.6200000,3.1900000,3.8100000,4.4800000,5.2200000,  &
+                6.0000000,6.8400000,7.7400000,8.6900000,9.6900000,10.7200000,11.8300000,&
+                0.0000000,0.0200000,0.0110000,0.0110000,0.0890000,0.0790000,0.0790000/),&
+         a3 = (/0.0083000,0.0085000,0.0086000,0.0087000,0.0089000,0.0092000,            &
+                0.0094000,0.0097000,0.0100000,0.0102000,0.0105000,0.0107900,0.0111000,  &
+                0.0164600,0.0114400,0.0118100,0.0122100,0.0126600,0.0144900,0.0131900,  &
+                0.0136000,0.0138200,0.0129700,0.0124800,0.0120700,0.0117100,0.0146800,  &
+                0.0113900,0.0110800,0.0107800,0.0105000,0.0102000,0.0100000,0.0097000,  &
+                0.0094000,0.0092000,0.0089000,0.0087000,0.0086000,0.0085000,0.0084000,  &
+                0.0159200,0.0192000,0.0191600,0.0192000,0.0181000,0.0181000,0.0181000/),&
+         a4 = (/0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,            &
+                0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,  &
+                0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,  &
+                0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,  &
+                0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,  &
+                0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,  &
+                0.0000000,0.6000000,0.6000000,0.6000000,0.6000000,0.6000000,0.6000000/),&
+         a5 = (/0.0056000,0.0056000,0.0056000,0.0055000,0.0056000,0.0055000,            &
+                0.0057000,0.0053000,0.0054000,0.0048000,0.0048000,0.0041700,0.0037500,  &
+                0.0077400,0.0029700,0.0021200,0.0009400,-0.0005500,0.0059700,-0.0024400,&
+                0.0034400,-0.0041300,0.0013200,-0.0003600,-0.0015900,-0.0026600,        &
+                -0.0047700,-0.0033400,-0.0041700,-0.0044800,-0.0051000,-0.0051000,      &
+                -0.0057000,-0.0055000,-0.0059000,-0.0056000,-0.0058000,-0.0057000,      &
+                -0.0056000,-0.0056000,-0.0056000,-0.0004400,0.0000000,0.0000000,        &
+                0.0000000,0.0000000,0.0000000,0.0000000/),                              & 
+         a6 = (/1.7000000,1.7000000,1.7000000,1.7000000,1.8000000,1.8000000,            &
+                1.8000000,1.9000000,1.8000000,2.0000000,1.9000000,2.1000000,2.1000000,  &
+                0.9000000,2.3000000,2.5000000,3.7000000,-3.1000000,0.8000000,0.1000000, &
+                0.5000000,0.7000000,-1.0000000,5.8000000,2.9000000,2.3000000,0.9000000, &
+                2.2000000,2.0000000,2.0000000,1.8000000,1.9000000,1.8000000,1.8000000,  &
+                1.7000000,1.8000000,1.7000000,1.7000000,1.7000000,1.7000000,1.7000000,  &
+                0.9000000,1.0000000,1.0000000,1.0000000,1.0000000,1.0000000,1.0000000/)
+    
+    ! Table2 parameters  v1, b1, b2, b3
+    real(wp),dimension(nbands_h2o),parameter ::                                          &
+         v1 = (/22.2350800,67.8139600,119.9959400,183.3101170,321.2256440,               &
+                325.1529190,336.1870000,380.1973720,390.1345080,437.3466670,439.1508120, &
+                443.0182950,448.0010750,470.8889740,474.6891270,488.4911330,503.5685320, &
+                504.4826920,556.9360020,620.7008070,658.0065000,752.0332270,841.0735950, &
+                859.8650000,899.4070000,902.5550000,906.2055240,916.1715820,970.3150220, &
+                987.9267640/),                                                           &
+         b1 = (/0.1090000,0.0011000,0.0007000,2.3000000,0.0464000,1.5400000,             &
+                0.0010000,11.9000000,0.0044000,0.0637000,0.9210000,0.1940000,10.6000000, &
+                0.3300000,1.2800000,0.2530000,0.0374000,0.0125000,510.0000000,5.0900000, &
+                0.2740000,250.0000000,0.0130000,0.1330000,0.0550000,0.0380000,0.1830000, &
+                8.5600000,9.1600000,138.0000000/),                                       &
+         b2 = (/2.1430000,8.7300000,8.3470000,0.6530000,6.1560000,1.5150000,             &
+                9.8020000,1.0180000,7.3180000,5.0150000,3.5610000,5.0150000,1.3700000,   &
+                3.5610000,2.3420000,2.8140000,6.6930000,6.6930000,0.1140000,2.1500000,   &
+                7.7670000,0.3360000,8.1130000,7.9890000,7.8450000,8.3600000,5.0390000,   &
+                1.3690000,1.8420000,0.1780000/),                                         &
+         b3 = (/0.0278400,0.0276000,0.0270000,0.0283500,0.0214000,0.0270000,             &
+                0.0265000,0.0276000,0.0190000,0.0137000,0.0164000,0.0144000,0.0238000,   &
+                0.0182000,0.0198000,0.0249000,0.0115000,0.0119000,0.0300000,0.0223000,   &
+                0.0300000,0.0286000,0.0141000,0.0286000,0.0286000,0.0264000,0.0234000,   &
+                0.0253000,0.0240000,0.0286000/)
+
+    ! Conversions
+    th     = 300._wp/T                                             ! unitless
+
+    ! DS2014 START: Using _wp for the exponential in the denominator results in slight errors
+    !               for dBze94. 0.01 % of values differ, relative range: 1.03e-05 to  1.78e-04
+    !e      = (RH*th*th*th*th*th)/(41.45_wp*10**(9.834_wp*th-10))   ! kPa
+    !e = (RH*th*th*th*th*th)/(41.45_wp*10**(9.834_wp*th-10))   ! kPa
+    e = SH*PRES_mb/(SH+0.622_wp)/1000._wp !kPa
+    ! DS2014 END
+
+    p      = PRES_mb/1000._wp-e                                      ! kPa
+    e_th   = e*th
+    one_th = 1 - th
+    pth3   = p*th*th*th
+    eth35  = e*th**(3.5)
+    
+    ! Term1
+    sumo = 0._wp
+    aux1 = 1.1_wp*e_th
+    do i=1,nbands_o2
+       aux2   = f/v0(i)
+       aux3   = v0(i)-f
+       aux4   = v0(i)+f
+       gm     = a3(i)*(p*th**(0.8_wp-a4(i))+aux1)
+       gm2    = gm*gm
+       delt   = a5(i)*p*th**a6(i)
+       x      = aux3*aux3+gm2
+       y      = aux4*aux4+gm2
+       fpp_o2 = (((1._wp/x)+(1._wp/y))*(gm*aux2) - (delt*aux2)*((aux3/(x))-(aux4/(x))))
+       s_o2   = a1(i)*pth3*exp(a2(i)*one_th)
+       sumo   = sumo + fpp_o2 * s_o2
+    enddo
+    term1 = sumo
+
+    ! Term2
+    gm0   = 5.6E-3_wp*(p+1.1_wp*e)*th**(0.8_wp)
+    a0    = 3.07E-4_wp
+    ap    = 1.4_wp*(1-1.2_wp*f**(1.5_wp)*1E-5)*1E-10
+    term2 = (2*a0*(gm0*(1+(f/gm0)*(f/gm0))*(1+(f/60._wp)**2))**(-1) + ap*p*th**(2.5_wp))*f*p*th*th
+
+    ! Term3
+    sumo = 0._wp
+    aux1 = 4.8_wp*e_th
+    do i=1,nbands_h2o
+       aux2    = f/v1(i)
+       aux3    = v1(i)-f
+       aux4    = v1(i)+f
+       gm      = b3(i)*(p*th**(0.8)+aux1)
+       gm2     = gm*gm
+       x       = aux3*aux3+gm2
+       y       = aux4*aux4+gm2
+       fpp_h2o = ((1._wp/x)+(1._wp/y))*(gm*aux2) ! - (delt*aux2)*((aux3/(x))-(aux4/(x)))
+       s_h2o   = b1(i)*eth35*exp(b2(i)*one_th)
+       sumo    = sumo + fpp_h2o * s_h2o
+    enddo
+    term3 = sumo
+
+    ! Term4
+    bf    = 1.4E-6_wp
+    be    = 5.41E-5_wp
+    term4 = (bf*p+be*e*th*th*th)*f*e*th**(2.5_wp)
+
+    ! Summation and result
+    npp   = term1 + term2 + term3 + term4
+    gases = 0.182_wp*f*npp
+    
+  end function gases
+ subroutine hydro_class_init(lsingle,ldouble,sd)
+    ! ##############################################################################################
+    ! Purpose:
+    !
+    !   Initialize variables used by the radar simulator.
+    !   Part of QuickBeam v3.0 by John Haynes and Roj Marchand
+    !   
+    ! Inputs:  
+    !   NAME            SIZE        DESCRIPTION
+    !   [lsingle]       (1)         Logical flag to use single moment
+    !   [ldouble]       (1)         Logical flag to use two moment
+    ! Outputs:
+    !   [sd]                        Structure that define hydrometeor types
+    !
+    ! Local variables:
+    !   [n_hydro]       (1)         Number of hydrometeor types
+    !   [hclass_type]   (nhclass)   Type of distribution (see quickbeam documentation)
+    !   [hclass_phase]  (nhclass)   1==ice, 0=liquid
+    !   [hclass_dmin]   (nhclass)   Minimum diameter allowed is drop size distribution N(D<Dmin)=0
+    !   [hclass_dmax]   (nhclass)   Maximum diameter allowed is drop size distribution N(D>Dmax)=0
+    !   [hclass_apm]    (nhclass)   Density of partical apm*D^bpm or constant = rho
+    !   [hclass_bpm]    (nhclass)   Density of partical apm*D^bpm or constant = rho
+    !   [hclass_rho]    (nhclass)   Density of partical apm*D^bpm or constant = rho
+    !   [hclass_p1]     (nhclass)   Default values of DSD parameters (see quickbeam documentation)
+    !   [hclass_p2]     (nhclass)   Default values of DSD parameters (see quickbeam documentation)
+    !   [hclass_p3]     (nhclass)   Default values of DSD parameters (see quickbeam documentation)    
+    ! Modified:
+    !   08/23/2006  placed into subroutine form (Roger Marchand)
+    !   June 2010   New interface to support "radar_simulator_params" structure
+    !   12/22/2014  Moved radar simulator (CLOUDSAT) configuration initialization to cloudsat_init
+    ! ##############################################################################################
+
+    ! ####################################################################################
+    ! NOTES on HCLASS variables
+    !
+    ! TYPE - Set to
+    ! 1 for modified gamma distribution,
+    ! 2 for exponential distribution,
+    ! 3 for power law distribution,
+    ! 4 for monodisperse distribution,
+    ! 5 for lognormal distribution.
+	!
+    ! PHASE - Set to 0 for liquid, 1 for ice.
+    ! DMIN  - The minimum drop size for this class (micron), ignored for monodisperse.
+    ! DMAX  - The maximum drop size for this class (micron), ignored for monodisperse.
+    ! Important note: The settings for DMIN and DMAX are
+    ! ignored in the current version for all distributions except for power
+    ! law. Except when the power law distribution is used, particle size
+    ! is fixed to vary from zero to infinity, a restriction that is expected
+    ! to be lifted in future versions. A placeholder must still be specified
+    ! for each.
+    ! Density of particles is given by apm*D^bpm or a fixed value rho. ONLY specify ONE of these two!!
+    ! APM - The alpha_m coefficient in equation (1) (kg m**-beta_m )
+    ! BPM - The beta_m coefficient in equation (1), see section 4.1.
+    ! RHO - Hydrometeor density (kg m-3 ).
+    ! 
+    ! P1, P2, P3 - are default distribution parameters that depend on the type
+    ! of distribution (see quickmbeam documentation for more information)
+    !
+    ! Modified Gamma (must set P3 and one of P1 or P2)
+    ! P1 - Set to the total particle number concentration Nt /rho_a (kg-1 ), where
+    ! rho_a is the density of air in the radar volume.
+    ! P2 - Set to the particle mean diameter D (micron).
+    ! P3 - Set to the distribution width nu.
+    !
+    ! Exponetial (set one of)
+    ! P1 - Set to a constant intercept parameter N0 (m-4).
+    ! P2 - Set to a constant lambda (micron-1).
+    !
+    ! Power Law
+    ! P1 - Set this to the value of a constant power law parameter br
+    !
+    ! Monodisperse
+    ! P1 - Set to a constant diameter D0 (micron) = Re.
+    !
+    ! Log-normal (must set P3 and one of P1 or P2)
+    ! P1 - Set to the total particle number concentration Nt /rho_a (kg-1 )
+    ! P2 - Set to the geometric mean particle radius rg (micron).
+    ! P3 - Set to the natural logarithm of the geometric standard deviation.
+    ! ####################################################################################
+    ! INPUTS
+    logical,intent(in) :: &
+       lsingle, & ! True -> use single moment
+       ldouble    ! True -> use two moment 
+                     
+    ! OUTPUTS
+    type(size_distribution),intent(out) ::&
+         sd              !
+
+   ! SINGLE MOMENT PARAMETERS
+   integer,parameter,dimension(N_HYDRO) :: &
+                    ! LSL  LSI  LSR  LSS  CVL  CVI  CVR  CVS  LSG    
+       HCLASS1_TYPE  = (/5,   1,   2,   2,   5,   1,   2,   2,   2/), & ! 
+       HCLASS1_PHASE = (/0,   1,   0,   1,   0,   1,   0,   1,   1/)    ! 
+   real(wp),parameter,dimension(N_HYDRO) ::&
+                      ! LSL   LSI    LSR    LSS    CVL   CVI    CVR    CVS    LSG    
+       HCLASS1_DMIN = (/ -1.,  -1.,   -1.,   -1.,   -1.,  -1.,   -1.,   -1.,   -1.  /),  &
+       HCLASS1_DMAX = (/ -1.,  -1.,   -1.,   -1.,   -1.,  -1.,   -1.,   -1.,   -1.  /),  &
+       HCLASS1_APM  = (/524., 110.8, 524.,   -1.,  524., 110.8, 524.,   -1.,   -1.  /),  &
+       HCLASS1_BPM  = (/  3.,   2.91,  3.,   -1.,    3.,   2.91,  3.,   -1.,   -1.  /),  &
+       HCLASS1_RHO  = (/ -1.,  -1.,   -1.,  100.,   -1.,  -1.,   -1.,  100.,  400.  /),  &
+       HCLASS1_P1   = (/ -1.,  -1.,    8.e6,  3.e6, -1.,  -1.,    8.e6,  3.e6,  4.e6/),  & 
+       HCLASS1_P2   = (/  6.,  40.,   -1.,   -1.,    6.,  40.,   -1.,   -1.,   -1.   /), & 
+       HCLASS1_P3   = (/  0.3,  2.,   -1.,   -1.,    0.3,  2.,   -1.,   -1.,   -1.   /)
+
+    ! TWO MOMENT PARAMETERS
+    integer,parameter,dimension(N_HYDRO) :: &
+                      ! LSL  LSI  LSR  LSS  CVL  CVI  CVR  CVS  LSG
+       HCLASS2_TYPE  = (/ 1,   1,   1,   1,   1,   1,   1,   1,   1/), &
+       HCLASS2_PHASE = (/ 0,   1,   0,   1,   0,   1,   0,   1,   1/)
+
+    real(wp),parameter,dimension(N_HYDRO) :: &
+                      ! LSL    LSI      LSR     LSS   CVL    CVI   CVR     CVS    LSG
+       HCLASS2_DMIN = (/ -1,     -1,     -1,     -1,    -1,    -1,   -1,     -1,   -1/), &
+       HCLASS2_DMAX = (/ -1,     -1,     -1,     -1,    -1,    -1,   -1,     -1,   -1/), &        
+       HCLASS2_APM  = (/524,     -1,    524,     -1,   524,    -1,  524,     -1,   -1/), &
+       HCLASS2_BPM  = (/  3,     -1,      3,     -1,     3,    -1,    3,     -1,   -1/), &
+       HCLASS2_RHO  = (/ -1,    500,     -1,    100,    -1,   500,   -1,    100,  900/), &
+       HCLASS2_P1   = (/ -1,     -1,     -1,     -1,    -1,    -1,   -1,     -1,   -1/), &
+       HCLASS2_P2   = (/ -1,     -1,     -1,     -1,    -1,    -1,   -1,     -1,   -1/), &
+       HCLASS2_P3   = (/ -2,      1,      1,      1,    -2,     1,    1,      1,    1/) 
+    
+    if (lsingle) then    
+       sd%dtype(1:N_HYDRO) = HCLASS1_TYPE(1:N_HYDRO)
+       sd%phase(1:N_HYDRO) = HCLASS1_PHASE(1:N_HYDRO)
+       sd%dmin(1:N_HYDRO)  = HCLASS1_DMIN(1:N_HYDRO)
+       sd%dmax(1:N_HYDRO)  = HCLASS1_DMAX(1:N_HYDRO)
+       sd%apm(1:N_HYDRO)   = HCLASS1_APM(1:N_HYDRO)
+       sd%bpm(1:N_HYDRO)   = HCLASS1_BPM(1:N_HYDRO)
+       sd%rho(1:N_HYDRO)   = HCLASS1_RHO(1:N_HYDRO)
+       sd%p1(1:N_HYDRO)    = HCLASS1_P1(1:N_HYDRO)
+       sd%p2(1:N_HYDRO)    = HCLASS1_P2(1:N_HYDRO)
+       sd%p3(1:N_HYDRO)    = HCLASS1_P3(1:N_HYDRO)
+    endif
+    if (ldouble) then    
+       sd%dtype(1:N_HYDRO) = HCLASS2_TYPE(1:N_HYDRO)
+       sd%phase(1:N_HYDRO) = HCLASS2_PHASE(1:N_HYDRO)
+       sd%dmin(1:N_HYDRO)  = HCLASS2_DMIN(1:N_HYDRO)
+       sd%dmax(1:N_HYDRO)  = HCLASS2_DMAX(1:N_HYDRO)
+       sd%apm(1:N_HYDRO)   = HCLASS2_APM(1:N_HYDRO)
+       sd%bpm(1:N_HYDRO)   = HCLASS2_BPM(1:N_HYDRO)
+       sd%rho(1:N_HYDRO)   = HCLASS2_RHO(1:N_HYDRO)
+       sd%p1(1:N_HYDRO)    = HCLASS2_P1(1:N_HYDRO)
+       sd%p2(1:N_HYDRO)    = HCLASS2_P2(1:N_HYDRO)
+       sd%p3(1:N_HYDRO)    = HCLASS2_P3(1:N_HYDRO)
+    endif    
+  end subroutine hydro_class_init    
+end module mod_quickbeam_optics
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/scops.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/scops.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cospv2/scops.F90	(revision 3605)
@@ -0,0 +1,240 @@
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+! Copyright (c) 2009, British Crown Copyright, the Met Office
+! All rights reserved.
+!
+! Redistribution and use in source and binary forms, with or without modification, are 
+! permitted provided that the following conditions are met:
+!
+! 1. Redistributions of source code must retain the above copyright notice, this list of 
+!    conditions and the following disclaimer.
+!
+! 2. Redistributions in binary form must reproduce the above copyright notice, this list
+!    of conditions and the following disclaimer in the documentation and/or other 
+!    materials provided with the distribution.
+!
+! 3. Neither the name of the copyright holder nor the names of its contributors may be 
+!    used to endorse or promote products derived from this software without specific prior
+!    written permission.
+!
+! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+! EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+! MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+! THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+! SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
+! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+!
+! History
+! May 2015 - D. Swales - Modified for COSPv2.0
+! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+module mod_scops
+  USE COSP_KINDS,     ONLY: wp
+  USE MOD_RNG!,        ONLY: rng_state,get_rng
+  use mod_cosp_error, ONLY: errorMessage
+
+  implicit none
+
+  integer,parameter :: default_overlap = 3 ! Used when invalid overlap assumption is provided.
+  
+contains
+  subroutine scops(npoints,nlev,ncol,rngs,cc,conv,overlap,frac_out,ncolprint)
+    INTEGER :: npoints,    &    ! Number of model points in the horizontal
+               nlev,       &    ! Number of model levels in column
+               ncol,       &    ! Number of subcolumns
+               overlap          ! Overlap type (1=max, 2=rand, 3=max/rand)
+    type(rng_state),dimension(npoints) :: rngs            
+    INTEGER, parameter :: huge32 = 2147483647
+    INTEGER, parameter :: i2_16  = 65536
+    INTEGER :: i,j,ilev,ibox,ncolprint,ilev2
+
+    REAL(WP), dimension(npoints,nlev) ::  &
+         cc,         &    ! Input cloud cover in each model level (fraction)
+                          ! NOTE:  This is the HORIZONTAL area of each
+                          !        grid box covered by clouds
+         conv,       &    ! Input convective cloud cover in each model level (fraction)
+                          ! NOTE:  This is the HORIZONTAL area of each
+                          !        grid box covered by convective clouds
+         tca              ! Total cloud cover in each model level (fraction)
+                          ! with extra layer of zeroes on top
+                          ! in this version this just contains the values input
+                          ! from cc but with an extra level
+    REAL(WP),intent(inout), dimension(npoints,ncol,nlev) :: &
+         frac_out         ! Boxes gridbox divided up into equivalent of BOX in 
+                          ! original version, but indexed by column then row, rather than
+                          ! by row then column
+    REAL(WP), dimension(npoints,ncol) :: &
+         threshold,   &   ! pointer to position in gridbox
+         maxocc,      &   ! Flag for max overlapped conv cld
+         maxosc,      &   ! Flag for max overlapped strat cld
+         boxpos,      &   ! ordered pointer to position in gridbox
+         threshold_min    ! minimum value to define range in with new threshold is chosen.
+    REAL(WP), dimension(npoints) :: &
+         ran              ! vector of random numbers
+
+    ! Test for valid input overlap assumption
+    if (overlap .ne. 1 .and. overlap .ne. 2 .and. overlap .ne. 3) then
+       overlap=default_overlap
+       call errorMessage('ERROR(scops): Invalid overlap assumption provided. Using default overlap assumption (max/ran)')
+    endif
+
+    boxpos = spread(([(i, i=1,ncol)]-0.5)/ncol,1,npoints)
+    
+    ! #######################################################################
+    ! Initialize working variables
+    ! #######################################################################
+    
+    ! Initialize frac_out to zero
+    frac_out(1:npoints,1:ncol,1:nlev)=0.0     
+    
+    ! Assign 2d tca array using 1d input array cc
+    tca(1:npoints,1:nlev) = cc(1:npoints,1:nlev)
+    
+    if (ncolprint.ne.0) then
+       write (6,'(a)') 'frac_out_pp_rev:'
+       do j=1,npoints,1000
+          write(6,'(a10)') 'j='
+          write(6,'(8I10)') j
+          write (6,'(8f5.2)') ((frac_out(j,ibox,ilev),ibox=1,ncolprint),ilev=1,nlev)
+       enddo
+       write (6,'(a)') 'ncol:'
+       write (6,'(I3)') ncol
+    endif
+    if (ncolprint.ne.0) then
+       write (6,'(a)') 'last_frac_pp:'
+       do j=1,npoints,1000
+          write(6,'(a10)') 'j='
+          write(6,'(8I10)') j
+          write (6,'(8f5.2)') (tca(j,1))
+       enddo
+    endif
+    
+    ! #######################################################################
+    ! ALLOCATE CLOUD INTO BOXES, FOR NCOLUMNS, NLEVELS
+    ! frac_out is the array that contains the information 
+    ! where 0 is no cloud, 1 is a stratiform cloud and 2 is a
+    ! convective cloud
+    ! #######################################################################
+    
+    ! Loop over vertical levels
+    DO ilev = 1,nlev
+       
+       ! Initialise threshold
+       IF (ilev.eq.1) then
+          ! If max overlap 
+          IF (overlap.eq.1) then
+             ! Select pixels spread evenly across the gridbox
+             threshold(1:npoints,1:ncol)=boxpos(1:npoints,1:ncol)
+          ELSE
+             DO ibox=1,ncol
+                !include 'congvec.f90'
+                ran(1:npoints) = get_rng(RNGS)
+                ! select random pixels from the non-convective
+                ! part the gridbox ( some will be converted into
+                ! convective pixels below )
+                threshold(1:npoints,ibox) = conv(1:npoints,ilev)+(1-conv(1:npoints,ilev))*ran(npoints)
+             enddo
+          ENDIF
+          IF (ncolprint.ne.0) then
+             write (6,'(a)') 'threshold_nsf2:'
+             do j=1,npoints,1000
+                write(6,'(a10)') 'j='
+                write(6,'(8I10)') j
+                write (6,'(8f5.2)') (threshold(j,ibox),ibox=1,ncolprint)
+             enddo
+          ENDIF
+       ENDIF
+       
+       IF (ncolprint.ne.0) then
+          write (6,'(a)') 'ilev:'
+          write (6,'(I2)') ilev
+       ENDIF
+       
+       DO ibox=1,ncol
+          ! All versions
+          !maxocc(1:npoints,ibox) = merge(1,0,boxpos(1:npoints,ibox) .le. conv(1:npoints,ilev))
+          !maxocc(1:npoints,ibox) = merge(1,0, conv(1:npoints,ilev) .gt. boxpos(1:npoints,ibox))
+          do j=1,npoints
+             if (boxpos(j,ibox).le.conv(j,ilev)) then
+                maxocc(j,ibox) = 1
+             else
+                maxocc(j,ibox) = 0
+             end if
+          enddo
+          
+          ! Max overlap
+          if (overlap.eq.1) then 
+             threshold_min(1:npoints,ibox) = conv(1:npoints,ilev)
+             maxosc(1:npoints,ibox)        = 1               
+          endif
+          
+          ! Random overlap
+          if (overlap.eq.2) then 
+             threshold_min(1:npoints,ibox) = conv(1:npoints,ilev)
+             maxosc(1:npoints,ibox)        = 0
+          endif
+          ! Max/Random overlap
+          if (overlap.eq.3) then 
+             ! DS2014 START: The bounds on tca are not valid when ilev=1.
+             !threshold_min(1:npoints,ibox) = max(conv(1:npoints,ilev),min(tca(1:npoints,ilev-1),tca(1:npoints,ilev)))
+             !maxosc(1:npoints,ibox) = merge(1,0,threshold(1:npoints,ibox) .lt. &
+             !     min(tca(1:npoints,ilev-1),tca(1:npoints,ilev)) .and. &
+             !     (threshold(1:npoints,ibox).gt.conv(1:npoints,ilev)))
+             if (ilev .ne. 1) then
+                threshold_min(1:npoints,ibox) = max(conv(1:npoints,ilev),min(tca(1:npoints,ilev-1),tca(1:npoints,ilev)))
+                maxosc(1:npoints,ibox) = merge(1,0,threshold(1:npoints,ibox) .lt. &
+                     min(tca(1:npoints,ilev-1),tca(1:npoints,ilev)) .and. &
+                     (threshold(1:npoints,ibox).gt.conv(1:npoints,ilev)))
+             else
+                threshold_min(1:npoints,ibox) = max(conv(1:npoints,ilev),min(0._wp,tca(1:npoints,ilev)))
+                maxosc(1:npoints,ibox) = merge(1,0,threshold(1:npoints,ibox) .lt. &
+                     min(0._wp,tca(1:npoints,ilev)) .and. &
+                     (threshold(1:npoints,ibox).gt.conv(1:npoints,ilev)))
+             endif
+          endif
+          
+          ! Reset threshold 
+          !include 'congvec.f90'
+          ran(1:npoints) = get_rng(RNGS)
+          
+          threshold(1:npoints,ibox)= maxocc(1:npoints,ibox)*(boxpos(1:npoints,ibox)) +            &
+               (1-maxocc(1:npoints,ibox))*((maxosc(1:npoints,ibox))*(threshold(1:npoints,ibox)) + &
+               (1-maxosc(1:npoints,ibox))*(threshold_min(1:npoints,ibox)+                         &
+               (1-threshold_min(1:npoints,ibox))*ran(1:npoints)))
+          
+          ! Fill frac_out with 1's where tca is greater than the threshold
+          frac_out(1:npoints,ibox,ilev) = merge(1,0,tca(1:npoints,ilev).gt.threshold(1:npoints,ibox))
+          
+          ! Code to partition boxes into startiform and convective parts goes here
+          where(threshold(1:npoints,ibox).le.conv(1:npoints,ilev) .and. conv(1:npoints,ilev).gt.0.) frac_out(1:npoints,ibox,ilev)=2
+       ENDDO ! ibox
+       
+       
+       ! Set last_frac to tca at this level, so as to be tca from last level next time round
+       if (ncolprint.ne.0) then
+          do j=1,npoints ,1000
+             write(6,'(a10)') 'j='
+             write(6,'(8I10)') j
+             write (6,'(a)') 'last_frac:'
+             write (6,'(8f5.2)') (tca(j,ilev))
+             write (6,'(a)') 'conv:'
+             write (6,'(8f5.2)') (conv(j,ilev),ibox=1,ncolprint)
+             write (6,'(a)') 'max_overlap_cc:'
+             write (6,'(8f5.2)') (maxocc(j,ibox),ibox=1,ncolprint)
+             write (6,'(a)') 'max_overlap_sc:'
+             write (6,'(8f5.2)') (maxosc(j,ibox),ibox=1,ncolprint)
+             write (6,'(a)') 'threshold_min_nsf2:'
+             write (6,'(8f5.2)') (threshold_min(j,ibox),ibox=1,ncolprint)
+             write (6,'(a)') 'threshold_nsf2:'
+             write (6,'(8f5.2)') (threshold(j,ibox),ibox=1,ncolprint)
+             write (6,'(a)') 'frac_out_pp_rev:'
+             write (6,'(8f5.2)') ((frac_out(j,ibox,ilev2),ibox=1,ncolprint),ilev2=1,nlev)
+          enddo
+       endif
+       
+    enddo ! Loop over nlev
+    
+    ! END
+  end subroutine scops
+end module mod_scops
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cpl_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cpl_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cpl_mod.F90	(revision 3605)
@@ -97,4 +97,16 @@
   !$OMP THREADPRIVATE(cpl_atm_co22D)
 
+!!!!!!!!!! variable for calving
+  INTEGER, PARAMETER :: nb_zone_calving = 3
+  REAL,ALLOCATABLE, DIMENSION(:,:,:),SAVE :: area_calving 
+  !$OMP THREADPRIVATE(area_calving)
+  REAL,ALLOCATABLE, DIMENSION(:,:),SAVE :: cell_area2D 
+  !$OMP THREADPRIVATE(cell_area2D)
+  INTEGER, SAVE :: ind_calving(nb_zone_calving) 
+  !$OMP THREADPRIVATE(ind_calving)
+
+  LOGICAL,SAVE :: cpl_old_calving
+  !$OMP THREADPRIVATE(cpl_old_calving)
+  
 CONTAINS
 !
@@ -105,7 +117,9 @@
     USE surface_data
     USE indice_sol_mod
-    USE mod_grid_phy_lmdz, ONLY : nbp_lon, nbp_lat
+    USE mod_grid_phy_lmdz, ONLY : nbp_lon, nbp_lat, grid1dTo2d_glo, klon_glo, grid_type, unstructured, regular_lonlat
     USE time_phylmdz_mod, ONLY: annee_ref, day_ini, itau_phy, itaufin_phy
     USE print_control_mod, ONLY: lunout
+    USE geometry_mod, ONLY : longitude_deg, latitude_deg, ind_cell_glo, cell_area
+    USE ioipsl_getin_p_mod, ONLY: getin_p
 
 ! Input arguments
@@ -127,4 +141,17 @@
     CHARACTER(len = 80)               :: abort_message
     CHARACTER(len=80)                 :: clintocplnam, clfromcplnam
+    REAL, DIMENSION(klon_mpi)         :: rlon_mpi, rlat_mpi, cell_area_mpi
+    INTEGER, DIMENSION(klon_mpi)           :: ind_cell_glo_mpi
+    REAL, DIMENSION(nbp_lon,jj_nb)         :: lon2D, lat2D
+    INTEGER :: mask_calving(nbp_lon,jj_nb,nb_zone_calving)
+    REAL :: pos
+
+!***************************************
+! Use old calving or not (default new calving method)
+! New calving method should be used with DYNAMICO and when using new coupling
+! weights.
+    cpl_old_calving=.FALSE.
+    CALL getin_p("cpl_old_calving",cpl_old_calving)
+
 
 !*************************************************************************************
@@ -204,8 +231,52 @@
 
 ! Allocate variable in carbon_cycle_mod
-       ALLOCATE(fco2_ocn_day(klon), stat = error)
+       IF (.NOT.ALLOCATED(fco2_ocn_day)) ALLOCATE(fco2_ocn_day(klon), stat = error)
        sum_error = sum_error + error
-    END IF
-
+    ENDIF
+
+! calving initialization
+    ALLOCATE(area_calving(nbp_lon, jj_nb, nb_zone_calving), stat = error)
+    sum_error = sum_error + error
+    ALLOCATE(cell_area2D(nbp_lon, jj_nb), stat = error)    
+    sum_error = sum_error + error
+
+
+    CALL gather_omp(longitude_deg,rlon_mpi)
+    CALL gather_omp(latitude_deg,rlat_mpi)
+    CALL gather_omp(ind_cell_glo,ind_cell_glo_mpi)
+    CALL gather_omp(cell_area,cell_area_mpi)
+      
+    IF (is_omp_master) THEN
+      CALL Grid1DTo2D_mpi(rlon_mpi,lon2D)
+      CALL Grid1DTo2D_mpi(rlat_mpi,lat2D)
+      CALL Grid1DTo2D_mpi(cell_area_mpi,cell_area2D)
+      mask_calving(:,:,:) = 0 
+      WHERE ( lat2D >= 40) mask_calving(:,:,1) = 1
+      WHERE ( lat2D < 40 .AND. lat2D > -50) mask_calving(:,:,2) = 1
+      WHERE ( lat2D <= -50) mask_calving(:,:,3) = 1
+    
+    
+      DO i=1,nb_zone_calving
+        area_calving(:,:,i)=mask_calving(:,:,i)*cell_area2D(:,:)
+        pos=1
+        IF (i>1) pos = 1 + ((nbp_lon*nbp_lat-1)*(i-1))/(nb_zone_calving-1)
+      
+        ind_calving(i)=0
+        IF (grid_type==unstructured) THEN
+
+          DO ig=1,klon_mpi
+            IF (ind_cell_glo_mpi(ig)==pos) ind_calving(i)=ig
+          ENDDO
+
+        ELSE IF (grid_type==regular_lonlat) THEN
+          IF ((ij_begin<=pos .AND. ij_end>=pos) .OR. (ij_begin<=pos .AND. is_south_pole_dyn )) THEN
+            ind_calving(i)=pos-(jj_begin-1)*nbp_lon
+          ENDIF
+        ENDIF
+     
+      ENDDO
+    ENDIF
+    
+           
     IF (sum_error /= 0) THEN
        abort_message='Pb allocation variables couplees'
@@ -236,10 +307,10 @@
        idayref = day_ini
        CALL ymds2ju(annee_ref, 1, idayref, 0.0, zjulian)
-       CALL gr_fi_ecrit(1,klon,nbp_lon,nbp_lat,rlon,zx_lon)
+       CALL grid1dTo2d_glo(rlon,zx_lon)
        DO i = 1, nbp_lon
           zx_lon(i,1) = rlon(i+1)
           zx_lon(i,nbp_lat) = rlon(i+1)
        ENDDO
-       CALL gr_fi_ecrit(1,klon,nbp_lon,nbp_lat,rlat,zx_lat)
+       CALL grid1dTo2d_glo(rlat,zx_lat)
        clintocplnam="cpl_atm_tauflx"
        CALL histbeg(clintocplnam,nbp_lon,zx_lon(:,1),nbp_lat,zx_lat(1,:),&
@@ -259,5 +330,5 @@
                 "-",nbp_lon,nbp_lat,nhoridct,1,1,1,-99,32,"inst",dtime,dtime)
          ENDIF
-       END DO
+       ENDDO
        CALL histend(nidct)
        CALL histsync(nidct)
@@ -272,5 +343,5 @@
                 "-",nbp_lon,nbp_lat,nhoridcs,1,1,1,-99,32,"inst",dtime,dtime)
          ENDIF
-       END DO
+       ENDDO
        CALL histend(nidcs)
        CALL histsync(nidcs)
@@ -286,5 +357,5 @@
        abort_message='carbon_cycle_cpl does not work with opa8'
        CALL abort_physic(modname,abort_message,1)
-    END IF
+    ENDIF
 
   END SUBROUTINE cpl_init
@@ -356,5 +427,5 @@
                 CALL histwrite(nidcs,inforecv(i)%name,itau_w,tab_read_flds(:,:,i),nbp_lon*(nbp_lat),ndexcs)
             ENDIF
-          END DO
+          ENDDO
        ENDIF
 
@@ -415,5 +486,5 @@
        ENDDO
 
-    END IF ! if time to receive
+    ENDIF ! if time to receive
 
   END SUBROUTINE cpl_receive_frac
@@ -466,7 +537,7 @@
        DO i=1,klon
           index(i)=i
-       END DO
+       ENDDO
        CALL cpl2gath(read_co2, fco2_ocn_day, klon, index)
-    END IF
+    ENDIF
 
 !*************************************************************************************
@@ -477,5 +548,5 @@
     DO i=1, knon
        tsurf_new(i) = tsurf_new(i)/(1. - sic_new(i))
-    END DO
+    ENDDO
 
   END SUBROUTINE cpl_receive_ocean_fields
@@ -529,5 +600,5 @@
        tsurf_new(i) = tsurf_new(i) / sic_new(i)
        alb_new(i)   = alb_new(i)   / sic_new(i)
-    END DO
+    ENDDO
 
   END SUBROUTINE cpl_receive_seaice_fields
@@ -637,5 +708,6 @@
           cpl_atm_co2(ig,cpl_index) = cpl_atm_co2(ig,cpl_index) + &
                co2_send(knindex(ig))/ REAL(nexca) 
-       END IF
+!!---OB: this is correct but why knindex ??
+       ENDIF
      ENDDO
 
@@ -682,5 +754,5 @@
              ALLOCATE(cpl_atm_co22D(nbp_lon,jj_nb), stat=error)
              sum_error = sum_error + error
-          END IF
+          ENDIF
 
           IF (sum_error /= 0) THEN
@@ -886,5 +958,5 @@
              ALLOCATE(cpl_atm_co22D(nbp_lon,jj_nb), stat=error)
              sum_error = sum_error + error
-          END IF
+          ENDIF
 
           IF (sum_error /= 0) THEN
@@ -917,5 +989,5 @@
        DO ig = 1, knon
           cpl_fder_tmp(knindex(ig))=cpl_fder(ig,cpl_index)
-       END DO
+       ENDDO
        CALL gath2cpl(cpl_fder_tmp(:), cpl_fder2D(:,:,cpl_index), &
             klon, unity)
@@ -1085,5 +1157,5 @@
 ! Local variables
 !*************************************************************************************
-    INTEGER                                              :: error, sum_error, j
+    INTEGER                                              :: error, sum_error, i,j,k
     INTEGER                                              :: itau_w
     INTEGER                                              :: time_sec
@@ -1102,6 +1174,8 @@
 ! Table with all fields to send to coupler
     REAL, DIMENSION(nbp_lon, jj_nb, maxsend)                 :: tab_flds
-    REAL, DIMENSION(klon_mpi)                            :: rlon_mpi, rlat_mpi
-
+    REAL, DIMENSION(klon_mpi)                                :: rlon_mpi, rlat_mpi
+    REAL  :: calving(nb_zone_calving)
+    REAL  :: calving_glo(nb_zone_calving)
+    
 #ifdef CPP_MPI
     INCLUDE 'mpif.h'
@@ -1130,5 +1204,5 @@
     
     IF (version_ocean=='nemo') THEN
-       tab_flds(:,:,ids_liqrun) = cpl_rriv2D(:,:) + cpl_rcoa2D(:,:)
+       tab_flds(:,:,ids_liqrun) = (cpl_rriv2D(:,:) + cpl_rcoa2D(:,:))
        IF (carbon_cycle_cpl) tab_flds(:,:,ids_atmco2)=cpl_atm_co22D(:,:)
     ELSE IF (version_ocean=='opa8') THEN
@@ -1139,5 +1213,5 @@
        tab_flds(:,:,ids_runcoa) = cpl_rcoa2D(:,:)
        tab_flds(:,:,ids_rivflu) = cpl_rriv2D(:,:)
-    END IF
+    ENDIF
 
 !*************************************************************************************
@@ -1158,38 +1232,64 @@
     IF (is_omp_root) THEN
 
-      DO j = 1, jj_nb
-         tmp_calv(:,j) = DOT_PRODUCT (cpl_rlic2D(1:nbp_lon,j), &
-              pctsrf2D(1:nbp_lon,j,is_lic)) / REAL(nbp_lon)
-      ENDDO
-    
-    
-      IF (is_parallel) THEN
-         IF (.NOT. is_north_pole_dyn) THEN
+      IF (cpl_old_calving) THEN   ! use old calving
+
+        DO j = 1, jj_nb
+           tmp_calv(:,j) = DOT_PRODUCT (cpl_rlic2D(1:nbp_lon,j), &
+                pctsrf2D(1:nbp_lon,j,is_lic)) / REAL(nbp_lon)
+        ENDDO
+    
+    
+        IF (is_parallel) THEN
+           IF (.NOT. is_north_pole_dyn) THEN
 #ifdef CPP_MPI
-            CALL MPI_RECV(Up,1,MPI_REAL_LMDZ,mpi_rank-1,1234,COMM_LMDZ_PHY,status,error)
-            CALL MPI_SEND(tmp_calv(1,1),1,MPI_REAL_LMDZ,mpi_rank-1,1234,COMM_LMDZ_PHY,error)
+              CALL MPI_RECV(Up,1,MPI_REAL_LMDZ,mpi_rank-1,1234,COMM_LMDZ_PHY,status,error)
+              CALL MPI_SEND(tmp_calv(1,1),1,MPI_REAL_LMDZ,mpi_rank-1,1234,COMM_LMDZ_PHY,error)
 #endif
-         ENDIF
+           ENDIF
        
-         IF (.NOT. is_south_pole_dyn) THEN
+           IF (.NOT. is_south_pole_dyn) THEN
 #ifdef CPP_MPI
-            CALL MPI_SEND(tmp_calv(1,jj_nb),1,MPI_REAL_LMDZ,mpi_rank+1,1234,COMM_LMDZ_PHY,error)
-            CALL MPI_RECV(down,1,MPI_REAL_LMDZ,mpi_rank+1,1234,COMM_LMDZ_PHY,status,error)
+              CALL MPI_SEND(tmp_calv(1,jj_nb),1,MPI_REAL_LMDZ,mpi_rank+1,1234,COMM_LMDZ_PHY,error)
+              CALL MPI_RECV(down,1,MPI_REAL_LMDZ,mpi_rank+1,1234,COMM_LMDZ_PHY,status,error)
 #endif
-         ENDIF
+           ENDIF
          
-         IF (.NOT. is_north_pole_dyn .AND. ii_begin /=1) THEN
-            Up=Up+tmp_calv(nbp_lon,1)
-            tmp_calv(:,1)=Up
-         ENDIF
+           IF (.NOT. is_north_pole_dyn .AND. ii_begin /=1) THEN
+              Up=Up+tmp_calv(nbp_lon,1)
+              tmp_calv(:,1)=Up
+           ENDIF
+           
+           IF (.NOT. is_south_pole_dyn .AND. ii_end /= nbp_lon) THEN
+              Down=Down+tmp_calv(1,jj_nb)
+              tmp_calv(:,jj_nb)=Down
+           ENDIF
+        ENDIF
+        tab_flds(:,:,ids_calvin) = tmp_calv(:,:)
+
+      ELSE
+         ! cpl_old_calving=FALSE
+         ! To be used with new method for calculation of coupling weights
+         DO k=1,nb_zone_calving
+            calving(k)=0
+            DO j = 1, jj_nb
+               calving(k)= calving(k)+DOT_PRODUCT(cpl_rlic2D(:,j)*area_calving(:,j,k),pctsrf2D(:,j,is_lic))
+            ENDDO
+         ENDDO
          
-         IF (.NOT. is_south_pole_dyn .AND. ii_end /= nbp_lon) THEN
-            Down=Down+tmp_calv(1,jj_nb)
-            tmp_calv(:,jj_nb)=Down	 
-         ENDIF
+#ifdef CPP_MPI
+         CALL MPI_ALLREDUCE(calving, calving_glo, nb_zone_calving, MPI_REAL_LMDZ, MPI_SUM, COMM_LMDZ_PHY, error)
+#endif
+         
+         tab_flds(:,:,ids_calvin) = 0
+         DO k=1,nb_zone_calving
+            IF (ind_calving(k)>0 ) THEN
+               j=(ind_calving(k)-1)/nbp_lon + 1
+               i=MOD(ind_calving(k)-1,nbp_lon)+1
+               tab_flds(i,j,ids_calvin) = calving_glo(k)
+            ENDIF
+         ENDDO
+         
       ENDIF
       
-      tab_flds(:,:,ids_calvin) = tmp_calv(:,:)
-
 !*************************************************************************************
 ! Calculate total flux for snow, rain and wind with weighted addition using the 
@@ -1252,5 +1352,5 @@
                   cpl_tauy2D(:,:,2) * pctsrf2D(:,:,is_sic) / deno(:,:)
           ENDWHERE
-       END IF
+       ENDIF
 
     ENDIF ! is_omp_root
@@ -1336,5 +1436,5 @@
        DEALLOCATE(cpl_atm_co22D, stat=error )
        sum_error = sum_error + error
-    END IF
+    ENDIF
 
     IF (sum_error /= 0) THEN
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/create_etat0_limit_unstruct.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/create_etat0_limit_unstruct.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/create_etat0_limit_unstruct.F90	(revision 3605)
@@ -0,0 +1,121 @@
+MODULE etat0_limit_unstruct_mod
+
+  LOGICAL, SAVE  :: create_etat0_limit
+!$OMP THREADPRIVATE(create_etat0_limit) 
+
+
+
+
+CONTAINS
+  
+  SUBROUTINE init_etat0_limit_unstruct
+#ifdef CPP_XIOS
+  USE xios, ONLY: xios_set_axis_attr, xios_set_fieldgroup_attr, &
+                  xios_set_filegroup_attr, xios_set_file_attr
+  USE mod_phys_lmdz_para, ONLY: is_omp_master
+  USE mod_grid_phy_lmdz, ONLY: grid_type, unstructured
+  USE ioipsl, ONLY : ioget_year_len
+  USE ioipsl_getin_p_mod, ONLY: getin_p
+  USE time_phylmdz_mod, ONLY : annee_ref
+  USE create_etat0_unstruct_mod, ONLY: init_create_etat0_unstruct
+  IMPLICIT NONE
+  
+    INTEGER :: iflag_phys,i
+    INTEGER :: ndays
+    REAL,ALLOCATABLE :: value(:)
+    
+      IF (grid_type==unstructured) THEN
+        CALL getin_p("iflag_phys",iflag_phys)
+        
+        CALL getin_p('create_etat0_limit',create_etat0_limit)
+        
+        ndays=ioget_year_len(annee_ref)
+        ALLOCATE(value(ndays))
+        DO i=1,ndays
+          value(i)=i-1
+        ENDDO
+        
+        IF (is_omp_master) CALL xios_set_axis_attr("time_year",n_glo=ndays,value=value) 
+        
+        IF (create_etat0_limit) THEN
+          IF (iflag_phys<100) THEN
+            IF (is_omp_master) CALL xios_set_fieldgroup_attr("etat0_limit_read",read_access=.TRUE.,enabled=.TRUE.)
+            IF (is_omp_master) CALL xios_set_filegroup_attr("etat0_limit_read",enabled=.TRUE.)
+          ENDIF
+          IF (is_omp_master) CALL xios_set_file_attr("limit_write",enabled=.TRUE.)
+          CALL init_create_etat0_unstruct
+        ENDIF
+      
+      ENDIF  
+
+#endif
+  END SUBROUTINE init_etat0_limit_unstruct
+  
+  SUBROUTINE create_etat0_limit_unstruct
+#ifdef CPP_XIOS
+  USE mod_grid_phy_lmdz, ONLY: grid_type, unstructured
+  USE create_etat0_unstruct_mod, ONLY: create_etat0_unstruct
+  USE create_limit_unstruct_mod, ONLY: create_limit_unstruct
+  USE phyaqua_mod, ONLY: iniaqua
+  USE phys_cal_mod, only: year_len
+  USE mod_phys_lmdz_para, ONLY: is_omp_master
+  USE ioipsl_getin_p_mod, ONLY: getin_p
+  USE dimphy, ONLY: klon
+  USE xios, ONLY: xios_context_finalize, xios_set_current_context, &
+                  xios_finalize
+  USE print_control_mod, ONLY: lunout
+  IMPLICIT NONE
+      INTEGER :: iflag_phys
+      INTEGER :: ierr
+      CHARACTER (LEN=20) :: modname='create_etat0_limit_unstruct'
+      CHARACTER (LEN=80) :: abort_message
+     
+      IF (grid_type==unstructured) THEN
+  
+        CALL getin_p("iflag_phys",iflag_phys)
+
+        IF (iflag_phys<100) THEN
+          IF ( create_etat0_limit) THEN
+              CALL create_etat0_unstruct
+              CALL create_limit_unstruct
+              IF (is_omp_master)  THEN
+                CALL xios_context_finalize()
+                CALL xios_set_current_context("icosagcm")   ! very bad, need to find an other solution
+                CALL xios_context_finalize()
+                CALL xios_finalize()
+#ifdef CPP_MPI    
+                CALL MPI_Finalize(ierr)
+#endif
+                abort_message='create_etat0_limit_unstruct, Initial state file are created, all is fine' 
+                CALL abort_physic(modname,abort_message,0)
+                STOP 0
+              ENDIF
+!$OMP BARRIER
+              abort_message='create_etat0_limit_unstruct, Initial state file are created, all is fine'
+              CALL abort_physic(modname,abort_message,0)
+          ENDIF 
+        ELSE
+          IF (create_etat0_limit) THEN 
+            CALL iniaqua(klon,year_len,iflag_phys)
+              IF (is_omp_master)  THEN
+                CALL xios_context_finalize()
+                CALL xios_set_current_context("icosagcm")   ! very bad, need to find an other solution
+                CALL xios_context_finalize()
+                CALL xios_finalize()
+#ifdef CPP_MPI
+                CALL MPI_Finalize(ierr)
+#endif
+              ENDIF
+!$OMP BARRIER
+              abort_message='create_etat0_limit_unstruct, Initial state file are created, all is fine' 
+              CALL abort_physic(modname,abort_message,0)
+              STOP 0
+          ENDIF
+        ENDIF
+      ENDIF
+        
+#endif
+  END SUBROUTINE create_etat0_limit_unstruct
+  
+END MODULE etat0_limit_unstruct_mod
+
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/create_etat0_unstruct.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/create_etat0_unstruct.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/create_etat0_unstruct.F90	(revision 3605)
@@ -0,0 +1,261 @@
+MODULE create_etat0_unstruct_mod
+
+
+
+
+
+
+CONTAINS
+  
+  SUBROUTINE init_create_etat0_unstruct
+#ifdef CPP_XIOS
+  USE xios
+  USE netcdf
+  USE mod_phys_lmdz_para
+  IMPLICIT NONE
+  INTEGER :: file_id, iret
+  
+   ! for coupling activate ocean fraction reading from file "ocean_fraction.nc"
+    IF (is_omp_master) THEN
+
+      IF (NF90_OPEN("ocean_fraction.nc", NF90_NOWRITE, file_id)==NF90_NOERR) THEN
+        CALL xios_set_file_attr("frac_ocean",enabled=.TRUE.)
+        CALL xios_set_field_attr("mask",field_ref="frac_ocean_read")
+        iret=NF90_CLOSE(file_id)
+      ELSE IF (NF90_OPEN("land_water_0.05.nc", NF90_NOWRITE, file_id)==NF90_NOERR) THEN
+        CALL xios_set_file_attr("land_water",name="land_water_0.05",enabled=.TRUE.)
+        CALL xios_set_field_attr("mask",field_ref="land_water")
+        iret=NF90_CLOSE(file_id)
+      ELSE IF (NF90_OPEN("land_water_0.25.nc", NF90_NOWRITE, file_id)==NF90_NOERR) THEN
+        CALL xios_set_file_attr("land_water",name="land_water_0.25",enabled=.TRUE.)
+        CALL xios_set_field_attr("mask",field_ref="land_water")
+        iret=NF90_CLOSE(file_id)
+      ELSE IF (NF90_OPEN("land_water_0.50.nc", NF90_NOWRITE, file_id)==NF90_NOERR) THEN
+        CALL xios_set_file_attr("land_water",name="land_water_0.50",enabled=.TRUE.)
+        CALL xios_set_field_attr("mask",field_ref="land_water")
+        iret=NF90_CLOSE(file_id)
+      ENDIF
+
+    ENDIF
+
+#endif
+  
+  END SUBROUTINE init_create_etat0_unstruct
+  
+ 
+  SUBROUTINE create_etat0_unstruct
+  USE dimphy
+#ifdef CPP_XIOS
+  USE xios
+  USE infotrac_phy
+  USE fonte_neige_mod
+  USE pbl_surface_mod
+  USE phys_state_var_mod
+  USE indice_sol_mod
+  USE mod_phys_lmdz_para
+  USE print_control_mod, ONLY: lunout
+  USE geometry_mod
+  USE ioipsl_getin_p_mod, ONLY: getin_p
+
+  IMPLICIT NONE
+  INCLUDE 'dimsoil.h'
+
+    LOGICAL :: no_ter_antartique   ! If true, no land points are allowed at Antartic
+    REAL,    DIMENSION(klon)                 :: tsol
+    REAL,    DIMENSION(klon)                 :: sn
+    REAL,    DIMENSION(klon)                 :: rugmer
+    REAL,    DIMENSION(klon)                 :: run_off_lic_0
+    REAL,    DIMENSION(klon)                 :: lic
+    REAL,    DIMENSION(klon)                 :: fder
+
+    REAL,    DIMENSION(klon,nbsrf)           :: qsolsrf, snsrf
+    REAL,    DIMENSION(klon,nsoilmx,nbsrf)   :: tsoil
+    
+    REAL,    DIMENSION(klon_mpi)             :: tsol_mpi, qsol_mpi, zmasq_mpi, lic_mpi
+    REAL,    DIMENSION(klon_mpi)             :: zmea_mpi, zstd_mpi, zsig_mpi, zgam_mpi, zthe_mpi
+    REAL,    DIMENSION(klon_mpi)             :: cell_area_mpi
+    REAL,    DIMENSION(klon_mpi,nbsrf)       :: pctsrf_mpi
+
+    INTEGER :: ji,j,i
+ 
+    IF (is_omp_master) THEN
+      CALL xios_recv_field("ts",tsol_mpi)
+      CALL xios_recv_field("qs",qsol_mpi)
+      CALL xios_recv_field("mask",zmasq_mpi)
+      CALL xios_recv_field("landice",lic_mpi)
+      CALL xios_recv_field("zmea",zmea_mpi)
+      CALL xios_recv_field("zstd",zstd_mpi)
+      CALL xios_recv_field("zsig",zsig_mpi)
+      CALL xios_recv_field("zgam",zgam_mpi)
+      CALL xios_recv_field("zthe",zthe_mpi)
+    ENDIF
+    CALL scatter_omp(tsol_mpi,tsol)
+    CALL scatter_omp(qsol_mpi,qsol)
+    CALL scatter_omp(zmasq_mpi,zmasq)
+    CALL scatter_omp(lic_mpi,lic)
+    CALL scatter_omp(zmea_mpi,zmea)
+    CALL scatter_omp(zstd_mpi,zstd)
+    CALL scatter_omp(zsig_mpi,zsig)
+    CALL scatter_omp(zgam_mpi,zgam)
+    CALL scatter_omp(zthe_mpi,zthe)
+
+    radsol(:)   = 0.0
+    rugmer(:) = 0.001
+    sn(:)     = 0
+
+    WHERE(qsol(:)<0) qsol(:)=0 
+        
+    WHERE(   zmasq(:)<EPSFRA) zmasq(:)=0.
+    WHERE(1.-zmasq(:)<EPSFRA) zmasq(:)=1.
+
+    pctsrf(:,:) = 0
+    pctsrf(:,is_lic)=lic
+    WHERE(pctsrf(:,is_lic)<EPSFRA) pctsrf(:,is_lic)=0. 
+    WHERE(zmasq(:)<EPSFRA)         pctsrf(:,is_lic)=0.
+
+    pctsrf(:,is_ter)=zmasq(:)
+
+!--- Adequation with soil/sea mask
+    DO ji=1,klon
+      IF(zmasq(ji)>EPSFRA) THEN 
+        IF(pctsrf(ji,is_lic)>=zmasq(ji)) THEN
+          pctsrf(ji,is_lic)=zmasq(ji)
+          pctsrf(ji,is_ter)=0.
+        ELSE
+          pctsrf(ji,is_ter)=zmasq(ji)-pctsrf(ji,is_lic)
+          IF(pctsrf(ji,is_ter)<EPSFRA) THEN
+            pctsrf(ji,is_ter)=0.
+            pctsrf(ji,is_lic)=zmasq(ji)
+          END IF 
+        END IF 
+      END IF 
+    END DO 
+
+
+  !--- Option no_ter_antartique removes all land fractions souther than 60S.
+  !--- Land ice is set instead of the land fractions on these latitudes.
+  !--- The ocean and sea-ice fractions are not changed.
+  no_ter_antartique=.FALSE.
+  CALL getin_p('no_ter_antartique',no_ter_antartique)
+  WRITE(lunout,*)"no_ter_antartique=",no_ter_antartique
+  IF (no_ter_antartique) THEN
+     ! Remove all land fractions souther than 60S and set land-ice instead
+     WRITE(lunout,*) "Remove land fractions souther than 60deg south by increasing"
+     WRITE(lunout,*) "the continental ice fractions. No land can now be found at Antartic."
+     DO ji=1, klon
+        IF (latitude_deg(ji)<-60.0) THEN
+           pctsrf(ji,is_lic) = pctsrf(ji,is_lic) + pctsrf(ji,is_ter)
+           pctsrf(ji,is_ter) = 0
+        END IF
+     END DO
+  END IF
+    
+! sub-surface ocean and sea ice (sea ice set to zero for start)
+!*******************************************************************************
+    pctsrf(:,is_oce)=(1.-zmasq(:))
+    WHERE(pctsrf(:,is_oce)<EPSFRA) pctsrf(:,is_oce)=0.
+    
+    zval(:)=max(0.,zmea-2*zstd(:))
+    zpic(:)=zmea+2*zstd(:)
+    
+!! WARNING    DON'T FORGET FOR LATER
+!!ym  IF(couple) pctsrf(:,is_oce)=ocemask_fi(:)
+!! 
+    
+! Init: tsol, qsol, sn, evap, tsoil, rain_fall, snow_fall, solsw, sollw, frugs
+!*******************************************************************************
+    DO i=1,nbsrf
+     ftsol(:,i) = tsol
+    END DO
+  
+    DO i=1,nbsrf
+     snsrf(:,i) = sn
+    END DO
+!albedo SB >>>
+!ym error : the sub surface dimension is the third not second
+!    falb_dir(:,is_ter,:)=0.08; falb_dir(:,is_lic,:)=0.6
+!    falb_dir(:,is_oce,:)=0.5;  falb_dir(:,is_sic,:)=0.6
+    falb_dir(:,:,is_ter)=0.08; falb_dir(:,:,is_lic)=0.6
+    falb_dir(:,:,is_oce)=0.5;  falb_dir(:,:,is_sic)=0.6
+
+!ym falb_dif has been forgotten, initialize with defaukt value found in phyetat0 or 0 ?
+!ym probably the uninitialized value was 0 for standard (regular grid) case
+    falb_dif(:,:,:)=0
+
+!albedo SB <<<
+    fevap(:,:) = 0.
+    DO i=1,nbsrf
+     qsolsrf(:,i)=150.
+    END DO
+ 
+    DO i=1,nbsrf 
+      DO j=1,nsoilmx
+        tsoil(:,j,i) = tsol
+      END DO
+    END DO
+ 
+    rain_fall = 0.; snow_fall = 0.
+    solsw = 165.;   sollw = -53.
+!ym warning missing init for sollwdown => set to 0
+  sollwdown  = 0.
+    
+    
+    t_ancien = 273.15
+    u_ancien=0
+    v_ancien=0
+    q_ancien = 0.
+    agesno = 0.
+
+    z0m(:,is_oce) = rugmer(:)
+
+   z0m(:,is_ter) = MAX(1.0e-05,zstd(:)*zsig(:)/2.0)
+   z0m(:,is_lic) = MAX(1.0e-05,zstd(:)*zsig(:)/2.0)
+
+   z0m(:,is_sic) = 0.001
+   z0h(:,:)=z0m(:,:)
+
+    fder = 0.0
+    clwcon = 0.0
+    rnebcon = 0.0
+    ratqs = 0.0
+    run_off_lic_0 = 0.0 
+    rugoro = 0.0
+
+! Before phyredem calling, surface modules and values to be saved in startphy.nc
+! are initialized
+!*******************************************************************************
+    pbl_tke(:,:,:) = 1.e-8 
+    zmax0(:) = 40.
+    f0(:) = 1.e-5
+    sig1(:,:) = 0.
+    w01(:,:) = 0.
+    wake_deltat(:,:) = 0.
+    wake_deltaq(:,:) = 0.
+    wake_s(:) = 0.
+    wake_cstar(:) = 0.
+    wake_fip(:) = 0.
+    wake_pe = 0.
+    fm_therm = 0.
+    entr_therm = 0.
+    detr_therm = 0.
+    ale_bl = 0.
+    ale_bl_trig =0. 
+    alp_bl =0.
+    CALL fonte_neige_init(run_off_lic_0)
+    CALL pbl_surface_init( fder, snsrf, qsolsrf, tsoil )
+
+    CALL gather_omp(cell_area,cell_area_mpi)
+    CALL gather_omp(pctsrf,pctsrf_mpi)
+    IF (is_omp_master) THEN
+      CALL xios_send_field("area_ce0l",cell_area_mpi)
+      CALL xios_send_field("fract_oce_ce0l",pctsrf_mpi(:,is_oce))
+      CALL xios_send_field("fract_sic_ce0l",pctsrf_mpi(:,is_sic))
+    ENDIF
+    
+    CALL phyredem( "startphy.nc" )
+
+#endif
+  END SUBROUTINE create_etat0_unstruct
+
+
+END MODULE create_etat0_unstruct_mod
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/create_limit_unstruct.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/create_limit_unstruct.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/create_limit_unstruct.F90	(revision 3605)
@@ -0,0 +1,319 @@
+MODULE create_limit_unstruct_mod
+    PRIVATE
+    INTEGER, PARAMETER                             :: lmdep=12
+
+    PUBLIC create_limit_unstruct
+
+CONTAINS
+
+
+  SUBROUTINE create_limit_unstruct
+  USE dimphy
+#ifdef CPP_XIOS
+  USE xios
+  USE ioipsl,             ONLY : ioget_year_len
+  USE time_phylmdz_mod, ONLY : annee_ref
+  USE indice_sol_mod
+  USE phys_state_var_mod
+  USE mod_phys_lmdz_para
+  IMPLICIT NONE
+    INCLUDE "iniprint.h"
+    REAL,    DIMENSION(:,:),ALLOCATABLE            :: sic
+    REAL,    DIMENSION(:,:),ALLOCATABLE            :: sst
+    REAL,    DIMENSION(klon,lmdep)                 :: rugos
+    REAL,    DIMENSION(klon,lmdep)                 :: albedo
+    REAL,    DIMENSION(:,:),ALLOCATABLE            :: sic_mpi
+    REAL,    DIMENSION(:,:),ALLOCATABLE            :: sst_mpi
+    REAL,    DIMENSION(klon_mpi,lmdep)             :: rugos_mpi
+    REAL,    DIMENSION(klon_mpi,lmdep)             :: albedo_mpi
+    INTEGER                                        :: ndays
+    REAL                                           :: fi_ice(klon)
+    REAL, ALLOCATABLE                              :: sic_year(:,:)
+    REAL, ALLOCATABLE                              :: sst_year(:,:)
+    REAL, ALLOCATABLE                              :: rugos_year(:,:)
+    REAL, ALLOCATABLE                              :: albedo_year(:,:)
+    REAL, ALLOCATABLE                              :: pctsrf_t(:,:,:)
+    REAL, ALLOCATABLE                              :: phy_bil(:,:)
+    REAL, ALLOCATABLE                              :: sst_year_mpi(:,:)
+    REAL, ALLOCATABLE                              :: rugos_year_mpi(:,:)
+    REAL, ALLOCATABLE                              :: albedo_year_mpi(:,:)
+    REAL, ALLOCATABLE                              :: pctsrf_t_mpi(:,:,:)
+    REAL, ALLOCATABLE                              :: phy_bil_mpi(:,:)
+    INTEGER :: l,k
+    INTEGER :: nbad
+    INTEGER :: sic_time_axis_size 
+    INTEGER :: sst_time_axis_size
+    CHARACTER(LEN=99)                  :: mess            ! error message
+    
+     
+    ndays=ioget_year_len(annee_ref)
+    
+    IF (is_omp_master) CALL xios_get_axis_attr("time_sic",n_glo=sic_time_axis_size)
+    CALL bcast_omp(sic_time_axis_size)
+    ALLOCATE(sic_mpi(klon_mpi,sic_time_axis_size))
+    ALLOCATE(sic(klon,sic_time_axis_size))
+    
+    
+    IF (is_omp_master) CALL xios_get_axis_attr("time_sst",n_glo=sst_time_axis_size)
+    CALL bcast_omp(sst_time_axis_size)
+    ALLOCATE(sst_mpi(klon_mpi,sst_time_axis_size))
+    ALLOCATE(sst(klon,sst_time_axis_size))
+    
+    IF (is_omp_master) THEN
+      CALL xios_recv_field("sic_limit",sic_mpi)
+      CALL xios_recv_field("sst_limit",sst_mpi)
+      CALL xios_recv_field("rugos_limit",rugos_mpi)
+      CALL xios_recv_field("albedo_limit",albedo_mpi)
+    ENDIF
+    CALL scatter_omp(sic_mpi,sic)
+    CALL scatter_omp(sst_mpi,sst)
+    CALL scatter_omp(rugos_mpi,rugos)
+    CALL scatter_omp(albedo_mpi,albedo)
+    
+    ALLOCATE(sic_year(klon,ndays))
+    ALLOCATE(sst_year(klon,ndays))
+    ALLOCATE(rugos_year(klon,ndays))
+    ALLOCATE(albedo_year(klon,ndays))
+    ALLOCATE(pctsrf_t(klon,nbsrf,ndays))
+    ALLOCATE(phy_bil(klon,ndays)); phy_bil=0.0
+
+
+! sic
+    IF (sic_time_axis_size==lmdep) THEN
+      CALL time_interpolation(ndays,sic,'gregorian',sic_year)
+    ELSE IF (sic_time_axis_size==ndays) THEN
+      sic_year=sic
+    ELSE
+      WRITE(mess,*) 'sic time axis is nor montly, nor daily. sic time interpolation ',&
+                    'is requiered but is not currently managed'
+      CALL abort_physic('create_limit_unstruct',TRIM(mess),1)
+    ENDIF
+    
+    sic_year(:,:)=sic_year(:,:)/100.  ! convert percent to fraction
+    WHERE(sic_year(:,:)>1.0) sic_year(:,:)=1.0    ! Some fractions have some time large negative values
+    WHERE(sic_year(:,:)<0.0) sic_year(:,:)=0.0    ! probably better to apply alse this filter before horizontal interpolation
+    
+! sst
+    IF (sst_time_axis_size==lmdep) THEN
+      CALL time_interpolation(ndays,sst,'gregorian',sst_year)
+    ELSE IF (sst_time_axis_size==ndays) THEN
+      sst_year=sst
+    ELSE
+      WRITE(mess,*)'sic time axis is nor montly, nor daily. sic time interpolation ',&
+                   'is requiered but is not currently managed'
+      CALL abort_physic('create_limit_unstruct',TRIM(mess),1)
+    ENDIF
+    WHERE(sst_year(:,:)<271.38) sst_year(:,:)=271.38
+
+
+! rugos    
+    DO l=1, lmdep
+      WHERE(NINT(zmasq(:))/=1) rugos(:,l)=0.001
+    ENDDO
+    CALL time_interpolation(ndays,rugos,'360d',rugos_year)
+
+! albedo    
+    CALL time_interpolation(ndays,albedo,'360d',albedo_year)
+
+
+    DO k=1,ndays
+      fi_ice=sic_year(:,k)
+      WHERE(fi_ice>=1.0  ) fi_ice=1.0
+      WHERE(fi_ice<EPSFRA) fi_ice=0.0
+      pctsrf_t(:,is_ter,k)=pctsrf(:,is_ter)       ! land soil
+      pctsrf_t(:,is_lic,k)=pctsrf(:,is_lic)       ! land ice
+
+!!     IF (icefile==trim(fcpldsic)) THEN           ! SIC=pICE*(1-LIC-TER)
+!!        pctsrf_t(:,is_sic,k)=fi_ice(:)*(1.-pctsrf(:,is_lic)-pctsrf(:,is_ter))
+!!     ELSE IF (icefile==trim(fhistsic)) THEN      ! SIC=pICE
+!!        pctsrf_t(:,is_sic,k)=fi_ice(:)
+!!     ELSE ! icefile==famipsic                    ! SIC=pICE-LIC
+        pctsrf_t(:,is_sic,k)=fi_ice-pctsrf_t(:,is_lic,k)
+!     END IF
+      WHERE(pctsrf_t(:,is_sic,k)<=0) pctsrf_t(:,is_sic,k)=0.
+      WHERE(1.0-zmasq<EPSFRA)
+        pctsrf_t(:,is_sic,k)=0.0
+        pctsrf_t(:,is_oce,k)=0.0
+      ELSEWHERE
+        WHERE(pctsrf_t(:,is_sic,k)>=1.0-zmasq)
+          pctsrf_t(:,is_sic,k)=1.0-zmasq
+          pctsrf_t(:,is_oce,k)=0.0
+        ELSEWHERE
+          pctsrf_t(:,is_oce,k)=1.0-zmasq-pctsrf_t(:,is_sic,k)
+          WHERE(pctsrf_t(:,is_oce,k)<EPSFRA)
+             pctsrf_t(:,is_oce,k)=0.0
+             pctsrf_t(:,is_sic,k)=1.0-zmasq
+          END WHERE
+        END WHERE
+      END WHERE
+      nbad=COUNT(pctsrf_t(:,is_oce,k)<0.0)
+      IF(nbad>0) WRITE(lunout,*) 'pb sous maille pour nb point = ',nbad
+      nbad=COUNT(abs(sum(pctsrf_t(:,:,k),dim=2)-1.0)>EPSFRA)
+      IF(nbad>0) WRITE(lunout,*) 'pb sous surface pour nb points = ',nbad
+    END DO
+    
+    ALLOCATE(sst_year_mpi(klon_mpi,ndays))
+    ALLOCATE(rugos_year_mpi(klon_mpi,ndays))
+    ALLOCATE(albedo_year_mpi(klon_mpi,ndays))
+    ALLOCATE(pctsrf_t_mpi(klon_mpi,nbsrf,ndays))
+    ALLOCATE(phy_bil_mpi(klon_mpi,ndays))
+    
+    CALL gather_omp(pctsrf_t   , pctsrf_t_mpi)
+    CALL gather_omp(sst_year   , sst_year_mpi)
+    CALL gather_omp(phy_bil    , phy_bil_mpi)
+    CALL gather_omp(albedo_year, albedo_year_mpi)
+    CALL gather_omp(rugos_year , rugos_year_mpi)
+
+    IF (is_omp_master) THEN
+      CALL xios_send_field("foce_limout",pctsrf_t_mpi(:,is_oce,:))
+      CALL xios_send_field("fsic_limout",pctsrf_t_mpi(:,is_sic,:))
+      CALL xios_send_field("fter_limout",pctsrf_t_mpi(:,is_ter,:))
+      CALL xios_send_field("flic_limout",pctsrf_t_mpi(:,is_lic,:))
+      CALL xios_send_field("sst_limout", sst_year_mpi)
+      CALL xios_send_field("bils_limout",phy_bil_mpi)
+      CALL xios_send_field("alb_limout", albedo_year_mpi) 
+      CALL xios_send_field("rug_limout", rugos_year_mpi) 
+    ENDIF
+#endif
+  END SUBROUTINE create_limit_unstruct
+  
+  
+  SUBROUTINE time_interpolation(ndays,field_in,calendar,field_out)
+  USE pchsp_95_m, only: pchsp_95
+  USE pchfe_95_m, only: pchfe_95
+  USE arth_m, only: arth
+  USE dimphy, ONLY : klon
+  USE ioipsl,             ONLY : ioget_year_len
+  USE time_phylmdz_mod, ONLY : annee_ref
+  USE mod_phys_lmdz_para
+  IMPLICIT NONE
+   INCLUDE "iniprint.h"
+
+   INTEGER,         INTENT(IN)  :: ndays
+   REAL,            INTENT(IN)  :: field_in(klon,lmdep)
+   CHARACTER(LEN=*),INTENT(IN)  :: calendar
+   REAL,            INTENT(OUT) :: field_out(klon,ndays)
+ 
+   INTEGER :: ndays_in
+   REAL    :: timeyear(lmdep)   
+   REAL    :: yder(lmdep)   
+   INTEGER :: ij,ierr, n_extrap
+   LOGICAL :: skip
+
+   CHARACTER (len = 50)         :: modname = 'create_limit_unstruct.time_interpolation'
+   CHARACTER (len = 80)         :: abort_message
+
+  
+   IF (is_omp_master) ndays_in=year_len(annee_ref, calendar)
+   CALL bcast_omp(ndays_in)
+   IF (is_omp_master) timeyear=mid_months(annee_ref, calendar, lmdep)
+   CALL bcast_omp(timeyear)
+    
+   n_extrap = 0
+   skip=.FALSE.
+   DO ij=1,klon
+     yder = pchsp_95(timeyear, field_in(ij, :), ibeg=2, iend=2, vc_beg=0., vc_end=0.)
+     CALL pchfe_95(timeyear, field_in(ij, :), yder, skip, arth(0., real(ndays_in) / ndays, ndays), field_out(ij, :), ierr)
+     if (ierr < 0) then
+        abort_message='error in pchfe_95'
+        CALL abort_physic(modname,abort_message,1)
+     endif
+     n_extrap = n_extrap + ierr
+   END DO
+   
+   IF (n_extrap /= 0) then
+     WRITE(lunout,*) "get_2Dfield pchfe_95: n_extrap = ", n_extrap
+   ENDIF 
+  
+  
+  END SUBROUTINE time_interpolation
+  !-------------------------------------------------------------------------------
+  !
+  FUNCTION year_len(y,cal_in)
+  !
+  !-------------------------------------------------------------------------------
+    USE ioipsl, ONLY : ioget_calendar,ioconf_calendar,lock_calendar,ioget_year_len
+    IMPLICIT NONE
+  !-------------------------------------------------------------------------------
+  ! Arguments:
+    INTEGER                       :: year_len
+    INTEGER,           INTENT(IN) :: y
+    CHARACTER(LEN=*),  INTENT(IN) :: cal_in
+  !-------------------------------------------------------------------------------
+  ! Local variables:
+    CHARACTER(LEN=20)             :: cal_out              ! calendar (for outputs)
+  !-------------------------------------------------------------------------------
+  !--- Getting the input calendar to reset at the end of the function
+    CALL ioget_calendar(cal_out)
+  
+  !--- Unlocking calendar and setting it to wanted one
+    CALL lock_calendar(.FALSE.); CALL ioconf_calendar(TRIM(cal_in))
+  
+  !--- Getting the number of days in this year
+    year_len=ioget_year_len(y)
+  
+  !--- Back to original calendar
+    CALL lock_calendar(.FALSE.); CALL ioconf_calendar(TRIM(cal_out))
+  
+  END FUNCTION year_len
+  !
+  !-------------------------------------------------------------------------------
+  
+  
+  !-------------------------------------------------------------------------------
+  !
+  FUNCTION mid_months(y,cal_in,nm)
+  !
+  !-------------------------------------------------------------------------------
+    USE ioipsl, ONLY : ioget_calendar,ioconf_calendar,lock_calendar,ioget_mon_len
+    IMPLICIT NONE
+  !-------------------------------------------------------------------------------
+  ! Arguments:
+    INTEGER,                INTENT(IN) :: y               ! year
+    CHARACTER(LEN=*),       INTENT(IN) :: cal_in          ! calendar
+    INTEGER,                INTENT(IN) :: nm              ! months/year number
+    REAL,    DIMENSION(nm)             :: mid_months      ! mid-month times
+  !-------------------------------------------------------------------------------
+  ! Local variables:
+    CHARACTER(LEN=99)                  :: mess            ! error message
+    CHARACTER(LEN=20)                  :: cal_out         ! calendar (for outputs)
+    INTEGER, DIMENSION(nm)             :: mnth            ! months lengths (days)
+    INTEGER                            :: m               ! months counter
+    INTEGER                            :: nd              ! number of days
+    INTEGER                            :: k
+  !-------------------------------------------------------------------------------
+    nd=year_len(y,cal_in)
+  
+    IF(nm==12) THEN
+  
+    !--- Getting the input calendar to reset at the end of the function
+      CALL ioget_calendar(cal_out)
+  
+    !--- Unlocking calendar and setting it to wanted one
+      CALL lock_calendar(.FALSE.); CALL ioconf_calendar(TRIM(cal_in))
+  
+    !--- Getting the length of each month
+      DO m=1,nm; mnth(m)=ioget_mon_len(y,m); END DO
+  
+    !--- Back to original calendar
+      CALL lock_calendar(.FALSE.); CALL ioconf_calendar(TRIM(cal_out))
+  
+    ELSE IF(MODULO(nd,nm)/=0) THEN
+      WRITE(mess,'(a,i3,a,i3,a)')'Unconsistent calendar: ',nd,' days/year, but ',&
+        nm,' months/year. Months number should divide days number.'
+      CALL abort_physic('mid_months',TRIM(mess),1)
+  
+    ELSE
+      mnth=(/(m,m=1,nm,nd/nm)/)
+    END IF
+  
+  !--- Mid-months times
+    mid_months(1)=0.5*REAL(mnth(1))
+    DO k=2,nm
+      mid_months(k)=mid_months(k-1)+0.5*REAL(mnth(k-1)+mnth(k))
+    END DO
+  
+  END FUNCTION mid_months
+  
+
+END MODULE create_limit_unstruct_mod
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cv30_routines.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cv30_routines.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cv30_routines.F90	(revision 3605)
@@ -3050,7 +3050,8 @@
   ! variables pour tracer dans precip de l'AA et des mel
   ! local variables:
-  INTEGER i, j, k
+  INTEGER i, j, k, nam1
   REAL epm(nloc, na, na)
 
+  nam1=na-1 ! Introduced because ep is not defined for j=na
   ! variables d'Emanuel : du second indice au troisieme
   ! --->    tab(i,k,j) -> de l origine k a l arrivee j
@@ -3082,5 +3083,5 @@
   ! fraction deau condensee dans les melanges convertie en precip : epm
   ! et eau condensée précipitée dans masse d'air saturé : l_m*dM_m/dzdz.dzdz
-  DO j = 1, na
+  DO j = 1, nam1
     DO k = 1, j - 1
       DO i = 1, ncum
@@ -3095,6 +3096,6 @@
   END DO
 
-  DO j = 1, na
-    DO k = 1, na
+  DO j = 1, nam1
+    DO k = 1, nam1
       DO i = 1, ncum
         IF (k>=icb(i) .AND. k<=inb(i)) THEN
@@ -3106,5 +3107,5 @@
   END DO
 
-  DO j = 1, na
+  DO j = 1, nam1
     DO k = 1, j - 1
       DO i = 1, ncum
@@ -3117,6 +3118,6 @@
 
   ! matrices pour calculer la tendance des concentrations dans cvltr.F90
-  DO j = 1, na
-    DO k = 1, na
+  DO j = 1, nam1
+    DO k = 1, nam1
       DO i = 1, ncum
         da(i, j) = da(i, j) + (1.-sij(i,k,j))*ment(i, k, j)
@@ -3127,5 +3128,5 @@
   END DO
 
-  DO j = 1, na
+  DO j = 1, nam1
     DO k = 1, j - 1
       DO i = 1, ncum
@@ -3298,4 +3299,6 @@
       integer i,k    
       real hp_bak(nloc,nd)
+      CHARACTER (LEN=20) :: modname='cv30_epmax_fn_cape'
+      CHARACTER (LEN=80) :: abort_message
 
         ! on recalcule ep et hp
@@ -3346,5 +3349,5 @@
            write(*,*) 'clw(i,k)=',clw(i,k)
            write(*,*) 'cpd,cpv=',cpd,cpv
-           stop
+           CALL abort_physic(modname,abort_message,0)
         endif
        enddo !do k=1,nl
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3_mixscale.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3_mixscale.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3_mixscale.F90	(revision 3605)
@@ -13,15 +13,20 @@
   include "cv3param.h"
 
-  INTEGER nloc, ncum, na
+!inputs:
+  INTEGER, INTENT (IN)                               :: ncum, na, nloc
+  REAL, DIMENSION (nloc, na), INTENT (IN)            :: m
+!input/outputs:
+  REAL, DIMENSION (nloc, na, na), INTENT (INOUT)     :: ment
+
+!local variables:
   INTEGER i, j, il
-  REAL ment(nloc, na, na), m(nloc, na)
 
-  DO j = 1, nl
-    DO i = 1, nl
-      DO il = 1, ncum
-        ment(il, i, j) = m(il, i)*ment(il, i, j)
+    DO j = 1, nl
+      DO i = 1, nl
+        DO il = 1, ncum
+          ment(il, i, j) = m(il, i)*ment(il, i, j)
+        END DO
       END DO
     END DO
-  END DO
 
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3_routines.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3_routines.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3_routines.F90	(revision 3605)
@@ -35,4 +35,5 @@
 
   include "cv3param.h"
+  include "cvflag.h"
   include "conema3.h"
 
@@ -125,4 +126,16 @@
      tlcrit=-55.0
      CALL getin_p('tlcrit',tlcrit)
+     ejectliq=0.
+     CALL getin_p('ejectliq',ejectliq)
+     ejectice=0.
+     CALL getin_p('ejectice',ejectice)
+     cvflag_prec_eject = .FALSE.
+     CALL getin_p('cvflag_prec_eject',cvflag_prec_eject)
+     qsat_depends_on_qt = .FALSE.
+     CALL getin_p('qsat_depends_on_qt',qsat_depends_on_qt)
+     adiab_ascent_mass_flux_depends_on_ejectliq = .FALSE.
+     CALL getin_p('adiab_ascent_mass_flux_depends_on_ejectliq',adiab_ascent_mass_flux_depends_on_ejectliq)
+     keepbug_ice_frac = .TRUE.
+     CALL getin_p('keepbug_ice_frac', keepbug_ice_frac)
 
     WRITE (*, *) 't_top_max=', t_top_max
@@ -144,4 +157,11 @@
     WRITE (*, *) 'elcrit=', elcrit
     WRITE (*, *) 'tlcrit=', tlcrit
+    WRITE (*, *) 'ejectliq=', ejectliq
+    WRITE (*, *) 'ejectice=', ejectice
+    WRITE (*, *) 'cvflag_prec_eject =', cvflag_prec_eject 
+    WRITE (*, *) 'qsat_depends_on_qt =', qsat_depends_on_qt 
+    WRITE (*, *) 'adiab_ascent_mass_flux_depends_on_ejectliq =', adiab_ascent_mass_flux_depends_on_ejectliq
+    WRITE (*, *) 'keepbug_ice_frac =', keepbug_ice_frac 
+
     first = .FALSE.
   END IF ! (first)
@@ -170,4 +190,5 @@
 
   include "cv3param.h"
+  include "cvflag.h"
 
 !inputs:
@@ -236,5 +257,6 @@
 ! debug          lv(i,k)= lv0-clmcpv*(t(i,k)-t0)
       lv(i, k) = lv0 - clmcpv*(t(i,k)-273.15)
-      lf(i, k) = lf0 - clmci*(t(i,k)-273.15)
+!!      lf(i, k) = lf0 - clmci*(t(i,k)-273.15)   ! erreur de signe !!
+      lf(i, k) = lf0 + clmci*(t(i,k)-273.15)
       cpn(i, k) = cpd*(1.0-q(i,k)) + cpv*q(i, k)
       cpx(i, k) = cpd*(1.0-q(i,k)) + cl*q(i, k)
@@ -289,4 +311,5 @@
   USE mod_phys_lmdz_transfert_para, ONLY : bcast
   USE add_phys_tend_mod, ONLY: fl_cor_ebil
+  USE print_control_mod, ONLY: prt_level
   IMPLICIT NONE
 
@@ -516,4 +539,8 @@
     END DO
   ENDIF
+  IF (prt_level .GE. 10) THEN
+    print *,'cv3_feed : iflag(1), pfeed(1), plcl(1), wghti(1,k) ', &
+                        iflag(1), pfeed(1), plcl(1), (wghti(1,k),k=1,10)
+  ENDIF
 
 ! -------------------------------------------------------------------
@@ -1105,5 +1132,6 @@
                          tnk, qnk, gznk, hnk, t, q, qs, gz, &
                          p, ph, h, tv, lv, lf, pbase, buoybase, plcl, &
-                         inb, tp, tvp, clw, hp, ep, sigp, buoy, frac)
+                         inb, tp, tvp, clw, hp, ep, sigp, buoy, &
+                         frac_a, frac_s, qpreca, qta)
   USE print_control_mod, ONLY: prt_level
   IMPLICIT NONE
@@ -1153,22 +1181,45 @@
   REAL, DIMENSION (nloc, nd), INTENT (OUT)           :: ep, sigp, hp
   REAL, DIMENSION (nloc, nd), INTENT (OUT)           :: buoy
-  REAL, DIMENSION (nloc, nd), INTENT (OUT)           :: frac
+  REAL, DIMENSION (nloc, nd), INTENT (OUT)           :: frac_a, frac_s
+  REAL, DIMENSION (nloc, nd), INTENT (OUT)           :: qpreca
+  REAL, DIMENSION (nloc, nd), INTENT (OUT)           :: qta
 
 !local variables:
   INTEGER i, j, k
-  REAL tg, qg, ahg, alv, alf, s, tc, es, esi, denom, rg, tca, elacrit
+  REAL smallestreal
+  REAL tg, qg, dqgdT, ahg, alv, alf, s, tc, es, esi, denom, rg, tca, elacrit
+  REAL                                               :: phinu2p
   REAL als
-  REAL qsat_new, snew, qi(nloc, nd)
-  REAL by, defrac, pden, tbis
-  REAL ah0(nloc), cape(nloc), capem(nloc), byp(nloc)
-  LOGICAL lcape(nloc)
-  INTEGER iposit(nloc)
-  REAL fracg
-  REAL deltap
+  REAL                                               :: qsat_new, snew
+  REAL, DIMENSION (nloc,nd)                          :: qi
+  REAL, DIMENSION (nloc,nd)                          :: ha    ! moist static energy of adiabatic ascents 
+                                                              ! taking into account precip ejection
+  REAL, DIMENSION (nloc,nd)                          :: hla   ! liquid water static energy of adiabatic ascents 
+                                                              ! taking into account precip ejection
+  REAL, DIMENSION (nloc,nd)                          :: qcld  ! specific cloud water
+  REAL, DIMENSION (nloc,nd)                          :: qhsat    ! specific humidity at saturation
+  REAL, DIMENSION (nloc,nd)                          :: dqhsatdT ! dqhsat/dT
+  REAL, DIMENSION (nloc,nd)                          :: frac  ! ice fraction function of envt temperature
+  REAL, DIMENSION (nloc,nd)                          :: qps   ! specific solid precipitation
+  REAL, DIMENSION (nloc,nd)                          :: qpl   ! specific liquid precipitation
+  REAL, DIMENSION (nloc)                             :: ah0, cape, capem, byp
+  LOGICAL, DIMENSION (nloc)                          :: lcape
+  INTEGER, DIMENSION (nloc)                          :: iposit
+  REAL                                               :: denomm1
+  REAL                                               :: by, defrac, pden, tbis
+  REAL                                               :: fracg
+  REAL                                               :: deltap
+  REAL, SAVE                                         :: Tx, Tm
+  DATA Tx/263.15/, Tm/243.15/
+!$OMP THREADPRIVATE(Tx, Tm)
+  REAL                                               :: aa, bb, dd, ddelta, discr
+  REAL                                               :: ff, fp
+  REAL                                               :: coefx, coefm, Zx, Zm, Ux, U, Um
 
   IF (prt_level >= 10) THEN
-    print *,'cv3_undilute2.0. t(1,k), q(1,k), qs(1,k) ', &
-                        (k, t(1,k), q(1,k), qs(1,k), k = 1,nl)
+    print *,'cv3_undilute2.0. icvflag_Tpa, t(1,k), q(1,k), qs(1,k) ', &
+                        icvflag_Tpa, (k, t(1,k), q(1,k), qs(1,k), k = 1,nl)
   ENDIF
+  smallestreal=tiny(smallestreal)
 
 ! =====================================================================
@@ -1181,4 +1232,5 @@
     END DO
   END DO
+
 
 ! =====================================================================
@@ -1197,9 +1249,298 @@
              qnk(i)*(lv0-clmcpv*(tnk(i)-273.15)) + gznk(i)
   END DO
-
+!
+!  Ice fraction
+!
+  IF (cvflag_ice) THEN
+    DO k = minorig, nl
+      DO i = 1, ncum
+          frac(i, k) = (Tx - t(i,k))/(Tx - Tm)
+          frac(i, k) = min(max(frac(i,k),0.0), 1.0)
+      END DO
+    END DO
+! Below cloud base, set ice fraction to cloud base value
+    DO k = 1, nl
+      DO i = 1, ncum
+        IF (k<icb(i)) THEN
+          frac(i,k) = frac(i,icb(i))
+        END IF
+      END DO
+    END DO
+  ELSE
+    DO k = 1, nl
+      DO i = 1, ncum
+          frac(i,k) = 0.
+      END DO
+    END DO
+  ENDIF ! (cvflag_ice)
+
+
+  DO k = minorig, nl
+    DO i = 1,ncum
+      ha(i,k) = ah0(i)
+      hla(i,k) = hnk(i)
+      qta(i,k) = qnk(i)
+      qpreca(i,k) = 0.
+      frac_a(i,k) = 0.
+      frac_s(i,k) = frac(i,k)
+      qpl(i,k) = 0.
+      qps(i,k) = 0.
+      qhsat(i,k) = qs(i,k)
+      qcld(i,k) = max(qta(i,k)-qhsat(i,k),0.)
+      IF (k <= icb(i)+1) THEN
+        qhsat(i,k) = qnk(i)-clw(i,k)
+        qcld(i,k) = clw(i,k)
+      ENDIF 
+    ENDDO
+  ENDDO
+
+!jyg<
+! =====================================================================
+! --- SET THE THE FRACTION OF PRECIPITATION FALLING OUTSIDE OF CLOUD
+! =====================================================================
+  DO k = 1, nl
+    DO i = 1, ncum
+      ep(i, k) = 0.0
+      sigp(i, k) = spfac
+    END DO
+  END DO
+!>jyg
+!
 
 ! ***  Find lifted parcel quantities above cloud base    ***
 
-
+!----------------------------------------------------------------------------
+!
+  IF (icvflag_Tpa == 2) THEN
+!
+!----------------------------------------------------------------------------
+!
+    DO k = minorig + 1, nl
+      DO i = 1,ncum
+        tp(i,k) = t(i,k)
+      ENDDO
+!!      alv = lv0 - clmcpv*(t(i,k)-273.15)
+!!      alf = lf0 + clmci*(t(i,k)-273.15)
+!!      als = alf + alv
+      DO j = 1,4
+        DO i = 1, ncum
+! ori	    if(k.ge.(icb(i)+1))then
+          IF (k>=(icbs(i)+1)) THEN                                ! convect3
+            tg = tp(i, k)
+            IF (tg .gt. Tx) THEN
+              es = 6.112*exp(17.67*(tg - 273.15)/(tg + 243.5 - 273.15))
+              qg = eps*es/(p(i,k)-es*(1.-eps))
+            ELSE
+              esi = exp(23.33086-(6111.72784/tg)+0.15215*log(tg))
+              qg = eps*esi/(p(i,k)-esi*(1.-eps))
+            ENDIF
+! Ice fraction
+            ff = 0.
+            fp = 1./(Tx - Tm)
+            IF (tg < Tx) THEN
+              IF (tg > Tm) THEN
+                ff = (Tx - tg)*fp
+              ELSE
+                ff = 1.
+              ENDIF ! (tg > Tm)
+            ENDIF ! (tg < Tx)
+! Intermediate variables
+            aa = cpd + (cl-cpd)*qnk(i) + lv(i,k)*lv(i,k)*qg/(rrv*tg*tg)
+            ahg = (cpd + (cl-cpd)*qnk(i))*tg + lv(i,k)*qg - &
+                  lf(i,k)*ff*(qnk(i) - qg) + gz(i,k)
+            dd = lf(i,k)*lv(i,k)*qg/(rrv*tg*tg)
+            ddelta = lf(i,k)*(qnk(i) - qg)
+            bb = aa + ddelta*fp + dd*fp*(Tx-tg)
+! Compute Zx and Zm
+            coefx = aa
+            coefm = aa + dd
+            IF (tg .gt. Tx) THEN
+              Zx = ahg            + coefx*(Tx - tg)
+              Zm = ahg - ddelta   + coefm*(Tm - tg)
+            ELSE
+              IF (tg .gt. Tm) THEN
+                Zx = ahg          + (coefx +fp*ddelta)*(Tx - Tg)
+                Zm = ahg          + (coefm +fp*ddelta)*(Tm - Tg)
+              ELSE
+                Zx = ahg + ddelta + coefx*(Tx - tg)
+                Zm = ahg          + coefm*(Tm - tg)
+              ENDIF ! (tg .gt. Tm)
+            ENDIF ! (tg .gt. Tx)
+! Compute the masks Um, U, Ux
+            Um = (sign(1., Zm-ah0(i))+1.)/2.
+            Ux = (sign(1., ah0(i)-Zx)+1.)/2.
+            U = (1. - Um)*(1. - Ux)
+! Compute the updated parcell temperature Tp : 3 cases depending on tg value
+            IF (tg .gt. Tx) THEN
+              discr = bb*bb - 4*dd*fp*(ah0(i) - ahg + ddelta*fp*(Tx-tg))
+              Tp(i,k) = tg + &
+                  Um*  (ah0(i) - ahg + ddelta)           /(aa + dd) + &
+                  U *2*(ah0(i) - ahg + ddelta*fp*(Tx-tg))/(bb + sqrt(discr)) + &
+                  Ux*  (ah0(i) - ahg)                    /aa
+            ELSEIF (tg .gt. Tm) THEN
+              discr = bb*bb - 4*dd*fp*(ah0(i) - ahg)
+              Tp(i,k) = tg + &
+                  Um*  (ah0(i) - ahg + ddelta*fp*(tg-Tm))/(aa + dd) + &
+                  U *2*(ah0(i) - ahg)                    /(bb + sqrt(discr)) + &
+                  Ux*  (ah0(i) - ahg + ddelta*fp*(tg-Tx))/aa
+            ELSE
+              discr = bb*bb - 4*dd*fp*(ah0(i) - ahg + ddelta*fp*(Tm-tg))
+              Tp(i,k) = tg + &
+                  Um*  (ah0(i) - ahg)                    /(aa + dd) + &
+                  U *2*(ah0(i) - ahg + ddelta*fp*(Tm-tg))/(bb + sqrt(discr)) + &
+                  Ux*  (ah0(i) - ahg - ddelta)           /aa
+            ENDIF ! (tg .gt. Tx)
+!
+!!     print *,' j, k, Um, U, Ux, aa, bb, discr, dd, ddelta ', j, k, Um, U, Ux, aa, bb, discr, dd, ddelta
+!!     print *,' j, k, ah0(i), ahg, tg, qg, tp(i,k), ff ', j, k, ah0(i), ahg, tg, qg, tp(i,k), ff
+          END IF ! (k>=(icbs(i)+1))
+        END DO ! i = 1, ncum
+      END DO ! j = 1,4
+      DO i = 1, ncum
+        IF (k>=(icbs(i)+1)) THEN                                ! convect3
+          tg = tp(i, k)
+          IF (tg .gt. Tx) THEN
+            es = 6.112*exp(17.67*(tg - 273.15)/(tg + 243.5 - 273.15))
+            qg = eps*es/(p(i,k)-es*(1.-eps))
+          ELSE
+            esi = exp(23.33086-(6111.72784/tg)+0.15215*log(tg))
+            qg = eps*esi/(p(i,k)-esi*(1.-eps))
+          ENDIF
+          clw(i, k) = qnk(i) - qg
+          clw(i, k) = max(0.0, clw(i,k))
+          tvp(i, k) = max(0., tp(i,k)*(1.+qg/eps-qnk(i)))
+! print*,tvp(i,k),'tvp'
+          IF (clw(i,k)<1.E-11) THEN
+            tp(i, k) = tv(i, k)
+            tvp(i, k) = tv(i, k)
+          END IF ! (clw(i,k)<1.E-11)
+        END IF ! (k>=(icbs(i)+1))
+      END DO ! i = 1, ncum
+    END DO ! k = minorig + 1, nl
+!----------------------------------------------------------------------------
+!
+  ELSE IF (icvflag_Tpa == 1) THEN  ! (icvflag_Tpa == 2)
+!
+!----------------------------------------------------------------------------
+!
+    DO k = minorig + 1, nl
+      DO i = 1,ncum
+        tp(i,k) = t(i,k)
+      ENDDO
+!!      alv = lv0 - clmcpv*(t(i,k)-273.15)
+!!      alf = lf0 + clmci*(t(i,k)-273.15)
+!!      als = alf + alv
+      DO j = 1,4
+        DO i = 1, ncum
+! ori	    if(k.ge.(icb(i)+1))then
+          IF (k>=(icbs(i)+1)) THEN                                ! convect3
+            tg = tp(i, k)
+            IF (tg .gt. Tx .OR. .NOT.cvflag_ice) THEN
+              es = 6.112*exp(17.67*(tg - 273.15)/(tg + 243.5 - 273.15))
+              qg = eps*es/(p(i,k)-es*(1.-eps))
+              dqgdT = lv(i,k)*qg/(rrv*tg*tg)
+            ELSE
+              esi = exp(23.33086-(6111.72784/tg)+0.15215*log(tg))
+              qg = eps*esi/(p(i,k)-esi*(1.-eps))
+              dqgdT = (lv(i,k)+lf(i,k))*qg/(rrv*tg*tg)
+            ENDIF
+            IF (qsat_depends_on_qt) THEN
+              dqgdT = dqgdT*(1.-qta(i,k-1))/(1.-qg)**2
+              qg = qg*(1.-qta(i,k-1))/(1.-qg)            
+            ENDIF
+            ahg = (cpd + (cl-cpd)*qta(i,k-1))*tg + lv(i,k)*qg - &
+                  lf(i,k)*frac(i,k)*(qta(i,k-1) - qg) + gz(i,k)
+            Tp(i,k) = tg + (ah0(i) - ahg)/ &
+                    (cpd + (cl-cpd)*qta(i,k-1) + (lv(i,k)+frac(i,k)*lf(i,k))*dqgdT)
+!!   print *,'undilute2 iterations k, Tp(i,k), ah0(i), ahg ', &
+!!                                 k, Tp(i,k), ah0(i), ahg
+          END IF ! (k>=(icbs(i)+1))
+        END DO ! i = 1, ncum
+      END DO ! j = 1,4
+      DO i = 1, ncum
+        IF (k>=(icbs(i)+1)) THEN                                ! convect3
+          tg = tp(i, k)
+          IF (tg .gt. Tx .OR. .NOT.cvflag_ice) THEN
+            es = 6.112*exp(17.67*(tg - 273.15)/(tg + 243.5 - 273.15))
+            qg = eps*es/(p(i,k)-es*(1.-eps))
+          ELSE
+            esi = exp(23.33086-(6111.72784/tg)+0.15215*log(tg))
+            qg = eps*esi/(p(i,k)-esi*(1.-eps))
+          ENDIF
+          IF (qsat_depends_on_qt) THEN
+            qg = qg*(1.-qta(i,k-1))/(1.-qg)            
+          ENDIF
+          qhsat(i,k) = qg
+        END IF ! (k>=(icbs(i)+1))
+      END DO ! i = 1, ncum
+      DO i = 1, ncum
+        IF (k>=(icbs(i)+1)) THEN                                ! convect3
+          clw(i, k) = qta(i,k-1) - qhsat(i,k)
+          clw(i, k) = max(0.0, clw(i,k))
+          tvp(i, k) = max(0., tp(i,k)*(1.+qhsat(i,k)/eps-qta(i,k-1)))
+! print*,tvp(i,k),'tvp'
+          IF (clw(i,k)<1.E-11) THEN
+            tp(i, k) = tv(i, k)
+            tvp(i, k) = tv(i, k)
+          END IF ! (clw(i,k)<1.E-11)
+        END IF ! (k>=(icbs(i)+1))
+      END DO ! i = 1, ncum
+!
+      IF (cvflag_prec_eject) THEN
+        DO i = 1, ncum
+          IF (k>=(icbs(i)+1)) THEN                                ! convect3
+!  Specific precipitation (liquid and solid) and ice content 
+!  before ejection of precipitation                                                     !!jygprl
+            elacrit = elcrit*min(max(1.-(tp(i,k)-T0)/Tlcrit, 0.), 1.)                   !!jygprl
+!!!!            qcld(i,k) = min(clw(i,k), elacrit)                                          !!jygprl
+            qcld(i,k) = min(clw(i,k), elacrit*(1.-qta(i,k-1))/(1.-elacrit))             !!jygprl
+            phinu2p = qhsat(i,k-1) + qcld(i,k-1) - (qhsat(i,k) + qcld(i,k))                     !!jygprl
+            qpl(i,k) = qpl(i,k-1) + (1.-frac(i,k))*phinu2p                            !!jygprl
+            qps(i,k) = qps(i,k-1) + frac(i,k)     *phinu2p                            !!jygprl
+            qi(i,k) = (1.-ejectliq)*clw(i,k)*frac(i,k) + &                            !!jygprl
+                     ejectliq*(qps(i,k-1) + frac(i,k)*(phinu2p+qcld(i,k)))            !!jygprl
+!!
+!  =====================================================================================
+!  Ejection of precipitation from adiabatic ascents if requested (cvflag_prec_eject=True):
+!  Compute the steps of total water (qta), of moist static energy (ha), of specific 
+!  precipitation (qpl and qps) and of specific cloud water (qcld) associated with precipitation
+!   ejection.
+!  =====================================================================================
+!  
+!   Verif
+            qpreca(i,k) = ejectliq*qpl(i,k) + ejectice*qps(i,k)                                   !!jygprl
+            frac_a(i,k) = ejectice*qps(i,k)/max(qpreca(i,k),smallestreal)                         !!jygprl
+            frac_s(i,k) = (1.-ejectliq)*frac(i,k) + &                                             !!jygprl
+               ejectliq*(1. - (qpl(i,k)+(1.-frac(i,k))*qcld(i,k))/max(clw(i,k),smallestreal))     !!jygprl
+!          
+            denomm1 = 1./(1. - qpreca(i,k))
+!          
+            qta(i,k) = qta(i,k-1) - &
+                      qpreca(i,k)*(1.-qta(i,k-1))*denomm1
+            ha(i,k)  = ha(i,k-1) + &
+                      ( qpreca(i,k)*(-(1.-qta(i,k-1))*(cl-cpd)*tp(i,k) + &
+                                  lv(i,k)*qhsat(i,k) - lf(i,k)*(frac_s(i,k)*qcld(i,k)+qps(i,k))) + &
+                        lf(i,k)*ejectice*qps(i,k))*denomm1
+            hla(i,k) = hla(i,k-1) + &
+                      ( qpreca(i,k)*(-(1.-qta(i,k-1))*(cpv-cpd)*tp(i,k) - &
+                                  lv(i,k)*((1.-frac_s(i,k))*qcld(i,k)+qpl(i,k)) - &
+                                  (lv(i,k)+lf(i,k))*(frac_s(i,k)*qcld(i,k)+qps(i,k))) + &
+                        lv(i,k)*ejectliq*qpl(i,k) + (lv(i,k)+lf(i,k))*ejectice*qps(i,k))*denomm1
+            qpl(i,k) = qpl(i,k)*(1.-ejectliq)*denomm1
+            qps(i,k) = qps(i,k)*(1.-ejectice)*denomm1
+            qcld(i,k) = qcld(i,k)*denomm1
+            qhsat(i,k) = qhsat(i,k)*(1.-qta(i,k))/(1.-qta(i,k-1))
+         END IF ! (k>=(icbs(i)+1))
+        END DO ! i = 1, ncum
+      ENDIF  ! (cvflag_prec_eject)
+! 
+    END DO ! k = minorig + 1, nl
+!
+!----------------------------------------------------------------------------
+!
+  ELSE IF (icvflag_Tpa == 0) THEN! (icvflag_Tpa == 2) ELSE IF(icvflag_Tpa == 1)
+!
+!----------------------------------------------------------------------------
+!
   DO k = minorig + 1, nl
     DO i = 1, ncum
@@ -1358,23 +1699,14 @@
   END DO
 
-  IF (prt_level >= 10) THEN
-    print *,'cv3_undilute2.1. tp(1,k), tvp(1,k) ', &
-                          (k, tp(1,k), tvp(1,k), k = 1,nl)
-  ENDIF
-
+!----------------------------------------------------------------------------
+!
+  ENDIF ! (icvflag_Tpa == 2) ELSEIF (icvflag_Tpa == 1) ELSE (icvflag_Tpa == 0)
+!
+!----------------------------------------------------------------------------
+!
 ! =====================================================================
-! --- SET THE PRECIPITATION EFFICIENCIES AND THE FRACTION OF
-! --- PRECIPITATION FALLING OUTSIDE OF CLOUD
+! --- SET THE PRECIPITATION EFFICIENCIES 
 ! --- THESE MAY BE FUNCTIONS OF TP(I), P(I) AND CLW(I)
 ! =====================================================================
-!
-!jyg<
-  DO k = 1, nl
-    DO i = 1, ncum
-      ep(i, k) = 0.0
-      sigp(i, k) = spfac
-    END DO
-  END DO
-!>jyg
 !
   IF (flag_epkeorig/=1) THEN
@@ -1413,4 +1745,10 @@
     END DO
   END IF
+!
+!   =========================================================================
+  IF (prt_level >= 10) THEN
+    print *,'cv3_undilute2.1. tp(1,k), tvp(1,k) ', &
+                          (k, tp(1,k), tvp(1,k), k = 1,nl)
+  ENDIF
 !
 ! =====================================================================
@@ -1648,24 +1986,37 @@
   IF (cvflag_ice) THEN
 !
+  IF (cvflag_prec_eject) THEN
+!!    DO k = minorig + 1, nl
+!!      DO i = 1, ncum
+!!        IF ((k>=icb(i)) .AND. (k<=inb(i))) THEN
+!!          frac_s(i,k) = qi(i,k)/max(clw(i,k),smallestreal)    
+!!          frac_s(i,k) = 1. - (qpl(i,k)+(1.-frac_s(i,k))*qcld(i,k))/max(clw(i,k),smallestreal)    
+!!        END IF
+!!      END DO
+!!    END DO
+  ELSE    ! (cvflag_prec_eject)
     DO k = minorig + 1, nl
       DO i = 1, ncum
         IF ((k>=icb(i)) .AND. (k<=inb(i))) THEN
-          frac(i, k) = 1. - (t(i,k)-243.15)/(263.15-243.15)
-          frac(i, k) = min(max(frac(i,k),0.0), 1.0)
-          hp(i, k) = hnk(i) + (lv(i,k)+(cpd-cpv)*t(i,k)+frac(i,k)*lf(i,k))* &
-                              ep(i, k)*clw(i, k)
+!jyg< frac computation moved to beginning of cv3_undilute2.
+!     kept here for compatibility test with CMip6 version
+          frac_s(i, k) = 1. - (t(i,k)-243.15)/(263.15-243.15)
+          frac_s(i, k) = min(max(frac_s(i,k),0.0), 1.0)
         END IF
       END DO
     END DO
-! Below cloud base, set ice fraction to cloud base value
-    DO k = 1, nl
+  ENDIF  ! (cvflag_prec_eject) ELSE
+    DO k = minorig + 1, nl
       DO i = 1, ncum
-        IF (k<icb(i)) THEN
-          frac(i,k) = frac(i,icb(i))
+        IF ((k>=icb(i)) .AND. (k<=inb(i))) THEN
+!!          hp(i, k) = hnk(i) + (lv(i,k)+(cpd-cpv)*t(i,k)+frac_s(i,k)*lf(i,k))* &     !!jygprl
+!!                              ep(i, k)*clw(i, k)                                    !!jygprl
+          hp(i, k) = hla(i,k-1) + (lv(i,k)+(cpd-cpv)*t(i,k)+frac_s(i,k)*lf(i,k))* &   !!jygprl
+                              ep(i, k)*clw(i, k)                                      !!jygprl
         END IF
       END DO
     END DO
 !
-  ELSE
+  ELSE   ! (cvflag_ice)
 !
     DO k = minorig + 1, nl
@@ -2350,9 +2701,9 @@
 SUBROUTINE cv3_unsat(nloc, ncum, nd, na, ntra, icb, inb, iflag, &
                      t, rr, rs, gz, u, v, tra, p, ph, &
-                     th, tv, lv, lf, cpn, ep, sigp, clw, &
+                     th, tv, lv, lf, cpn, ep, sigp, clw, frac_s, qpreca, frac_a, qta , &                       !!jygprl
                      m, ment, elij, delt, plcl, coef_clos, &
                      mp, rp, up, vp, trap, wt, water, evap, fondue, ice, &
                      faci, b, sigd, &
-                     wdtrainA, wdtrainM)                                      ! RomP
+                     wdtrainA, wdtrainS, wdtrainM)                                      ! RomP
   USE print_control_mod, ONLY: prt_level, lunout
   IMPLICIT NONE
@@ -2372,7 +2723,12 @@
   REAL, DIMENSION (nloc, na), INTENT (IN)            :: gz
   REAL, DIMENSION (nloc, nd), INTENT (IN)            :: u, v
-  REAL tra(nloc, nd, ntra)
-  REAL p(nloc, nd), ph(nloc, nd+1)
-  REAL, DIMENSION (nloc, na), INTENT (IN)            :: ep, sigp, clw
+  REAL, DIMENSION (nloc, nd, ntra), INTENT(IN)       :: tra
+  REAL, DIMENSION (nloc, nd), INTENT (IN)            :: p
+  REAL, DIMENSION (nloc, nd+1), INTENT (IN)          :: ph
+  REAL, DIMENSION (nloc, na), INTENT (IN)            :: ep, sigp, clw   !adiab ascent shedding
+  REAL, DIMENSION (nloc, na), INTENT (IN)            :: frac_s          !ice fraction in adiab ascent shedding !!jygprl
+  REAL, DIMENSION (nloc, na), INTENT (IN)            :: qpreca          !adiab ascent precip                   !!jygprl
+  REAL, DIMENSION (nloc, na), INTENT (IN)            :: frac_a          !ice fraction in adiab ascent precip   !!jygprl
+  REAL, DIMENSION (nloc, na), INTENT (IN)            :: qta             !adiab ascent specific total water     !!jygprl
   REAL, DIMENSION (nloc, na), INTENT (IN)            :: th, tv, lv, cpn
   REAL, DIMENSION (nloc, na), INTENT (IN)            :: lf
@@ -2387,5 +2743,6 @@
   REAL, DIMENSION (nloc, na), INTENT (OUT)           :: mp, rp, up, vp
   REAL, DIMENSION (nloc, na), INTENT (OUT)           :: water, evap, wt
-  REAL, DIMENSION (nloc, na), INTENT (OUT)           :: ice, fondue, faci
+  REAL, DIMENSION (nloc, na), INTENT (OUT)           :: ice, fondue
+  REAL, DIMENSION (nloc, na), INTENT (OUT)           :: faci            ! ice fraction in precipitation
   REAL, DIMENSION (nloc, na, ntra), INTENT (OUT)     :: trap
   REAL, DIMENSION (nloc, na), INTENT (OUT)           :: b
@@ -2395,8 +2752,9 @@
 ! Distinction des wdtrain
 ! Pa = wdtrainA     Pm = wdtrainM
-  REAL, DIMENSION (nloc, na), INTENT (OUT)           :: wdtrainA, wdtrainM
+  REAL, DIMENSION (nloc, na), INTENT (OUT)           :: wdtrainA, wdtrainS, wdtrainM
 
 !local variables
   INTEGER i, j, k, il, num1, ndp1
+  REAL smallestreal
   REAL tinv, delti, coef
   REAL awat, afac, afac1, afac2, bfac
@@ -2405,8 +2763,10 @@
   REAL ampmax, thaw
   REAL tevap(nloc)
-  REAL lvcp(nloc, na), lfcp(nloc, na)
-  REAL h(nloc, na), hm(nloc, na)
-  REAL frac(nloc, na)
-  REAL fraci(nloc, na), prec(nloc, na)
+  REAL, DIMENSION (nloc, na)      :: lvcp, lfcp
+  REAL, DIMENSION (nloc, na)      :: h, hm
+  REAL, DIMENSION (nloc, na)      :: ma
+  REAL, DIMENSION (nloc, na)      :: frac          ! ice fraction in precipitation source
+  REAL, DIMENSION (nloc, na)      :: fraci         ! provisionnal ice fraction in precipitation
+  REAL, DIMENSION (nloc, na)      :: prec
   REAL wdtrain(nloc)
   LOGICAL lwork(nloc), mplus(nloc)
@@ -2415,4 +2775,6 @@
 ! ------------------------------------------------------
 IF (prt_level .GE. 10) print *,' ->cv3_unsat, iflag(1) ', iflag(1)
+
+smallestreal=tiny(smallestreal)
 
 ! =============================
@@ -2434,4 +2796,5 @@
 !! RomP >>>
 wdtrainA(:,:) = 0.
+wdtrainS(:,:) = 0.
 wdtrainM(:,:) = 0.
 !! RomP <<<
@@ -2489,4 +2852,39 @@
   END DO
 
+!
+! Get adiabatic ascent mass flux 
+!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+  IF (adiab_ascent_mass_flux_depends_on_ejectliq) THEN
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!!! Warning : this option leads to water conservation violation
+!!!           Expert only
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+    DO il = 1, ncum
+      ma(il, nlp) = 0.
+      ma(il, 1)   = 0.
+    END DO
+
+  DO i = nl, 2, -1
+      DO il = 1, ncum
+        ma(il, i) = ma(il, i+1)*(1.-qta(il,i))/(1.-qta(il,i-1)) + m(il, i)
+      END DO
+  END DO
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+  ELSE ! (adiab_ascent_mass_flux_depends_on_ejectliq)
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+    DO il = 1, ncum
+      ma(il, nlp) = 0.
+      ma(il, 1)   = 0.
+    END DO
+
+  DO i = nl, 2, -1
+      DO il = 1, ncum
+        ma(il, i) = ma(il, i+1) + m(il, i)
+      END DO
+  END DO
+
+  ENDIF ! (adiab_ascent_mass_flux_depends_on_ejectliq) ELSE
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 
 ! ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
@@ -2513,15 +2911,12 @@
 ! ***              calculate detrained precipitation             ***
 
-    DO il = 1, ncum
-      IF (i<=inb(il) .AND. lwork(il)) THEN
-        IF (cvflag_grav) THEN
-          wdtrain(il) = grav*ep(il, i)*m(il, i)*clw(il, i)
-          wdtrainA(il, i) = wdtrain(il)/grav                        !   Pa   RomP
-        ELSE
-          wdtrain(il) = 10.0*ep(il, i)*m(il, i)*clw(il, i)
-          wdtrainA(il, i) = wdtrain(il)/10.                         !   Pa   RomP
-        END IF
-      END IF
-    END DO
+
+    DO il = 1, ncum                                                   
+      IF (i<=inb(il) .AND. lwork(il)) THEN                            
+        wdtrain(il) = grav*ep(il, i)*m(il, i)*clw(il, i)            
+        wdtrainS(il, i) = wdtrain(il)/grav                                            !   Ps   jyg
+!!        wdtrainA(il, i) = wdtrain(il)/grav                                          !   Ps   RomP
+      END IF                                                          
+    END DO                                                            
 
     IF (i>1) THEN
@@ -2531,11 +2926,7 @@
             awat = elij(il, j, i) - (1.-ep(il,i))*clw(il, i)
             awat = max(awat, 0.0)
-            IF (cvflag_grav) THEN
-              wdtrain(il) = wdtrain(il) + grav*awat*ment(il, j, i)
-              wdtrainM(il, i) = wdtrain(il)/grav - wdtrainA(il, i)  !   Pm  RomP
-            ELSE
-              wdtrain(il) = wdtrain(il) + 10.0*awat*ment(il, j, i)
-              wdtrainM(il, i) = wdtrain(il)/10. - wdtrainA(il, i)   !   Pm  RomP
-            END IF
+            wdtrain(il) = wdtrain(il) + grav*awat*ment(il, j, i)
+            wdtrainM(il, i) = wdtrain(il)/grav - wdtrainS(il, i)    !   Pm  jyg
+!!            wdtrainM(il, i) = wdtrain(il)/grav - wdtrainA(il, i)  !   Pm  RomP
           END IF
         END DO
@@ -2543,4 +2934,35 @@
     END IF
 
+    IF (cvflag_prec_eject) THEN
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+      IF (adiab_ascent_mass_flux_depends_on_ejectliq) THEN
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!!! Warning : this option leads to water conservation violation
+!!!           Expert only
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+          IF ( i > 1) THEN
+            DO il = 1, ncum
+              IF (i<=inb(il) .AND. lwork(il)) THEN
+                wdtrainA(il,i) = ma(il, i+1)*(qta(il, i-1)-qta(il,i))/(1. - qta(il, i-1))    !   Pa   jygprl
+                wdtrain(il) = wdtrain(il) + grav*wdtrainA(il,i)
+              END IF
+            END DO
+          ENDIF  ! ( i > 1)
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+      ELSE ! (adiab_ascent_mass_flux_depends_on_ejectliq)
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+          IF ( i > 1) THEN
+            DO il = 1, ncum
+              IF (i<=inb(il) .AND. lwork(il)) THEN
+                wdtrainA(il,i) = ma(il, i+1)*(qta(il, i-1)-qta(il,i))                        !   Pa   jygprl
+                wdtrain(il) = wdtrain(il) + grav*wdtrainA(il,i)
+              END IF
+            END DO
+          ENDIF  ! ( i > 1)
+
+      ENDIF ! (adiab_ascent_mass_flux_depends_on_ejectliq) ELSE
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+    ENDIF  ! (cvflag_prec_eject)
+
 
 ! ***    find rain water and evaporation using provisional   ***
@@ -2548,4 +2970,36 @@
 
 
+    IF (cvflag_ice) THEN                                                                                !!jygprl
+      IF (cvflag_prec_eject) THEN
+        DO il = 1, ncum                                                                                   !!jygprl
+          IF (i<=inb(il) .AND. lwork(il)) THEN                                                            !!jygprl
+            frac(il, i) = (frac_a(il,i)*wdtrainA(il,i)+frac_s(il,i)*(wdtrainS(il,i)+wdtrainM(il,i))) / &  !!jygprl
+                          max(wdtrainA(il,i)+wdtrainS(il,i)+wdtrainM(il,i),smallestreal)                  !!jygprl
+            fraci(il, i) = frac(il, i)                                                                    !!jygprl
+          END IF                                                                                          !!jygprl
+        END DO                                                                                            !!jygprl
+      ELSE  ! (cvflag_prec_eject)
+        DO il = 1, ncum                                                                                   !!jygprl
+          IF (i<=inb(il) .AND. lwork(il)) THEN                                                            !!jygprl
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+            IF (keepbug_ice_frac) THEN
+              frac(il, i) = frac_s(il, i)
+!       Ice fraction computed again here as a function of the temperature seen by unsaturated downdraughts
+!       (i.e. the cold pool temperature) for compatibility with earlier versions.
+              fraci(il, i) = 1. - (t(il,i)-243.15)/(263.15-243.15)
+              fraci(il, i) = min(max(fraci(il,i),0.0), 1.0)
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+            ELSE  ! (keepbug_ice_frac)
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+              frac(il, i) = frac_s(il, i)
+              fraci(il, i) = frac(il, i)                                                                    !!jygprl
+            ENDIF  ! (keepbug_ice_frac)
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+          END IF                                                                                          !!jygprl
+        END DO                                                                                            !!jygprl
+      ENDIF  ! (cvflag_prec_eject)
+    END IF                                                                                              !!jygprl
+
+
     DO il = 1, ncum
       IF (i<=inb(il) .AND. lwork(il)) THEN
@@ -2553,29 +3007,9 @@
         wt(il, i) = 45.0
 
-        IF (cvflag_ice) THEN
-          frac(il, inb(il)) = 1. - (t(il,inb(il))-243.15)/(263.15-243.15)
-          frac(il, inb(il)) = min(max(frac(il,inb(il)),0.), 1.)
-          fraci(il, inb(il)) = frac(il, inb(il))
-        ELSE
-          CONTINUE
-        END IF
-
         IF (i<inb(il)) THEN
-
-          IF (cvflag_ice) THEN
-!CR:tmax_fonte_cv: T for which ice is totally melted (used to be 275.15)
-            thaw = (t(il,i)-273.15)/(tmax_fonte_cv-273.15)
-            thaw = min(max(thaw,0.0), 1.0)
-            frac(il, i) = frac(il, i)*(1.-thaw)
-          ELSE
-            CONTINUE
-          END IF
-
           rp(il, i) = rp(il, i+1) + &
                       (cpd*(t(il,i+1)-t(il,i))+gz(il,i+1)-gz(il,i))/lv(il, i)
           rp(il, i) = 0.5*(rp(il,i)+rr(il,i))
         END IF
-        fraci(il, i) = 1. - (t(il,i)-243.15)/(263.15-243.15)
-        fraci(il, i) = min(max(fraci(il,i),0.0), 1.0)
         rp(il, i) = max(rp(il,i), 0.0)
         rp(il, i) = amin1(rp(il,i), rs(il,i))
@@ -2998,4 +3432,5 @@
 
   RETURN
+
 END SUBROUTINE cv3_unsat
 
@@ -3004,5 +3439,5 @@
                      t, rr, t_wake, rr_wake, s_wake, u, v, tra, &
                      gz, p, ph, h, hp, lv, lf, cpn, th, th_wake, &
-                     ep, clw, m, tp, mp, rp, up, vp, trap, &
+                     ep, clw, qpreca, m, tp, mp, rp, up, vp, trap, &
                      wt, water, ice, evap, fondue, faci, b, sigd, &
                      ment, qent, hent, iflag_mix, uent, vent, &
@@ -3014,5 +3449,5 @@
 !!                     tls, tps,                             ! useless . jyg
                      qcondc, wd, &
-                     ftd, fqd, qnk, qtc, sigt, tau_cld_cv, coefw_cld_cv)
+                     ftd, fqd, qta, qtc, sigt, tau_cld_cv, coefw_cld_cv)
 
     USE print_control_mod, ONLY: lunout, prt_level
@@ -3054,5 +3489,7 @@
       REAL, DIMENSION (nloc, na, na, ntra), INTENT (IN)  :: traent
       REAL, DIMENSION (nloc, nd), INTENT (IN)            :: tv, tvp, wghti
-      REAL,INTENT(IN)                                    :: tau_cld_cv, coefw_cld_cv
+      REAL, DIMENSION (nloc, nd), INTENT (IN)            :: qta
+      REAL, DIMENSION (nloc, na),INTENT(IN)              :: qpreca
+      REAL, INTENT(IN)                                   :: tau_cld_cv, coefw_cld_cv
 !
 !input/output:
@@ -3083,4 +3520,5 @@
       REAL                                               :: ax, bx, cx, dx, ex
       REAL                                               :: cpinv, rdcp, dpinv
+      REAL                                               :: sigaq
       REAL, DIMENSION (nloc)                             ::  awat
       REAL, DIMENSION (nloc, nd)                         :: lvcp, lfcp              ! , mke ! unused . jyg
@@ -3100,5 +3538,4 @@
       REAL, DIMENSION (nloc)                             :: sument
       REAL, DIMENSION (nloc, nd)                         :: sigment, qtment             ! cld
-      REAL, DIMENSION (nloc)                             :: qnk
       REAL sumdq !jyg
 ! 
@@ -3211,4 +3648,33 @@
   END DO
 
+! - Adiabatic ascent mass flux "ma" and cloud base mass flux "cbmf"
+!-----------------------------------------------------------------
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+  IF (adiab_ascent_mass_flux_depends_on_ejectliq) THEN
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!!! Warning : this option leads to water conservation violation
+!!!           Expert only
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+  DO il = 1, ncum
+    ma(il, nlp) = 0.
+    ma(il, 1)   = 0.
+  END DO
+  DO k = nl, 2, -1
+    DO il = 1, ncum
+      ma(il, k) = ma(il, k+1)*(1.-qta(il, k))/(1.-qta(il, k-1)) + m(il, k)
+      cbmf(il) = max(cbmf(il), ma(il,k))
+    END DO
+  END DO
+  DO k = 2,nl
+    DO il = 1, ncum
+      IF (k <icb(il)) THEN
+        ma(il, k) = ma(il, k-1) + wghti(il,k-1)*cbmf(il)
+      ENDIF
+    END DO
+  END DO
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+  ELSE ! (adiab_ascent_mass_flux_depends_on_ejectliq)
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! Line kept for compatibility with earlier versions
   DO k = 2, nl
     DO il = 1, ncum
@@ -3219,4 +3685,24 @@
   END DO
 
+  DO il = 1, ncum
+    ma(il, nlp) = 0.
+    ma(il, 1)   = 0.
+  END DO
+  DO k = nl, 2, -1
+    DO il = 1, ncum
+      ma(il, k) = ma(il, k+1) + m(il, k)
+    END DO
+  END DO
+  DO k = 2,nl
+    DO il = 1, ncum
+      IF (k <icb(il)) THEN
+        ma(il, k) = ma(il, k-1) + wghti(il,k-1)*cbmf(il)
+      ENDIF
+    END DO
+  END DO
+
+  ENDIF ! (adiab_ascent_mass_flux_depends_on_ejectliq) ELSE
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!
 !    print*,'cv3_yield avant ft'
 ! am is the part of cbmf taken from the first level
@@ -3355,14 +3841,72 @@
 !***    Compute convective mass fluxes upwd and dnwd      ***
 
+!
+! =================================================
+!              upward fluxes                      |
+! ------------------------------------------------
+!
 upwd(:,:) = 0.
 up_to(:,:) = 0.
 up_from(:,:) = 0.
-dnwd(:,:) = 0.
-dn_to(:,:) = 0.
-dn_from(:,:) = 0.
-!
-! =================================================
-!              upward fluxes                      |
-! ------------------------------------------------
+!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+  IF (adiab_ascent_mass_flux_depends_on_ejectliq) THEN
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! The decrease of the adiabatic ascent mass flux due to ejection of precipitation 
+!! is taken into account. 
+!! WARNING : in the present version, taking into account the mass-flux decrease due to 
+!! precipitation ejection leads to water conservation violation.
+!
+! - Upward mass flux of mixed draughts
+!---------------------------------------
+DO i = 2, nl
+  DO j = 1, i-1
+    DO il = 1, ncum
+      IF (i<=inb(il)) THEN
+        up_to(il,i) = up_to(il,i) + ment(il,j,i)
+      ENDIF
+    ENDDO
+  ENDDO
+ENDDO
+!
+DO j = 3, nl
+  DO i = 2, j-1
+    DO il = 1, ncum
+      IF (j<=inb(il)) THEN
+        up_from(il,i) = up_from(il,i) + ment(il,i,j)
+      ENDIF
+    ENDDO
+  ENDDO
+ENDDO
+!
+! The difference between upwd(il,i) and upwd(il,i-1) is due to updrafts ending in layer 
+!(i-1) (theses drafts cross interface (i-1) but not interface(i)) and to updrafts starting 
+!from layer (i-1) (theses drafts cross interface (i) but not interface(i-1)): 
+! 
+DO i = 2, nlp
+  DO il = 1, ncum
+    IF (i<=inb(il)+1) THEN
+      upwd(il,i) = max(0., upwd(il,i-1) - up_to(il,i-1) + up_from(il,i-1))
+    ENDIF
+  ENDDO
+ENDDO
+!
+! - Total upward mass flux
+!---------------------------
+DO i = 2, nlp
+  DO il = 1, ncum
+    IF (i<=inb(il)+1) THEN
+      upwd(il,i) = upwd(il,i) + ma(il,i)
+    ENDIF
+  ENDDO
+ENDDO
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+  ELSE ! (adiab_ascent_mass_flux_depends_on_ejectliq)
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! The decrease of the adiabatic ascent mass flux due to ejection of precipitation 
+!! is not taken into account. 
+!
+! - Upward mass flux
+!-------------------
 DO i = 2, nl
   DO il = 1, ncum
@@ -3387,6 +3931,5 @@
   ENDDO
 ENDDO
-!!DO i = 2, nl
-!!  DO j = i+1, nl          !! Permuter les boucles i et j
+!
 DO j = 3, nl
   DO i = 2, j-1
@@ -3410,8 +3953,16 @@
   ENDDO
 ENDDO
+
+
+  ENDIF ! (adiab_ascent_mass_flux_depends_on_ejectliq) ELSE
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
 !
 ! =================================================
 !              downward fluxes                    |
 ! ------------------------------------------------
+dnwd(:,:) = 0.
+dn_to(:,:) = 0.
+dn_from(:,:) = 0.
 DO i = 1, nl
   DO j = i+1, nl
@@ -3424,6 +3975,4 @@
 ENDDO
 !
-!!DO i = 2, nl
-!!  DO j = 1, i-1          !! Permuter les boucles i et j 
 DO j = 1, nl
   DO i = j+1, nl
@@ -3749,5 +4298,10 @@
     END DO ! cld
 
+!ym BIG Warning : it seems that the k loop is missing !!!
+!ym Strong advice to check this
+!ym add a k loop temporary 
+
 ! (particular case: no detraining level is found)                              ! cld
+! Verif merge Dynamico<<<<<<< .working
     DO il = 1, ncum                                                            ! cld
       IF (i<=inb(il) .AND. nent(il,i)==0 .AND. iflag(il)<=1) THEN              ! cld
@@ -3761,4 +4315,15 @@
       END IF                                                                   ! cld
     END DO                                                                     ! cld
+! Verif merge Dynamico =======
+! Verif merge Dynamico     DO k = i + 1, nl
+! Verif merge Dynamico       DO il = 1, ncum        !ym k loop added                                    ! cld
+! Verif merge Dynamico         IF (i<=inb(il) .AND. nent(il,i)==0 .AND. iflag(il)<=1) THEN              ! cld
+! Verif merge Dynamico           qcond(il, i) = qcond(il, i) + (1.-ep(il,i))*clw(il, i)                 ! cld
+! Verif merge Dynamico           qtment(il, i) = qent(il,k,i) + qtment(il,i)                          ! cld
+! Verif merge Dynamico           nqcond(il, i) = nqcond(il, i) + 1.                                     ! cld
+! Verif merge Dynamico         END IF                                                                   ! cld
+! Verif merge Dynamico       END DO
+! Verif merge Dynamico     ENDDO                                                                     ! cld
+! Verif merge Dynamico >>>>>>> .merge-right.r3413
 
     DO il = 1, ncum                                                            ! cld
@@ -4181,4 +4746,35 @@
 !!!!
 !!!!      ENDDO
+
+!!  DO i = 1, nlp
+!!    DO il = 1, ncum
+!!      ma(il, i) = 0
+!!    END DO
+!!  END DO
+!!
+!!  DO i = 1, nl
+!!    DO j = i, nl
+!!      DO il = 1, ncum
+!!        ma(il, i) = ma(il, i) + m(il, j)
+!!      END DO
+!!    END DO
+!!  END DO
+
+!jyg<  (loops stop at nl)
+!!  DO i = nl + 1, nd
+!!    DO il = 1, ncum
+!!      ma(il, i) = 0.
+!!    END DO
+!!  END DO
+!>jyg
+
+!!  DO i = 1, nl
+!!    DO il = 1, ncum
+!!      IF (i<=(icb(il)-1)) THEN
+!!        ma(il, i) = 0
+!!      END IF
+!!    END DO
+!!  END DO
+
 !-----------------------------------------------------------
         ENDIF !(.NOT.ok_optim_yield)                      !|
@@ -4205,33 +4801,4 @@
 !>jyg
 
-  DO i = 1, nlp
-    DO il = 1, ncum
-      ma(il, i) = 0
-    END DO
-  END DO
-
-  DO i = 1, nl
-    DO j = i, nl
-      DO il = 1, ncum
-        ma(il, i) = ma(il, i) + m(il, j)
-      END DO
-    END DO
-  END DO
-
-!jyg<  (loops stop at nl)
-!!  DO i = nl + 1, nd
-!!    DO il = 1, ncum
-!!      ma(il, i) = 0.
-!!    END DO
-!!  END DO
-!>jyg
-
-  DO i = 1, nl
-    DO il = 1, ncum
-      IF (i<=(icb(il)-1)) THEN
-        ma(il, i) = 0
-      END IF
-    END DO
-  END DO
 
 ! cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
@@ -4320,9 +4887,16 @@
 ! 14/01/15 AJ delta n'a rien à faire là...                                                 
     DO il = 1, ncum                                                  ! cld
-      IF (wa(il,i)>0.0 .AND. iflag(il)<=1) &                         ! cld
+!!      IF (wa(il,i)>0.0 .AND. iflag(il)<=1) &                         ! cld
+!!        siga(il, i) = mac(il, i)/(coefw_cld_cv*wa(il, i)) &          ! cld
+!!        *rrd*tvp(il, i)/p(il, i)/100.                                ! cld
+!!
+!!      siga(il, i) = min(siga(il,i), 1.0)                             ! cld
+      sigaq = 0.
+      IF (wa(il,i)>0.0 .AND. iflag(il)<=1)  THEN                     ! cld
         siga(il, i) = mac(il, i)/(coefw_cld_cv*wa(il, i)) &          ! cld
-        *rrd*tvp(il, i)/p(il, i)/100.                                ! cld
-
-      siga(il, i) = min(siga(il,i), 1.0)                             ! cld
+                     *rrd*tvp(il, i)/p(il, i)/100.                   ! cld
+        siga(il, i) = min(siga(il,i), 1.0)                           ! cld
+        sigaq = siga(il,i)*qta(il,i-1)                               ! cld
+      ENDIF
 
 ! IM cf. FH 
@@ -4336,9 +4910,10 @@
         sigment(il,i)=sument(il)*tau_cld_cv/(ph(il,i)-ph(il,i+1))    ! cld
         sigment(il, i) = min(1.e-4+sigment(il,i), 1.0 - siga(il,i))  ! cld
-        qtc(il, i) = (siga(il,i)*qnk(il)+sigment(il,i)*qtment(il,i)) & ! cld
+!!        qtc(il, i) = (siga(il,i)*qta(il,i-1)+sigment(il,i)*qtment(il,i)) & ! cld
+        qtc(il, i) = (sigaq+sigment(il,i)*qtment(il,i)) & ! cld
                      /(siga(il,i)+sigment(il,i))                     ! cld
         sigt(il,i) = sigment(il, i) + siga(il, i)
 
-!        qtc(il, i) = siga(il,i)*qnk(il)+(1.-siga(il,i))*qtment(il,i) ! cld
+!        qtc(il, i) = siga(il,i)*qta(il,i-1)+(1.-siga(il,i))*qtment(il,i) ! cld
 !     print*,'BIGAUSSIAN CONV',siga(il,i),sigment(il,i),qtc(il,i)  
       		
@@ -4629,6 +5204,6 @@
       do k=1,nl
         do i=1,ncum
-	  hp(i,k)=h(i,k)
-	enddo
+          hp(i,k)=h(i,k)
+        enddo
       enddo
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3a_uncompress.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3a_uncompress.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3a_uncompress.F90	(revision 3605)
@@ -10,6 +10,6 @@
                            asupmaxmin, &
                            da, phi, mp, phi2, d1a, dam, sigij, &                ! RomP+AC+jyg
-                           clw, elij, evap, ep, epmlmMm, eplaMm, &              ! RomP
-                           wdtrainA, wdtrainM, &                                ! RomP
+                           qta, clw, elij, evap, ep, epmlmMm, eplaMm, &         ! RomP+jyg
+                           wdtrainA, wdtrainS, wdtrainM, &                      ! RomP
                            qtc, sigt,          &
                            epmax_diag, & ! epmax_cape
@@ -24,6 +24,6 @@
                            asupmaxmin1, &
                            da1, phi1, mp1, phi21, d1a1, dam1, sigij1, &         ! RomP+AC+jyg
-                           clw1, elij1, evap1, ep1, epmlmMm1, eplaMm1, &        ! RomP
-                           wdtrainA1, wdtrainM1, &                              ! RomP
+                           qta1, clw1, elij1, evap1, ep1, epmlmMm1, eplaMm1, &  ! RomP+jyg
+                           wdtrainA1, wdtrainS1, wdtrainM1, &                   ! RomP
                            qtc1, sigt1, &
                            epmax_diag1) ! epmax_cape
@@ -75,4 +75,5 @@
   REAL, DIMENSION (nloc, nd), INTENT (IN)            :: d1a, dam               !RomP
   REAL, DIMENSION (nloc, nd, nd), INTENT (IN)        :: sigij                  !RomP
+  REAL, DIMENSION (nloc, nd), INTENT (IN)            :: qta                    !jyg
   REAL, DIMENSION (nloc, nd), INTENT (IN)            :: clw                    !RomP
   REAL, DIMENSION (nloc, nd, nd), INTENT (IN)        :: elij                   !RomP
@@ -81,5 +82,5 @@
   REAL, DIMENSION (nloc, nd), INTENT (IN)            :: eplamM                 !RomP+jyg
   REAL, DIMENSION (nloc, nd), INTENT (IN)            :: qtc, sigt              !RomP
-  REAL, DIMENSION (nloc, nd), INTENT (IN)            :: wdtrainA, wdtrainM     !RomP
+  REAL, DIMENSION (nloc, nd), INTENT (IN)            :: wdtrainA, wdtrainS, wdtrainM     !RomP
 
   ! outputs:
@@ -111,4 +112,5 @@
   REAL, DIMENSION (len, nd), INTENT (OUT)            :: d1a1, dam1 !RomP       !RomP
   REAL, DIMENSION (len, nd, nd), INTENT (OUT)        :: sigij1                 !RomP
+  REAL, DIMENSION (len, nd), INTENT (OUT)            :: qta1                   !jyg
   REAL, DIMENSION (len, nd), INTENT (OUT)            :: clw1                   !RomP
   REAL, DIMENSION (len, nd, nd), INTENT (OUT)        :: elij1                  !RomP
@@ -117,5 +119,5 @@
   REAL, DIMENSION (len, nd), INTENT (OUT)            :: eplamM1                !RomP+jyg
   REAL, DIMENSION (len, nd), INTENT (OUT)            :: qtc1, sigt1            !RomP
-  REAL, DIMENSION (len, nd), INTENT (OUT)            :: wdtrainA1, wdtrainM1   !RomP
+  REAL, DIMENSION (len, nd), INTENT (OUT)            :: wdtrainA1, wdtrainS1, wdtrainM1   !RomP
 
 
@@ -175,4 +177,5 @@
         d1a1(idcum(i), k) = d1a(i, k) !RomP
         dam1(idcum(i), k) = dam(i, k) !RomP
+        qta1(idcum(i), k) = qta(i, k) !jyg
         clw1(idcum(i), k) = clw(i, k) !RomP
         evap1(idcum(i), k) = evap(i, k) !RomP
@@ -180,4 +183,5 @@
         eplamM1(idcum(i), k) = eplamM(i, k) !RomP+jyg
         wdtrainA1(idcum(i), k) = wdtrainA(i, k) !RomP
+        wdtrainS1(idcum(i), k) = wdtrainS(i, k) !RomP
         wdtrainM1(idcum(i), k) = wdtrainM(i, k) !RomP
         qtc1(idcum(i), k) = qtc(i, k)
@@ -300,4 +304,5 @@
       d1a1(:, 1:nl) = d1a(:, 1:nl)            !RomP
       dam1(:, 1:nl) = dam(:, 1:nl)            !RomP
+      qta1(:, 1:nl) = qta(:, 1:nl)            !jyg
       clw1(:, 1:nl) = clw(:, 1:nl)            !RomP
       evap1(:, 1:nl) = evap(:, 1:nl)          !RomP
@@ -305,4 +310,5 @@
       eplamM1(:, 1:nl) = eplamM(:, 1:nl)       !RomP+jyg
       wdtrainA1(:, 1:nl) = wdtrainA(:, 1:nl)  !RomP
+      wdtrainS1(:, 1:nl) = wdtrainS(:, 1:nl)  !RomP
       wdtrainM1(:, 1:nl) = wdtrainM(:, 1:nl)  !RomP
       qtc1(:, 1:nl) = qtc(:, 1:nl)
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3p1_closure.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3p1_closure.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3p1_closure.F90	(revision 3605)
@@ -537,9 +537,9 @@
     ELSE
       ! Calculate wbeff
-      IF (flag_wb==0) THEN
+      IF (NINT(flag_wb)==0) THEN
         wbeff(il) = wbmax
-      ELSE IF (flag_wb==1) THEN
+      ELSE IF (NINT(flag_wb)==1) THEN
         wbeff(il) = wbmax/(1.+500./(ph(il,1)-plfc(il)))
-      ELSE IF (flag_wb==2) THEN
+      ELSE IF (NINT(flag_wb)==2) THEN
         wbeff(il) = wbmax*(0.01*(ph(il,1)-plfc(il)))**2
       ELSE ! Option provisoire ou le iflag_wb/10 est considere comme une vitesse
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3p2_closure.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3p2_closure.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3p2_closure.F90	(revision 3605)
@@ -23,4 +23,5 @@
   include "cvthermo.h"
   include "cv3param.h"
+  include "cvflag.h"
   include "YOMCST2.h"
   include "YOMCST.h"
@@ -608,9 +609,9 @@
     ELSE
       ! Calculate wbeff
-      IF (flag_wb==0) THEN
+      IF (NINT(flag_wb)==0) THEN
         wbeff(il) = wbmax
-      ELSE IF (flag_wb==1) THEN
+      ELSE IF (NINT(flag_wb)==1) THEN
         wbeff(il) = wbmax/(1.+500./(ph(il,1)-plfc(il)))
-      ELSE IF (flag_wb==2) THEN
+      ELSE IF (NINT(flag_wb)==2) THEN
         wbeff(il) = wbmax*(0.01*(ph(il,1)-plfc(il)))**2
       END IF
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3p_mixing.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3p_mixing.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3p_mixing.F90	(revision 3605)
@@ -1,4 +1,4 @@
 SUBROUTINE cv3p_mixing(nloc, ncum, nd, na, ntra, icb, nk, inb, &
-                       ph, t, rr, rs, u, v, tra, h, lv, lf, frac, qnk, &
+                       ph, t, rr, rs, u, v, tra, h, lv, lf, frac, qta, &
                        unk, vnk, hp, tv, tvp, ep, clw, sig, &
                        Ment, Qent, hent, uent, vent, nent, &
@@ -29,5 +29,6 @@
   INTEGER, DIMENSION (nloc), INTENT (IN)             :: icb, inb, nk
   REAL, DIMENSION (nloc, nd), INTENT (IN)            :: sig
-  REAL, DIMENSION (nloc), INTENT (IN)                :: qnk, unk, vnk
+  REAL, DIMENSION (nloc), INTENT (IN)                :: unk, vnk
+  REAL, DIMENSION (nloc, nd), INTENT (IN)            :: qta
   REAL, DIMENSION (nloc, nd+1), INTENT (IN)          :: ph
   REAL, DIMENSION (nloc, nd), INTENT (IN)            :: t, rr, rs
@@ -173,5 +174,6 @@
                            .AND. (j<=inb(il))) THEN
 
-            rti = qnk(il) - ep(il, i)*clw(il, i)
+!!            rti = qnk(il) - ep(il, i)*clw(il, i)
+            rti = qta(il,i-1) - ep(il, i)*clw(il, i)
             bf2 = 1. + lv(il, j)*lv(il, j)*rs(il, j)/(rrv*t(il,j)*t(il,j)*cpd)
 !jyg(from aj)<
@@ -219,4 +221,8 @@
             Sij(il, i, j) = amax1(0.0, Sij(il,i,j))
             Sij(il, i, j) = amin1(1.0, Sij(il,i,j))
+          ELSE IF (j > i) THEN
+            IF (prt_level >= 10) THEN
+              print *,'cv3p_mixing i, j, Sij given by the no-precip eq. ', i, j, Sij(il,i,j)
+            ENDIF
           END IF ! new
         END DO
@@ -248,5 +254,6 @@
 !!!       Ment(il,i,i)=m(il,i)
         Ment(il, i, i) = 1.
-        Qent(il, i, i) = qnk(il) - ep(il, i)*clw(il, i)
+!!        Qent(il, i, i) = qnk(il) - ep(il, i)*clw(il, i)
+        Qent(il, i, i) = qta(il,i-1) - ep(il, i)*clw(il, i)
         uent(il, i, i) = unk(il)
         vent(il, i, i) = vnk(il)
@@ -332,5 +339,6 @@
       IF (i>=icb(il) .AND. i<=inb(il)) THEN
         lwork(il) = (nent(il,i)/=0)
-        rti = qnk(il) - ep(il, i)*clw(il, i)
+!!        rti = qnk(il) - ep(il, i)*clw(il, i)
+        rti = qta(il,i-1) - ep(il, i)*clw(il, i)
 !jyg<
         IF (cvflag_ice) THEN
@@ -462,5 +470,6 @@
             lwork(il)) THEN
           IF (Sij(il,i,j)>0.0) THEN
-            rti = qnk(il) - ep(il, i)*clw(il, i)
+!!            rti = qnk(il) - ep(il, i)*clw(il, i)
+            rti = qta(il,i-1) - ep(il, i)*clw(il, i)
             Qmixmax(il) = Qmix(Sjmax(il))
             Qmixmin(il) = Qmix(Sjmin(il))
@@ -590,5 +599,6 @@
               lwork(il)) THEN
             IF (Sij(il,i,j)>0.0) THEN
-              rti = qnk(il) - ep(il, i)*clw(il, i)
+!!              rti = qnk(il) - ep(il, i)*clw(il, i)
+              rti = qta(il,i-1) - ep(il, i)*clw(il, i)
 !!!             Ment(il,i,i) = m(il,i)*abs(Qmixmax(il)*(1.-Sjmax(il))
               Ment(il, i, i) = abs(Qmixmax(il)*(1.-Sjmax(il))+Rmixmax(il) - &
@@ -659,5 +669,6 @@
 ! cc        Ment(il,i,i)=m(il,i)
         Ment(il, i, i) = 1.
-        Qent(il, i, i) = qnk(il) - ep(il, i)*clw(il, i)
+!!        Qent(il, i, i) = qnk(il) - ep(il, i)*clw(il, i)
+        Qent(il, i, i) = qta(il,i-1) - ep(il, i)*clw(il, i)
         uent(il, i, i) = unk(il)
         vent(il, i, i) = vnk(il)
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3param.h
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3param.h	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cv3param.h	(revision 3605)
@@ -7,12 +7,8 @@
 !------------------------------------------------------------
 
-      logical ok_homo_tend
-      logical ok_optim_yield
-      logical ok_entrain
-      logical ok_convstop
-      logical ok_intermittent
+      integer flag_epKEorig
+      real flag_wb
+      integer cv_flag_feed
       integer noff, minorig, nl, nlp, nlm
-      integer cv_flag_feed
-      integer flag_epKEorig,flag_wb
       real sigdz, spfac
       real pbcrit, ptcrit
@@ -27,4 +23,6 @@
       real delta
       real betad
+      real ejectliq
+      real ejectice
 
       COMMON /cv3param/ sigdz, spfac &
@@ -39,11 +37,8 @@
                       ,wbmax &
                       ,delta, betad  &
+                      ,ejectliq, ejectice &
                       ,flag_epKEorig &
                       ,flag_wb, cv_flag_feed &
-                      ,noff, minorig, nl, nlp, nlm  &
-                      ,ok_convstop, ok_intermittent &
-                      ,ok_optim_yield &
-                      ,ok_entrain &
-                      ,ok_homo_tend
+                      ,noff, minorig, nl, nlp, nlm
 !$OMP THREADPRIVATE(/cv3param/)
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cv_driver.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cv_driver.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cv_driver.F90	(revision 3605)
@@ -568,5 +568,5 @@
                 ,cape,ep,hp,icb,inb,clw,nk,t,h,lv &
                 ,epmax_diag)
-        ! on écrase ep et recalcule hp
+        ! on Ã©crase ep et recalcule hp
     END IF
 
@@ -681,4 +681,7 @@
 ! ==================================================================
 SUBROUTINE cv_flag(iflag_ice_thermo)
+
+  USE ioipsl_getin_p_mod, ONLY : getin_p
+
   IMPLICIT NONE
 
@@ -693,4 +696,17 @@
   cvflag_grav = .TRUE.
   cvflag_ice = iflag_ice_thermo >= 1
+  !
+! si icvflag_Tpa=0, alors la fraction de glace dans l'ascendance adiabatique est
+  ! fonction de la temperature de l'environnement et la temperature de l'ascendance est 
+  ! calculee en deux itérations, une en supposant qu'il n'y a pas de glace et l'autre 
+  ! en ajoutant la glace (ancien schéma d'Arnaud Jam).
+! si icvflag_Tpa=1, alors la fraction de glace dans l'ascendance adiabatique est
+  ! fonction de la temperature de l'environnement et la temperature de l'ascendance est 
+  ! calculee en une seule iteration.
+! si icvflag_Tpa=2, alors la fraction de glace dans l'ascendance adiabatique est
+  ! fonction de la temperature de l'ascendance et la temperature de l'ascendance est 
+  ! calculee en une seule iteration.
+  icvflag_Tpa=0  
+  call getin_p('icvflag_Tpa', icvflag_Tpa)
 
   RETURN
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cva_driver.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cva_driver.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cva_driver.F90	(revision 3605)
@@ -25,6 +25,6 @@
 !!                      elij1,evap1,ep1,epmlmMm1,eplaMm1, &                ! RomP
                       da1, phi1, mp1, phi21, d1a1, dam1, sigij1, wghti1, & ! RomP, RL
-                      clw1, elij1, evap1, ep1, epmlmMm1, eplaMm1, &        ! RomP, RL
-                      wdtrainA1, wdtrainM1, qtc1, sigt1, tau_cld_cv, &
+                      qta1, clw1, elij1, evap1, ep1, epmlmMm1, eplaMm1, &  ! RomP, RL
+                      wdtrainA1, wdtrainS1, wdtrainM1, qtc1, sigt1, tau_cld_cv, &     !!jygprl
                       coefw_cld_cv, &                                      ! RomP, AJ
                       epmax_diag1)  ! epmax_cape
@@ -124,5 +124,7 @@
 !                                      of dimension ND, defined at same grid levels as T, Q, QS and P.
 
-! wdtrainA1     Real           Output   precipitation detrained from adiabatic draught;
+! wdtrainA1     Real           Output   precipitation ejected from adiabatic draught;
+!                                         should be used in tracer transport (cvltr)
+! wdtrainS1     Real           Output   precipitation detrained from shedding of adiabatic draught;
 !                                         used in tracer transport (cvltr)
 ! wdtrainM1     Real           Output   precipitation detrained from mixed draughts;
@@ -248,5 +250,5 @@
 
 ! RomP >>>
-  REAL, DIMENSION (len, nd), INTENT (OUT)            :: wdtrainA1, wdtrainM1 ! precipitation sources (extensive)
+  REAL, DIMENSION (len, nd), INTENT (OUT)            :: wdtrainA1, wdtrainS1, wdtrainM1 ! precipitation sources (extensive)
   REAL, DIMENSION (len, nd), INTENT (OUT)            :: mp1  ! unsat. mass flux (staggered grid)
   REAL, DIMENSION (len, nd), INTENT (OUT)            :: da1  ! detrained mass flux of adiab. asc. air (extensive)
@@ -258,4 +260,5 @@
   REAL, DIMENSION (len, nd, nd), INTENT (OUT)        :: sigij1 ! mass fraction of env. air in mixed draughts (intensive) 
   REAL, DIMENSION (len, nd, nd), INTENT (OUT)        :: elij1! cond. water per unit mass of mixed draughts (intensive) 
+  REAL, DIMENSION (len, nd), INTENT (OUT)            :: qta1 ! total water per unit mass of the adiab. asc. (intensive)
   REAL, DIMENSION (len, nd), INTENT (OUT)            :: clw1 ! cond. water per unit mass of the adiab. asc. (intensive) 
 !JYG,RL
@@ -467,4 +470,5 @@
   REAL tv_wake(nloc, nd)
   REAL clw(nloc, nd)
+  REAL, DIMENSION(nloc, nd)    :: qta, qpreca                       !!jygprl
   REAL dph(nloc, nd)
   REAL pbase(nloc), buoybase(nloc), th(nloc, nd)
@@ -477,4 +481,5 @@
   REAL cin(nloc)
   REAL m(nloc, nd)
+  REAL mm(nloc, nd)
   REAL ment(nloc, nd, nd), sigij(nloc, nd, nd)
   REAL qent(nloc, nd, nd)
@@ -494,5 +499,5 @@
   REAL, DIMENSION(len,nd)     :: wt, water, evap
   REAL, DIMENSION(len,nd)     :: ice, fondue, b
-  REAL, DIMENSION(len,nd)     :: frac, faci
+  REAL, DIMENSION(len,nd)     :: frac_a, frac_s, faci               !!jygprl
   REAL ft(nloc, nd), fq(nloc, nd)
   REAL ftd(nloc, nd), fqd(nloc, nd)
@@ -523,5 +528,5 @@
  
 ! RomP >>>
-  REAL wdtrainA(nloc, nd), wdtrainM(nloc, nd)
+  REAL wdtrainA(nloc, nd), wdtrainS(nloc, nd), wdtrainM(nloc, nd)   !!jygprl
   REAL da(len, nd), phi(len, nd, nd)
   REAL epmlmMm(nloc, nd, nd), eplaMm(nloc, nd)
@@ -613,4 +618,7 @@
   asupmaxmin1(:) = 0.
 
+  tvp(:, :) = 0. !ym missing init, need to have a look by developpers
+  tv(:, :) = 0. !ym missing init, need to have a look by developpers
+
   DO il = 1, len
     cin1(il) = -100000.
@@ -633,4 +641,5 @@
   qtc1(:, :) = 0.
   wdtrainA1(:, :) = 0.
+  wdtrainS1(:, :) = 0.
   wdtrainM1(:, :) = 0.
   da1(:, :) = 0.
@@ -643,4 +652,5 @@
   sigij1(:, :, :) = 0.
   elij1(:, :, :) = 0.
+  qta1(:,:) = 0.
   clw1(:,:) = 0.
   wghti1(:,:) = 0.
@@ -903,5 +913,5 @@
                          p, ph, h, tv, lv, lf, pbase, buoybase, plcl, &
                          inb, tp, tvp, clw, hp, ep, sigp, buoy, &
-                         frac)
+                         frac_a, frac_s, qpreca, qta)                        !!jygprl
     END IF
 
@@ -912,5 +922,5 @@
                         tnk, qnk, gznk, t, q, qs, gz, &
                         p, dph, h, tv, lv, &
-                        inb, inbis, tp, tvp, clw, hp, ep, sigp, frac)
+                        inb, inbis, tp, tvp, clw, hp, ep, sigp, frac_s)
     END IF
 
@@ -920,5 +930,5 @@
              PRINT *, 'cva_driver -> cv3_epmax_cape'
     call cv3_epmax_fn_cape(nloc,ncum,nd &
-                , ep,hp,icb,inb,clw,nk,t,h,hnk,lv,lf,frac &
+                , ep,hp,icb,inb,clw,nk,t,h,hnk,lv,lf,frac_s &
                 , pbase, p, ph, tv, buoy, sig, w0,iflag &
                 , epmax_diag)
@@ -938,5 +948,6 @@
              PRINT *, 'cva_driver -> cv3p_mixing'
         CALL cv3p_mixing(nloc, ncum, nd, nd, ntra, icb, nk, inb, &           ! na->nd
-                         ph, t, q, qs, u, v, tra, h, lv, lf, frac, qnk, &
+!!                         ph, t, q, qs, u, v, tra, h, lv, lf, frac, qnk, &
+                         ph, t, q, qs, u, v, tra, h, lv, lf, frac_s, qta, &      !!jygprl
                          unk, vnk, hp, tv, tvp, ep, clw, sig, &
                          ment, qent, hent, uent, vent, nent, &
@@ -1018,10 +1029,16 @@
              PRINT *, 'cva_driver -> cv3_mixing'
         CALL cv3_mixing(nloc, ncum, nd, nd, ntra, icb, nk, inb, &             ! na->nd
-                        ph, t, q, qs, u, v, tra, h, lv, lf, frac, qnk, &
+                        ph, t, q, qs, u, v, tra, h, lv, lf, frac_s, qnk, &
                         unk, vnk, hp, tv, tvp, ep, clw, m, sig, &
                         ment, qent, uent, vent, nent, sigij, elij, ments, qents, traent)
         CALL zilch(hent, nloc*nd*nd)
       ELSE
-        CALL cv3_mixscale(nloc, ncum, nd, ment, m)
+!!jyg:  Essais absurde pour voir
+!!        mm(:,1) = 0.
+!!        DO  i = 2,nd
+!!          mm(:,i) = m(:,i)*(1.-qta(:,i-1))
+!!        ENDDO
+        mm(:,:) = m(:,:)
+        CALL cv3_mixscale(nloc, ncum, nd, ment, mm)
         IF (debut) THEN
           PRINT *, ' cv3_mixscale-> '
@@ -1059,9 +1076,10 @@
                      t_wake, q_wake, qs_wake, gz, u, v, tra, p, ph, &
                      th_wake, tv_wake, lv_wake, lf_wake, cpn_wake, &
-                     ep, sigp, clw, &
+                     ep, sigp, clw, frac_s, qpreca, frac_a, qta, &                    !!jygprl
                      m, ment, elij, delt, plcl, coef_clos, &
                      mp, qp, up, vp, trap, wt, water, evap, fondue, ice, &
                      faci, b, sigd, &
-                     wdtrainA, wdtrainM)                                       ! RomP
+!!                     wdtrainA, wdtrainM)                                       ! RomP
+                     wdtrainA, wdtrainS, wdtrainM)                               !!jygprl
 !
       IF (prt_level >= 10) THEN
@@ -1072,8 +1090,8 @@
            evap(igout,k), fondue(igout,k)
         ENDDO
-        Print *, 'cva_driver after cv3_unsat: wdtrainA, wdtrainM '
+        Print *, 'cva_driver after cv3_unsat: wdtrainA, wdtrainS, wdtrainM '     !!jygprl
         DO k = 1,nd
-        write (6, '(i4,2(1x,e13.6))'), &
-           k, wdtrainA(igout,k), wdtrainM(igout,k)
+        write (6, '(i4,3(1x,e13.6))'), &
+           k, wdtrainA(igout,k), wdtrainS(igout,k), wdtrainM(igout,k)            !!jygprl
         ENDDO
       ENDIF
@@ -1109,5 +1127,5 @@
                      t, q, t_wake, q_wake, s_wake, u, v, tra, &
                      gz, p, ph, h, hp, lv, lf, cpn, th, th_wake, &
-                     ep, clw, m, tp, mp, qp, up, vp, trap, &
+                     ep, clw, qpreca, m, tp, mp, qp, up, vp, trap, &
                      wt, water, ice, evap, fondue, faci, b, sigd, &
                      ment, qent, hent, iflag_mix, uent, vent, &
@@ -1118,5 +1136,8 @@
 !!                     tls, tps, &                            ! useless . jyg
                      qcondc, wd, &
-                     ftd, fqd, qnk, qtc, sigt, tau_cld_cv, coefw_cld_cv)
+!!                     ftd, fqd, qnk, qtc, sigt, tau_cld_cv, coefw_cld_cv)
+                     ftd, fqd, qta, qtc, sigt, tau_cld_cv, coefw_cld_cv)         !!jygprl
+!
+!         Test conseravtion de l'eau
 !
       IF (debut) THEN
@@ -1139,5 +1160,5 @@
                      t, q, u, v, &
                      gz, p, ph, h, hp, lv, cpn, &
-                     ep, clw, frac, m, mp, qp, up, vp, &
+                     ep, clw, frac_s, m, mp, qp, up, vp, &
                      wt, water, evap, &
                      ment, qent, uent, vent, nent, elij, &
@@ -1184,6 +1205,6 @@
                            asupmaxmin, &
                            da, phi, mp, phi2, d1a, dam, sigij, &         ! RomP
-                           clw, elij, evap, ep, epmlmMm, eplaMm, &       ! RomP
-                           wdtrainA, wdtrainM, &                         ! RomP
+                           qta, clw, elij, evap, ep, epmlmMm, eplaMm, &  ! RomP
+                           wdtrainA, wdtrainS, wdtrainM, &                         ! RomP
                            qtc, sigt, epmax_diag, & ! epmax_cape
                            iflag1, kbas1, ktop1, &
@@ -1196,7 +1217,7 @@
                            Plim11, plim21, asupmax1, supmax01, &
                            asupmaxmin1, &
-                           da1, phi1, mp1, phi21, d1a1, dam1, sigij1,  & ! RomP
-                           clw1, elij1, evap1, ep1, epmlmMm1, eplaMm1, & ! RomP
-                           wdtrainA1, wdtrainM1,                       & ! RomP
+                           da1, phi1, mp1, phi21, d1a1, dam1, sigij1,  &       ! RomP
+                           qta1, clw1, elij1, evap1, ep1, epmlmMm1, eplaMm1, & ! RomP
+                           wdtrainA1, wdtrainS1, wdtrainM1,                  & ! RomP
                            qtc1, sigt1, epmax_diag1) ! epmax_cape
 !   
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/cvflag.h
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/cvflag.h	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/cvflag.h	(revision 3605)
@@ -4,5 +4,24 @@
       logical cvflag_grav
       logical cvflag_ice
+      logical ok_optim_yield
+      logical ok_entrain
+      logical ok_homo_tend
+      logical ok_convstop
+      logical ok_intermittent
+      logical cvflag_prec_eject
+      logical qsat_depends_on_qt
+      logical adiab_ascent_mass_flux_depends_on_ejectliq
+      logical keepbug_ice_frac
+      integer icvflag_Tpa
 
-      COMMON /cvflag/ cvflag_grav, cvflag_ice  
+      COMMON /cvflag/ icvflag_Tpa, &
+                      cvflag_grav, cvflag_ice, &
+                      ok_optim_yield, &
+                      ok_entrain, &
+                      ok_homo_tend, &
+                      ok_convstop, ok_intermittent, &
+                      cvflag_prec_eject, &
+                      qsat_depends_on_qt, &
+                      adiab_ascent_mass_flux_depends_on_ejectliq, &
+                      keepbug_ice_frac
 !$OMP THREADPRIVATE(/cvflag/)
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/dimphy.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/dimphy.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/dimphy.F90	(revision 3605)
@@ -1,3 +1,6 @@
-MODULE dimphy
+!
+! $Id$
+!
+  MODULE dimphy
   
   INTEGER,SAVE :: klon
@@ -33,7 +36,27 @@
 !$OMP END MASTER    
     ALLOCATE(zmasq(klon))    
+    zmasq=0.
     
   END SUBROUTINE Init_dimphy
 
+  SUBROUTINE Init_dimphy1D(klon0,klev0)
+! 1D special version of dimphy without ALLOCATE(zmasq)
+! which will be allocated in iniphysiq
+  IMPLICIT NONE
+  
+    INTEGER, INTENT(in) :: klon0
+    INTEGER, INTENT(in) :: klev0
+    
+    klon=klon0
+    kdlon=klon
+    kidia=1
+    kfdia=klon
+    klev=klev0
+    klevp1=klev+1
+    klevm1=klev-1
+    kflev=klev
+    
+  END SUBROUTINE Init_dimphy1D
+
   
 END MODULE dimphy
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/1DUTILS.h
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/1DUTILS.h	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/1DUTILS.h	(revision 3605)
@@ -2,5 +2,5 @@
 
 !
-! $Id: conf_unicol.F 1279 2010-08-04 17:20:56Z lahellec $
+! $Id$
 !
 !
@@ -540,10 +540,21 @@
        CALL getin('nudging_w',nudging_w)
 
+! RELIQUE ANCIENS FORMAT. ECRASE PAR LE SUIVANT
 !Config  Key  = nudging_q
 !Config  Desc = forcage ou non par nudging sur q
 !Config  Def  = false
 !Config  Help = forcage ou non par nudging sur q
-       nudging_q =0
-       CALL getin('nudging_q',nudging_q)
+       nudging_qv =0
+       CALL getin('nudging_q',nudging_qv)
+       CALL getin('nudging_qv',nudging_qv)
+
+       p_nudging_u=11000.
+       p_nudging_v=11000.
+       p_nudging_t=11000.
+       p_nudging_qv=11000.
+       CALL getin('p_nudging_u',p_nudging_u)
+       CALL getin('p_nudging_v',p_nudging_v)
+       CALL getin('p_nudging_t',p_nudging_t)
+       CALL getin('p_nudging_qv',p_nudging_qv)
 
 !Config  Key  = nudging_t
@@ -599,5 +610,5 @@
       write(lunout,*)' nudging_v  = ', nudging_v
       write(lunout,*)' nudging_t  = ', nudging_t
-      write(lunout,*)' nudging_q  = ', nudging_q
+      write(lunout,*)' nudging_qv  = ', nudging_qv
       IF (forcing_type .eq.40) THEN
         write(lunout,*) '--- Forcing type GCSS Old --- with:'
@@ -814,7 +825,5 @@
       character*80 abort_message
 !
-      INTEGER nb
-      SAVE nb
-      DATA nb / 0 /
+      INTEGER pass
 
       CALL open_restartphy(fichnom)
@@ -828,10 +837,10 @@
       ENDDO
 
-      modname = 'dyn1dredem'
-      ierr = NF_OPEN(fichnom, NF_WRITE, nid)
-      IF (ierr .NE. NF_NOERR) THEN
-         abort_message="Pb. d ouverture "//fichnom
-         CALL abort_gcm('Modele 1D',abort_message,1)
-      ENDIF
+!     modname = 'dyn1dredem'
+!     ierr = NF_OPEN(fichnom, NF_WRITE, nid)
+!     IF (ierr .NE. NF_NOERR) THEN
+!        abort_message="Pb. d ouverture "//fichnom
+!        CALL abort_gcm('Modele 1D',abort_message,1)
+!     ENDIF
 
       DO l=1,length
@@ -885,28 +894,32 @@
        tab_cntrl(31) = FLOAT(itau_dyn + itaufin)
 !
-      CALL put_var("controle","Param. de controle Dyn1D",tab_cntrl)
+      DO pass=1,2
+      CALL put_var(pass,"controle","Param. de controle Dyn1D",tab_cntrl)
 !
 
 !  Ecriture/extension de la coordonnee temps
 
-      nb = nb + 1
 
 !  Ecriture des champs
 !
-      CALL put_field("plev","p interfaces sauf la nulle",plev)
-      CALL put_field("play","",play)
-      CALL put_field("phi","geopotentielle",phi)
-      CALL put_field("phis","geopotentiell de surface",phis)
-      CALL put_field("presnivs","",presnivs)
-      CALL put_field("ucov","",ucov)
-      CALL put_field("vcov","",vcov)
-      CALL put_field("temp","",temp)
-      CALL put_field("omega2","",omega2)
+      CALL put_field(pass,"plev","p interfaces sauf la nulle",plev)
+      CALL put_field(pass,"play","",play)
+      CALL put_field(pass,"phi","geopotentielle",phi)
+      CALL put_field(pass,"phis","geopotentiell de surface",phis)
+      CALL put_field(pass,"presnivs","",presnivs)
+      CALL put_field(pass,"ucov","",ucov)
+      CALL put_field(pass,"vcov","",vcov)
+      CALL put_field(pass,"temp","",temp)
+      CALL put_field(pass,"omega2","",omega2)
 
       Do iq=1,nqtot
-        CALL put_field("q"//nmq(iq),"eau vap ou condens et traceurs",           &
+        CALL put_field(pass,"q"//nmq(iq),"eau vap ou condens et traceurs",           &
      &                                                      q(:,:,iq))
       EndDo
-      CALL close_restartphy
+    IF (pass==1) CALL enddef_restartphy
+    IF (pass==2) CALL close_restartphy
+
+
+      ENDDO
 
 !
@@ -1458,3383 +1471,4 @@
 
 !======================================================================
-      SUBROUTINE read_togacoare(fich_toga,nlev_toga,nt_toga                     &
-     &             ,ts_toga,plev_toga,t_toga,q_toga,u_toga,v_toga,w_toga        &
-     &             ,ht_toga,vt_toga,hq_toga,vq_toga)
-      implicit none
-
-!-------------------------------------------------------------------------
-! Read TOGA-COARE forcing data 
-!-------------------------------------------------------------------------
-
-      integer nlev_toga,nt_toga
-      real ts_toga(nt_toga),plev_toga(nlev_toga,nt_toga)
-      real t_toga(nlev_toga,nt_toga),q_toga(nlev_toga,nt_toga)
-      real u_toga(nlev_toga,nt_toga),v_toga(nlev_toga,nt_toga)
-      real w_toga(nlev_toga,nt_toga)
-      real ht_toga(nlev_toga,nt_toga),vt_toga(nlev_toga,nt_toga)
-      real hq_toga(nlev_toga,nt_toga),vq_toga(nlev_toga,nt_toga)
-      character*80 fich_toga
-
-      integer k,ip
-      real bid
-
-      integer iy,im,id,ih
-      
-       real plev_min
-
-       plev_min = 55.  ! pas de tendance de vap. d eau au-dessus de 55 hPa
-
-      open(21,file=trim(fich_toga),form='formatted')
-      read(21,'(a)') 
-      do ip = 1, nt_toga
-      read(21,'(a)') 
-      read(21,'(a)') 
-      read(21,223) iy, im, id, ih, bid, ts_toga(ip), bid,bid,bid,bid
-      read(21,'(a)') 
-      read(21,'(a)') 
-
-       do k = 1, nlev_toga
-         read(21,230) plev_toga(k,ip), t_toga(k,ip), q_toga(k,ip)          &
-     &       ,u_toga(k,ip), v_toga(k,ip), w_toga(k,ip)                     &
-     &       ,ht_toga(k,ip), vt_toga(k,ip), hq_toga(k,ip), vq_toga(k,ip)
-
-! conversion in SI units:
-         t_toga(k,ip)=t_toga(k,ip)+273.15     ! K
-         q_toga(k,ip)=q_toga(k,ip)*0.001      ! kg/kg
-         w_toga(k,ip)=w_toga(k,ip)*100./3600. ! Pa/s
-! no water vapour tendency above 55 hPa
-         if (plev_toga(k,ip) .lt. plev_min) then
-          q_toga(k,ip) = 0.
-          hq_toga(k,ip) = 0.
-          vq_toga(k,ip) =0.
-         endif
-       enddo
-
-         ts_toga(ip)=ts_toga(ip)+273.15       ! K
-       enddo
-       close(21)
-
-  223 format(4i3,6f8.2)
-  230 format(6f9.3,4e11.3)
-
-          return
-          end
-
-!-------------------------------------------------------------------------
-      SUBROUTINE read_sandu(fich_sandu,nlev_sandu,nt_sandu,ts_sandu)
-      implicit none
-
-!-------------------------------------------------------------------------
-! Read I.SANDU case forcing data
-!-------------------------------------------------------------------------
-
-      integer nlev_sandu,nt_sandu
-      real ts_sandu(nt_sandu)
-      character*80 fich_sandu
-
-      integer ip
-      integer iy,im,id,ih
-
-      real plev_min
-
-      print*,'nlev_sandu',nlev_sandu
-      plev_min = 55000.  ! pas de tendance de vap. d eau au-dessus de 55 hPa
-
-      open(21,file=trim(fich_sandu),form='formatted')
-      read(21,'(a)')
-      do ip = 1, nt_sandu
-      read(21,'(a)')
-      read(21,'(a)')
-      read(21,223) iy, im, id, ih, ts_sandu(ip)
-      print *,'ts=',iy,im,id,ih,ip,ts_sandu(ip)
-      enddo
-      close(21)
-
-  223 format(4i3,f8.2)
-
-          return
-          end
-
-!=====================================================================
-!-------------------------------------------------------------------------
-      SUBROUTINE read_astex(fich_astex,nlev_astex,nt_astex,div_astex,      &
-     & ts_astex,ug_astex,vg_astex,ufa_astex,vfa_astex)
-      implicit none
-
-!-------------------------------------------------------------------------
-! Read Astex case forcing data
-!-------------------------------------------------------------------------
-
-      integer nlev_astex,nt_astex
-      real div_astex(nt_astex),ts_astex(nt_astex),ug_astex(nt_astex)
-      real vg_astex(nt_astex),ufa_astex(nt_astex),vfa_astex(nt_astex)
-      character*80 fich_astex
-
-      integer ip
-      integer iy,im,id,ih
-
-       real plev_min
-
-      print*,'nlev_astex',nlev_astex
-       plev_min = 55000.  ! pas de tendance de vap. d eau au-dessus de 55 hPa
-
-      open(21,file=trim(fich_astex),form='formatted')
-      read(21,'(a)')
-      read(21,'(a)')
-      do ip = 1, nt_astex
-      read(21,'(a)')
-      read(21,'(a)')
-      read(21,223) iy, im, id, ih, div_astex(ip),ts_astex(ip),             &
-     &ug_astex(ip),vg_astex(ip),ufa_astex(ip),vfa_astex(ip)
-      ts_astex(ip)=ts_astex(ip)+273.15
-      print *,'ts=',iy,im,id,ih,ip,div_astex(ip),ts_astex(ip),             &
-     &ug_astex(ip),vg_astex(ip),ufa_astex(ip),vg_astex(ip)
-      enddo
-      close(21)
-
-  223 format(4i3,e13.2,f7.2,f7.3,f7.2,f7.3,f7.2)
-
-          return
-          end
-!=====================================================================
-      subroutine read_twpice(fich_twpice,nlevel,ntime                       &
-     &     ,T_srf,plev,T,q,u,v,omega                                       &
-     &     ,T_adv_h,T_adv_v,q_adv_h,q_adv_v)
-
-!program reading forcings of the TWP-ICE experiment
-
-!      use netcdf
-
-      implicit none
-
-#include "netcdf.inc"
-
-      integer ntime,nlevel
-      integer l,k
-      character*80 :: fich_twpice
-      real*8 time(ntime)
-      real*8 lat, lon, alt, phis
-      real*8 lev(nlevel)
-      real*8 plev(nlevel,ntime)
-
-      real*8 T(nlevel,ntime)
-      real*8 q(nlevel,ntime),u(nlevel,ntime)
-      real*8 v(nlevel,ntime)
-      real*8 omega(nlevel,ntime), div(nlevel,ntime)
-      real*8 T_adv_h(nlevel,ntime)
-      real*8 T_adv_v(nlevel,ntime), q_adv_h(nlevel,ntime)
-      real*8 q_adv_v(nlevel,ntime)
-      real*8 s(nlevel,ntime), s_adv_h(nlevel,ntime)
-      real*8 s_adv_v(nlevel,ntime)
-      real*8 p_srf_aver(ntime), p_srf_center(ntime)
-      real*8 T_srf(ntime)
-
-      integer nid, ierr
-      integer nbvar3d
-      parameter(nbvar3d=20)
-      integer var3didin(nbvar3d)
-
-      ierr = NF_OPEN(fich_twpice,NF_NOWRITE,nid)
-      if (ierr.NE.NF_NOERR) then
-         write(*,*) 'ERROR: Pb opening forcings cdf file '
-         write(*,*) NF_STRERROR(ierr)
-         stop ""
-      endif
-
-      ierr=NF_INQ_VARID(nid,"lat",var3didin(1))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'lat'
-         endif
-      
-       ierr=NF_INQ_VARID(nid,"lon",var3didin(2))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'lon'
-         endif
-
-       ierr=NF_INQ_VARID(nid,"alt",var3didin(3))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'alt'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"phis",var3didin(4))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'phis'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"T",var3didin(5))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'T'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"q",var3didin(6))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'q'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"u",var3didin(7))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'u'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"v",var3didin(8))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'v'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"omega",var3didin(9))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'omega'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"div",var3didin(10))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'div'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"T_adv_h",var3didin(11))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'T_adv_h'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"T_adv_v",var3didin(12))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'T_adv_v'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"q_adv_h",var3didin(13))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'q_adv_h'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"q_adv_v",var3didin(14))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'q_adv_v'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"s",var3didin(15))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 's'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"s_adv_h",var3didin(16))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 's_adv_h'
-         endif
-    
-      ierr=NF_INQ_VARID(nid,"s_adv_v",var3didin(17))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 's_adv_v'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"p_srf_aver",var3didin(18))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'p_srf_aver'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"p_srf_center",var3didin(19))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'p_srf_center'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"T_srf",var3didin(20))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'T_srf'
-         endif
-
-!dimensions lecture
-      call catchaxis(nid,ntime,nlevel,time,lev,ierr)
-
-!pressure 
-       do l=1,ntime
-       do k=1,nlevel
-          plev(k,l)=lev(k)
-       enddo
-       enddo
-          
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(1),lat)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(1),lat)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!         write(*,*)'lecture lat ok',lat
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(2),lon)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(2),lon)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!         write(*,*)'lecture lon ok',lon
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(3),alt)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(3),alt)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture alt ok',alt
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(4),phis)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(4),phis)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture phis ok',phis
-          
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(5),T)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(5),T)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!         write(*,*)'lecture T ok'
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(6),q)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(6),q)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!         write(*,*)'lecture q ok'
-!q in kg/kg
-       do l=1,ntime
-       do k=1,nlevel
-          q(k,l)=q(k,l)/1000.
-       enddo
-       enddo
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(7),u)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(7),u)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!         write(*,*)'lecture u ok'
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(8),v)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(8),v)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!         write(*,*)'lecture v ok'
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(9),omega)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(9),omega)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!         write(*,*)'lecture omega ok'
-!omega in mb/hour
-       do l=1,ntime
-       do k=1,nlevel
-          omega(k,l)=omega(k,l)*100./3600.
-       enddo
-       enddo
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(10),div)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(10),div)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!         write(*,*)'lecture div ok'
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(11),T_adv_h)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(11),T_adv_h)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!         write(*,*)'lecture T_adv_h ok'
-!T adv in K/s
-       do l=1,ntime
-       do k=1,nlevel
-          T_adv_h(k,l)=T_adv_h(k,l)/3600.
-       enddo
-       enddo
-
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(12),T_adv_v)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(12),T_adv_v)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!         write(*,*)'lecture T_adv_v ok'
-!T adv in K/s
-       do l=1,ntime
-       do k=1,nlevel
-          T_adv_v(k,l)=T_adv_v(k,l)/3600.
-       enddo
-       enddo
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(13),q_adv_h)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(13),q_adv_h)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!         write(*,*)'lecture q_adv_h ok'
-!q adv in kg/kg/s
-       do l=1,ntime
-       do k=1,nlevel
-          q_adv_h(k,l)=q_adv_h(k,l)/1000./3600.
-       enddo
-       enddo
-
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(14),q_adv_v)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(14),q_adv_v)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!         write(*,*)'lecture q_adv_v ok'
-!q adv in kg/kg/s
-       do l=1,ntime
-       do k=1,nlevel
-          q_adv_v(k,l)=q_adv_v(k,l)/1000./3600.
-       enddo
-       enddo
-
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(15),s)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(15),s)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(16),s_adv_h)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(16),s_adv_h)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(17),s_adv_v)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(17),s_adv_v)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(18),p_srf_aver)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(18),p_srf_aver)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(19),p_srf_center)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(19),p_srf_center)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(20),T_srf)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(20),T_srf)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!         write(*,*)'lecture T_srf ok', T_srf
-
-         return 
-         end subroutine read_twpice
-!=====================================================================
-         subroutine catchaxis(nid,ttm,llm,time,lev,ierr)
-
-!         use netcdf
-
-         implicit none
-#include "netcdf.inc"
-         integer nid,ttm,llm
-         real*8 time(ttm)
-         real*8 lev(llm)
-         integer ierr
-
-         integer timevar,levvar
-         integer timelen,levlen
-         integer timedimin,levdimin
-
-! Control & lecture on dimensions
-! ===============================
-         ierr=NF_INQ_DIMID(nid,"time",timedimin)
-         ierr=NF_INQ_VARID(nid,"time",timevar)
-         if (ierr.NE.NF_NOERR) then
-            write(*,*) 'ERROR: Field <time> is missing'
-            stop ""  
-         endif
-         ierr=NF_INQ_DIMLEN(nid,timedimin,timelen)
-
-         ierr=NF_INQ_DIMID(nid,"lev",levdimin)
-         ierr=NF_INQ_VARID(nid,"lev",levvar)
-         if (ierr.NE.NF_NOERR) then
-             write(*,*) 'ERROR: Field <lev> is lacking'
-             stop "" 
-         endif
-         ierr=NF_INQ_DIMLEN(nid,levdimin,levlen)
-
-         if((timelen/=ttm).or.(levlen/=llm)) then
-            write(*,*) 'ERROR: Not the good lenght for axis'
-            write(*,*) 'longitude: ',timelen,ttm+1
-            write(*,*) 'latitude: ',levlen,llm
-            stop ""  
-         endif
-
-!#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,timevar,time)
-         ierr = NF_GET_VAR_DOUBLE(nid,levvar,lev)
-!#else
-!        ierr = NF_GET_VAR_REAL(nid,timevar,time)
-!        ierr = NF_GET_VAR_REAL(nid,levvar,lev)
-!#endif
-
-       return
-       end
-!=====================================================================
-
-       SUBROUTINE interp_sandu_vertical(play,nlev_sandu,plev_prof          &
-     &         ,t_prof,thl_prof,q_prof,u_prof,v_prof,w_prof                &
-     &         ,omega_prof,o3mmr_prof                                      &
-     &         ,t_mod,thl_mod,q_mod,u_mod,v_mod,w_mod                      &
-     &         ,omega_mod,o3mmr_mod,mxcalc)
-
-       implicit none
-
-#include "dimensions.h"
-
-!-------------------------------------------------------------------------
-! Vertical interpolation of SANDUREF forcing data onto model levels
-!-------------------------------------------------------------------------
-
-       integer nlevmax
-       parameter (nlevmax=41)
-       integer nlev_sandu,mxcalc
-!       real play(llm), plev_prof(nlevmax)
-!       real t_prof(nlevmax),q_prof(nlevmax)
-!       real u_prof(nlevmax),v_prof(nlevmax), w_prof(nlevmax)
-!       real ht_prof(nlevmax),vt_prof(nlevmax)
-!       real hq_prof(nlevmax),vq_prof(nlevmax)
-
-       real play(llm), plev_prof(nlev_sandu)
-       real t_prof(nlev_sandu),thl_prof(nlev_sandu),q_prof(nlev_sandu)
-       real u_prof(nlev_sandu),v_prof(nlev_sandu), w_prof(nlev_sandu)
-       real omega_prof(nlev_sandu),o3mmr_prof(nlev_sandu)
-
-       real t_mod(llm),thl_mod(llm),q_mod(llm)
-       real u_mod(llm),v_mod(llm), w_mod(llm)
-       real omega_mod(llm),o3mmr_mod(llm)
-
-       integer l,k,k1,k2
-       real frac,frac1,frac2,fact
-
-       do l = 1, llm
-
-        if (play(l).ge.plev_prof(nlev_sandu)) then
-
-        mxcalc=l
-         k1=0
-         k2=0
-
-         if (play(l).le.plev_prof(1)) then
-
-         do k = 1, nlev_sandu-1
-          if (play(l).le.plev_prof(k).and. play(l).gt.plev_prof(k+1)) then
-            k1=k
-            k2=k+1
-          endif
-         enddo
-
-         if (k1.eq.0 .or. k2.eq.0) then
-          write(*,*) 'PB! k1, k2 = ',k1,k2
-          write(*,*) 'l,play(l) = ',l,play(l)/100
-         do k = 1, nlev_sandu-1
-          write(*,*) 'k,plev_prof(k) = ',k,plev_prof(k)/100
-         enddo
-         endif
-
-         frac = (plev_prof(k2)-play(l))/(plev_prof(k2)-plev_prof(k1))
-         t_mod(l)= t_prof(k2) - frac*(t_prof(k2)-t_prof(k1))
-         thl_mod(l)= thl_prof(k2) - frac*(thl_prof(k2)-thl_prof(k1))
-         q_mod(l)= q_prof(k2) - frac*(q_prof(k2)-q_prof(k1))
-         u_mod(l)= u_prof(k2) - frac*(u_prof(k2)-u_prof(k1))
-         v_mod(l)= v_prof(k2) - frac*(v_prof(k2)-v_prof(k1))
-         w_mod(l)= w_prof(k2) - frac*(w_prof(k2)-w_prof(k1))
-         omega_mod(l)=omega_prof(k2)-frac*(omega_prof(k2)-omega_prof(k1))
-         o3mmr_mod(l)=o3mmr_prof(k2)-frac*(o3mmr_prof(k2)-o3mmr_prof(k1))
-
-         else !play>plev_prof(1)
-
-         k1=1
-         k2=2
-         frac1 = (play(l)-plev_prof(k2))/(plev_prof(k1)-plev_prof(k2))
-         frac2 = (play(l)-plev_prof(k1))/(plev_prof(k1)-plev_prof(k2))
-         t_mod(l)= frac1*t_prof(k1) - frac2*t_prof(k2)
-         thl_mod(l)= frac1*thl_prof(k1) - frac2*thl_prof(k2)
-         q_mod(l)= frac1*q_prof(k1) - frac2*q_prof(k2)
-         u_mod(l)= frac1*u_prof(k1) - frac2*u_prof(k2)
-         v_mod(l)= frac1*v_prof(k1) - frac2*v_prof(k2)
-         w_mod(l)= frac1*w_prof(k1) - frac2*w_prof(k2)
-         omega_mod(l)= frac1*omega_prof(k1) - frac2*omega_prof(k2)
-         o3mmr_mod(l)= frac1*o3mmr_prof(k1) - frac2*o3mmr_prof(k2)
-
-         endif ! play.le.plev_prof(1)
-
-        else ! above max altitude of forcing file
-
-!jyg
-         fact=20.*(plev_prof(nlev_sandu)-play(l))/plev_prof(nlev_sandu) !jyg
-         fact = max(fact,0.)                                           !jyg
-         fact = exp(-fact)                                             !jyg
-         t_mod(l)= t_prof(nlev_sandu)                                   !jyg
-         thl_mod(l)= thl_prof(nlev_sandu)                                   !jyg
-         q_mod(l)= q_prof(nlev_sandu)*fact                              !jyg
-         u_mod(l)= u_prof(nlev_sandu)*fact                              !jyg
-         v_mod(l)= v_prof(nlev_sandu)*fact                              !jyg
-         w_mod(l)= w_prof(nlev_sandu)*fact                              !jyg
-         omega_mod(l)= omega_prof(nlev_sandu)*fact                      !jyg
-         o3mmr_mod(l)= o3mmr_prof(nlev_sandu)*fact                      !jyg
-
-        endif ! play
-
-       enddo ! l
-
-       do l = 1,llm
-!      print *,'t_mod(l),thl_mod(l),q_mod(l),u_mod(l),v_mod(l) ',
-!    $        l,t_mod(l),thl_mod(l),q_mod(l),u_mod(l),v_mod(l)
-       enddo
-
-          return
-          end
-!=====================================================================
-       SUBROUTINE interp_astex_vertical(play,nlev_astex,plev_prof          &
-     &         ,t_prof,thl_prof,qv_prof,ql_prof,qt_prof,u_prof,v_prof      &
-     &         ,w_prof,tke_prof,o3mmr_prof                                 &
-     &         ,t_mod,thl_mod,qv_mod,ql_mod,qt_mod,u_mod,v_mod,w_mod       &
-     &         ,tke_mod,o3mmr_mod,mxcalc)
-
-       implicit none
-
-#include "dimensions.h"
-
-!-------------------------------------------------------------------------
-! Vertical interpolation of Astex forcing data onto model levels
-!-------------------------------------------------------------------------
-
-       integer nlevmax
-       parameter (nlevmax=41)
-       integer nlev_astex,mxcalc
-!       real play(llm), plev_prof(nlevmax)
-!       real t_prof(nlevmax),qv_prof(nlevmax)
-!       real u_prof(nlevmax),v_prof(nlevmax), w_prof(nlevmax)
-!       real ht_prof(nlevmax),vt_prof(nlevmax)
-!       real hq_prof(nlevmax),vq_prof(nlevmax)
-
-       real play(llm), plev_prof(nlev_astex)
-       real t_prof(nlev_astex),thl_prof(nlev_astex),qv_prof(nlev_astex)
-       real u_prof(nlev_astex),v_prof(nlev_astex), w_prof(nlev_astex)
-       real o3mmr_prof(nlev_astex),ql_prof(nlev_astex)
-       real qt_prof(nlev_astex),tke_prof(nlev_astex)
-
-       real t_mod(llm),thl_mod(llm),qv_mod(llm)
-       real u_mod(llm),v_mod(llm), w_mod(llm),tke_mod(llm)
-       real o3mmr_mod(llm),ql_mod(llm),qt_mod(llm)
-
-       integer l,k,k1,k2
-       real frac,frac1,frac2,fact
-
-       do l = 1, llm
-
-        if (play(l).ge.plev_prof(nlev_astex)) then
-
-        mxcalc=l
-         k1=0
-         k2=0
-
-         if (play(l).le.plev_prof(1)) then
-
-         do k = 1, nlev_astex-1
-          if (play(l).le.plev_prof(k).and. play(l).gt.plev_prof(k+1)) then
-            k1=k
-            k2=k+1
-          endif
-         enddo
-
-         if (k1.eq.0 .or. k2.eq.0) then
-          write(*,*) 'PB! k1, k2 = ',k1,k2
-          write(*,*) 'l,play(l) = ',l,play(l)/100
-         do k = 1, nlev_astex-1
-          write(*,*) 'k,plev_prof(k) = ',k,plev_prof(k)/100
-         enddo
-         endif
-
-         frac = (plev_prof(k2)-play(l))/(plev_prof(k2)-plev_prof(k1))
-         t_mod(l)= t_prof(k2) - frac*(t_prof(k2)-t_prof(k1))
-         thl_mod(l)= thl_prof(k2) - frac*(thl_prof(k2)-thl_prof(k1))
-         qv_mod(l)= qv_prof(k2) - frac*(qv_prof(k2)-qv_prof(k1))
-         ql_mod(l)= ql_prof(k2) - frac*(ql_prof(k2)-ql_prof(k1))
-         qt_mod(l)= qt_prof(k2) - frac*(qt_prof(k2)-qt_prof(k1))
-         u_mod(l)= u_prof(k2) - frac*(u_prof(k2)-u_prof(k1))
-         v_mod(l)= v_prof(k2) - frac*(v_prof(k2)-v_prof(k1))
-         w_mod(l)= w_prof(k2) - frac*(w_prof(k2)-w_prof(k1))
-         tke_mod(l)= tke_prof(k2) - frac*(tke_prof(k2)-tke_prof(k1))
-         o3mmr_mod(l)=o3mmr_prof(k2)-frac*(o3mmr_prof(k2)-o3mmr_prof(k1))
-
-         else !play>plev_prof(1)
-
-         k1=1
-         k2=2
-         frac1 = (play(l)-plev_prof(k2))/(plev_prof(k1)-plev_prof(k2))
-         frac2 = (play(l)-plev_prof(k1))/(plev_prof(k1)-plev_prof(k2))
-         t_mod(l)= frac1*t_prof(k1) - frac2*t_prof(k2)
-         thl_mod(l)= frac1*thl_prof(k1) - frac2*thl_prof(k2)
-         qv_mod(l)= frac1*qv_prof(k1) - frac2*qv_prof(k2)
-         ql_mod(l)= frac1*ql_prof(k1) - frac2*ql_prof(k2)
-         qt_mod(l)= frac1*qt_prof(k1) - frac2*qt_prof(k2)
-         u_mod(l)= frac1*u_prof(k1) - frac2*u_prof(k2)
-         v_mod(l)= frac1*v_prof(k1) - frac2*v_prof(k2)
-         w_mod(l)= frac1*w_prof(k1) - frac2*w_prof(k2)
-         tke_mod(l)= frac1*tke_prof(k1) - frac2*tke_prof(k2)
-         o3mmr_mod(l)= frac1*o3mmr_prof(k1) - frac2*o3mmr_prof(k2)
-
-         endif ! play.le.plev_prof(1)
-
-        else ! above max altitude of forcing file
-
-!jyg
-         fact=20.*(plev_prof(nlev_astex)-play(l))/plev_prof(nlev_astex) !jyg
-         fact = max(fact,0.)                                           !jyg
-         fact = exp(-fact)                                             !jyg
-         t_mod(l)= t_prof(nlev_astex)                                   !jyg
-         thl_mod(l)= thl_prof(nlev_astex)                                   !jyg
-         qv_mod(l)= qv_prof(nlev_astex)*fact                              !jyg
-         ql_mod(l)= ql_prof(nlev_astex)*fact                              !jyg
-         qt_mod(l)= qt_prof(nlev_astex)*fact                              !jyg
-         u_mod(l)= u_prof(nlev_astex)*fact                              !jyg
-         v_mod(l)= v_prof(nlev_astex)*fact                              !jyg
-         w_mod(l)= w_prof(nlev_astex)*fact                              !jyg
-         tke_mod(l)= tke_prof(nlev_astex)*fact                              !jyg
-         o3mmr_mod(l)= o3mmr_prof(nlev_astex)*fact                      !jyg
-
-        endif ! play
-
-       enddo ! l
-
-       do l = 1,llm
-!      print *,'t_mod(l),thl_mod(l),qv_mod(l),u_mod(l),v_mod(l) ',
-!    $        l,t_mod(l),thl_mod(l),qv_mod(l),u_mod(l),v_mod(l)
-       enddo
-
-          return
-          end
-
-!======================================================================
-      SUBROUTINE read_rico(fich_rico,nlev_rico,ps_rico,play                &
-     &             ,ts_rico,t_rico,q_rico,u_rico,v_rico,w_rico             &
-     &             ,dth_dyn,dqh_dyn)
-      implicit none
-
-!-------------------------------------------------------------------------
-! Read RICO forcing data 
-!-------------------------------------------------------------------------
-#include "dimensions.h"
-
-
-      integer nlev_rico
-      real ts_rico,ps_rico
-      real t_rico(llm),q_rico(llm)
-      real u_rico(llm),v_rico(llm)
-      real w_rico(llm)
-      real dth_dyn(llm)
-      real dqh_dyn(llm)
-      
-
-      real play(llm),zlay(llm)
-     
-
-      real prico(nlev_rico),zrico(nlev_rico)
-
-      character*80 fich_rico
-
-      integer k,l
-
-      
-      print*,fich_rico
-      open(21,file=trim(fich_rico),form='formatted')
-        do k=1,llm
-      zlay(k)=0.
-         enddo
-      
-        read(21,*) ps_rico,ts_rico
-        prico(1)=ps_rico
-        zrico(1)=0.0
-      do l=2,nlev_rico
-        read(21,*) k,prico(l),zrico(l)
-      enddo
-       close(21)
-
-      do k=1,llm
-        do l=1,80
-          if(prico(l)>play(k)) then
-              if(play(k)>prico(l+1)) then
-                zlay(k)=zrico(l)+(play(k)-prico(l)) *                      &
-     &              (zrico(l+1)-zrico(l))/(prico(l+1)-prico(l))
-              else 
-                zlay(k)=zrico(l)+(play(k)-prico(80))*                      &
-     &              (zrico(81)-zrico(80))/(prico(81)-prico(80))
-              endif
-          endif
-        enddo
-        print*,k,zlay(k)
-        ! U
-        if(0 < zlay(k) .and. zlay(k) < 4000) then
-          u_rico(k)=-9.9 + (-1.9 + 9.9)*zlay(k)/4000
-        elseif(4000 < zlay(k) .and. zlay(k) < 12000) then
-       u_rico(k)=  -1.9 + (30.0 + 1.9) /                                   &
-     &          (12000 - 4000) * (zlay(k) - 4000)
-        elseif(12000 < zlay(k) .and. zlay(k) < 13000) then
-          u_rico(k)=30.0
-        elseif(13000 < zlay(k) .and. zlay(k) < 20000) then
-          u_rico(k)=30.0 - (30.0) /                                        &
-     & (20000 - 13000) * (zlay(k) - 13000)
-        else
-          u_rico(k)=0.0
-        endif
-
-!Q_v
-        if(0 < zlay(k) .and. zlay(k) < 740) then
-          q_rico(k)=16.0 + (13.8 - 16.0) / (740) * zlay(k)
-        elseif(740 < zlay(k) .and. zlay(k) < 3260) then
-          q_rico(k)=13.8 + (2.4 - 13.8) /                                   &
-     &          (3260 - 740) * (zlay(k) - 740)
-        elseif(3260 < zlay(k) .and. zlay(k) < 4000) then
-          q_rico(k)=2.4 + (1.8 - 2.4) /                                    &
-     &               (4000 - 3260) * (zlay(k) - 3260)
-        elseif(4000 < zlay(k) .and. zlay(k) < 9000) then
-          q_rico(k)=1.8 + (0 - 1.8) /                                      &
-     &             (9000 - 4000) * (zlay(k) - 4000)
-        else
-          q_rico(k)=0.0
-        endif
-
-!T
-        if(0 < zlay(k) .and. zlay(k) < 740) then
-          t_rico(k)=299.2 + (292.0 - 299.2) / (740) * zlay(k)
-        elseif(740 < zlay(k) .and. zlay(k) < 4000) then
-          t_rico(k)=292.0 + (278.0 - 292.0) /                              &                       
-     &       (4000 - 740) * (zlay(k) - 740)
-        elseif(4000 < zlay(k) .and. zlay(k) < 15000) then
-          t_rico(k)=278.0 + (203.0 - 278.0) /                              &
-     &       (15000 - 4000) * (zlay(k) - 4000)
-        elseif(15000 < zlay(k) .and. zlay(k) < 17500) then
-          t_rico(k)=203.0 + (194.0 - 203.0) /                              & 
-     &       (17500 - 15000)* (zlay(k) - 15000)
-        elseif(17500 < zlay(k) .and. zlay(k) < 20000) then
-          t_rico(k)=194.0 + (206.0 - 194.0) /                              &
-     &       (20000 - 17500)* (zlay(k) - 17500)
-        elseif(20000 < zlay(k) .and. zlay(k) < 60000) then
-          t_rico(k)=206.0 + (270.0 - 206.0) /                              & 
-     &        (60000 - 20000)* (zlay(k) - 20000)
-        endif
-
-! W
-        if(0 < zlay(k) .and. zlay(k) < 2260 ) then
-          w_rico(k)=- (0.005/2260) * zlay(k)
-        elseif(2260 < zlay(k) .and. zlay(k) < 4000 ) then
-          w_rico(k)=- 0.005
-        elseif(4000 < zlay(k) .and. zlay(k) < 5000 ) then
-       w_rico(k)=- 0.005 + (0.005/ (5000 - 4000)) * (zlay(k) - 4000)
-        else
-          w_rico(k)=0.0
-        endif
-
-! dThrz+dTsw0+dTlw0
-        if(0 < zlay(k) .and. zlay(k) < 4000) then
-          dth_dyn(k)=- 2.51 / 86400 + (-2.18 + 2.51 )/                     &
-     &               (86400*4000) * zlay(k)
-        elseif(4000 < zlay(k) .and. zlay(k) < 5000) then
-          dth_dyn(k)=- 2.18 / 86400 + ( 2.18 ) /                           &
-     &           (86400*(5000 - 4000)) * (zlay(k) - 4000)
-        else
-          dth_dyn(k)=0.0
-        endif
-! dQhrz
-        if(0 < zlay(k) .and. zlay(k) < 3000) then
-          dqh_dyn(k)=-1.0 / 86400 + (0.345 + 1.0)/                         &
-     &                    (86400*3000) * (zlay(k))
-        elseif(3000 < zlay(k) .and. zlay(k) < 4000) then
-          dqh_dyn(k)=0.345 / 86400
-        elseif(4000 < zlay(k) .and. zlay(k) < 5000) then
-          dqh_dyn(k)=0.345 / 86400 +                                       &
-     &   (-0.345)/(86400 * (5000 - 4000)) * (zlay(k)-4000)
-        else
-          dqh_dyn(k)=0.0
-        endif
-
-!?        if(play(k)>6e4) then
-!?          ratqs0(1,k)=ratqsbas*(plev(1)-play(k))/(plev(1)-6e4)
-!?        elseif((play(k)>3e4).and.(play(k)<6e4)) then
-!?          ratqs0(1,k)=ratqsbas+(ratqshaut-ratqsbas)&
-!?                          *(6e4-play(k))/(6e4-3e4)
-!?        else
-!?          ratqs0(1,k)=ratqshaut
-!?        endif
-
-      enddo
-
-      do k=1,llm
-      q_rico(k)=q_rico(k)/1e3 
-      dqh_dyn(k)=dqh_dyn(k)/1e3
-      v_rico(k)=-3.8
-      enddo
-
-          return
-          end
-
-!======================================================================
-        SUBROUTINE interp_sandu_time(day,day1,annee_ref                    &
-     &             ,year_ini_sandu,day_ini_sandu,nt_sandu,dt_sandu         &
-     &             ,nlev_sandu,ts_sandu,ts_prof)
-        implicit none
-
-!---------------------------------------------------------------------------------------
-! Time interpolation of a 2D field to the timestep corresponding to day
-!
-! day: current julian day (e.g. 717538.2)
-! day1: first day of the simulation
-! nt_sandu: total nb of data in the forcing (e.g. 13 for Sanduref)
-! dt_sandu: total time interval (in sec) between 2 forcing data (e.g. 6h for Sanduref)
-!---------------------------------------------------------------------------------------
-! inputs:
-        integer annee_ref
-        integer nt_sandu,nlev_sandu
-        integer year_ini_sandu
-        real day, day1,day_ini_sandu,dt_sandu
-        real ts_sandu(nt_sandu)
-! outputs:
-        real ts_prof
-! local:
-        integer it_sandu1, it_sandu2
-        real timeit,time_sandu1,time_sandu2,frac
-! Check that initial day of the simulation consistent with SANDU period:
-       if (annee_ref.ne.2006 ) then
-        print*,'Pour SANDUREF, annee_ref doit etre 2006 '
-        print*,'Changer annee_ref dans run.def'
-        stop
-       endif
-!      if (annee_ref.eq.2006 .and. day1.lt.day_ini_sandu) then
-!       print*,'SANDUREF debute le 15 Juillet 2006 (jour julien=196)'
-!       print*,'Changer dayref dans run.def'
-!       stop
-!      endif
-
-! Determine timestep relative to the 1st day of TOGA-COARE:
-!       timeit=(day-day1)*86400.
-!       if (annee_ref.eq.1992) then
-!        timeit=(day-day_ini_sandu)*86400.
-!       else
-!        timeit=(day+61.-1.)*86400. ! 61 days between Nov01 and Dec31 1992
-!       endif
-      timeit=(day-day_ini_sandu)*86400
-
-! Determine the closest observation times:
-       it_sandu1=INT(timeit/dt_sandu)+1
-       it_sandu2=it_sandu1 + 1
-       time_sandu1=(it_sandu1-1)*dt_sandu
-       time_sandu2=(it_sandu2-1)*dt_sandu
-       print *,'timeit day day_ini_sandu',timeit,day,day_ini_sandu
-       print *,'it_sandu1,it_sandu2,time_sandu1,time_sandu2',              &
-     &          it_sandu1,it_sandu2,time_sandu1,time_sandu2
-
-       if (it_sandu1 .ge. nt_sandu) then
-        write(*,*) 'PB-stop: day, it_sandu1, it_sandu2, timeit: '          &
-     &        ,day,it_sandu1,it_sandu2,timeit/86400.
-        stop
-       endif
-
-! time interpolation:
-       frac=(time_sandu2-timeit)/(time_sandu2-time_sandu1)
-       frac=max(frac,0.0)
-
-       ts_prof = ts_sandu(it_sandu2)                                       &
-     &          -frac*(ts_sandu(it_sandu2)-ts_sandu(it_sandu1))
-
-         print*,                                                           &
-     &'day,annee_ref,day_ini_sandu,timeit,it_sandu1,it_sandu2,SST:',       &
-     &day,annee_ref,day_ini_sandu,timeit/86400.,it_sandu1,                  &
-     &it_sandu2,ts_prof
-
-        return
-        END
-!=====================================================================
-!-------------------------------------------------------------------------
-      SUBROUTINE read_armcu(fich_armcu,nlev_armcu,nt_armcu,                &
-     & sens,flat,adv_theta,rad_theta,adv_qt)
-      implicit none
-
-!-------------------------------------------------------------------------
-! Read ARM_CU case forcing data
-!-------------------------------------------------------------------------
-
-      integer nlev_armcu,nt_armcu
-      real sens(nt_armcu),flat(nt_armcu)
-      real adv_theta(nt_armcu),rad_theta(nt_armcu),adv_qt(nt_armcu)
-      character*80 fich_armcu
-
-      integer ip
-
-      integer iy,im,id,ih,in
-
-      print*,'nlev_armcu',nlev_armcu
-
-      open(21,file=trim(fich_armcu),form='formatted')
-      read(21,'(a)')
-      do ip = 1, nt_armcu
-      read(21,'(a)')
-      read(21,'(a)')
-      read(21,223) iy, im, id, ih, in, sens(ip),flat(ip),                  &
-     &             adv_theta(ip),rad_theta(ip),adv_qt(ip)
-      print *,'forcages=',iy,im,id,ih,in, sens(ip),flat(ip),               &
-     &             adv_theta(ip),rad_theta(ip),adv_qt(ip)
-      enddo
-      close(21)
-
-  223 format(5i3,5f8.3)
-
-          return
-          end
-
-!=====================================================================
-       SUBROUTINE interp_toga_vertical(play,nlev_toga,plev_prof            &
-     &         ,t_prof,q_prof,u_prof,v_prof,w_prof                         &
-     &         ,ht_prof,vt_prof,hq_prof,vq_prof                            &
-     &         ,t_mod,q_mod,u_mod,v_mod,w_mod                              &
-     &         ,ht_mod,vt_mod,hq_mod,vq_mod,mxcalc)
- 
-       implicit none
- 
-#include "dimensions.h"
-
-!-------------------------------------------------------------------------
-! Vertical interpolation of TOGA-COARE forcing data onto model levels
-!-------------------------------------------------------------------------
- 
-       integer nlevmax
-       parameter (nlevmax=41)
-       integer nlev_toga,mxcalc
-!       real play(llm), plev_prof(nlevmax) 
-!       real t_prof(nlevmax),q_prof(nlevmax)
-!       real u_prof(nlevmax),v_prof(nlevmax), w_prof(nlevmax)
-!       real ht_prof(nlevmax),vt_prof(nlevmax)
-!       real hq_prof(nlevmax),vq_prof(nlevmax)
- 
-       real play(llm), plev_prof(nlev_toga) 
-       real t_prof(nlev_toga),q_prof(nlev_toga)
-       real u_prof(nlev_toga),v_prof(nlev_toga), w_prof(nlev_toga)
-       real ht_prof(nlev_toga),vt_prof(nlev_toga)
-       real hq_prof(nlev_toga),vq_prof(nlev_toga)
- 
-       real t_mod(llm),q_mod(llm)
-       real u_mod(llm),v_mod(llm), w_mod(llm)
-       real ht_mod(llm),vt_mod(llm)
-       real hq_mod(llm),vq_mod(llm)
- 
-       integer l,k,k1,k2
-       real frac,frac1,frac2,fact
- 
-       do l = 1, llm
-
-        if (play(l).ge.plev_prof(nlev_toga)) then
- 
-        mxcalc=l
-         k1=0
-         k2=0
-
-         if (play(l).le.plev_prof(1)) then
-
-         do k = 1, nlev_toga-1
-          if (play(l).le.plev_prof(k).and. play(l).gt.plev_prof(k+1)) then
-            k1=k
-            k2=k+1
-          endif
-         enddo
-
-         if (k1.eq.0 .or. k2.eq.0) then
-          write(*,*) 'PB! k1, k2 = ',k1,k2
-          write(*,*) 'l,play(l) = ',l,play(l)/100
-         do k = 1, nlev_toga-1
-          write(*,*) 'k,plev_prof(k) = ',k,plev_prof(k)/100
-         enddo
-         endif
-
-         frac = (plev_prof(k2)-play(l))/(plev_prof(k2)-plev_prof(k1))
-         t_mod(l)= t_prof(k2) - frac*(t_prof(k2)-t_prof(k1))
-         q_mod(l)= q_prof(k2) - frac*(q_prof(k2)-q_prof(k1))
-         u_mod(l)= u_prof(k2) - frac*(u_prof(k2)-u_prof(k1))
-         v_mod(l)= v_prof(k2) - frac*(v_prof(k2)-v_prof(k1))
-         w_mod(l)= w_prof(k2) - frac*(w_prof(k2)-w_prof(k1))
-         ht_mod(l)= ht_prof(k2) - frac*(ht_prof(k2)-ht_prof(k1))
-         vt_mod(l)= vt_prof(k2) - frac*(vt_prof(k2)-vt_prof(k1))
-         hq_mod(l)= hq_prof(k2) - frac*(hq_prof(k2)-hq_prof(k1))
-         vq_mod(l)= vq_prof(k2) - frac*(vq_prof(k2)-vq_prof(k1))
-     
-         else !play>plev_prof(1)
-
-         k1=1
-         k2=2
-         frac1 = (play(l)-plev_prof(k2))/(plev_prof(k1)-plev_prof(k2))
-         frac2 = (play(l)-plev_prof(k1))/(plev_prof(k1)-plev_prof(k2))
-         t_mod(l)= frac1*t_prof(k1) - frac2*t_prof(k2)
-         q_mod(l)= frac1*q_prof(k1) - frac2*q_prof(k2)
-         u_mod(l)= frac1*u_prof(k1) - frac2*u_prof(k2)
-         v_mod(l)= frac1*v_prof(k1) - frac2*v_prof(k2)
-         w_mod(l)= frac1*w_prof(k1) - frac2*w_prof(k2)
-         ht_mod(l)= frac1*ht_prof(k1) - frac2*ht_prof(k2)
-         vt_mod(l)= frac1*vt_prof(k1) - frac2*vt_prof(k2)
-         hq_mod(l)= frac1*hq_prof(k1) - frac2*hq_prof(k2)
-         vq_mod(l)= frac1*vq_prof(k1) - frac2*vq_prof(k2)
-
-         endif ! play.le.plev_prof(1)
-
-        else ! above max altitude of forcing file
- 
-!jyg
-         fact=20.*(plev_prof(nlev_toga)-play(l))/plev_prof(nlev_toga) !jyg
-         fact = max(fact,0.)                                           !jyg
-         fact = exp(-fact)                                             !jyg
-         t_mod(l)= t_prof(nlev_toga)                                   !jyg
-         q_mod(l)= q_prof(nlev_toga)*fact                              !jyg
-         u_mod(l)= u_prof(nlev_toga)*fact                              !jyg
-         v_mod(l)= v_prof(nlev_toga)*fact                              !jyg
-         w_mod(l)= 0.0                                                 !jyg
-         ht_mod(l)= ht_prof(nlev_toga)                                 !jyg
-         vt_mod(l)= vt_prof(nlev_toga)                                 !jyg
-         hq_mod(l)= hq_prof(nlev_toga)*fact                            !jyg
-         vq_mod(l)= vq_prof(nlev_toga)*fact                            !jyg
- 
-        endif ! play
- 
-       enddo ! l
-
-!       do l = 1,llm
-!       print *,'t_mod(l),q_mod(l),ht_mod(l),hq_mod(l) ',
-!     $        l,t_mod(l),q_mod(l),ht_mod(l),hq_mod(l)
-!       enddo
- 
-          return
-          end
- 
-!=====================================================================
-       SUBROUTINE interp_case_vertical(play,nlev_cas,plev_prof_cas            &
-     &         ,t_prof_cas,q_prof_cas,u_prof_cas,v_prof_cas,ug_prof_cas,vg_prof_cas,vitw_prof_cas                         &
-     &         ,du_prof_cas,hu_prof_cas,vu_prof_cas,dv_prof_cas,hv_prof_cas,vv_prof_cas           &
-     &         ,dt_prof_cas,ht_prof_cas,vt_prof_cas,dtrad_prof_cas,dq_prof_cas,hq_prof_cas,vq_prof_cas                            &
-     &         ,t_mod_cas,q_mod_cas,u_mod_cas,v_mod_cas,ug_mod_cas,vg_mod_cas,w_mod_cas                              &
-     &         ,du_mod_cas,hu_mod_cas,vu_mod_cas,dv_mod_cas,hv_mod_cas,vv_mod_cas               &
-     &         ,dt_mod_cas,ht_mod_cas,vt_mod_cas,dtrad_mod_cas,dq_mod_cas,hq_mod_cas,vq_mod_cas,mxcalc)
- 
-       implicit none
- 
-#include "dimensions.h"
-
-!-------------------------------------------------------------------------
-! Vertical interpolation of TOGA-COARE forcing data onto mod_casel levels
-!-------------------------------------------------------------------------
- 
-       integer nlevmax
-       parameter (nlevmax=41)
-       integer nlev_cas,mxcalc
-!       real play(llm), plev_prof(nlevmax) 
-!       real t_prof(nlevmax),q_prof(nlevmax)
-!       real u_prof(nlevmax),v_prof(nlevmax), w_prof(nlevmax)
-!       real ht_prof(nlevmax),vt_prof(nlevmax)
-!       real hq_prof(nlevmax),vq_prof(nlevmax)
- 
-       real play(llm), plev_prof_cas(nlev_cas) 
-       real t_prof_cas(nlev_cas),q_prof_cas(nlev_cas)
-       real u_prof_cas(nlev_cas),v_prof_cas(nlev_cas)
-       real ug_prof_cas(nlev_cas),vg_prof_cas(nlev_cas), vitw_prof_cas(nlev_cas)
-       real du_prof_cas(nlev_cas),hu_prof_cas(nlev_cas),vu_prof_cas(nlev_cas)
-       real dv_prof_cas(nlev_cas),hv_prof_cas(nlev_cas),vv_prof_cas(nlev_cas)
-       real dt_prof_cas(nlev_cas),ht_prof_cas(nlev_cas),vt_prof_cas(nlev_cas),dtrad_prof_cas(nlev_cas)
-       real dq_prof_cas(nlev_cas),hq_prof_cas(nlev_cas),vq_prof_cas(nlev_cas)
- 
-       real t_mod_cas(llm),q_mod_cas(llm)
-       real u_mod_cas(llm),v_mod_cas(llm)
-       real ug_mod_cas(llm),vg_mod_cas(llm), w_mod_cas(llm)
-       real du_mod_cas(llm),hu_mod_cas(llm),vu_mod_cas(llm)
-       real dv_mod_cas(llm),hv_mod_cas(llm),vv_mod_cas(llm)
-       real dt_mod_cas(llm),ht_mod_cas(llm),vt_mod_cas(llm),dtrad_mod_cas(llm)
-       real dq_mod_cas(llm),hq_mod_cas(llm),vq_mod_cas(llm)
- 
-       integer l,k,k1,k2
-       real frac,frac1,frac2,fact
- 
-       do l = 1, llm
-
-        if (play(l).ge.plev_prof_cas(nlev_cas)) then
- 
-        mxcalc=l
-         k1=0
-         k2=0
-
-         if (play(l).le.plev_prof_cas(1)) then
-
-         do k = 1, nlev_cas-1
-          if (play(l).le.plev_prof_cas(k).and. play(l).gt.plev_prof_cas(k+1)) then
-            k1=k
-            k2=k+1
-          endif
-         enddo
-
-         if (k1.eq.0 .or. k2.eq.0) then
-          write(*,*) 'PB! k1, k2 = ',k1,k2
-          write(*,*) 'l,play(l) = ',l,play(l)/100
-         do k = 1, nlev_cas-1
-          write(*,*) 'k,plev_prof_cas(k) = ',k,plev_prof_cas(k)/100
-         enddo
-         endif
-
-         frac = (plev_prof_cas(k2)-play(l))/(plev_prof_cas(k2)-plev_prof_cas(k1))
-         t_mod_cas(l)= t_prof_cas(k2) - frac*(t_prof_cas(k2)-t_prof_cas(k1))
-         q_mod_cas(l)= q_prof_cas(k2) - frac*(q_prof_cas(k2)-q_prof_cas(k1))
-         u_mod_cas(l)= u_prof_cas(k2) - frac*(u_prof_cas(k2)-u_prof_cas(k1))
-         v_mod_cas(l)= v_prof_cas(k2) - frac*(v_prof_cas(k2)-v_prof_cas(k1))
-         ug_mod_cas(l)= ug_prof_cas(k2) - frac*(ug_prof_cas(k2)-ug_prof_cas(k1))
-         vg_mod_cas(l)= vg_prof_cas(k2) - frac*(vg_prof_cas(k2)-vg_prof_cas(k1))
-         w_mod_cas(l)= vitw_prof_cas(k2) - frac*(vitw_prof_cas(k2)-vitw_prof_cas(k1))
-         du_mod_cas(l)= du_prof_cas(k2) - frac*(du_prof_cas(k2)-du_prof_cas(k1))
-         hu_mod_cas(l)= hu_prof_cas(k2) - frac*(hu_prof_cas(k2)-hu_prof_cas(k1))
-         vu_mod_cas(l)= vu_prof_cas(k2) - frac*(vu_prof_cas(k2)-vu_prof_cas(k1))
-         dv_mod_cas(l)= dv_prof_cas(k2) - frac*(dv_prof_cas(k2)-dv_prof_cas(k1))
-         hv_mod_cas(l)= hv_prof_cas(k2) - frac*(hv_prof_cas(k2)-hv_prof_cas(k1))
-         vv_mod_cas(l)= vv_prof_cas(k2) - frac*(vv_prof_cas(k2)-vv_prof_cas(k1))
-         dt_mod_cas(l)= dt_prof_cas(k2) - frac*(dt_prof_cas(k2)-dt_prof_cas(k1))
-         ht_mod_cas(l)= ht_prof_cas(k2) - frac*(ht_prof_cas(k2)-ht_prof_cas(k1))
-         vt_mod_cas(l)= vt_prof_cas(k2) - frac*(vt_prof_cas(k2)-vt_prof_cas(k1))
-         dq_mod_cas(l)= dq_prof_cas(k2) - frac*(dq_prof_cas(k2)-dq_prof_cas(k1))
-         hq_mod_cas(l)= hq_prof_cas(k2) - frac*(hq_prof_cas(k2)-hq_prof_cas(k1))
-         vq_mod_cas(l)= vq_prof_cas(k2) - frac*(vq_prof_cas(k2)-vq_prof_cas(k1))
-         dtrad_mod_cas(l)= dtrad_prof_cas(k2) - frac*(dtrad_prof_cas(k2)-dtrad_prof_cas(k1))
-     
-         else !play>plev_prof_cas(1)
-
-         k1=1
-         k2=2
-         frac1 = (play(l)-plev_prof_cas(k2))/(plev_prof_cas(k1)-plev_prof_cas(k2))
-         frac2 = (play(l)-plev_prof_cas(k1))/(plev_prof_cas(k1)-plev_prof_cas(k2))
-         t_mod_cas(l)= frac1*t_prof_cas(k1) - frac2*t_prof_cas(k2)
-         q_mod_cas(l)= frac1*q_prof_cas(k1) - frac2*q_prof_cas(k2)
-         u_mod_cas(l)= frac1*u_prof_cas(k1) - frac2*u_prof_cas(k2)
-         v_mod_cas(l)= frac1*v_prof_cas(k1) - frac2*v_prof_cas(k2)
-         ug_mod_cas(l)= frac1*ug_prof_cas(k1) - frac2*ug_prof_cas(k2)
-         vg_mod_cas(l)= frac1*vg_prof_cas(k1) - frac2*vg_prof_cas(k2)
-         w_mod_cas(l)= frac1*vitw_prof_cas(k1) - frac2*vitw_prof_cas(k2)
-         du_mod_cas(l)= frac1*du_prof_cas(k1) - frac2*du_prof_cas(k2)
-         hu_mod_cas(l)= frac1*hu_prof_cas(k1) - frac2*hu_prof_cas(k2)
-         vu_mod_cas(l)= frac1*vu_prof_cas(k1) - frac2*vu_prof_cas(k2)
-         dv_mod_cas(l)= frac1*dv_prof_cas(k1) - frac2*dv_prof_cas(k2)
-         hv_mod_cas(l)= frac1*hv_prof_cas(k1) - frac2*hv_prof_cas(k2)
-         vv_mod_cas(l)= frac1*vv_prof_cas(k1) - frac2*vv_prof_cas(k2)
-         dt_mod_cas(l)= frac1*dt_prof_cas(k1) - frac2*dt_prof_cas(k2)
-         ht_mod_cas(l)= frac1*ht_prof_cas(k1) - frac2*ht_prof_cas(k2)
-         vt_mod_cas(l)= frac1*vt_prof_cas(k1) - frac2*vt_prof_cas(k2)
-         dq_mod_cas(l)= frac1*dq_prof_cas(k1) - frac2*dq_prof_cas(k2)
-         hq_mod_cas(l)= frac1*hq_prof_cas(k1) - frac2*hq_prof_cas(k2)
-         vq_mod_cas(l)= frac1*vq_prof_cas(k1) - frac2*vq_prof_cas(k2)
-         dtrad_mod_cas(l)= frac1*dtrad_prof_cas(k1) - frac2*dtrad_prof_cas(k2)
-
-         endif ! play.le.plev_prof_cas(1)
-
-        else ! above max altitude of forcing file
- 
-!jyg
-         fact=20.*(plev_prof_cas(nlev_cas)-play(l))/plev_prof_cas(nlev_cas) !jyg
-         fact = max(fact,0.)                                           !jyg
-         fact = exp(-fact)                                             !jyg
-         t_mod_cas(l)= t_prof_cas(nlev_cas)                                   !jyg
-         q_mod_cas(l)= q_prof_cas(nlev_cas)*fact                              !jyg
-         u_mod_cas(l)= u_prof_cas(nlev_cas)*fact                              !jyg
-         v_mod_cas(l)= v_prof_cas(nlev_cas)*fact                              !jyg
-         ug_mod_cas(l)= ug_prof_cas(nlev_cas)*fact                              !jyg
-         vg_mod_cas(l)= vg_prof_cas(nlev_cas)*fact                              !jyg
-         w_mod_cas(l)= 0.0                                                 !jyg
-         du_mod_cas(l)= du_prof_cas(nlev_cas)*fact 
-         hu_mod_cas(l)= hu_prof_cas(nlev_cas)*fact                            !jyg
-         vu_mod_cas(l)= vu_prof_cas(nlev_cas)*fact                            !jyg
-         dv_mod_cas(l)= dv_prof_cas(nlev_cas)*fact 
-         hv_mod_cas(l)= hv_prof_cas(nlev_cas)*fact                            !jyg
-         vv_mod_cas(l)= vv_prof_cas(nlev_cas)*fact                            !jyg
-         dt_mod_cas(l)= dt_prof_cas(nlev_cas) 
-         ht_mod_cas(l)= ht_prof_cas(nlev_cas)                                 !jyg
-         vt_mod_cas(l)= vt_prof_cas(nlev_cas)                                 !jyg
-         dq_mod_cas(l)= dq_prof_cas(nlev_cas)*fact 
-         hq_mod_cas(l)= hq_prof_cas(nlev_cas)*fact                            !jyg
-         vq_mod_cas(l)= vq_prof_cas(nlev_cas)*fact                            !jyg
-         dtrad_mod_cas(l)= dtrad_prof_cas(nlev_cas)*fact                      !jyg
- 
-        endif ! play
- 
-       enddo ! l
-
-!       do l = 1,llm
-!       print *,'t_mod_cas(l),q_mod_cas(l),ht_mod_cas(l),hq_mod_cas(l) ',
-!     $        l,t_mod_cas(l),q_mod_cas(l),ht_mod_cas(l),hq_mod_cas(l)
-!       enddo
- 
-          return
-          end
-!***************************************************************************** 
-!=====================================================================
-       SUBROUTINE interp_dice_vertical(play,nlev_dice,nt_dice,plev_prof   &
-     &         ,th_prof,qv_prof,u_prof,v_prof,o3_prof                     &
-     &         ,ht_prof,hq_prof,hu_prof,hv_prof,w_prof,omega_prof         &
-     &         ,th_mod,qv_mod,u_mod,v_mod,o3_mod                          &
-     &         ,ht_mod,hq_mod,hu_mod,hv_mod,w_mod,omega_mod,mxcalc)
- 
-       implicit none
- 
-#include "dimensions.h"
-
-!-------------------------------------------------------------------------
-! Vertical interpolation of Dice forcing data onto model levels
-!-------------------------------------------------------------------------
- 
-       integer nlevmax
-       parameter (nlevmax=41)
-       integer nlev_dice,mxcalc,nt_dice
- 
-       real play(llm), plev_prof(nlev_dice) 
-       real th_prof(nlev_dice),qv_prof(nlev_dice)
-       real u_prof(nlev_dice),v_prof(nlev_dice) 
-       real o3_prof(nlev_dice)
-       real ht_prof(nlev_dice),hq_prof(nlev_dice)
-       real hu_prof(nlev_dice),hv_prof(nlev_dice)
-       real w_prof(nlev_dice),omega_prof(nlev_dice)
- 
-       real th_mod(llm),qv_mod(llm)
-       real u_mod(llm),v_mod(llm), o3_mod(llm)
-       real ht_mod(llm),hq_mod(llm)
-       real hu_mod(llm),hv_mod(llm),w_mod(llm),omega_mod(llm)
- 
-       integer l,k,k1,k2,kp
-       real aa,frac,frac1,frac2,fact
- 
-       do l = 1, llm
-
-        if (play(l).ge.plev_prof(nlev_dice)) then
- 
-        mxcalc=l
-         k1=0
-         k2=0
-
-         if (play(l).le.plev_prof(1)) then
-
-         do k = 1, nlev_dice-1
-          if (play(l).le.plev_prof(k) .and. play(l).gt.plev_prof(k+1)) then
-            k1=k
-            k2=k+1
-          endif
-         enddo
-
-         if (k1.eq.0 .or. k2.eq.0) then
-          write(*,*) 'PB! k1, k2 = ',k1,k2
-          write(*,*) 'l,play(l) = ',l,play(l)/100
-         do k = 1, nlev_dice-1
-          write(*,*) 'k,plev_prof(k) = ',k,plev_prof(k)/100
-         enddo
-         endif
-
-         frac = (plev_prof(k2)-play(l))/(plev_prof(k2)-plev_prof(k1))
-         th_mod(l)= th_prof(k2) - frac*(th_prof(k2)-th_prof(k1))
-         qv_mod(l)= qv_prof(k2) - frac*(qv_prof(k2)-qv_prof(k1))
-         u_mod(l)= u_prof(k2) - frac*(u_prof(k2)-u_prof(k1))
-         v_mod(l)= v_prof(k2) - frac*(v_prof(k2)-v_prof(k1))
-         o3_mod(l)= o3_prof(k2) - frac*(o3_prof(k2)-o3_prof(k1))
-         ht_mod(l)= ht_prof(k2) - frac*(ht_prof(k2)-ht_prof(k1))
-         hq_mod(l)= hq_prof(k2) - frac*(hq_prof(k2)-hq_prof(k1))
-         hu_mod(l)= hu_prof(k2) - frac*(hu_prof(k2)-hu_prof(k1))
-         hv_mod(l)= hv_prof(k2) - frac*(hv_prof(k2)-hv_prof(k1))
-         w_mod(l)= w_prof(k2) - frac*(w_prof(k2)-w_prof(k1))
-         omega_mod(l)= omega_prof(k2) - frac*(omega_prof(k2)-omega_prof(k1))
-     
-         else !play>plev_prof(1)
-
-         k1=1
-         k2=2
-         frac1 = (play(l)-plev_prof(k2))/(plev_prof(k1)-plev_prof(k2))
-         frac2 = (play(l)-plev_prof(k1))/(plev_prof(k1)-plev_prof(k2))
-         th_mod(l)= frac1*th_prof(k1) - frac2*th_prof(k2)
-         qv_mod(l)= frac1*qv_prof(k1) - frac2*qv_prof(k2)
-         u_mod(l)= frac1*u_prof(k1) - frac2*u_prof(k2)
-         v_mod(l)= frac1*v_prof(k1) - frac2*v_prof(k2)
-         o3_mod(l)= frac1*o3_prof(k1) - frac2*o3_prof(k2)
-         ht_mod(l)= frac1*ht_prof(k1) - frac2*ht_prof(k2)
-         hq_mod(l)= frac1*hq_prof(k1) - frac2*hq_prof(k2)
-         hu_mod(l)= frac1*hu_prof(k1) - frac2*hu_prof(k2)
-         hv_mod(l)= frac1*hv_prof(k1) - frac2*hv_prof(k2)
-         w_mod(l)= frac1*w_prof(k1) - frac2*w_prof(k2)
-         omega_mod(l)= frac1*omega_prof(k1) - frac2*omega_prof(k2)
-
-         endif ! play.le.plev_prof(1)
-
-        else ! above max altitude of forcing file
- 
-!jyg
-         fact=20.*(plev_prof(nlev_dice)-play(l))/plev_prof(nlev_dice) !jyg
-         fact = max(fact,0.)                                           !jyg
-         fact = exp(-fact)                                             !jyg
-         th_mod(l)= th_prof(nlev_dice)                                 !jyg
-         qv_mod(l)= qv_prof(nlev_dice)*fact                            !jyg
-         u_mod(l)= u_prof(nlev_dice)*fact                              !jyg
-         v_mod(l)= v_prof(nlev_dice)*fact                              !jyg
-         o3_mod(l)= o3_prof(nlev_dice)*fact                            !jyg
-         ht_mod(l)= ht_prof(nlev_dice)                                 !jyg
-         hq_mod(l)= hq_prof(nlev_dice)*fact                            !jyg
-         hu_mod(l)= hu_prof(nlev_dice)                                 !jyg
-         hv_mod(l)= hv_prof(nlev_dice)                                 !jyg
-         w_mod(l)= 0.                                                  !jyg
-         omega_mod(l)= 0.                                              !jyg
- 
-        endif ! play
- 
-       enddo ! l
-
-!       do l = 1,llm
-!       print *,'t_mod(l),q_mod(l),ht_mod(l),hq_mod(l) ',
-!     $        l,t_mod(l),q_mod(l),ht_mod(l),hq_mod(l)
-!       enddo
- 
-          return
-          end
-
-!======================================================================
-        SUBROUTINE interp_astex_time(day,day1,annee_ref                    &
-     &             ,year_ini_astex,day_ini_astex,nt_astex,dt_astex         &
-     &             ,nlev_astex,div_astex,ts_astex,ug_astex,vg_astex        &
-     &             ,ufa_astex,vfa_astex,div_prof,ts_prof,ug_prof,vg_prof   &
-     &             ,ufa_prof,vfa_prof)
-        implicit none
-
-!---------------------------------------------------------------------------------------
-! Time interpolation of a 2D field to the timestep corresponding to day
-!
-! day: current julian day (e.g. 717538.2)
-! day1: first day of the simulation
-! nt_astex: total nb of data in the forcing (e.g. 41 for Astex)
-! dt_astex: total time interval (in sec) between 2 forcing data (e.g. 1h for Astex)
-!---------------------------------------------------------------------------------------
-
-! inputs:
-        integer annee_ref
-        integer nt_astex,nlev_astex
-        integer year_ini_astex
-        real day, day1,day_ini_astex,dt_astex
-        real div_astex(nt_astex),ts_astex(nt_astex),ug_astex(nt_astex)
-        real vg_astex(nt_astex),ufa_astex(nt_astex),vfa_astex(nt_astex)
-! outputs:
-        real div_prof,ts_prof,ug_prof,vg_prof,ufa_prof,vfa_prof
-! local:
-        integer it_astex1, it_astex2
-        real timeit,time_astex1,time_astex2,frac
-
-! Check that initial day of the simulation consistent with ASTEX period:
-       if (annee_ref.ne.1992 ) then
-        print*,'Pour Astex, annee_ref doit etre 1992 '
-        print*,'Changer annee_ref dans run.def'
-        stop
-       endif
-       if (annee_ref.eq.1992 .and. day1.lt.day_ini_astex) then
-        print*,'Astex debute le 13 Juin 1992 (jour julien=165)'
-        print*,'Changer dayref dans run.def'
-        stop
-       endif
-
-! Determine timestep relative to the 1st day of TOGA-COARE:
-!       timeit=(day-day1)*86400.
-!       if (annee_ref.eq.1992) then
-!        timeit=(day-day_ini_astex)*86400.
-!       else
-!        timeit=(day+2.-1.)*86400. ! 2 days between Jun13 and Jun15 1992
-!       endif
-      timeit=(day-day_ini_astex)*86400
-
-! Determine the closest observation times:
-       it_astex1=INT(timeit/dt_astex)+1
-       it_astex2=it_astex1 + 1
-       time_astex1=(it_astex1-1)*dt_astex
-       time_astex2=(it_astex2-1)*dt_astex
-       print *,'timeit day day_ini_astex',timeit,day,day_ini_astex
-       print *,'it_astex1,it_astex2,time_astex1,time_astex2',              &
-     &          it_astex1,it_astex2,time_astex1,time_astex2
-
-       if (it_astex1 .ge. nt_astex) then
-        write(*,*) 'PB-stop: day, it_astex1, it_astex2, timeit: '          &
-     &        ,day,it_astex1,it_astex2,timeit/86400.
-        stop
-       endif
-
-! time interpolation:
-       frac=(time_astex2-timeit)/(time_astex2-time_astex1)
-       frac=max(frac,0.0)
-
-       div_prof = div_astex(it_astex2)                                     &
-     &          -frac*(div_astex(it_astex2)-div_astex(it_astex1))
-       ts_prof = ts_astex(it_astex2)                                        &
-     &          -frac*(ts_astex(it_astex2)-ts_astex(it_astex1))
-       ug_prof = ug_astex(it_astex2)                                       &
-     &          -frac*(ug_astex(it_astex2)-ug_astex(it_astex1))
-       vg_prof = vg_astex(it_astex2)                                       &
-     &          -frac*(vg_astex(it_astex2)-vg_astex(it_astex1))
-       ufa_prof = ufa_astex(it_astex2)                                     &
-     &          -frac*(ufa_astex(it_astex2)-ufa_astex(it_astex1))
-       vfa_prof = vfa_astex(it_astex2)                                     &
-     &          -frac*(vfa_astex(it_astex2)-vfa_astex(it_astex1))
-
-         print*,                                                           &
-     &'day,annee_ref,day_ini_astex,timeit,it_astex1,it_astex2,SST:',       &
-     &day,annee_ref,day_ini_astex,timeit/86400.,it_astex1,                 &
-     &it_astex2,div_prof,ts_prof,ug_prof,vg_prof,ufa_prof,vfa_prof 
-
-        return
-        END
-
-!======================================================================
-        SUBROUTINE interp_toga_time(day,day1,annee_ref                     &
-     &             ,year_ini_toga,day_ini_toga,nt_toga,dt_toga,nlev_toga   &
-     &             ,ts_toga,plev_toga,t_toga,q_toga,u_toga,v_toga,w_toga   &
-     &             ,ht_toga,vt_toga,hq_toga,vq_toga                        &
-     &             ,ts_prof,plev_prof,t_prof,q_prof,u_prof,v_prof,w_prof   &
-     &             ,ht_prof,vt_prof,hq_prof,vq_prof)
-        implicit none
-
-!---------------------------------------------------------------------------------------
-! Time interpolation of a 2D field to the timestep corresponding to day
-!
-! day: current julian day (e.g. 717538.2)
-! day1: first day of the simulation
-! nt_toga: total nb of data in the forcing (e.g. 480 for TOGA-COARE)
-! dt_toga: total time interval (in sec) between 2 forcing data (e.g. 6h for TOGA-COARE)
-!---------------------------------------------------------------------------------------
-
-#include "compar1d.h"
-
-! inputs:
-        integer annee_ref
-        integer nt_toga,nlev_toga
-        integer year_ini_toga
-        real day, day1,day_ini_toga,dt_toga
-        real ts_toga(nt_toga)
-        real plev_toga(nlev_toga,nt_toga),t_toga(nlev_toga,nt_toga)
-        real q_toga(nlev_toga,nt_toga),u_toga(nlev_toga,nt_toga)
-        real v_toga(nlev_toga,nt_toga),w_toga(nlev_toga,nt_toga)
-        real ht_toga(nlev_toga,nt_toga),vt_toga(nlev_toga,nt_toga)
-        real hq_toga(nlev_toga,nt_toga),vq_toga(nlev_toga,nt_toga)
-! outputs:
-        real ts_prof
-        real plev_prof(nlev_toga),t_prof(nlev_toga)
-        real q_prof(nlev_toga),u_prof(nlev_toga)
-        real v_prof(nlev_toga),w_prof(nlev_toga)
-        real ht_prof(nlev_toga),vt_prof(nlev_toga)
-        real hq_prof(nlev_toga),vq_prof(nlev_toga)
-! local:
-        integer it_toga1, it_toga2,k
-        real timeit,time_toga1,time_toga2,frac
-
-
-        if (forcing_type.eq.2) then
-! Check that initial day of the simulation consistent with TOGA-COARE period:
-       if (annee_ref.ne.1992 .and. annee_ref.ne.1993) then
-        print*,'Pour TOGA-COARE, annee_ref doit etre 1992 ou 1993'
-        print*,'Changer annee_ref dans run.def'
-        stop
-       endif
-       if (annee_ref.eq.1992 .and. day1.lt.day_ini_toga) then
-        print*,'TOGA-COARE a debute le 1er Nov 1992 (jour julien=306)'
-        print*,'Changer dayref dans run.def'
-        stop
-       endif
-       if (annee_ref.eq.1993 .and. day1.gt.day_ini_toga+119) then
-        print*,'TOGA-COARE a fini le 28 Feb 1993 (jour julien=59)'
-        print*,'Changer dayref ou nday dans run.def'
-        stop
-       endif
-
-       else if (forcing_type.eq.4) then
-
-! Check that initial day of the simulation consistent with TWP-ICE period:
-       if (annee_ref.ne.2006) then
-        print*,'Pour TWP-ICE, annee_ref doit etre 2006'
-        print*,'Changer annee_ref dans run.def'
-        stop
-       endif
-       if (annee_ref.eq.2006 .and. day1.lt.day_ini_toga) then
-        print*,'TWP-ICE a debute le 17 Jan 2006 (jour julien=17)'
-        print*,'Changer dayref dans run.def'
-        stop
-       endif
-       if (annee_ref.eq.2006 .and. day1.gt.day_ini_toga+26) then
-        print*,'TWP-ICE a fini le 12 Feb 2006 (jour julien=43)'
-        print*,'Changer dayref ou nday dans run.def'
-        stop
-       endif
-
-       endif
-
-! Determine timestep relative to the 1st day of TOGA-COARE:
-!       timeit=(day-day1)*86400.
-!       if (annee_ref.eq.1992) then
-!        timeit=(day-day_ini_toga)*86400.
-!       else
-!        timeit=(day+61.-1.)*86400. ! 61 days between Nov01 and Dec31 1992
-!       endif
-      timeit=(day-day_ini_toga)*86400
-
-! Determine the closest observation times:
-       it_toga1=INT(timeit/dt_toga)+1
-       it_toga2=it_toga1 + 1
-       time_toga1=(it_toga1-1)*dt_toga
-       time_toga2=(it_toga2-1)*dt_toga
-
-       if (it_toga1 .ge. nt_toga) then
-        write(*,*) 'PB-stop: day, it_toga1, it_toga2, timeit: '            &
-     &        ,day,it_toga1,it_toga2,timeit/86400.
-        stop
-       endif
-
-! time interpolation:
-       frac=(time_toga2-timeit)/(time_toga2-time_toga1)
-       frac=max(frac,0.0)
-
-       ts_prof = ts_toga(it_toga2)                                         &
-     &          -frac*(ts_toga(it_toga2)-ts_toga(it_toga1))
-
-!        print*,
-!     :'day,annee_ref,day_ini_toga,timeit,it_toga1,it_toga2,SST:',
-!     :day,annee_ref,day_ini_toga,timeit/86400.,it_toga1,it_toga2,ts_prof
-
-       do k=1,nlev_toga
-        plev_prof(k) = 100.*(plev_toga(k,it_toga2)                         &
-     &          -frac*(plev_toga(k,it_toga2)-plev_toga(k,it_toga1)))
-        t_prof(k) = t_toga(k,it_toga2)                                     &
-     &          -frac*(t_toga(k,it_toga2)-t_toga(k,it_toga1))
-        q_prof(k) = q_toga(k,it_toga2)                                     &
-     &          -frac*(q_toga(k,it_toga2)-q_toga(k,it_toga1))
-        u_prof(k) = u_toga(k,it_toga2)                                     &
-     &          -frac*(u_toga(k,it_toga2)-u_toga(k,it_toga1))
-        v_prof(k) = v_toga(k,it_toga2)                                     &
-     &          -frac*(v_toga(k,it_toga2)-v_toga(k,it_toga1))
-        w_prof(k) = w_toga(k,it_toga2)                                     &
-     &          -frac*(w_toga(k,it_toga2)-w_toga(k,it_toga1))
-        ht_prof(k) = ht_toga(k,it_toga2)                                   &
-     &          -frac*(ht_toga(k,it_toga2)-ht_toga(k,it_toga1))
-        vt_prof(k) = vt_toga(k,it_toga2)                                   &
-     &          -frac*(vt_toga(k,it_toga2)-vt_toga(k,it_toga1))
-        hq_prof(k) = hq_toga(k,it_toga2)                                   &
-     &          -frac*(hq_toga(k,it_toga2)-hq_toga(k,it_toga1))
-        vq_prof(k) = vq_toga(k,it_toga2)                                   &
-     &          -frac*(vq_toga(k,it_toga2)-vq_toga(k,it_toga1))
-        enddo
-
-        return
-        END
-
-!======================================================================
-        SUBROUTINE interp_dice_time(day,day1,annee_ref                    &
-     &             ,year_ini_dice,day_ini_dice,nt_dice,dt_dice            &
-     &             ,nlev_dice,shf_dice,lhf_dice,lwup_dice,swup_dice       &
-     &             ,tg_dice,ustar_dice,psurf_dice,ug_dice,vg_dice         &
-     &             ,ht_dice,hq_dice,hu_dice,hv_dice,w_dice,omega_dice     &
-     &             ,shf_prof,lhf_prof,lwup_prof,swup_prof,tg_prof         &
-     &             ,ustar_prof,psurf_prof,ug_prof,vg_prof                 &
-     &             ,ht_prof,hq_prof,hu_prof,hv_prof,w_prof,omega_prof)
-        implicit none
-
-!---------------------------------------------------------------------------------------
-! Time interpolation of a 2D field to the timestep corresponding to day
-!
-! day: current julian day (e.g. 717538.2)
-! day1: first day of the simulation
-! nt_dice: total nb of data in the forcing (e.g. 145 for Dice)
-! dt_dice: total time interval (in sec) between 2 forcing data (e.g. 30min. for Dice)
-!---------------------------------------------------------------------------------------
-
-#include "compar1d.h"
-
-! inputs:
-        integer annee_ref
-        integer nt_dice,nlev_dice
-        integer year_ini_dice
-        real day, day1,day_ini_dice,dt_dice
-        real shf_dice(nt_dice),lhf_dice(nt_dice),lwup_dice(nt_dice)
-        real swup_dice(nt_dice),tg_dice(nt_dice),ustar_dice(nt_dice)
-        real psurf_dice(nt_dice),ug_dice(nt_dice),vg_dice(nt_dice)
-        real ht_dice(nlev_dice,nt_dice),hq_dice(nlev_dice,nt_dice)
-        real hu_dice(nlev_dice,nt_dice),hv_dice(nlev_dice,nt_dice)
-        real w_dice(nlev_dice,nt_dice),omega_dice(nlev_dice,nt_dice)
-! outputs:
-        real tg_prof,shf_prof,lhf_prof,lwup_prof,swup_prof
-        real ustar_prof,psurf_prof,ug_prof,vg_prof
-        real ht_prof(nlev_dice),hq_prof(nlev_dice)
-        real hu_prof(nlev_dice),hv_prof(nlev_dice)
-        real w_prof(nlev_dice),omega_prof(nlev_dice)
-! local:
-        integer it_dice1, it_dice2,k
-        real timeit,time_dice1,time_dice2,frac
-
-
-        if (forcing_type.eq.7) then
-! Check that initial day of the simulation consistent with Dice period:
-       print *,'annee_ref=',annee_ref
-       print *,'day1=',day1
-       print *,'day_ini_dice=',day_ini_dice
-       if (annee_ref.ne.1999) then
-        print*,'Pour Dice, annee_ref doit etre 1999'
-        print*,'Changer annee_ref dans run.def'
-        stop
-       endif
-       if (annee_ref.eq.1999 .and. day1.gt.day_ini_dice) then
-        print*,'Dice a debute le 23 Oct 1999 (jour julien=296)'
-        print*,'Changer dayref dans run.def',day1,day_ini_dice
-        stop
-       endif
-       if (annee_ref.eq.1999 .and. day1.gt.day_ini_dice+2) then
-        print*,'Dice a fini le 25 Oct 1999 (jour julien=298)'
-        print*,'Changer dayref ou nday dans run.def',day1,day_ini_dice
-        stop
-       endif
-
-       endif
-
-! Determine timestep relative to the 1st day of TOGA-COARE:
-!       timeit=(day-day1)*86400.
-!       if (annee_ref.eq.1992) then
-!        timeit=(day-day_ini_dice)*86400.
-!       else
-!        timeit=(day+61.-1.)*86400. ! 61 days between Nov01 and Dec31 1992
-!       endif
-      timeit=(day-day_ini_dice)*86400
-
-! Determine the closest observation times:
-       it_dice1=INT(timeit/dt_dice)+1
-       it_dice2=it_dice1 + 1
-       time_dice1=(it_dice1-1)*dt_dice
-       time_dice2=(it_dice2-1)*dt_dice
-
-       if (it_dice1 .ge. nt_dice) then
-        write(*,*) 'PB-stop: day, it_dice1, it_dice2, timeit: ',day,it_dice1,it_dice2,timeit/86400.
-        stop
-       endif
-
-! time interpolation:
-       frac=(time_dice2-timeit)/(time_dice2-time_dice1)
-       frac=max(frac,0.0)
-
-       shf_prof = shf_dice(it_dice2)-frac*(shf_dice(it_dice2)-shf_dice(it_dice1))
-       lhf_prof = lhf_dice(it_dice2)-frac*(lhf_dice(it_dice2)-lhf_dice(it_dice1))
-       lwup_prof = lwup_dice(it_dice2)-frac*(lwup_dice(it_dice2)-lwup_dice(it_dice1))
-       swup_prof = swup_dice(it_dice2)-frac*(swup_dice(it_dice2)-swup_dice(it_dice1))
-       tg_prof = tg_dice(it_dice2)-frac*(tg_dice(it_dice2)-tg_dice(it_dice1))
-       ustar_prof = ustar_dice(it_dice2)-frac*(ustar_dice(it_dice2)-ustar_dice(it_dice1))
-       psurf_prof = psurf_dice(it_dice2)-frac*(psurf_dice(it_dice2)-psurf_dice(it_dice1))
-       ug_prof = ug_dice(it_dice2)-frac*(ug_dice(it_dice2)-ug_dice(it_dice1))
-       vg_prof = vg_dice(it_dice2)-frac*(vg_dice(it_dice2)-vg_dice(it_dice1))
-
-!        print*,
-!     :'day,annee_ref,day_ini_dice,timeit,it_dice1,it_dice2,SST:',
-!     :day,annee_ref,day_ini_dice,timeit/86400.,it_dice1,it_dice2,ts_prof
-
-       do k=1,nlev_dice
-        ht_prof(k) = ht_dice(k,it_dice2)-frac*(ht_dice(k,it_dice2)-ht_dice(k,it_dice1))
-        hq_prof(k) = hq_dice(k,it_dice2)-frac*(hq_dice(k,it_dice2)-hq_dice(k,it_dice1))
-        hu_prof(k) = hu_dice(k,it_dice2)-frac*(hu_dice(k,it_dice2)-hu_dice(k,it_dice1))
-        hv_prof(k) = hv_dice(k,it_dice2)-frac*(hv_dice(k,it_dice2)-hv_dice(k,it_dice1))
-        w_prof(k) = w_dice(k,it_dice2)-frac*(w_dice(k,it_dice2)-w_dice(k,it_dice1))
-        omega_prof(k) = omega_dice(k,it_dice2)-frac*(omega_dice(k,it_dice2)-omega_dice(k,it_dice1))
-        enddo
-
-        return
-        END
-
-!======================================================================
-        SUBROUTINE interp_gabls4_time(day,day1,annee_ref                              &
-     &             ,year_ini_gabls4,day_ini_gabls4,nt_gabls4,dt_gabls4,nlev_gabls4    &
-     &             ,ug_gabls4,vg_gabls4,ht_gabls4,hq_gabls4,tg_gabls4                          &
-     &             ,ug_prof,vg_prof,ht_prof,hq_prof,tg_prof)
-        implicit none
-
-!---------------------------------------------------------------------------------------
-! Time interpolation of a 2D field to the timestep corresponding to day
-!
-! day: current julian day 
-! day1: first day of the simulation
-! nt_gabls4: total nb of data in the forcing (e.g. 37 for gabls4)
-! dt_gabls4: total time interval (in sec) between 2 forcing data (e.g. 60min. for gabls4)
-!---------------------------------------------------------------------------------------
-
-#include "compar1d.h"
-
-! inputs:
-        integer annee_ref
-        integer nt_gabls4,nlev_gabls4
-        integer year_ini_gabls4
-        real day, day1,day_ini_gabls4,dt_gabls4
-        real ug_gabls4(nlev_gabls4,nt_gabls4),vg_gabls4(nlev_gabls4,nt_gabls4)
-        real ht_gabls4(nlev_gabls4,nt_gabls4),hq_gabls4(nlev_gabls4,nt_gabls4)
-        real tg_gabls4(nt_gabls4), tg_prof
-! outputs:
-        real ug_prof(nlev_gabls4),vg_prof(nlev_gabls4)
-        real ht_prof(nlev_gabls4),hq_prof(nlev_gabls4)
-! local:
-        integer it_gabls41, it_gabls42,k
-        real timeit,time_gabls41,time_gabls42,frac
-
-
-
-! Check that initial day of the simulation consistent with gabls4 period:
-       if (forcing_type.eq.8 ) then
-       print *,'annee_ref=',annee_ref
-       print *,'day1=',day1
-       print *,'day_ini_gabls4=',day_ini_gabls4
-       if (annee_ref.ne.2009) then
-        print*,'Pour gabls4, annee_ref doit etre 2009'
-        print*,'Changer annee_ref dans run.def'
-        stop
-       endif
-       if (annee_ref.eq.2009 .and. day1.gt.day_ini_gabls4) then
-        print*,'gabls4 a debute le 11 dec 2009 (jour julien=345)'
-        print*,'Changer dayref dans run.def',day1,day_ini_gabls4
-        stop
-       endif
-       if (annee_ref.eq.2009 .and. day1.gt.day_ini_gabls4+2) then
-        print*,'gabls4 a fini le 12 dec 2009 (jour julien=346)'
-        print*,'Changer dayref ou nday dans run.def',day1,day_ini_gabls4
-        stop
-       endif
-       endif
-
-      timeit=(day-day_ini_gabls4)*86400
-       print *,'day,day_ini_gabls4=',day,day_ini_gabls4
-       print *,'nt_gabls4,dt,timeit=',nt_gabls4,dt_gabls4,timeit
-
-! Determine the closest observation times:
-       it_gabls41=INT(timeit/dt_gabls4)+1
-       it_gabls42=it_gabls41 + 1
-       time_gabls41=(it_gabls41-1)*dt_gabls4
-       time_gabls42=(it_gabls42-1)*dt_gabls4
-
-       if (it_gabls41 .ge. nt_gabls4) then
-        write(*,*) 'PB-stop: day, it_gabls41, it_gabls42, timeit: ',day,it_gabls41,it_gabls42,timeit/86400.
-        stop
-       endif
-
-! time interpolation:
-       frac=(time_gabls42-timeit)/(time_gabls42-time_gabls41)
-       frac=max(frac,0.0)
-
-
-       do k=1,nlev_gabls4
-        ug_prof(k) = ug_gabls4(k,it_gabls42)-frac*(ug_gabls4(k,it_gabls42)-ug_gabls4(k,it_gabls41))
-        vg_prof(k) = vg_gabls4(k,it_gabls42)-frac*(vg_gabls4(k,it_gabls42)-vg_gabls4(k,it_gabls41))
-        ht_prof(k) = ht_gabls4(k,it_gabls42)-frac*(ht_gabls4(k,it_gabls42)-ht_gabls4(k,it_gabls41))
-        hq_prof(k) = hq_gabls4(k,it_gabls42)-frac*(hq_gabls4(k,it_gabls42)-hq_gabls4(k,it_gabls41))
-        enddo
-        tg_prof=tg_gabls4(it_gabls42)-frac*(tg_gabls4(it_gabls42)-tg_gabls4(it_gabls41))
-        return
-        END
-
-!======================================================================
-        SUBROUTINE interp_armcu_time(day,day1,annee_ref                    &
-     &             ,year_ini_armcu,day_ini_armcu,nt_armcu,dt_armcu         &
-     &             ,nlev_armcu,fs_armcu,fl_armcu,at_armcu,rt_armcu         &
-     &             ,aqt_armcu,fs_prof,fl_prof,at_prof,rt_prof,aqt_prof)
-        implicit none
-
-!---------------------------------------------------------------------------------------
-! Time interpolation of a 2D field to the timestep corresponding to day
-!
-! day: current julian day (e.g. 717538.2)
-! day1: first day of the simulation
-! nt_armcu: total nb of data in the forcing (e.g. 31 for armcu)
-! dt_armcu: total time interval (in sec) between 2 forcing data (e.g. 1/2h for armcu)
-! fs= sensible flux
-! fl= latent flux
-! at,rt,aqt= advective and radiative tendencies
-!---------------------------------------------------------------------------------------
-
-! inputs:
-        integer annee_ref
-        integer nt_armcu,nlev_armcu
-        integer year_ini_armcu
-        real day, day1,day_ini_armcu,dt_armcu
-        real fs_armcu(nt_armcu),fl_armcu(nt_armcu),at_armcu(nt_armcu)
-        real rt_armcu(nt_armcu),aqt_armcu(nt_armcu)
-! outputs:
-        real fs_prof,fl_prof,at_prof,rt_prof,aqt_prof
-! local:
-        integer it_armcu1, it_armcu2,k
-        real timeit,time_armcu1,time_armcu2,frac
-
-! Check that initial day of the simulation consistent with ARMCU period:
-       if (annee_ref.ne.1997 ) then
-        print*,'Pour ARMCU, annee_ref doit etre 1997 '
-        print*,'Changer annee_ref dans run.def'
-        stop
-       endif
-
-      timeit=(day-day_ini_armcu)*86400
-
-! Determine the closest observation times:
-       it_armcu1=INT(timeit/dt_armcu)+1
-       it_armcu2=it_armcu1 + 1
-       time_armcu1=(it_armcu1-1)*dt_armcu
-       time_armcu2=(it_armcu2-1)*dt_armcu
-       print *,'timeit day day_ini_armcu',timeit,day,day_ini_armcu
-       print *,'it_armcu1,it_armcu2,time_armcu1,time_armcu2',              &
-     &          it_armcu1,it_armcu2,time_armcu1,time_armcu2
-
-       if (it_armcu1 .ge. nt_armcu) then
-        write(*,*) 'PB-stop: day, it_armcu1, it_armcu2, timeit: '          &
-     &        ,day,it_armcu1,it_armcu2,timeit/86400.
-        stop
-       endif
-
-! time interpolation:
-       frac=(time_armcu2-timeit)/(time_armcu2-time_armcu1)
-       frac=max(frac,0.0)
-
-       fs_prof = fs_armcu(it_armcu2)                                       &
-     &          -frac*(fs_armcu(it_armcu2)-fs_armcu(it_armcu1))
-       fl_prof = fl_armcu(it_armcu2)                                       &
-     &          -frac*(fl_armcu(it_armcu2)-fl_armcu(it_armcu1))
-       at_prof = at_armcu(it_armcu2)                                       &
-     &          -frac*(at_armcu(it_armcu2)-at_armcu(it_armcu1))
-       rt_prof = rt_armcu(it_armcu2)                                       &
-     &          -frac*(rt_armcu(it_armcu2)-rt_armcu(it_armcu1))
-       aqt_prof = aqt_armcu(it_armcu2)                                       &
-     &          -frac*(aqt_armcu(it_armcu2)-aqt_armcu(it_armcu1))
-
-         print*,                                                           &
-     &'day,annee_ref,day_ini_armcu,timeit,it_armcu1,it_armcu2,SST:',       &
-     &day,annee_ref,day_ini_armcu,timeit/86400.,it_armcu1,                 &
-     &it_armcu2,fs_prof,fl_prof,at_prof,rt_prof,aqt_prof
-
-        return
-        END
-
-!=====================================================================
-      subroutine readprofiles(nlev_max,kmax,ntrac,height,                  &
-     &           thlprof,qtprof,uprof,                                     &
-     &           vprof,e12prof,ugprof,vgprof,                              &
-     &           wfls,dqtdxls,dqtdyls,dqtdtls,                             &
-     &           thlpcar,tracer,nt1,nt2)
-      implicit none
-
-        integer nlev_max,kmax,kmax2,ntrac
-        logical :: llesread = .true.
-
-        real height(nlev_max),thlprof(nlev_max),qtprof(nlev_max),          &
-     &       uprof(nlev_max),vprof(nlev_max),e12prof(nlev_max),            &
-     &       ugprof(nlev_max),vgprof(nlev_max),wfls(nlev_max),             &
-     &       dqtdxls(nlev_max),dqtdyls(nlev_max),dqtdtls(nlev_max),        &
-     &           thlpcar(nlev_max),tracer(nlev_max,ntrac)
-
-        real height1(nlev_max)
-
-        integer, parameter :: ilesfile=1
-        integer :: ierr,k,itrac,nt1,nt2
-
-        if(.not.(llesread)) return
-
-       open (ilesfile,file='prof.inp.001',status='old',iostat=ierr)
-        if (ierr /= 0) stop 'ERROR:Prof.inp does not exist'
-        read (ilesfile,*) kmax
-        do k=1,kmax
-          read (ilesfile,*) height1(k),thlprof(k),qtprof (k),               &
-     &                      uprof (k),vprof  (k),e12prof(k)
-        enddo
-        close(ilesfile)
-
-       open(ilesfile,file='lscale.inp.001',status='old',iostat=ierr)
-        if (ierr /= 0) stop 'ERROR:Lscale.inp does not exist'
-        read (ilesfile,*) kmax2
-        if (kmax .ne. kmax2) then
-          print *, 'fichiers prof.inp et lscale.inp incompatibles :'
-          print *, 'nbre de niveaux : ',kmax,' et ',kmax2
-          stop 'lecture profiles'
-        endif
-        do k=1,kmax
-          read (ilesfile,*) height(k),ugprof(k),vgprof(k),wfls(k),         &
-     &                      dqtdxls(k),dqtdyls(k),dqtdtls(k),thlpcar(k)
-        end do
-        do k=1,kmax
-          if (height(k) .ne. height1(k)) then
-            print *, 'fichiers prof.inp et lscale.inp incompatibles :'
-            print *, 'les niveaux different : ',k,height1(k), height(k)
-            stop
-          endif
-        end do
-        close(ilesfile)
-
-       open(ilesfile,file='trac.inp.001',status='old',iostat=ierr)
-        if (ierr /= 0) then
-            print*,'WARNING : trac.inp does not exist'
-        else
-        read (ilesfile,*) kmax2,nt1,nt2
-        if (nt2>ntrac) then
-          stop 'Augmenter le nombre de traceurs dans traceur.def'
-        endif
-        if (kmax .ne. kmax2) then
-          print *, 'fichiers prof.inp et lscale.inp incompatibles :'
-          print *, 'nbre de niveaux : ',kmax,' et ',kmax2
-          stop 'lecture profiles'
-        endif
-        do k=1,kmax
-          read (ilesfile,*) height(k),(tracer(k,itrac),itrac=nt1,nt2)
-        end do
-        close(ilesfile)
-        endif
-
-        return
-        end
-!======================================================================
-      subroutine readprofile_sandu(nlev_max,kmax,height,pprof,tprof,       &
-     &       thlprof,qprof,uprof,vprof,wprof,omega,o3mmr)
-!======================================================================
-      implicit none
-
-        integer nlev_max,kmax
-        logical :: llesread = .true.
-
-        real height(nlev_max),pprof(nlev_max),tprof(nlev_max)
-        real thlprof(nlev_max)
-        real qprof(nlev_max),uprof(nlev_max),vprof(nlev_max)
-        real wprof(nlev_max),omega(nlev_max),o3mmr(nlev_max)
-
-        integer, parameter :: ilesfile=1
-        integer :: k,ierr
-
-        if(.not.(llesread)) return
-
-       open (ilesfile,file='prof.inp.001',status='old',iostat=ierr)
-        if (ierr /= 0) stop 'ERROR:Prof.inp does not exist'
-        read (ilesfile,*) kmax
-        do k=1,kmax
-          read (ilesfile,*) height(k),pprof(k),  tprof(k),thlprof(k),      &
-     &                      qprof (k),uprof(k),  vprof(k),  wprof(k),      &
-     &                      omega (k),o3mmr(k)
-        enddo
-        close(ilesfile)
-
-        return
-        end
-
-!======================================================================
-      subroutine readprofile_astex(nlev_max,kmax,height,pprof,tprof,       &
-     &    thlprof,qvprof,qlprof,qtprof,uprof,vprof,wprof,tkeprof,o3mmr)
-!======================================================================
-      implicit none
-
-        integer nlev_max,kmax
-        logical :: llesread = .true.
-
-        real height(nlev_max),pprof(nlev_max),tprof(nlev_max),             &
-     &  thlprof(nlev_max),qlprof(nlev_max),qtprof(nlev_max),               &
-     &  qvprof(nlev_max),uprof(nlev_max),vprof(nlev_max),                  &
-     &  wprof(nlev_max),tkeprof(nlev_max),o3mmr(nlev_max)
-
-        integer, parameter :: ilesfile=1
-        integer :: ierr,k
-
-        if(.not.(llesread)) return
-
-       open (ilesfile,file='prof.inp.001',status='old',iostat=ierr)
-        if (ierr /= 0) stop 'ERROR:Prof.inp does not exist'
-        read (ilesfile,*) kmax
-        do k=1,kmax
-          read (ilesfile,*) height(k),pprof(k),  tprof(k),thlprof(k),      &
-     &                qvprof (k),qlprof (k),qtprof (k),                    &
-     &                uprof(k),  vprof(k),  wprof(k),tkeprof(k),o3mmr(k)
-        enddo
-        close(ilesfile)
-
-        return
-        end
-
-
-
-!======================================================================
-      subroutine readprofile_armcu(nlev_max,kmax,height,pprof,uprof,       &
-     &       vprof,thetaprof,tprof,qvprof,rvprof,aprof,bprof)
-!======================================================================
-      implicit none
-
-        integer nlev_max,kmax
-        logical :: llesread = .true.
-
-        real height(nlev_max),pprof(nlev_max),tprof(nlev_max)
-        real thetaprof(nlev_max),rvprof(nlev_max)
-        real qvprof(nlev_max),uprof(nlev_max),vprof(nlev_max)
-        real aprof(nlev_max+1),bprof(nlev_max+1)
-
-        integer, parameter :: ilesfile=1
-        integer, parameter :: ifile=2
-        integer :: ierr,jtot,k
-
-        if(.not.(llesread)) return
-
-! Read profiles at full levels
-       IF(nlev_max.EQ.19) THEN
-       open (ilesfile,file='prof.inp.19',status='old',iostat=ierr)
-       print *,'On ouvre prof.inp.19'
-       ELSE
-       open (ilesfile,file='prof.inp.40',status='old',iostat=ierr)
-       print *,'On ouvre prof.inp.40'
-       ENDIF
-        if (ierr /= 0) stop 'ERROR:Prof.inp does not exist'
-        read (ilesfile,*) kmax
-        do k=1,kmax
-          read (ilesfile,*) height(k)    ,pprof(k),  uprof(k), vprof(k),   &
-     &                      thetaprof(k) ,tprof(k), qvprof(k),rvprof(k)
-        enddo
-        close(ilesfile)
-
-! Vertical coordinates half levels for eta-coordinates (plev = alpha + beta * psurf) 
-       IF(nlev_max.EQ.19) THEN
-       open (ifile,file='proh.inp.19',status='old',iostat=ierr)
-       print *,'On ouvre proh.inp.19'
-       if (ierr /= 0) stop 'ERROR:Proh.inp.19 does not exist'
-       ELSE
-       open (ifile,file='proh.inp.40',status='old',iostat=ierr)
-       print *,'On ouvre proh.inp.40'
-       if (ierr /= 0) stop 'ERROR:Proh.inp.40 does not exist'
-       ENDIF
-        read (ifile,*) kmax
-        do k=1,kmax
-          read (ifile,*) jtot,aprof(k),bprof(k)
-        enddo
-        close(ifile)
-
-        return
-        end
-
-!=====================================================================
-      subroutine read_fire(fich_fire,nlevel,ntime                          &
-     &     ,zz,thl,qt,u,v,tke                                              &
-     &     ,ug,vg,wls,dqtdx,dqtdy,dqtdt,thl_rad)
-
-!program reading forcings of the FIRE case study
-
-
-      implicit none
-
-#include "netcdf.inc"
-
-      integer ntime,nlevel
-      character*80 :: fich_fire
-      real*8 zz(nlevel)
-
-      real*8 thl(nlevel)
-      real*8 qt(nlevel),u(nlevel)
-      real*8 v(nlevel),tke(nlevel)
-      real*8 ug(nlevel,ntime),vg(nlevel,ntime),wls(nlevel,ntime)
-      real*8 dqtdx(nlevel,ntime),dqtdy(nlevel,ntime)
-      real*8 dqtdt(nlevel,ntime),thl_rad(nlevel,ntime)
-
-      integer nid, ierr
-      integer nbvar3d
-      parameter(nbvar3d=30)
-      integer var3didin(nbvar3d)
-
-      ierr = NF_OPEN(fich_fire,NF_NOWRITE,nid)
-      if (ierr.NE.NF_NOERR) then
-         write(*,*) 'ERROR: Pb opening forcings nc file '
-         write(*,*) NF_STRERROR(ierr)
-         stop ""
-      endif
-
-
-       ierr=NF_INQ_VARID(nid,"zz",var3didin(1)) 
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'lev'
-         endif
-
-
-      ierr=NF_INQ_VARID(nid,"thetal",var3didin(2))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'temp'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"qt",var3didin(3))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'qv'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"u",var3didin(4))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'u'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"v",var3didin(5))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'v'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"tke",var3didin(6))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'tke'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"ugeo",var3didin(7))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'ug'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"vgeo",var3didin(8))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'vg'
-         endif
-      
-      ierr=NF_INQ_VARID(nid,"wls",var3didin(9))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'wls'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"dqtdx",var3didin(10))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'dqtdx'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"dqtdy",var3didin(11))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'dqtdy'
-      endif
-
-      ierr=NF_INQ_VARID(nid,"dqtdt",var3didin(12))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'dqtdt'
-      endif
-
-      ierr=NF_INQ_VARID(nid,"thl_rad",var3didin(13))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'thl_rad'
-      endif
-!dimensions lecture
-!      call catchaxis(nid,ntime,nlevel,time,z,ierr)
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(1),zz)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(1),zz)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture z ok',zz
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(2),thl)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(2),thl)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture thl ok',thl
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(3),qt)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(3),qt)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture qt ok',qt
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(4),u)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(4),u)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture u ok',u
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(5),v)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(5),v)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture v ok',v
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(6),tke)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(6),tke)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture tke ok',tke
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(7),ug)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(7),ug)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture ug ok',ug
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(8),vg)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(8),vg)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture vg ok',vg
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(9),wls)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(9),wls)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture wls ok',wls
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(10),dqtdx)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(10),dqtdx)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture dqtdx ok',dqtdx
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(11),dqtdy)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(11),dqtdy)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture dqtdy ok',dqtdy
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(12),dqtdt)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(12),dqtdt)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture dqtdt ok',dqtdt
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(13),thl_rad)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(13),thl_rad)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture thl_rad ok',thl_rad
-
-         return 
-         end subroutine read_fire
-!=====================================================================
-      subroutine read_dice(fich_dice,nlevel,ntime                         &
-     &     ,zz,pres,t,qv,u,v,o3                                          &
-     &     ,shf,lhf,lwup,swup,tg,ustar,psurf,ug,vg                        &
-     &     ,hadvt,hadvq,hadvu,hadvv,w,omega)
-
-!program reading initial profils and forcings of the Dice case study
-
-
-      implicit none
-
-#include "netcdf.inc"
-#include "YOMCST.h"
-
-      integer ntime,nlevel
-      integer l,k
-      character*80 :: fich_dice
-      real*8 time(ntime)
-      real*8 zz(nlevel)
-
-      real*8 th(nlevel),pres(nlevel),t(nlevel)
-      real*8 qv(nlevel),u(nlevel),v(nlevel),o3(nlevel)
-      real*8 shf(ntime),lhf(ntime),lwup(ntime),swup(ntime),tg(ntime)
-      real*8 ustar(ntime),psurf(ntime),ug(ntime),vg(ntime)
-      real*8 hadvt(nlevel,ntime),hadvq(nlevel,ntime),hadvu(nlevel,ntime)
-      real*8 hadvv(nlevel,ntime),w(nlevel,ntime),omega(nlevel,ntime)
-      real*8 pzero
-
-      integer nid, ierr
-      integer nbvar3d
-      parameter(nbvar3d=30)
-      integer var3didin(nbvar3d)
-
-      pzero=100000.
-      ierr = NF_OPEN(fich_dice,NF_NOWRITE,nid)
-      if (ierr.NE.NF_NOERR) then
-         write(*,*) 'ERROR: Pb opening forcings nc file '
-         write(*,*) NF_STRERROR(ierr)
-         stop ""
-      endif
-
-
-       ierr=NF_INQ_VARID(nid,"height",var3didin(1)) 
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'height'
-         endif
-
-       ierr=NF_INQ_VARID(nid,"pf",var3didin(11)) 
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'pf'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"theta",var3didin(12))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'theta'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"qv",var3didin(13))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'qv'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"u",var3didin(14))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'u'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"v",var3didin(15))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'v'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"o3mmr",var3didin(16))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'o3'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"shf",var3didin(2))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'shf'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"lhf",var3didin(3))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'lhf'
-         endif
-      
-      ierr=NF_INQ_VARID(nid,"lwup",var3didin(4))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'lwup'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"swup",var3didin(5))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'dqtdx'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"Tg",var3didin(6))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'Tg'
-      endif
-
-      ierr=NF_INQ_VARID(nid,"ustar",var3didin(7))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'ustar'
-      endif
-
-      ierr=NF_INQ_VARID(nid,"psurf",var3didin(8))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'psurf'
-      endif
-
-      ierr=NF_INQ_VARID(nid,"Ug",var3didin(9))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'Ug'
-      endif
-
-      ierr=NF_INQ_VARID(nid,"Vg",var3didin(10))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'Vg'
-      endif
-
-      ierr=NF_INQ_VARID(nid,"hadvT",var3didin(17))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'hadvT'
-      endif
-
-      ierr=NF_INQ_VARID(nid,"hadvq",var3didin(18))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'hadvq'
-      endif
-
-      ierr=NF_INQ_VARID(nid,"hadvu",var3didin(19))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'hadvu'
-      endif
-
-      ierr=NF_INQ_VARID(nid,"hadvv",var3didin(20))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'hadvv'
-      endif
-
-      ierr=NF_INQ_VARID(nid,"w",var3didin(21))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'w'
-      endif
-
-      ierr=NF_INQ_VARID(nid,"omega",var3didin(22))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'omega'
-      endif
-!dimensions lecture
-!      call catchaxis(nid,ntime,nlevel,time,z,ierr)
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(1),zz)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(1),zz)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture zz ok',zz
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(11),pres)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(11),pres)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture pres ok',pres
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(12),th)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(12),th)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture th ok',th
-           do k=1,nlevel
-             t(k)=th(k)*(pres(k)/pzero)**rkappa
-           enddo
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(13),qv)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(13),qv)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture qv ok',qv
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(14),u)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(14),u)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture u ok',u
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(15),v)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(15),v)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture v ok',v
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(16),o3)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(16),o3)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture o3 ok',o3
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(2),shf)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(2),shf)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture shf ok',shf
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(3),lhf)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(3),lhf)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture lhf ok',lhf
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(4),lwup)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(4),lwup)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture lwup ok',lwup
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(5),swup)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(5),swup)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture swup ok',swup
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(6),tg)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(6),tg)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture tg ok',tg
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(7),ustar)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(7),ustar)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture ustar ok',ustar
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(8),psurf)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(8),psurf)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture psurf ok',psurf
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(9),ug)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(9),ug)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture ug ok',ug
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(10),vg)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(10),vg)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture vg ok',vg
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(17),hadvt)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(17),hadvt)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture hadvt ok',hadvt
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(18),hadvq)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(18),hadvq)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture hadvq ok',hadvq
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(19),hadvu)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(19),hadvu)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture hadvu ok',hadvu
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(20),hadvv)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(20),hadvv)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture hadvv ok',hadvv
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(21),w)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(21),w)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture w ok',w
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(22),omega)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(22),omega)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-!          write(*,*)'lecture omega ok',omega
-
-         return 
-         end subroutine read_dice
-!=====================================================================
-      subroutine read_gabls4(fich_gabls4,nlevel,ntime,nsol                    &
-     &     ,zz,depth_sn,ug,vg,pf,th,t,qv,u,v,hadvt,hadvq,tg,tsnow,snow_dens)
-
-!program reading initial profils and forcings of the Gabls4 case study
-
-
-      implicit none
-
-#include "netcdf.inc"
-
-      integer ntime,nlevel,nsol
-      integer l,k
-      character*80 :: fich_gabls4
-      real*8 time(ntime)
-
-!  ATTENTION: visiblement quand on lit gabls4_driver.nc on recupere les donnees 
-! dans un ordre inverse par rapport a la convention LMDZ
-! ==> il faut tout inverser  (MPL 20141024)
-! les variables indexees "_i" sont celles qui sont lues dans gabls4_driver.nc
-      real*8 zz_i(nlevel),th_i(nlevel),pf_i(nlevel),t_i(nlevel)
-      real*8 qv_i(nlevel),u_i(nlevel),v_i(nlevel),ug_i(nlevel,ntime),vg_i(nlevel,ntime)
-      real*8 hadvt_i(nlevel,ntime),hadvq_i(nlevel,ntime)
-
-      real*8 zz(nlevel),th(nlevel),pf(nlevel),t(nlevel)
-      real*8 qv(nlevel),u(nlevel),v(nlevel),ug(nlevel,ntime),vg(nlevel,ntime)
-      real*8 hadvt(nlevel,ntime),hadvq(nlevel,ntime)
-
-      real*8 depth_sn(nsol),tsnow(nsol),snow_dens(nsol)
-      real*8 tg(ntime)
-      integer nid, ierr
-      integer nbvar3d
-      parameter(nbvar3d=30)
-      integer var3didin(nbvar3d)
-
-      ierr = NF_OPEN(fich_gabls4,NF_NOWRITE,nid)
-      if (ierr.NE.NF_NOERR) then
-         write(*,*) 'ERROR: Pb opening forcings nc file '
-         write(*,*) NF_STRERROR(ierr)
-         stop ""
-      endif
-
-
-       ierr=NF_INQ_VARID(nid,"height",var3didin(1)) 
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'height'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"depth_sn",var3didin(2))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'depth_sn'
-      endif
-
-      ierr=NF_INQ_VARID(nid,"Ug",var3didin(3))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'Ug'
-      endif
-
-      ierr=NF_INQ_VARID(nid,"Vg",var3didin(4))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'Vg'
-      endif
-       ierr=NF_INQ_VARID(nid,"pf",var3didin(5)) 
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'pf'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"theta",var3didin(6))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'theta'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"tempe",var3didin(7))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'tempe'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"qv",var3didin(8))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'qv'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"u",var3didin(9))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'u'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"v",var3didin(10))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'v'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"hadvT",var3didin(11))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'hadvt'
-         endif
-
-      ierr=NF_INQ_VARID(nid,"hadvQ",var3didin(12))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'hadvq'
-      endif
-
-      ierr=NF_INQ_VARID(nid,"Tsnow",var3didin(14))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'tsnow'
-      endif
-
-      ierr=NF_INQ_VARID(nid,"snow_density",var3didin(15))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'snow_density'
-      endif
-
-      ierr=NF_INQ_VARID(nid,"Tg",var3didin(16))
-         if(ierr/=NF_NOERR) then
-           write(*,*) NF_STRERROR(ierr)
-           stop 'Tg'
-      endif
-
-
-!dimensions lecture
-!      call catchaxis(nid,ntime,nlevel,time,z,ierr)
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(1),zz_i)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(1),zz_i)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(2),depth_sn)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(2),depth_sn)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(3),ug_i)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(3),ug_i)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(4),vg_i)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(4),vg_i)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(5),pf_i)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(5),pf_i)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(6),th_i)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(6),th_i)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(7),t_i)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(7),t_i)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(8),qv_i)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(8),qv_i)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(9),u_i)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(9),u_i)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(10),v_i)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(10),v_i)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(11),hadvt_i)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(11),hadvt_i)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(12),hadvq_i)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(12),hadvq_i)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(14),tsnow)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(14),tsnow)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
- 
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(15),snow_dens)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(15),snow_dens)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-
-#ifdef NC_DOUBLE
-         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(16),tg)
-#else
-         ierr = NF_GET_VAR_REAL(nid,var3didin(16),tg)
-#endif
-         if(ierr/=NF_NOERR) then
-            write(*,*) NF_STRERROR(ierr)
-            stop "getvarup"
-         endif
-
-! On remet les variables lues dans le bon ordre des niveaux (MPL 20141024)
-         do k=1,nlevel
-           zz(k)=zz_i(nlevel+1-k)
-           ug(k,:)=ug_i(nlevel+1-k,:)
-           vg(k,:)=vg_i(nlevel+1-k,:)
-           pf(k)=pf_i(nlevel+1-k)
-           print *,'pf=',pf(k)
-           th(k)=th_i(nlevel+1-k)
-           t(k)=t_i(nlevel+1-k)
-           qv(k)=qv_i(nlevel+1-k)
-           u(k)=u_i(nlevel+1-k)
-           v(k)=v_i(nlevel+1-k)
-           hadvt(k,:)=hadvt_i(nlevel+1-k,:)
-           hadvq(k,:)=hadvq_i(nlevel+1-k,:)
-         enddo
-         return 
- end subroutine read_gabls4
-!=====================================================================
-
-!     Reads CIRC input files      
-
-      SUBROUTINE read_circ(nlev_circ,cf,lwp,iwp,reliq,reice,t,z,p,pm,h2o,o3,sza)
-      
-      parameter (ncm_1=49180)
-#include "YOMCST.h"
-
-      real albsfc(ncm_1), albsfc_w(ncm_1)
-      real cf(nlev_circ), icefra(nlev_circ), deice(nlev_circ), &
-           reliq(nlev_circ), reice(nlev_circ), lwp(nlev_circ), iwp(nlev_circ)
-      real t(nlev_circ+1), z(nlev_circ+1), dz(nlev_circ), p(nlev_circ+1)
-      real aer_beta(nlev_circ), waer(nlev_circ), gaer(nlev_circ)
-      real pm(nlev_circ), tm(nlev_circ), h2o(nlev_circ), o3(nlev_circ)
-      real co2(nlev_circ), n2o(nlev_circ), co(nlev_circ), ch4(nlev_circ), &
-           o2(nlev_circ), ccl4(nlev_circ), f11(nlev_circ), f12(nlev_circ)
-!     za= zenital angle
-!     sza= cosinus angle zenital
-      real wavn(ncm_1), ssf(ncm_1),za,sza
-      integer nlev
-
-
-!     Open the files
-
-      open (11, file='Tsfc_sza_nlev_case.txt', status='old')
-      open (12, file='level_input_case.txt', status='old')
-      open (13, file='layer_input_case.txt', status='old')
-      open (14, file='aerosol_input_case.txt', status='old')
-      open (15, file='cloud_input_case.txt', status='old')
-      open (16, file='sfcalbedo_input_case.txt', status='old')
-      
-!     Read scalar information
-      do iskip=1,5
-         read (11, *)
-      enddo
-      read (11, '(i8)') nlev
-      read (11, '(f10.2)') tsfc
-      read (11, '(f10.2)') za
-      read (11, '(f10.4)') sw_dn_toa
-      sza=cos(za/180.*RPI)
-      print *,'nlev,tsfc,sza,sw_dn_toa,RPI',nlev,tsfc,sza,sw_dn_toa,RPI
-      close(11)
-
-!     Read level information
-      read (12, *)
-      do il=1,nlev
-         read (12, 302) ilev, z(il), p(il), t(il)
-         z(il)=z(il)*1000.    ! z donne en km
-         p(il)=p(il)*100.     ! p donne en mb
-      enddo
-302   format (i8, f8.3, 2f9.2)
-      close(12)
-
-!     Read layer information (midpoint values)
-      do iskip=1,3
-         read (13, *)
-      enddo
-      do il=1,nlev-1
-         read (13, 303) ilev,pm(il),tm(il),h2o(il),co2(il),o3(il), &
-                        n2o(il),co(il),ch4(il),o2(il),ccl4(il), &
-                        f11(il),f12(il)
-         pm(il)=pm(il)*100.
-      enddo
-303   format (i8, 2f9.2, 10(2x,e13.7))      
-      close(13)
-      
-!     Read aerosol layer information
-      do iskip=1,3
-         read (14, *)
-      enddo
-      read (14, '(f10.2)') aer_alpha
-      read (14, *)
-      read (14, *)
-      do il=1,nlev-1
-         read (14, 304) ilev, aer_beta(il), waer(il), gaer(il)
-      enddo
-304   format (i8, f9.5, 2f8.3)
-      close(14)
-      
-!     Read cloud information
-      do iskip=1,3
-         read (15, *)
-      enddo
-      do il=1,nlev-1
-         read (15, 305) ilev, cf(il), lwp(il), iwp(il), reliq(il), reice(il)
-         lwp(il)=lwp(il)/1000.          ! lwp donne en g/kg
-         iwp(il)=iwp(il)/1000.          ! iwp donne en g/kg
-         reliq(il)=reliq(il)/1000000.   ! reliq donne en microns
-         reice(il)=reice(il)/1000000.   ! reice donne en microns
-      enddo
-305   format (i8, f8.3, 4f9.2)
-      close(15)
-
-!     Read surface albedo (weighted & unweighted) and spectral solar irradiance
-      do iskip=1,6
-         read (16, *)
-      enddo
-      do icm_1=1,ncm_1
-         read (16, 306) wavn(icm_1), albsfc(icm_1), albsfc_w(icm_1), ssf(icm_1)
-      enddo
-306   format(f10.1, 2f12.5, f14.8)
-      close(16)
- 
-      return 
-      end subroutine read_circ
-!=====================================================================
-!     Reads RTMIP input files      
-
-      SUBROUTINE read_rtmip(nlev_rtmip,play,plev,t,h2o,o3)
-      
-#include "YOMCST.h"
-
-      real t(nlev_rtmip), pt(nlev_rtmip),pb(nlev_rtmip),h2o(nlev_rtmip), o3(nlev_rtmip)
-      real temp(nlev_rtmip), play(nlev_rtmip),ovap(nlev_rtmip), oz(nlev_rtmip),plev(nlev_rtmip+1)
-      integer nlev
-
-
-!     Open the files
-
-      open (11, file='low_resolution_profile.txt', status='old')
-      
-!     Read level information
-      read (11, *)
-      do il=1,nlev_rtmip
-         read (11, 302) pt(il), pb(il), t(il),h2o(il),o3(il)
-      enddo
-      do il=1,nlev_rtmip
-         play(il)=pt(nlev_rtmip-il+1)*100.     ! p donne en mb
-         temp(il)=t(nlev_rtmip-il+1)
-         ovap(il)=h2o(nlev_rtmip-il+1)
-         oz(il)=o3(nlev_rtmip-il+1)
-      enddo
-      do il=1,39
-         plev(il)=play(il)+(play(il+1)-play(il))/2.
-         print *,'il p t ovap oz=',il,plev(il),temp(il),ovap(il),oz(il)
-      enddo
-      plev(41)=101300.
-302   format (e16.10,3x,e16.10,3x,e16.10,3x,e12.6,3x,e12.6)
-      close(12)
- 
-      return 
-      end subroutine read_rtmip
-!=====================================================================
 
 !  Subroutines for nudging
@@ -5125,7 +1759,7 @@
        real frac,frac1,frac2,fact
  
-       do l = 1, llm
-       print *,'debut interp2, play=',l,play(l)
-       enddo
+!       do l = 1, llm
+!       print *,'debut interp2, play=',l,play(l)
+!       enddo
 !      do l = 1, nlev_cas
 !      print *,'debut interp2, plev_prof_cas=',l,play(l),plev_prof_cas(l)
@@ -5137,5 +1771,5 @@
  
         mxcalc=l
-        print *,'debut interp2, mxcalc=',mxcalc
+!        print *,'debut interp2, mxcalc=',mxcalc
          k1=0
          k2=0
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/1D_decl_cases.h
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/1D_decl_cases.h	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/1D_decl_cases.h	(revision 3605)
@@ -34,4 +34,5 @@
         real w_mod(llm), t_mod(llm),q_mod(llm)
         real u_mod(llm),v_mod(llm), ht_mod(llm),vt_mod(llm),ug_mod(llm),vg_mod(llm)
+	real temp_nudg_mod(llm),qv_nudg_mod(llm),u_nudg_mod(llm),v_nudg_mod(llm)
         real hq_mod(llm),vq_mod(llm),qv_mod(llm),ql_mod(llm),qt_mod(llm)
         real th_mod(llm)
@@ -95,35 +96,37 @@
 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 !Declarations specifiques au cas GABLS4   (MPL 20141023)
-        character*80 :: fich_gabls4
-        integer nlev_gabls4, nt_gabls4, nsol_gabls4
-        parameter (nlev_gabls4=90, nt_gabls4=37, nsol_gabls4=19)  
-        integer year_ini_gabls4, day_ini_gabls4, mth_ini_gabls4
-        real heure_ini_gabls4
-        real day_ju_ini_gabls4   ! Julian day of gabls4 first day
-        parameter (year_ini_gabls4=2009) 
-        parameter (mth_ini_gabls4=12)
-        parameter (day_ini_gabls4=11)  ! 11 = 11 decembre 2009
-        parameter (heure_ini_gabls4=0.) !0UTC en secondes
-        real dt_gabls4
-        parameter (dt_gabls4=3600.) ! 1 forcage ttes les heures
-
+!FHADETRUIRE
+!       character*80 :: fich_gabls4
+!       integer nlev_gabls4, nt_gabls4, nsol_gabls4
+!       parameter (nlev_gabls4=90, nt_gabls4=37, nsol_gabls4=19)  
+!       integer year_ini_gabls4, day_ini_gabls4, mth_ini_gabls4
+!       real heure_ini_gabls4
+!       real day_ju_ini_gabls4   ! Julian day of gabls4 first day
+!       parameter (year_ini_gabls4=2009) 
+!       parameter (mth_ini_gabls4=12)
+!       parameter (day_ini_gabls4=11)  ! 11 = 11 decembre 2009
+!       parameter (heure_ini_gabls4=0.) !0UTC en secondes
+!       real dt_gabls4
+!       parameter (dt_gabls4=3600.) ! 1 forcage ttes les heures
+!
 !profils initiaux:
-        real plev_gabls4(nlev_gabls4)
-        real zz_gabls4(nlev_gabls4)
-        real th_gabls4(nlev_gabls4),t_gabls4(nlev_gabls4),qv_gabls4(nlev_gabls4)
-        real u_gabls4(nlev_gabls4), v_gabls4(nlev_gabls4)
-        real depth_sn_gabls4(nsol_gabls4),tsnow_gabls4(nsol_gabls4),snow_dens_gabls4(nsol_gabls4)
-        real t_gabi(nlev_gabls4),qv_gabi(nlev_gabls4)
-        real u_gabi(nlev_gabls4), v_gabi(nlev_gabls4),ug_gabi(nlev_gabls4), vg_gabi(nlev_gabls4)
-        real ht_gabi(nlev_gabls4),hq_gabi(nlev_gabls4),poub(nlev_gabls4)
-        
+!       real plev_gabls4(nlev_gabls4)
+!       real zz_gabls4(nlev_gabls4)
+!       real th_gabls4(nlev_gabls4),t_gabls4(nlev_gabls4),qv_gabls4(nlev_gabls4)
+!       real u_gabls4(nlev_gabls4), v_gabls4(nlev_gabls4)
+!       real depth_sn_gabls4(nsol_gabls4),tsnow_gabls4(nsol_gabls4),snow_dens_gabls4(nsol_gabls4)
+!       real t_gabi(nlev_gabls4),qv_gabi(nlev_gabls4)
+!       real u_gabi(nlev_gabls4), v_gabi(nlev_gabls4),ug_gabi(nlev_gabls4), vg_gabi(nlev_gabls4)
+!       real ht_gabi(nlev_gabls4),hq_gabi(nlev_gabls4),poub(nlev_gabls4)
+!       
 !forcings
-        real ht_gabls4(nlev_gabls4,nt_gabls4),hq_gabls4(nlev_gabls4,nt_gabls4)
-        real ug_gabls4(nlev_gabls4,nt_gabls4),vg_gabls4(nlev_gabls4,nt_gabls4)
-        real tg_gabls4(nt_gabls4)
-        real ht_profg(nlev_gabls4),hq_profg(nlev_gabls4)
-        real ug_profg(nlev_gabls4),vg_profg(nlev_gabls4)
-        real tg_profg
-         
+! Lignes a detruire ...
+!       real ht_gabls4(nlev_gabls4,nt_gabls4),hq_gabls4(nlev_gabls4,nt_gabls4)
+!       real ug_gabls4(nlev_gabls4,nt_gabls4),vg_gabls4(nlev_gabls4,nt_gabls4)
+!       real tg_gabls4(nt_gabls4)
+!       real ht_profg(nlev_gabls4),hq_profg(nlev_gabls4)
+!       real ug_profg(nlev_gabls4),vg_profg(nlev_gabls4)
+!       real tg_profg
+!        
 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 
@@ -281,4 +284,5 @@
         real qv_mod_cas(llm),ql_mod_cas(llm),qi_mod_cas(llm)
         real ug_mod_cas(llm),vg_mod_cas(llm)
+        real temp_nudg_mod_cas(llm),qv_nudg_mod_cas(llm),v_nudg_mod_cas(llm),u_nudg_mod_cas(llm)
         real u_mod_cas(llm),v_mod_cas(llm)
         real omega_mod_cas(llm)
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/1D_interp_cases.h
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/1D_interp_cases.h	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/1D_interp_cases.h	(revision 3605)
@@ -1,845 +1,26 @@
-!
-! $Id$
-!
-!---------------------------------------------------------------------
-! Forcing_LES case: constant dq_dyn
-!---------------------------------------------------------------------
-      if (forcing_LES) then
-        DO l = 1,llm
-          d_q_adv(l,1) = dq_dyn(l,1)
-        ENDDO
-      endif ! forcing_LES
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Interpolation forcing in time and onto model levels
-!---------------------------------------------------------------------
-      if (forcing_GCSSold) then
 
-       call get_uvd(it,timestep,fich_gcssold_ctl,fich_gcssold_dat,              &
-     &               ht_gcssold,hq_gcssold,hw_gcssold,                          &
-     &               hu_gcssold,hv_gcssold,                                     &
-     &               hthturb_gcssold,hqturb_gcssold,Ts_gcssold,                 &
-     &               imp_fcg_gcssold,ts_fcg_gcssold,                            &
-     &               Tp_fcg_gcssold,Turb_fcg_gcssold)
-       if (prt_level.ge.1) then
-         print *,' get_uvd -> hqturb_gcssold ',it,hqturb_gcssold
-       endif
-! large-scale forcing :
-!!!      tsurf = ts_gcssold
-      do l = 1, llm
-!       u(l) = hu_gcssold(l) !  on prescrit le vent
-!       v(l) = hv_gcssold(l)    !  on prescrit le vent
-!       omega(l) = hw_gcssold(l)
-!       rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
-!       omega2(l)=-rho(l)*omega(l)
-       omega(l) = hw_gcssold(l)
-       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
-
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
-       d_t_adv(l) = ht_gcssold(l)
-       d_q_adv(l,1) = hq_gcssold(l)
-       dt_cooling(l) = 0.0
-      enddo
-
-      endif ! forcing_GCSSold
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Interpolation Toga forcing 
-!---------------------------------------------------------------------
-      if (forcing_toga) then
-
-       if (prt_level.ge.1) then
-        print*,                                                             &
-     & '#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/dt_toga=',     &
-     &    day,day1,(day-day1)*86400.,(day-day1)*86400/dt_toga
-       endif
+         print*,'FORCING CASE forcing_case2'
+!       print*,                                                             &
+!    & '#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/pdt_cas=',     &
+!    &    daytime,day1,(daytime-day1)*86400.,                               &
+!    &    (daytime-day1)*86400/pdt_cas
 
 ! time interpolation:
-        CALL interp_toga_time(daytime,day1,annee_ref                        &
-     &             ,year_ini_toga,day_ju_ini_toga,nt_toga,dt_toga           &
-     &             ,nlev_toga,ts_toga,plev_toga,t_toga,q_toga,u_toga        &
-     &             ,v_toga,w_toga,ht_toga,vt_toga,hq_toga,vq_toga           &
-     &             ,ts_prof,plev_prof,t_prof,q_prof,u_prof,v_prof,w_prof    &
-     &             ,ht_prof,vt_prof,hq_prof,vq_prof)
-
-        if (type_ts_forcing.eq.1) ts_cur = ts_prof ! SST used in read_tsurf1d
-
-! vertical interpolation:
-      CALL interp_toga_vertical(play,nlev_toga,plev_prof                    &
-     &         ,t_prof,q_prof,u_prof,v_prof,w_prof                          &
-     &         ,ht_prof,vt_prof,hq_prof,vq_prof                             &
-     &         ,t_mod,q_mod,u_mod,v_mod,w_mod                               &
-     &         ,ht_mod,vt_mod,hq_mod,vq_mod,mxcalc)
-
-! large-scale forcing :
-      tsurf = ts_prof
-      do l = 1, llm
-       u(l) = u_mod(l) ! sb: on prescrit le vent
-       v(l) = v_mod(l) ! sb: on prescrit le vent
-!       omega(l) = w_prof(l)
-!       rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
-!       omega2(l)=-rho(l)*omega(l)
-       omega(l) = w_mod(l)
-       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
-
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
-       d_t_adv(l) = alpha*omega(l)/rcpd-(ht_mod(l)+vt_mod(l))
-       d_q_adv(l,1) = -(hq_mod(l)+vq_mod(l))
-       dt_cooling(l) = 0.0
-      enddo
-
-      endif ! forcing_toga
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-! Interpolation DICE forcing 
-!---------------------------------------------------------------------
-      if (forcing_dice) then
-
-       if (prt_level.ge.1) then
-        print*,'#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/dt_dice=',&
-     &    day,day1,(day-day1)*86400.,(day-day1)*86400/dt_dice
-       endif
-
-! time interpolation:
-      CALL interp_dice_time(daytime,day1,annee_ref                    &
-     &             ,year_ini_dice,day_ju_ini_dice,nt_dice,dt_dice     & 
-     &             ,nlev_dice,shf_dice,lhf_dice,lwup_dice,swup_dice   &
-     &             ,tg_dice,ustar_dice,psurf_dice,ug_dice,vg_dice     &
-     &             ,ht_dice,hq_dice,hu_dice,hv_dice,w_dice,omega_dice &
-     &             ,shf_prof,lhf_prof,lwup_prof,swup_prof,tg_prof     &
-     &             ,ustar_prof,psurf_prof,ug_profd,vg_profd           &
-     &             ,ht_profd,hq_profd,hu_profd,hv_profd,w_profd       &
-     &             ,omega_profd)
-!     do l = 1, llm
-!     print *,'llm l omega_profd',llm,l,omega_profd(l)
-!     enddo
-
-        if (type_ts_forcing.eq.1) ts_cur = tg_prof ! SST used in read_tsurf1d
-
-! vertical interpolation:
-      CALL interp_dice_vertical(play,nlev_dice,nt_dice,plev_dice        &
-     &         ,t_dice,qv_dice,u_dice,v_dice,o3_dice                   &
-     &         ,ht_profd,hq_profd,hu_profd,hv_profd,w_profd,omega_profd &
-     &         ,t_mod,qv_mod,u_mod,v_mod,o3_mod                        &
-     &         ,ht_mod,hq_mod,hu_mod,hv_mod,w_mod,omega_mod,mxcalc)
-!     do l = 1, llm
-!      print *,'llm l omega_mod',llm,l,omega_mod(l)
-!     enddo
-
-! Les forcages DICE sont donnes /jour et non /seconde !
-      ht_mod(:)=ht_mod(:)/86400.
-      hq_mod(:)=hq_mod(:)/86400.
-      hu_mod(:)=hu_mod(:)/86400.
-      hv_mod(:)=hv_mod(:)/86400.
-
-!calcul de l'advection verticale a partir du omega (repris cas TWPICE, MPL 05082013)
-!Calcul des gradients verticaux
-!initialisation
-      d_t_z(:)=0.
-      d_q_z(:)=0.
-      d_u_z(:)=0.
-      d_v_z(:)=0.
-      DO l=2,llm-1
-       d_t_z(l)=(temp(l+1)-temp(l-1))/(play(l+1)-play(l-1))
-       d_q_z(l)=(q(l+1,1)-q(l-1,1)) /(play(l+1)-play(l-1))
-       d_u_z(l)=(u(l+1)-u(l-1))/(play(l+1)-play(l-1))
-       d_v_z(l)=(v(l+1)-v(l-1))/(play(l+1)-play(l-1))
-      ENDDO
-      d_t_z(1)=d_t_z(2)
-      d_q_z(1)=d_q_z(2)
-!     d_u_z(1)=u(2)/(play(2)-psurf)/5.
-!     d_v_z(1)=v(2)/(play(2)-psurf)/5.
-      d_u_z(1)=0.
-      d_v_z(1)=0.
-      d_t_z(llm)=d_t_z(llm-1)
-      d_q_z(llm)=d_q_z(llm-1)
-      d_u_z(llm)=d_u_z(llm-1)
-      d_v_z(llm)=d_v_z(llm-1)
-
-!Calcul de l advection verticale: 
-! utiliser omega (Pa/s) et non w (m/s) !! MP 20131108
-      d_t_dyn_z(:)=omega_mod(:)*d_t_z(:)
-      d_q_dyn_z(:)=omega_mod(:)*d_q_z(:)
-      d_u_dyn_z(:)=omega_mod(:)*d_u_z(:)
-      d_v_dyn_z(:)=omega_mod(:)*d_v_z(:)
-
-! large-scale forcing :
-!     tsurf = tg_prof    MPL 20130925 commente
-      psurf = psurf_prof
-! For this case, fluxes are imposed
-      fsens=-1*shf_prof
-      flat=-1*lhf_prof
-      ust=ustar_prof
-      tg=tg_prof
-      print *,'ust= ',ust
-      do l = 1, llm
-       ug(l)= ug_profd
-       vg(l)= vg_profd
-!       omega(l) = w_prof(l)
-!      rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
-!       omega2(l)=-rho(l)*omega(l)
-!      omega(l) = w_mod(l)*(-rg*rho(l))
-       omega(l) = omega_mod(l)
-       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
-
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
-       d_t_adv(l) = alpha*omega(l)/rcpd+ht_mod(l)-d_t_dyn_z(l)
-       d_q_adv(l,1) = hq_mod(l)-d_q_dyn_z(l)
-       d_u_adv(l) = hu_mod(l)-d_u_dyn_z(l)
-       d_v_adv(l) = hv_mod(l)-d_v_dyn_z(l)
-       dt_cooling(l) = 0.0
-      enddo
-
-      endif ! forcing_dice
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-! Interpolation gabls4 forcing 
-!---------------------------------------------------------------------
-      if (forcing_gabls4 ) then
-
-       if (prt_level.ge.1) then
-        print*,'#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/dt_gabls4=',&
-     &    day,day1,(day-day1)*86400.,(day-day1)*86400/dt_gabls4
-       endif
-
-! time interpolation:
-      CALL interp_gabls4_time(daytime,day1,annee_ref                                     &
-     &             ,year_ini_gabls4,day_ju_ini_gabls4,nt_gabls4,dt_gabls4,nlev_gabls4  & 
-     &             ,ug_gabls4,vg_gabls4,ht_gabls4,hq_gabls4,tg_gabls4                            &
-     &             ,ug_profg,vg_profg,ht_profg,hq_profg,tg_profg)
-
-        if (type_ts_forcing.eq.1) ts_cur = tg_prof ! SST used in read_tsurf1d
-
-! vertical interpolation:
-! on re-utilise le programme interp_dice_vertical: les transformations sur 
-! plev_gabls4,th_gabls4,qv_gabls4,u_gabls4,v_gabls4 ne sont pas prises en compte.
-! seules celles sur ht_profg,hq_profg,ug_profg,vg_profg sont prises en compte.
-
-      CALL interp_dice_vertical(play,nlev_gabls4,nt_gabls4,plev_gabls4         &
-!    &         ,t_gabls4,qv_gabls4,u_gabls4,v_gabls4,poub            &
-     &         ,poub,poub,poub,poub,poub                             &
-     &         ,ht_profg,hq_profg,ug_profg,vg_profg,poub,poub        &
-     &         ,t_mod,qv_mod,u_mod,v_mod,o3_mod                      &
-     &         ,ht_mod,hq_mod,ug_mod,vg_mod,w_mod,omega_mod,mxcalc)
-
-      do l = 1, llm
-       ug(l)= ug_mod(l)
-       vg(l)= vg_mod(l)
-       d_t_adv(l)=ht_mod(l)
-       d_q_adv(l,1)=hq_mod(l)
-      enddo
-
-      endif ! forcing_gabls4
-!---------------------------------------------------------------------
-
-!---------------------------------------------------------------------
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Interpolation forcing TWPice
-!---------------------------------------------------------------------
-      if (forcing_twpice) then
-
-        print*,                                                             &
-     & '#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/dt_twpi=',     &
-     &    daytime,day1,(daytime-day1)*86400.,                               &
-     &    (daytime-day1)*86400/dt_twpi
-
-! time interpolation:
-        CALL interp_toga_time(daytime,day1,annee_ref                        &
-     &       ,year_ini_twpi,day_ju_ini_twpi,nt_twpi,dt_twpi,nlev_twpi       &
-     &       ,ts_twpi,plev_twpi,t_twpi,q_twpi,u_twpi,v_twpi,w_twpi          &
-     &       ,ht_twpi,vt_twpi,hq_twpi,vq_twpi                               &
-     &       ,ts_proftwp,plev_proftwp,t_proftwp,q_proftwp,u_proftwp         &
-     &       ,v_proftwp,w_proftwp                                           &
-     &       ,ht_proftwp,vt_proftwp,hq_proftwp,vq_proftwp)
-
-! vertical interpolation:
-      CALL interp_toga_vertical(play,nlev_twpi,plev_proftwp                 &
-     &         ,t_proftwp,q_proftwp,u_proftwp,v_proftwp,w_proftwp           &
-     &         ,ht_proftwp,vt_proftwp,hq_proftwp,vq_proftwp                 &
-     &         ,t_mod,q_mod,u_mod,v_mod,w_mod                               &
-     &         ,ht_mod,vt_mod,hq_mod,vq_mod,mxcalc)
-
-
-!calcul de l'advection verticale a partir du omega
-!Calcul des gradients verticaux
-!initialisation
-      d_t_z(:)=0.
-      d_q_z(:)=0.
-      d_t_dyn_z(:)=0.
-      d_q_dyn_z(:)=0.
-      DO l=2,llm-1
-       d_t_z(l)=(temp(l+1)-temp(l-1))/(play(l+1)-play(l-1))
-       d_q_z(l)=(q(l+1,1)-q(l-1,1))/(play(l+1)-play(l-1))
-      ENDDO
-      d_t_z(1)=d_t_z(2)
-      d_q_z(1)=d_q_z(2)
-      d_t_z(llm)=d_t_z(llm-1)
-      d_q_z(llm)=d_q_z(llm-1)
-
-!Calcul de l advection verticale
-      d_t_dyn_z(:)=w_mod(:)*d_t_z(:)
-      d_q_dyn_z(:)=w_mod(:)*d_q_z(:)
-
-!wind nudging above 500m with a 2h time scale
-        do l=1,llm
-        if (nudge_wind) then
-!           if (phi(l).gt.5000.) then
-        if (phi(l).gt.0.) then
-        u(l)=u(l)+timestep*(u_mod(l)-u(l))/(2.*3600.)
-        v(l)=v(l)+timestep*(v_mod(l)-v(l))/(2.*3600.)
-           endif    
-        else
-        u(l) = u_mod(l) 
-        v(l) = v_mod(l)
-        endif
-        enddo
-
-!CR:nudging of q and theta with a 6h time scale above 15km
-        if (nudge_thermo) then
-        do l=1,llm
-           zz(l)=phi(l)/9.8
-           if ((zz(l).le.16000.).and.(zz(l).gt.15000.)) then
-             zfact=(zz(l)-15000.)/1000.
-        q(l,1)=q(l,1)+timestep*(q_mod(l)-q(l,1))/(6.*3600.)*zfact
-        temp(l)=temp(l)+timestep*(t_mod(l)-temp(l))/(6.*3600.)*zfact
-           else if (zz(l).gt.16000.) then 
-        q(l,1)=q(l,1)+timestep*(q_mod(l)-q(l,1))/(6.*3600.)
-        temp(l)=temp(l)+timestep*(t_mod(l)-temp(l))/(6.*3600.)
-           endif
-        enddo    
-        endif
-
-      do l = 1, llm
-       omega(l) = w_mod(l)
-       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
-!calcul de l'advection totale
-        if (cptadvw) then
-        d_t_adv(l) = alpha*omega(l)/rcpd+ht_mod(l)-d_t_dyn_z(l)
-!        print*,'temp vert adv',l,ht_mod(l),vt_mod(l),-d_t_dyn_z(l)
-        d_q_adv(l,1) = hq_mod(l)-d_q_dyn_z(l)
-!        print*,'q vert adv',l,hq_mod(l),vq_mod(l),-d_q_dyn_z(l)
-        else
-        d_t_adv(l) = alpha*omega(l)/rcpd+(ht_mod(l)+vt_mod(l))
-        d_q_adv(l,1) = (hq_mod(l)+vq_mod(l))
-        endif
-       dt_cooling(l) = 0.0
-      enddo
-
-      endif ! forcing_twpice
-
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Interpolation forcing AMMA
-!---------------------------------------------------------------------
-
-       if (forcing_amma) then
-
-        print*,                                                             &
-     & '#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/dt_amma=',     &
-     &    daytime,day1,(daytime-day1)*86400.,                               &
-     &    (daytime-day1)*86400/dt_amma
-
-! time interpolation using TOGA interpolation routine
-        CALL interp_amma_time(daytime,day1,annee_ref                        &
-     &       ,year_ini_amma,day_ju_ini_amma,nt_amma,dt_amma,nlev_amma       &
-     &       ,vitw_amma,ht_amma,hq_amma,lat_amma,sens_amma                  &
-     &       ,vitw_profamma,ht_profamma,hq_profamma,lat_profamma            &
-     &       ,sens_profamma)
-
-      print*,'apres interpolation temporelle AMMA'
-
-      do k=1,nlev_amma
-         th_profamma(k)=0.
-         q_profamma(k)=0.
-         u_profamma(k)=0.
-         v_profamma(k)=0.
-         vt_profamma(k)=0.
-         vq_profamma(k)=0.
-       enddo
-! vertical interpolation using TOGA interpolation routine:
-!      write(*,*)'avant interp vert', t_proftwp
-      CALL interp_toga_vertical(play,nlev_amma,plev_amma                      &
-     &         ,th_profamma,q_profamma,u_profamma,v_profamma                 &
-     &         ,vitw_profamma                                               &
-     &         ,ht_profamma,vt_profamma,hq_profamma,vq_profamma             &
-     &         ,t_mod,q_mod,u_mod,v_mod,w_mod                               &
-     &         ,ht_mod,vt_mod,hq_mod,vq_mod,mxcalc)
-       write(*,*) 'Profil initial forcing AMMA interpole'
-
-
-!calcul de l'advection verticale a partir du omega
-!Calcul des gradients verticaux
-!initialisation
-      do l=1,llm
-      d_t_z(l)=0.
-      d_q_z(l)=0.
-      enddo
-
-      DO l=2,llm-1
-       d_t_z(l)=(temp(l+1)-temp(l-1))/(play(l+1)-play(l-1))
-       d_q_z(l)=(q(l+1,1)-q(l-1,1))/(play(l+1)-play(l-1))
-      ENDDO
-      d_t_z(1)=d_t_z(2)
-      d_q_z(1)=d_q_z(2)
-      d_t_z(llm)=d_t_z(llm-1)
-      d_q_z(llm)=d_q_z(llm-1)
-
-
-      do l = 1, llm
-       rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
-       omega(l) = w_mod(l)*(-rg*rho(l))
-       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
-!calcul de l'advection totale
-!        d_t_adv(l) = alpha*omega(l)/rcpd+ht_mod(l)-omega(l)*d_t_z(l)
-!attention: on impose dth
-        d_t_adv(l) = alpha*omega(l)/rcpd+                                  &
-     &         ht_mod(l)*(play(l)/pzero)**rkappa-omega(l)*d_t_z(l)
-!        d_t_adv(l) = 0.
-!        print*,'temp vert adv',l,ht_mod(l),vt_mod(l),-d_t_dyn_z(l)
-        d_q_adv(l,1) = hq_mod(l)-omega(l)*d_q_z(l)
-!        d_q_adv(l,1) = 0.
-!        print*,'q vert adv',l,hq_mod(l),vq_mod(l),-d_q_dyn_z(l)
-   
-       dt_cooling(l) = 0.0
-      enddo
-
-
-!     ok_flux_surf=.false.
-      fsens=-1.*sens_profamma
-      flat=-1.*lat_profamma
-
-      endif ! forcing_amma
-
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Interpolation forcing Rico
-!---------------------------------------------------------------------
-      if (forcing_rico) then
-!      call lstendH(llm,omega,dt_dyn,dq_dyn,du_dyn, dv_dyn,q,temp,u,v,play)
-       call lstendH(llm,nqtot,omega,dt_dyn,dq_dyn,q,temp,u,v,play)
-
-        do l=1,llm
-       d_t_adv(l) =  (dth_rico(l) +  dt_dyn(l))
-       d_q_adv(l,1) = (dqh_rico(l) +  dq_dyn(l,1))
-       d_q_adv(l,2) = 0.
-        enddo
-      endif  ! forcing_rico
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Interpolation forcing Arm_cu
-!---------------------------------------------------------------------
-      if (forcing_armcu) then
-
-        print*,                                                             &
-     & '#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/dt_armcu=',    &
-     &    day,day1,(day-day1)*86400.,(day-day1)*86400/dt_armcu
-
-! time interpolation:
-! ATTENTION, cet appel ne convient pas pour TOGA !!
-! revoir 1DUTILS.h et les arguments
-      CALL interp_armcu_time(daytime,day1,annee_ref                         &
-     &            ,year_ini_armcu,day_ju_ini_armcu,nt_armcu,dt_armcu        &
-     &            ,nlev_armcu,sens_armcu,flat_armcu,adv_theta_armcu          &
-     &            ,rad_theta_armcu,adv_qt_armcu,sens_prof,flat_prof         &
-     &            ,adv_theta_prof,rad_theta_prof,adv_qt_prof)
-
-! vertical interpolation:
-! No vertical interpolation if nlev imposed to 19 or 40
-
-! For this case, fluxes are imposed
-       fsens=-1*sens_prof
-       flat=-1*flat_prof
-
-! Advective forcings are given in K or g/kg ... BY HOUR
-      do l = 1, llm
-       ug(l)= u_mod(l)
-       vg(l)= v_mod(l)
-       IF((phi(l)/RG).LT.1000) THEN
-         d_t_adv(l) = (adv_theta_prof + rad_theta_prof)/3600.
-         d_q_adv(l,1) = adv_qt_prof/1000./3600.
-         d_q_adv(l,2) = 0.0
-!        print *,'INF1000: phi dth dq1 dq2',
-!    :  phi(l)/RG,d_t_adv(l),d_q_adv(l,1),d_q_adv(l,2)
-       ELSEIF ((phi(l)/RG).GE.1000.AND.(phi(l)/RG).lt.3000) THEN
-         fact=((phi(l)/RG)-1000.)/2000.
-         fact=1-fact
-         d_t_adv(l) = (adv_theta_prof + rad_theta_prof)*fact/3600.
-         d_q_adv(l,1) = adv_qt_prof*fact/1000./3600.
-         d_q_adv(l,2) = 0.0
-!        print *,'SUP1000: phi fact dth dq1 dq2',
-!    :  phi(l)/RG,fact,d_t_adv(l),d_q_adv(l,1),d_q_adv(l,2)
-       ELSE
-         d_t_adv(l) = 0.0
-         d_q_adv(l,1) = 0.0
-         d_q_adv(l,2) = 0.0
-!        print *,'SUP3000: phi dth dq1 dq2',
-!    :  phi(l)/RG,d_t_adv(l),d_q_adv(l,1),d_q_adv(l,2)
-       ENDIF
-      dt_cooling(l) = 0.0  
-!     print *,'Interp armcu: phi dth dq1 dq2',
-!    :  l,phi(l),d_t_adv(l),d_q_adv(l,1),d_q_adv(l,2)
-      enddo
-      endif ! forcing_armcu
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Interpolation forcing in time and onto model levels
-!---------------------------------------------------------------------
-      if (forcing_sandu) then
-
-        print*,                                                             &
-     & '#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/dt_sandu=',    &
-     &    day,day1,(day-day1)*86400.,(day-day1)*86400/dt_sandu 
-
-! time interpolation:
-! ATTENTION, cet appel ne convient pas pour TOGA !!
-! revoir 1DUTILS.h et les arguments
-      CALL interp_sandu_time(daytime,day1,annee_ref                         &
-     &             ,year_ini_sandu,day_ju_ini_sandu,nt_sandu,dt_sandu       &
-     &             ,nlev_sandu                                              &
-     &             ,ts_sandu,ts_prof)
-
-        if (type_ts_forcing.eq.1) ts_cur = ts_prof ! SST used in read_tsurf1d
-
-! vertical interpolation:
-      CALL interp_sandu_vertical(play,nlev_sandu,plev_profs                 &
-     &         ,t_profs,thl_profs,q_profs,u_profs,v_profs,w_profs           &
-     &         ,omega_profs,o3mmr_profs                                     &
-     &         ,t_mod,thl_mod,q_mod,u_mod,v_mod,w_mod                       &
-     &         ,omega_mod,o3mmr_mod,mxcalc)
-!calcul de l'advection verticale
-!Calcul des gradients verticaux
-!initialisation
-      d_t_z(:)=0.
-      d_q_z(:)=0.
-      d_t_dyn_z(:)=0.
-      d_q_dyn_z(:)=0.
-! schema centre
-!     DO l=2,llm-1
-!      d_t_z(l)=(temp(l+1)-temp(l-1))
-!    &          /(play(l+1)-play(l-1))
-!      d_q_z(l)=(q(l+1,1)-q(l-1,1))
-!    &          /(play(l+1)-play(l-1))
-! schema amont
-      DO l=2,llm-1
-       d_t_z(l)=(temp(l+1)-temp(l))/(play(l+1)-play(l))
-       d_q_z(l)=(q(l+1,1)-q(l,1))/(play(l+1)-play(l))
-!     print *,'l temp2 temp0 play2 play0 omega_mod',
-!    & temp(l+1),temp(l-1),play(l+1),play(l-1),omega_mod(l)
-      ENDDO
-      d_t_z(1)=d_t_z(2)
-      d_q_z(1)=d_q_z(2)
-      d_t_z(llm)=d_t_z(llm-1)
-      d_q_z(llm)=d_q_z(llm-1)
-
-!  calcul de l advection verticale
-! Confusion w (m/s) et omega (Pa/s) !!
-      d_t_dyn_z(:)=omega_mod(:)*d_t_z(:)
-      d_q_dyn_z(:)=omega_mod(:)*d_q_z(:)
-!     do l=1,llm
-!      print *,'d_t_dyn omega_mod d_t_z d_q_dyn d_q_z',
-!    :l,d_t_dyn_z(l),omega_mod(l),d_t_z(l),d_q_dyn_z(l),d_q_z(l)
-!     enddo
-
-
-! large-scale forcing : pour le cas Sandu ces forcages sont la SST
-! et une divergence constante -> profil de omega
-      tsurf = ts_prof
-      write(*,*) 'SST suivante: ',tsurf
-      do l = 1, llm
-       omega(l) = omega_mod(l)
-       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
-
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
-!
-!      d_t_adv(l) = 0.0
-!      d_q_adv(l,1) = 0.0
-!CR:test advection=0
-!calcul de l'advection verticale
-        d_t_adv(l) = alpha*omega(l)/rcpd-d_t_dyn_z(l)
-!        print*,'temp adv',l,-d_t_dyn_z(l)
-        d_q_adv(l,1) = -d_q_dyn_z(l)
-!        print*,'q adv',l,-d_q_dyn_z(l)
-       dt_cooling(l) = 0.0
-      enddo
-      endif ! forcing_sandu
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Interpolation forcing in time and onto model levels
-!---------------------------------------------------------------------
-      if (forcing_astex) then
-
-        print*,                                                             &
-     & '#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/dt_astex=',    &
-     &    day,day1,(day-day1)*86400.,(day-day1)*86400/dt_astex
-
-! time interpolation:
-! ATTENTION, cet appel ne convient pas pour TOGA !!
-! revoir 1DUTILS.h et les arguments
-      CALL interp_astex_time(daytime,day1,annee_ref                         &
-     &             ,year_ini_astex,day_ju_ini_astex,nt_astex,dt_astex       &
-     &             ,nlev_astex,div_astex,ts_astex,ug_astex,vg_astex         &
-     &             ,ufa_astex,vfa_astex,div_prof,ts_prof,ug_prof,vg_prof    &
-     &             ,ufa_prof,vfa_prof)
-
-        if (type_ts_forcing.eq.1) ts_cur = ts_prof ! SST used in read_tsurf1d
-
-! vertical interpolation:
-      CALL interp_astex_vertical(play,nlev_astex,plev_profa                 &
-     &         ,t_profa,thl_profa,qv_profa,ql_profa,qt_profa                &
-     &         ,u_profa,v_profa,w_profa,tke_profa,o3mmr_profa               &
-     &         ,t_mod,thl_mod,qv_mod,ql_mod,qt_mod,u_mod,v_mod,w_mod        &
-     &         ,tke_mod,o3mmr_mod,mxcalc)
-!calcul de l'advection verticale
-!Calcul des gradients verticaux
-!initialisation
-      d_t_z(:)=0.
-      d_q_z(:)=0.
-      d_t_dyn_z(:)=0.
-      d_q_dyn_z(:)=0.
-! schema centre
-!     DO l=2,llm-1
-!      d_t_z(l)=(temp(l+1)-temp(l-1))
-!    &          /(play(l+1)-play(l-1))
-!      d_q_z(l)=(q(l+1,1)-q(l-1,1))
-!    &          /(play(l+1)-play(l-1))
-! schema amont
-      DO l=2,llm-1
-       d_t_z(l)=(temp(l+1)-temp(l))/(play(l+1)-play(l))
-       d_q_z(l)=(q(l+1,1)-q(l,1))/(play(l+1)-play(l))
-!     print *,'l temp2 temp0 play2 play0 omega_mod',
-!    & temp(l+1),temp(l-1),play(l+1),play(l-1),omega_mod(l)
-      ENDDO
-      d_t_z(1)=d_t_z(2)
-      d_q_z(1)=d_q_z(2)
-      d_t_z(llm)=d_t_z(llm-1)
-      d_q_z(llm)=d_q_z(llm-1)
-
-!  calcul de l advection verticale
-! Confusion w (m/s) et omega (Pa/s) !!
-      d_t_dyn_z(:)=w_mod(:)*d_t_z(:)
-      d_q_dyn_z(:)=w_mod(:)*d_q_z(:)
-!     do l=1,llm
-!      print *,'d_t_dyn omega_mod d_t_z d_q_dyn d_q_z',
-!    :l,d_t_dyn_z(l),omega_mod(l),d_t_z(l),d_q_dyn_z(l),d_q_z(l)
-!     enddo
-
-
-! large-scale forcing : pour le cas Astex ces forcages sont la SST
-! la divergence,ug,vg,ufa,vfa
-      tsurf = ts_prof
-      write(*,*) 'SST suivante: ',tsurf
-      do l = 1, llm
-       omega(l) = w_mod(l)
-       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
-
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
-!
-!      d_t_adv(l) = 0.0
-!      d_q_adv(l,1) = 0.0
-!CR:test advection=0
-!calcul de l'advection verticale
-        d_t_adv(l) = alpha*omega(l)/rcpd-d_t_dyn_z(l)
-!        print*,'temp adv',l,-d_t_dyn_z(l)
-        d_q_adv(l,1) = -d_q_dyn_z(l)
-!        print*,'q adv',l,-d_q_dyn_z(l)
-       dt_cooling(l) = 0.0
-      enddo
-      endif ! forcing_astex
-
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Interpolation forcing standard case
-!---------------------------------------------------------------------
-      if (forcing_case) then
-
-        print*,                                                             &
-     & '#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/pdt_cas=',     &
-     &    daytime,day1,(daytime-day1)*86400.,                               &
-     &    (daytime-day1)*86400/pdt_cas
-
-! time interpolation:
-        CALL interp_case_time(daytime,day1,annee_ref                                        &
-!    &       ,year_ini_cas,day_ju_ini_cas,nt_cas,pdt_cas,nlev_cas                           &
-     &       ,nt_cas,nlev_cas                                                               &
-     &       ,ts_cas,plev_cas,t_cas,q_cas,u_cas,v_cas,ug_cas,vg_cas                         &
-     &       ,vitw_cas,du_cas,hu_cas,vu_cas                                                 &
-     &       ,dv_cas,hv_cas,vv_cas,dt_cas,ht_cas,vt_cas,dtrad_cas                           &
-     &       ,dq_cas,hq_cas,vq_cas,lat_cas,sens_cas,ustar_cas                               &
-     &       ,uw_cas,vw_cas,q1_cas,q2_cas                                                   &
-     &       ,ts_prof_cas,plev_prof_cas,t_prof_cas,q_prof_cas,u_prof_cas,v_prof_cas         &
-     &       ,ug_prof_cas,vg_prof_cas,vitw_prof_cas,du_prof_cas,hu_prof_cas,vu_prof_cas     &
-     &       ,dv_prof_cas,hv_prof_cas,vv_prof_cas,dt_prof_cas,ht_prof_cas,vt_prof_cas       &
-     &       ,dtrad_prof_cas,dq_prof_cas,hq_prof_cas,vq_prof_cas,lat_prof_cas               &
-     &       ,sens_prof_cas,ustar_prof_cas,uw_prof_cas,vw_prof_cas,q1_prof_cas,q2_prof_cas)
-
-             ts_cur = ts_prof_cas 
-             psurf=plev_prof_cas(1)
-
-! vertical interpolation:
-      CALL interp_case_vertical(play,nlev_cas,plev_prof_cas            &
-     &         ,t_prof_cas,q_prof_cas,u_prof_cas,v_prof_cas,ug_prof_cas,vg_prof_cas,vitw_prof_cas                         &
-     &         ,du_prof_cas,hu_prof_cas,vu_prof_cas,dv_prof_cas,hv_prof_cas,vv_prof_cas           &
-     &         ,dt_prof_cas,ht_prof_cas,vt_prof_cas,dtrad_prof_cas,dq_prof_cas,hq_prof_cas,vq_prof_cas           &
-     &         ,t_mod_cas,q_mod_cas,u_mod_cas,v_mod_cas,ug_mod_cas,vg_mod_cas,w_mod_cas                              &
-     &         ,du_mod_cas,hu_mod_cas,vu_mod_cas,dv_mod_cas,hv_mod_cas,vv_mod_cas               &
-     &         ,dt_mod_cas,ht_mod_cas,vt_mod_cas,dtrad_mod_cas,dq_mod_cas,hq_mod_cas,vq_mod_cas,mxcalc)
-
-
-!calcul de l'advection verticale a partir du omega
-!Calcul des gradients verticaux
-!initialisation
-      d_t_z(:)=0.
-      d_q_z(:)=0.
-      d_u_z(:)=0.
-      d_v_z(:)=0.
-      d_t_dyn_z(:)=0.
-      d_q_dyn_z(:)=0.
-      d_u_dyn_z(:)=0.
-      d_v_dyn_z(:)=0.
-      DO l=2,llm-1
-       d_t_z(l)=(temp(l+1)-temp(l-1))/(play(l+1)-play(l-1))
-       d_q_z(l)=(q(l+1,1)-q(l-1,1))/(play(l+1)-play(l-1))
-       d_u_z(l)=(u(l+1)-u(l-1))/(play(l+1)-play(l-1))
-       d_v_z(l)=(v(l+1)-v(l-1))/(play(l+1)-play(l-1))
-      ENDDO
-      d_t_z(1)=d_t_z(2)
-      d_q_z(1)=d_q_z(2)
-      d_u_z(1)=d_u_z(2)
-      d_v_z(1)=d_v_z(2)
-      d_t_z(llm)=d_t_z(llm-1)
-      d_q_z(llm)=d_q_z(llm-1)
-      d_u_z(llm)=d_u_z(llm-1)
-      d_v_z(llm)=d_v_z(llm-1)
-
-!Calcul de l advection verticale
-
-      d_t_dyn_z(:)=w_mod_cas(:)*d_t_z(:)
-
-      d_q_dyn_z(:)=w_mod_cas(:)*d_q_z(:)
-      d_u_dyn_z(:)=w_mod_cas(:)*d_u_z(:)
-      d_v_dyn_z(:)=w_mod_cas(:)*d_v_z(:)
-
-!wind nudging 
-      if (nudge_u.gt.0.) then
-        do l=1,llm
-           u(l)=u(l)+timestep*(u_mod_cas(l)-u(l))/(nudge_u)
-        enddo
-      else
-        do l=1,llm
-        u(l) = u_mod_cas(l) 
-        enddo
-      endif
-
-      if (nudge_v.gt.0.) then
-        do l=1,llm
-           v(l)=v(l)+timestep*(v_mod_cas(l)-v(l))/(nudge_v)
-        enddo
-      else
-        do l=1,llm
-        v(l) = v_mod_cas(l) 
-        enddo
-      endif
-
-      if (nudge_w.gt.0.) then
-        do l=1,llm
-           w(l)=w(l)+timestep*(w_mod_cas(l)-w(l))/(nudge_w)
-        enddo
-      else
-        do l=1,llm
-        w(l) = w_mod_cas(l) 
-        enddo
-      endif
-
-!nudging of q and temp 
-      if (nudge_t.gt.0.) then
-        do l=1,llm
-           temp(l)=temp(l)+timestep*(t_mod_cas(l)-temp(l))/(nudge_t)
-        enddo
-      endif
-      if (nudge_q.gt.0.) then
-        do l=1,llm
-           q(l,1)=q(l,1)+timestep*(q_mod_cas(l)-q(l,1))/(nudge_q)
-        enddo
-      endif
-
-      do l = 1, llm
-       omega(l) = w_mod_cas(l)  ! juste car w_mod_cas en Pa/s (MPL 20170310)
-       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
-
-!calcul advection
-        if ((tend_u.eq.1).and.(tend_w.eq.0)) then
-           d_u_adv(l)=du_mod_cas(l)
-        else if ((tend_u.eq.1).and.(tend_w.eq.1)) then
-           d_u_adv(l)=hu_mod_cas(l)-d_u_dyn_z(l)
-        endif
-
-        if ((tend_v.eq.1).and.(tend_w.eq.0)) then
-           d_v_adv(l)=dv_mod_cas(l)
-        else if ((tend_v.eq.1).and.(tend_w.eq.1)) then
-           d_v_adv(l)=hv_mod_cas(l)-d_v_dyn_z(l)
-        endif
-
-        if ((tend_t.eq.1).and.(tend_w.eq.0)) then
-!           d_t_adv(l)=alpha*omega(l)/rcpd+dt_mod_cas(l)
-           d_t_adv(l)=alpha*omega(l)/rcpd-dt_mod_cas(l)
-        else if ((tend_t.eq.1).and.(tend_w.eq.1)) then
-!           d_t_adv(l)=alpha*omega(l)/rcpd+ht_mod_cas(l)-d_t_dyn_z(l)
-           d_t_adv(l)=alpha*omega(l)/rcpd-ht_mod_cas(l)-d_t_dyn_z(l)
-        endif
-
-        if ((tend_q.eq.1).and.(tend_w.eq.0)) then
-!           d_q_adv(l,1)=dq_mod_cas(l)
-           d_q_adv(l,1)=-1*dq_mod_cas(l)
-        else if ((tend_q.eq.1).and.(tend_w.eq.1)) then
-!           d_q_adv(l,1)=hq_mod_cas(l)-d_q_dyn_z(l)
-           d_q_adv(l,1)=-1*hq_mod_cas(l)-d_q_dyn_z(l)
-        endif
-         
-        if (tend_rayo.eq.1) then
-           dt_cooling(l) = dtrad_mod_cas(l)
-!          print *,'dt_cooling=',dt_cooling(l)
-        else
-           dt_cooling(l) = 0.0
-        endif
-      enddo
-
-! Faut-il multiplier par -1 ? (MPL 20160713)
-      IF(ok_flux_surf) THEN
-       fsens=sens_prof_cas
-       flat=lat_prof_cas
-      ENDIF
-!
-      IF (ok_prescr_ust) THEN
-       ust=ustar_prof_cas
-       print *,'ust=',ust
-      ENDIF
-      endif ! forcing_case
-
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Interpolation forcing standard case
-!---------------------------------------------------------------------
-      if (forcing_case2) then
-
-        print*,                                                             &
-     & '#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/pdt_cas=',     &
-     &    daytime,day1,(daytime-day1)*86400.,                               &
-     &    (daytime-day1)*86400/pdt_cas
-
-! time interpolation:
-        CALL interp2_case_time(daytime,day1,annee_ref                                       &
+        CALL interp_case_time_std(daytime,day1,annee_ref                                       &
 !    &       ,year_ini_cas,day_ju_ini_cas,nt_cas,pdt_cas,nlev_cas                           &
      &       ,nt_cas,nlev_cas                                                               &
      &       ,ts_cas,ps_cas,plev_cas,t_cas,th_cas,thv_cas,thl_cas,qv_cas,ql_cas,qi_cas      &
-     &       ,u_cas,v_cas,ug_cas,vg_cas,vitw_cas,omega_cas,du_cas,hu_cas,vu_cas             &
+     &       ,u_cas,v_cas,ug_cas,vg_cas                                                     &
+     &       ,temp_nudg_cas,qv_nudg_cas,u_nudg_cas,v_nudg_cas                               &
+     &       ,vitw_cas,omega_cas,du_cas,hu_cas,vu_cas                                       &
      &       ,dv_cas,hv_cas,vv_cas,dt_cas,ht_cas,vt_cas,dtrad_cas                           &
      &       ,dq_cas,hq_cas,vq_cas,dth_cas,hth_cas,vth_cas,lat_cas,sens_cas,ustar_cas       &
      &       ,uw_cas,vw_cas,q1_cas,q2_cas,tke_cas                                           &
 !
-     &       ,ts_prof_cas,plev_prof_cas,t_prof_cas,theta_prof_cas,thv_prof_cas  &
+     &       ,ts_prof_cas,ps_prof_cas,plev_prof_cas,t_prof_cas,theta_prof_cas,thv_prof_cas  &
      &       ,thl_prof_cas,qv_prof_cas,ql_prof_cas,qi_prof_cas                              &
-     &       ,u_prof_cas,v_prof_cas,ug_prof_cas,vg_prof_cas,vitw_prof_cas,omega_prof_cas    &
+     &       ,u_prof_cas,v_prof_cas,ug_prof_cas,vg_prof_cas                                 &
+     &       ,temp_nudg_prof_cas,qv_nudg_prof_cas,u_nudg_prof_cas,v_nudg_prof_cas           &
+     &       ,vitw_prof_cas,omega_prof_cas                                                  &
      &       ,du_prof_cas,hu_prof_cas,vu_prof_cas                                           &
      &       ,dv_prof_cas,hv_prof_cas,vv_prof_cas,dt_prof_cas,ht_prof_cas,vt_prof_cas       &
@@ -853,8 +34,10 @@
 
 ! vertical interpolation:
-      CALL interp2_case_vertical(play,nlev_cas,plev_prof_cas                                              &
-     &         ,t_prof_cas,theta_prof_cas,thv_prof_cas,thl_prof_cas                                          &
+      CALL interp2_case_vertical_std(play,nlev_cas,plev_prof_cas                                              &
+     &         ,t_prof_cas,theta_prof_cas,thv_prof_cas,thl_prof_cas                                       &
      &         ,qv_prof_cas,ql_prof_cas,qi_prof_cas,u_prof_cas,v_prof_cas                                 &
-     &         ,ug_prof_cas,vg_prof_cas,vitw_prof_cas,omega_prof_cas                                      &
+     &         ,ug_prof_cas,vg_prof_cas                                                                   &
+     &         ,temp_nudg_prof_cas,qv_nudg_prof_cas,u_nudg_prof_cas,v_nudg_prof_cas                       &
+     &         ,vitw_prof_cas,omega_prof_cas                                      &
      &         ,du_prof_cas,hu_prof_cas,vu_prof_cas,dv_prof_cas,hv_prof_cas,vv_prof_cas                   &
      &         ,dt_prof_cas,ht_prof_cas,vt_prof_cas,dtrad_prof_cas,dq_prof_cas,hq_prof_cas,vq_prof_cas    &
@@ -862,5 +45,7 @@
 !
      &         ,t_mod_cas,theta_mod_cas,thv_mod_cas,thl_mod_cas,qv_mod_cas,ql_mod_cas,qi_mod_cas          &
-     &         ,u_mod_cas,v_mod_cas,ug_mod_cas,vg_mod_cas,w_mod_cas,omega_mod_cas                         &
+     &         ,u_mod_cas,v_mod_cas,ug_mod_cas,vg_mod_cas                                                 &
+     &         ,temp_nudg_mod_cas,qv_nudg_mod_cas,u_nudg_mod_cas,v_nudg_mod_cas                           &
+     &         ,w_mod_cas,omega_mod_cas                                                                   &
      &         ,du_mod_cas,hu_mod_cas,vu_mod_cas,dv_mod_cas,hv_mod_cas,vv_mod_cas                         &
      &         ,dt_mod_cas,ht_mod_cas,vt_mod_cas,dtrad_mod_cas,dq_mod_cas,hq_mod_cas,vq_mod_cas           &
@@ -884,11 +69,30 @@
       d_u_dyn_z(:)=0.
       d_v_dyn_z(:)=0.
-      DO l=2,llm-1
-       d_t_z(l)=(temp(l+1)-temp(l-1))/(play(l+1)-play(l-1))
-       d_th_z(l)=(teta(l+1)-teta(l-1))/(play(l+1)-play(l-1))
-       d_q_z(l)=(q(l+1,1)-q(l-1,1))/(play(l+1)-play(l-1))
-       d_u_z(l)=(u(l+1)-u(l-1))/(play(l+1)-play(l-1))
-       d_v_z(l)=(v(l+1)-v(l-1))/(play(l+1)-play(l-1))
-      ENDDO
+      if (1==0) then
+         DO l=2,llm-1
+          d_t_z(l)=(temp(l+1)-temp(l-1))/(play(l+1)-play(l-1))
+          d_th_z(l)=(teta(l+1)-teta(l-1))/(play(l+1)-play(l-1))
+          d_q_z(l)=(q(l+1,1)-q(l-1,1))/(play(l+1)-play(l-1))
+          d_u_z(l)=(u(l+1)-u(l-1))/(play(l+1)-play(l-1))
+          d_v_z(l)=(v(l+1)-v(l-1))/(play(l+1)-play(l-1))
+         ENDDO
+      else
+         DO l=2,llm-1
+	    IF (omega(l)>0.) THEN
+             d_t_z(l)=(temp(l+1)-temp(l))/(play(l+1)-play(l))
+             d_th_z(l)=(teta(l+1)-teta(l))/(play(l+1)-play(l))
+             d_q_z(l)=(q(l+1,1)-q(l,1))/(play(l+1)-play(l))
+             d_u_z(l)=(u(l+1)-u(l))/(play(l+1)-play(l))
+             d_v_z(l)=(v(l+1)-v(l))/(play(l+1)-play(l))
+	    ELSE
+             d_t_z(l)=(temp(l-1)-temp(l))/(play(l-1)-play(l))
+             d_th_z(l)=(teta(l-1)-teta(l))/(play(l-1)-play(l))
+             d_q_z(l)=(q(l-1,1)-q(l,1))/(play(l-1)-play(l))
+             d_u_z(l)=(u(l-1)-u(l))/(play(l-1)-play(l))
+             d_v_z(l)=(v(l-1)-v(l))/(play(l-1)-play(l))
+	    ENDIF
+	 ENDDO
+      endif
+      d_t_z(1)=d_t_z(2)
       d_t_z(1)=d_t_z(2)
       d_th_z(1)=d_th_z(2)
@@ -902,11 +106,17 @@
       d_v_z(llm)=d_v_z(llm-1)
 
+! TRAVAIL : PRENDRE DES NOTATIONS COHERENTES POUR W
+      do l = 1, llm
+! Modif w_mod_cas -> omega_mod_cas (MM+MPL 20170309)
+       omega(l) = -w_mod_cas(l)*play(l)*rg/(rd*temp(l))
+      enddo
+
 !Calcul de l advection verticale
 ! Modif w_mod_cas -> omega_mod_cas (MM+MPL 20170310)
-      d_t_dyn_z(:)=omega_mod_cas(:)*d_t_z(:)
-      d_th_dyn_z(:)=omega_mod_cas(:)*d_th_z(:)
-      d_q_dyn_z(:)=omega_mod_cas(:)*d_q_z(:)
-      d_u_dyn_z(:)=omega_mod_cas(:)*d_u_z(:)
-      d_v_dyn_z(:)=omega_mod_cas(:)*d_v_z(:)
+      d_t_dyn_z(:)=omega(:)*d_t_z(:)
+      d_th_dyn_z(:)=omega(:)*d_th_z(:)
+      d_q_dyn_z(:)=omega(:)*d_q_z(:)
+      d_u_dyn_z(:)=omega(:)*d_u_z(:)
+      d_v_dyn_z(:)=omega(:)*d_v_z(:)
 
 !geostrophic wind 
@@ -917,91 +127,33 @@
         enddo
       endif
-!wind nudging 
-      if (nudging_u.gt.0.) then
-        do l=1,llm
-           u(l)=u(l)+timestep*(u_mod_cas(l)-u(l))/(nudge_u)
-        enddo
-!     else
-!       do l=1,llm
-!          u(l) = u_mod_cas(l) 
-!       enddo
-      endif
-
-      if (nudging_v.gt.0.) then
-        do l=1,llm
-           v(l)=v(l)+timestep*(v_mod_cas(l)-v(l))/(nudge_v)
-        enddo
-!     else
-!       do l=1,llm
-!          v(l) = v_mod_cas(l) 
-!       enddo
-      endif
-
-      if (nudging_w.gt.0.) then
-        do l=1,llm
-           w(l)=w(l)+timestep*(w_mod_cas(l)-w(l))/(nudge_w)
-        enddo
- !    else
- !      do l=1,llm
- !         w(l) = w_mod_cas(l) 
- !      enddo
-      endif
-
-!nudging of q and temp 
-      if (nudging_t.gt.0.) then
-        do l=1,llm
-           temp(l)=temp(l)+timestep*(t_mod_cas(l)-temp(l))/(nudge_t)
-        enddo
-      endif
-      if (nudging_q.gt.0.) then
-        do l=1,llm
-           q(l,1)=q(l,1)+timestep*(q_mod_cas(l)-q(l,1))/(nudge_q)
-        enddo
-      endif
 
       do l = 1, llm
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 ! Modif w_mod_cas -> omega_mod_cas (MM+MPL 20170309)
+       !!! omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
        omega(l) = omega_mod_cas(l)
-       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+       omega2(l)= omega_mod_cas(l)/rg*airefi ! flxmass_w calcule comme ds physiq
 
-!calcul advections
-        if ((forc_u.eq.1).and.(forc_w.eq.0)) then
-           d_u_adv(l)=du_mod_cas(l)
-        else if ((forc_u.eq.1).and.(forc_w.eq.1)) then
-           d_u_adv(l)=hu_mod_cas(l)-d_u_dyn_z(l)
-        endif
+! On effectue la somme du forcage total et de la decomposition
+! horizontal/vertical en supposant que soit l'un soit l'autre
+! sont remplis mais jamais les deux
 
-        if ((forc_v.eq.1).and.(forc_w.eq.0)) then
-           d_v_adv(l)=dv_mod_cas(l)
-        else if ((forc_v.eq.1).and.(forc_w.eq.1)) then
-           d_v_adv(l)=hv_mod_cas(l)-d_v_dyn_z(l)
-        endif
+       d_t_adv(l) = dt_mod_cas(l)+ht_mod_cas(l)+vt_mod_cas(l)
+       d_q_adv(l,1) = dq_mod_cas(l)+hq_mod_cas(l)+vq_mod_cas(l)
+       d_q_adv(l,2) = 0.0
+       d_u_adv(l) = du_mod_cas(l)+hu_mod_cas(l)+vu_mod_cas(l)
+       d_v_adv(l) = dv_mod_cas(l)+hv_mod_cas(l)+vv_mod_cas(l)
 
-! Puisque dth a ete converti en dt, on traite de la meme facon 
-! les flags tadv et thadv
-        if ((tadv.eq.1.or.thadv.eq.1) .and. (forc_w.eq.0)) then
-!          d_t_adv(l)=alpha*omega(l)/rcpd-dt_mod_cas(l)
-           d_t_adv(l)=alpha*omega(l)/rcpd+dt_mod_cas(l)
-        else if ((tadv.eq.1.or.thadv.eq.1) .and. (forc_w.eq.1)) then
-!          d_t_adv(l)=alpha*omega(l)/rcpd-ht_mod_cas(l)-d_t_dyn_z(l)
-           d_t_adv(l)=alpha*omega(l)/rcpd+ht_mod_cas(l)-d_t_dyn_z(l)
-        endif
-
-!       if ((thadv.eq.1) .and. (forc_w.eq.0)) then
-!          d_t_adv(l)=alpha*omega(l)/rcpd-dth_mod_cas(l)
-!          d_t_adv(l)=alpha*omega(l)/rcpd+dth_mod_cas(l)
-!       else if ((thadv.eq.1) .and. (forc_w.eq.1)) then
-!          d_t_adv(l)=alpha*omega(l)/rcpd-hth_mod_cas(l)-d_t_dyn_z(l)
-!          d_t_adv(l)=alpha*omega(l)/rcpd+hth_mod_cas(l)-d_t_dyn_z(l)
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! CONSERVE EN ATTENDANT QUE LE CAS EN QUESTION FONCTIONNE EN STD !!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!if (forc_w==1) then
+!          d_q_adv(l,1)=d_q_adv(l,1)-d_q_dyn_z(l)
+!          d_t_adv(l)=d_t_adv(l)-d_t_dyn_z(l)
+!          d_v_adv(l)=d_v_adv(l)-d_v_dyn_z(l)
+!          d_u_adv(l)=d_u_adv(l)-d_u_dyn_z(l)
 !       endif
-
-        if ((qadv.eq.1) .and. (forc_w.eq.0)) then
-           d_q_adv(l,1)=dq_mod_cas(l)
-!          d_q_adv(l,1)=-1*dq_mod_cas(l)
-        else if ((qadv.eq.1) .and. (forc_w.eq.1)) then
-           d_q_adv(l,1)=hq_mod_cas(l)-d_q_dyn_z(l)
-!          d_q_adv(l,1)=-1*hq_mod_cas(l)-d_q_dyn_z(l)
-        endif
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
          
         if (trad.eq.1) then
@@ -1025,5 +177,2 @@
        print *,'ust=',ust
       ENDIF
-      endif ! forcing_case2
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/1D_nudge_sandu_astex.h
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/1D_nudge_sandu_astex.h	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/1D_nudge_sandu_astex.h	(revision 3605)
@@ -33,2 +33,10 @@
 
 
+	print*,'OLDLMDZ1D IOPH'
+      CALL iophys_ecrit('relax_thl',klev,'relax_thl','m/s',relax_thl)
+      CALL iophys_ecrit('d_t_adv',klev,'d_t_adv','m/s',d_t_adv)
+      CALL iophys_ecrit('temp',klev,'temp','m/s',temp)
+      CALL iophys_ecrit('q',klev,'q','m/s',q(:,1))
+      CALL iophys_ecrit('relax_q',klev,'relax_q','m/s',relax_q(:,1))
+      CALL iophys_ecrit('d_q_adv',klev,'d_q_adv','m/s',d_q_adv(:,1))
+
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/1D_read_forc_cases.h
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/1D_read_forc_cases.h	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/1D_read_forc_cases.h	(revision 3605)
@@ -11,928 +11,30 @@
       nq2=0
 
-      if (forcing_les .or. forcing_radconv                                      &
-     &    .or. forcing_GCSSold .or. forcing_fire) then
+      print*,'FORCING ,forcing_SCM',forcing_SCM
+      if (forcing_SCM) then
 
-      if (forcing_fire) then
-!----------------------------------------------------------------------
-!read fire forcings from fire.nc
-!----------------------------------------------------------------------
-      fich_fire='fire.nc'
-      call read_fire(fich_fire,nlev_fire,nt_fire                                &
-     &     ,height,tttprof,qtprof,uprof,vprof,e12prof                           &
-     &     ,ugprof,vgprof,wfls,dqtdxls                                          &
-     &     ,dqtdyls,dqtdtls,thlpcar)
-      write(*,*) 'Forcing FIRE lu'
-      kmax=120            ! nombre de niveaux dans les profils et forcages
-      else 
-!----------------------------------------------------------------------
-! Read profiles from files: prof.inp.001 and lscale.inp.001
-! (repris de readlesfiles)
-!----------------------------------------------------------------------
-
-      call readprofiles(nlev_max,kmax,nqtot,height,                             &
-     &           tttprof,qtprof,uprof,vprof,                                    &
-     &           e12prof,ugprof,vgprof,                                         &
-     &           wfls,dqtdxls,dqtdyls,dqtdtls,                                  &
-     &           thlpcar,qprof,nq1,nq2)
-      endif
-
-! compute altitudes of play levels.
-      zlay(1) =zsurf +  rd*tsurf*(psurf-play(1))/(rg*psurf)
-      do l = 2,llm
-        zlay(l) = zlay(l-1)+rd*tsurf*(psurf-play(1))/(rg*psurf)
-      enddo
-
-!----------------------------------------------------------------------
-! Interpolation of the profiles given on the input file to
-! model levels
-!----------------------------------------------------------------------
-      zlay(1) = zsurf +  rd*tsurf*(psurf-play(1))/(rg*psurf)
-      do l=1,llm
-        ! Above the max altutide of the input file
-
-        if (zlay(l)<height(kmax)) mxcalc=l
-
-        frac = (height(kmax)-zlay(l))/(height (kmax)-height(kmax-1))
-        ttt =tttprof(kmax)-frac*(tttprof(kmax)-tttprof(kmax-1))
-       if ((forcing_GCSSold .AND. tp_ini_GCSSold) .OR. forcing_fire)then ! pot. temp. in initial profile
-          temp(l) = ttt*(play(l)/pzero)**rkappa
-          teta(l) = ttt
-       else
-          temp(l) = ttt
-          teta(l) = ttt*(pzero/play(l))**rkappa
-       endif
-          print *,' temp,teta ',l,temp(l),teta(l)
-        q(l,1)  = qtprof(kmax)-frac*( qtprof(kmax)- qtprof(kmax-1))
-        u(l)    =  uprof(kmax)-frac*(  uprof(kmax)-  uprof(kmax-1))
-        v(l)    =  vprof(kmax)-frac*(  vprof(kmax)-  vprof(kmax-1))
-        ug(l)   = ugprof(kmax)-frac*( ugprof(kmax)- ugprof(kmax-1))
-        vg(l)   = vgprof(kmax)-frac*( vgprof(kmax)- vgprof(kmax-1))
-        IF (nq2>0) q(l,nq1:nq2)=qprof(kmax,nq1:nq2)                         &
-     &               -frac*(qprof(kmax,nq1:nq2)-qprof(kmax-1,nq1:nq2))
-        omega(l)=   wfls(kmax)-frac*(   wfls(kmax)-   wfls(kmax-1))
-
-        dq_dyn(l,1) = dqtdtls(kmax)-frac*(dqtdtls(kmax)-dqtdtls(kmax-1))
-        dt_cooling(l)=thlpcar(kmax)-frac*(thlpcar(kmax)-thlpcar(kmax-1))
-        do k=2,kmax
-          print *,'k l height(k) height(k-1) zlay(l) frac=',k,l,height(k),height(k-1),zlay(l),frac
-          frac = (height(k)-zlay(l))/(height(k)-height(k-1))
-          if(l==1) print*,'k, height, tttprof',k,height(k),tttprof(k)
-          if(zlay(l)>height(k-1).and.zlay(l)<height(k)) then
-            ttt =tttprof(k)-frac*(tttprof(k)-tttprof(k-1))
-       if ((forcing_GCSSold .AND. tp_ini_GCSSold) .OR. forcing_fire)then ! pot. temp. in initial profile
-          temp(l) = ttt*(play(l)/pzero)**rkappa
-          teta(l) = ttt
-       else
-          temp(l) = ttt
-          teta(l) = ttt*(pzero/play(l))**rkappa
-       endif
-          print *,' temp,teta ',l,temp(l),teta(l)
-            q(l,1)  = qtprof(k)-frac*( qtprof(k)- qtprof(k-1))
-            u(l)    =  uprof(k)-frac*(  uprof(k)-  uprof(k-1))
-            v(l)    =  vprof(k)-frac*(  vprof(k)-  vprof(k-1))
-            ug(l)   = ugprof(k)-frac*( ugprof(k)- ugprof(k-1))
-            vg(l)   = vgprof(k)-frac*( vgprof(k)- vgprof(k-1))
-            IF (nq2>0) q(l,nq1:nq2)=qprof(k,nq1:nq2)                        &
-     &                   -frac*(qprof(k,nq1:nq2)-qprof(k-1,nq1:nq2))
-            omega(l)=   wfls(k)-frac*(   wfls(k)-   wfls(k-1))
-            dq_dyn(l,1)=dqtdtls(k)-frac*(dqtdtls(k)-dqtdtls(k-1))
-            dt_cooling(l)=thlpcar(k)-frac*(thlpcar(k)-thlpcar(k-1))
-          elseif(zlay(l)<height(1)) then ! profils uniformes pour z<height(1)
-            ttt =tttprof(1)
-       if ((forcing_GCSSold .AND. tp_ini_GCSSold) .OR. forcing_fire)then ! pot. temp. in initial profile
-          temp(l) = ttt*(play(l)/pzero)**rkappa
-          teta(l) = ttt
-       else
-          temp(l) = ttt
-          teta(l) = ttt*(pzero/play(l))**rkappa
-       endif
-            q(l,1)  = qtprof(1)
-            u(l)    =  uprof(1)
-            v(l)    =  vprof(1)
-            ug(l)   = ugprof(1)
-            vg(l)   = vgprof(1)
-            omega(l)=   wfls(1)
-            IF (nq2>0) q(l,nq1:nq2)=qprof(1,nq1:nq2)
-            dq_dyn(l,1)  =dqtdtls(1)
-            dt_cooling(l)=thlpcar(1)
-          endif
-        enddo 
-
-        temp(l)=max(min(temp(l),350.),150.)
-        rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
-        if (l .lt. llm) then
-          zlay(l+1) = zlay(l) + (play(l)-play(l+1))/(rg*rho(l))
-        endif
-        omega2(l)=-rho(l)*omega(l)
-        omega(l)= omega(l)*(-rg*rho(l)) !en Pa/s
-        if (l>1) then
-        if(zlay(l-1)>height(kmax)) then
-           omega(l)=0.0
-           omega2(l)=0.0
-        endif   
-        endif
-        if(q(l,1)<0.) q(l,1)=0.0
-        q(l,2)  = 0.0
-      enddo
-
-      endif ! forcing_les .or. forcing_GCSSold .or. forcing_fire
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Forcing for GCSSold:
-!---------------------------------------------------------------------
-      if (forcing_GCSSold) then
-       fich_gcssold_ctl = './forcing.ctl'
-       fich_gcssold_dat = './forcing8.dat'
-       call copie(llm,play,psurf,fich_gcssold_ctl)
-       call get_uvd2(it,timestep,fich_gcssold_ctl,fich_gcssold_dat,         &
-     &               ht_gcssold,hq_gcssold,hw_gcssold,                      &
-     &               hu_gcssold,hv_gcssold,                                 &
-     &               hthturb_gcssold,hqturb_gcssold,Ts_gcssold,             &
-     &               imp_fcg_gcssold,ts_fcg_gcssold,                        &
-     &               Tp_fcg_gcssold,Turb_fcg_gcssold)
-       print *,' get_uvd2 -> hqturb_gcssold ',hqturb_gcssold
-      endif ! forcing_GCSSold
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Forcing for RICO:
-!---------------------------------------------------------------------
-      if (forcing_rico) then
-
-!       call writefield_phy('omega', omega,llm+1)
-      fich_rico = 'rico.txt'
-       call read_rico(fich_rico,nlev_rico,ps_rico,play                      &
-     &             ,ts_rico,t_rico,q_rico,u_rico,v_rico,w_rico              &
-     &             ,dth_rico,dqh_rico)
-        print*, ' on a lu et prepare RICO'
-
-       mxcalc=llm
-       print *, airefi, ' airefi '
-       do l = 1, llm
-       rho(l)  = play(l)/(rd*t_rico(l)*(1.+(rv/rd-1.)*q_rico(l)))
-       temp(l) = t_rico(l)
-       q(l,1) = q_rico(l)
-       q(l,2) = 0.0
-       u(l) = u_rico(l)
-       v(l) = v_rico(l)
-       ug(l)=u_rico(l)
-       vg(l)=v_rico(l)
-       omega(l) = -w_rico(l)*rg
-       omega2(l) = omega(l)/rg*airefi
-       enddo
-      endif
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Forcing from TOGA-COARE experiment (Ciesielski et al. 2002) :
-!---------------------------------------------------------------------
-
-      if (forcing_toga) then
-
-! read TOGA-COARE forcing (native vertical grid, nt_toga timesteps):
-      fich_toga = './d_toga/ifa_toga_coare_v21_dime.txt'
-      CALL read_togacoare(fich_toga,nlev_toga,nt_toga                       &
-     &         ,ts_toga,plev_toga,t_toga,q_toga,u_toga,v_toga,w_toga        &
-     &         ,ht_toga,vt_toga,hq_toga,vq_toga)
-
-       write(*,*) 'Forcing TOGA lu'
-
-! time interpolation for initial conditions:
-      write(*,*) 'AVT 1ere INTERPOLATION: day,day1 = ',day,day1
-      CALL interp_toga_time(daytime,day1,annee_ref                          &
-     &             ,year_ini_toga,day_ju_ini_toga,nt_toga,dt_toga           &
-     &             ,nlev_toga,ts_toga,plev_toga,t_toga,q_toga,u_toga        &
-     &             ,v_toga,w_toga,ht_toga,vt_toga,hq_toga,vq_toga           &
-     &             ,ts_prof,plev_prof,t_prof,q_prof,u_prof,v_prof,w_prof    &
-     &             ,ht_prof,vt_prof,hq_prof,vq_prof)
-
-! vertical interpolation:
-      CALL interp_toga_vertical(play,nlev_toga,plev_prof                    &
-     &         ,t_prof,q_prof,u_prof,v_prof,w_prof                          &
-     &         ,ht_prof,vt_prof,hq_prof,vq_prof                             &
-     &         ,t_mod,q_mod,u_mod,v_mod,w_mod                               &
-     &         ,ht_mod,vt_mod,hq_mod,vq_mod,mxcalc)
-       write(*,*) 'Profil initial forcing TOGA interpole'
-
-! initial and boundary conditions :
-      tsurf = ts_prof
-      write(*,*) 'SST initiale: ',tsurf
-      do l = 1, llm
-       temp(l) = t_mod(l)
-       q(l,1) = q_mod(l)
-       q(l,2) = 0.0
-       u(l) = u_mod(l)
-       v(l) = v_mod(l)
-       omega(l) = w_mod(l)
-       omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
-!?       rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
-!?       omega2(l)=-rho(l)*omega(l)
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
-       d_t_adv(l) = alpha*omega(l)/rcpd-(ht_mod(l)+vt_mod(l))
-       d_q_adv(l,1) = -(hq_mod(l)+vq_mod(l))
-       d_q_adv(l,2) = 0.0
-      enddo
-
-      endif ! forcing_toga
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Forcing from TWPICE experiment (Shaocheng et al. 2010) :
-!---------------------------------------------------------------------
-
-      if (forcing_twpice) then
-!read TWP-ICE forcings
-     fich_twpice='d_twpi/twp180iopsndgvarana_v2.1_C3.c1.20060117.000000.cdf'
-      call read_twpice(fich_twpice,nlev_twpi,nt_twpi                        &
-     &     ,ts_twpi,plev_twpi,t_twpi,q_twpi,u_twpi,v_twpi,w_twpi            &
-     &     ,ht_twpi,vt_twpi,hq_twpi,vq_twpi)
-
-      write(*,*) 'Forcing TWP-ICE lu'
-!Time interpolation for initial conditions using TOGA interpolation routine
-         write(*,*) 'AVT 1ere INTERPOLATION: day,day1 = ',daytime,day1   
-      CALL interp_toga_time(daytime,day1,annee_ref                          &
-     &          ,year_ini_twpi,day_ju_ini_twpi,nt_twpi,dt_twpi,nlev_twpi    &
-     &             ,ts_twpi,plev_twpi,t_twpi,q_twpi,u_twpi,v_twpi,w_twpi    &
-     &             ,ht_twpi,vt_twpi,hq_twpi,vq_twpi                         &
-     &             ,ts_proftwp,plev_proftwp,t_proftwp,q_proftwp             &
-     &             ,u_proftwp,v_proftwp,w_proftwp                           &
-     &             ,ht_proftwp,vt_proftwp,hq_proftwp,vq_proftwp)
-
-! vertical interpolation using TOGA interpolation routine:
-!      write(*,*)'avant interp vert', t_proftwp
-      CALL interp_toga_vertical(play,nlev_twpi,plev_proftwp                 &
-     &         ,t_proftwp,q_proftwp,u_proftwp,v_proftwp,w_proftwp           &
-     &         ,ht_proftwp,vt_proftwp,hq_proftwp,vq_proftwp                 &
-     &         ,t_mod,q_mod,u_mod,v_mod,w_mod                               &
-     &         ,ht_mod,vt_mod,hq_mod,vq_mod,mxcalc)
-!       write(*,*) 'Profil initial forcing TWP-ICE interpole',t_mod
-
-! initial and boundary conditions :
-!      tsurf = ts_proftwp
-      write(*,*) 'SST initiale: ',tsurf
-      do l = 1, llm
-       temp(l) = t_mod(l)
-       q(l,1) = q_mod(l)
-       q(l,2) = 0.0
-       u(l) = u_mod(l)
-       v(l) = v_mod(l)
-       omega(l) = w_mod(l)
-       omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
-
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
-!on applique le forcage total au premier pas de temps
-!attention: signe different de toga
-       d_t_adv(l) = alpha*omega(l)/rcpd+(ht_mod(l)+vt_mod(l))
-       d_q_adv(l,1) = (hq_mod(l)+vq_mod(l))
-       d_q_adv(l,2) = 0.0
-      enddo     
-       
-      endif !forcing_twpice
-
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Forcing from AMMA experiment (Couvreux et al. 2010) :
-!---------------------------------------------------------------------
-
-      if (forcing_amma) then
-
-      call read_1D_cases
-
-      write(*,*) 'Forcing AMMA lu'
-
-!champs initiaux:
-      do k=1,nlev_amma
-         th_ammai(k)=th_amma(k)
-         q_ammai(k)=q_amma(k)
-         u_ammai(k)=u_amma(k)
-         v_ammai(k)=v_amma(k)
-         vitw_ammai(k)=vitw_amma(k,12)
-         ht_ammai(k)=ht_amma(k,12)
-         hq_ammai(k)=hq_amma(k,12)
-         vt_ammai(k)=0.
-         vq_ammai(k)=0.
-      enddo   
-      omega(:)=0.      
-      omega2(:)=0.
-      rho(:)=0.
-! vertical interpolation using TOGA interpolation routine:
-!      write(*,*)'avant interp vert', t_proftwp
-      CALL interp_toga_vertical(play,nlev_amma,plev_amma                    &
-     &         ,th_ammai,q_ammai,u_ammai,v_ammai,vitw_ammai                 &
-     &         ,ht_ammai,vt_ammai,hq_ammai,vq_ammai                         &
-     &         ,t_mod,q_mod,u_mod,v_mod,w_mod                               &
-     &         ,ht_mod,vt_mod,hq_mod,vq_mod,mxcalc)
-!       write(*,*) 'Profil initial forcing TWP-ICE interpole',t_mod
-
-! initial and boundary conditions :
-!      tsurf = ts_proftwp
-      write(*,*) 'SST initiale mxcalc: ',tsurf,mxcalc
-      do l = 1, llm
-! Ligne du dessous ?? decommenter si on lit theta au lieu de temp
-!      temp(l) = t_mod(l)*(play(l)/pzero)**rkappa 
-       temp(l) = t_mod(l) 
-       q(l,1) = q_mod(l)
-       q(l,2) = 0.0
-!      print *,'read_forc: l,temp,q=',l,temp(l),q(l,1)
-       u(l) = u_mod(l)
-       v(l) = v_mod(l)
-       rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
-       omega(l) = w_mod(l)*(-rg*rho(l))
-       omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
-
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
-!on applique le forcage total au premier pas de temps
-!attention: signe different de toga
-       d_t_adv(l) = alpha*omega(l)/rcpd+ht_mod(l)
-!forcage en th
-!       d_t_adv(l) = ht_mod(l)
-       d_q_adv(l,1) = hq_mod(l)
-       d_q_adv(l,2) = 0.0
-       dt_cooling(l)=0.
-      enddo     
-       write(*,*) 'Prof initeforcing AMMA interpole temp39',temp(39)
-      
-
-!     ok_flux_surf=.false.
-      fsens=-1.*sens_amma(12)
-      flat=-1.*lat_amma(12)
-       
-      endif !forcing_amma
-
-
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Forcing from DICE experiment (see file DICE_protocol_vn2-3.pdf)
-!---------------------------------------------------------------------
-
-      if (forcing_dice) then
-!read DICE forcings
-      fich_dice='dice_driver.nc'
-      call read_dice(fich_dice,nlev_dice,nt_dice                    &
-     &     ,zz_dice,plev_dice,t_dice,qv_dice,u_dice,v_dice,o3_dice &
-     &     ,shf_dice,lhf_dice,lwup_dice,swup_dice,tg_dice,ustar_dice& 
-     &     ,psurf_dice,ug_dice,vg_dice,ht_dice,hq_dice              &
-     &     ,hu_dice,hv_dice,w_dice,omega_dice)
-
-      write(*,*) 'Forcing DICE lu'
-
-!champs initiaux:
-      do k=1,nlev_dice
-         t_dicei(k)=t_dice(k)
-         qv_dicei(k)=qv_dice(k)
-         u_dicei(k)=u_dice(k)
-         v_dicei(k)=v_dice(k)
-         o3_dicei(k)=o3_dice(k)
-         ht_dicei(k)=ht_dice(k,1)
-         hq_dicei(k)=hq_dice(k,1)
-         hu_dicei(k)=hu_dice(k,1)
-         hv_dicei(k)=hv_dice(k,1)
-         w_dicei(k)=w_dice(k,1)
-         omega_dicei(k)=omega_dice(k,1)
-      enddo   
-      omega(:)=0.      
-      omega2(:)=0.
-      rho(:)=0.
-! vertical interpolation using TOGA interpolation routine:
-!      write(*,*)'avant interp vert', t_proftwp
-!
-!     CALL interp_dice_time(daytime,day1,annee_ref
-!    i             ,year_ini_dice,day_ju_ini_dice,nt_dice,dt_dice
-!    i             ,nlev_dice,shf_dice,lhf_dice,lwup_dice,swup_dice
-!    i             ,tg_dice,ustar_dice,psurf_dice,ug_dice,vg_dice
-!    i             ,ht_dice,hq_dice,hu_dice,hv_dice,w_dice,omega_dice
-!    o             ,shf_prof,lhf_prof,lwup_prof,swup_prof,tg_prof
-!    o             ,ustar_prof,psurf_prof,ug_profd,vg_profd
-!    o             ,ht_profd,hq_profd,hu_profd,hv_profd,w_profd
-!    o             ,omega_profd)
-
-      CALL interp_dice_vertical(play,nlev_dice,nt_dice,plev_dice       &
-     &         ,t_dicei,qv_dicei,u_dicei,v_dicei,o3_dicei             &
-     &         ,ht_dicei,hq_dicei,hu_dicei,hv_dicei,w_dicei,omega_dicei&
-     &         ,t_mod,qv_mod,u_mod,v_mod,o3_mod                       &
-     &         ,ht_mod,hq_mod,hu_mod,hv_mod,w_mod,omega_mod,mxcalc)
-
-! Pour tester les advections horizontales de T et Q, on met w_mod et omega_mod ?? zero (MPL 20131108)
-!     w_mod(:,:)=0.
-!     omega_mod(:,:)=0.
-
-!       write(*,*) 'Profil initial forcing DICE interpole',t_mod
-! Les forcages DICE sont donnes /jour et non /seconde !
-      ht_mod(:)=ht_mod(:)/86400.
-      hq_mod(:)=hq_mod(:)/86400.
-      hu_mod(:)=hu_mod(:)/86400.
-      hv_mod(:)=hv_mod(:)/86400.
-
-! initial and boundary conditions :
-      write(*,*) 'SST initiale mxcalc: ',tsurf,mxcalc
-      do l = 1, llm
-! Ligne du dessous ?? decommenter si on lit theta au lieu de temp
-!      temp(l) = th_mod(l)*(play(l)/pzero)**rkappa 
-       temp(l) = t_mod(l) 
-       q(l,1) = qv_mod(l)
-       q(l,2) = 0.0
-!      print *,'read_forc: l,temp,q=',l,temp(l),q(l,1)
-       u(l) = u_mod(l)
-       v(l) = v_mod(l)
-       ug(l)=ug_dice(1)
-       vg(l)=vg_dice(1)
-       rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
-!      omega(l) = w_mod(l)*(-rg*rho(l))
-       omega(l) = omega_mod(l)
-       omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
-
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
-!on applique le forcage total au premier pas de temps
-!attention: signe different de toga
-       d_t_adv(l) = alpha*omega(l)/rcpd+ht_mod(l)
-!forcage en th
-!       d_t_adv(l) = ht_mod(l)
-       d_q_adv(l,1) = hq_mod(l)
-       d_q_adv(l,2) = 0.0
-       dt_cooling(l)=0.
-      enddo     
-       write(*,*) 'Profil initial forcing DICE interpole temp39',temp(39)
-      
-
-!     ok_flux_surf=.false.
-      fsens=-1.*shf_dice(1)
-      flat=-1.*lhf_dice(1)
-! Le cas Dice doit etre force avec ustar mais on peut simplifier en forcant par 
-! le coefficient de trainee en surface cd**2=ustar*vent(k=1)
-! On commence ici a stocker ustar dans cdrag puis on terminera le calcul dans pbl_surface
-! MPL 05082013
-      ust=ustar_dice(1)
-      tg=tg_dice(1)
-      print *,'ust= ',ust
-      IF (tsurf .LE. 0.) THEN
-       tsurf= tg_dice(1)
-      ENDIF
-      psurf= psurf_dice(1)
-      solsw_in = (1.-albedo)/albedo*swup_dice(1)
-      sollw_in = (0.7*RSIGMA*temp(1)**4)-lwup_dice(1)
-      PRINT *,'1D_READ_FORC : solsw, sollw',solsw_in,sollw_in
-      endif !forcing_dice
-
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Forcing from GABLS4 experiment
-!---------------------------------------------------------------------
-
-!!!! Si la temperature de surface n'est pas impos??e:
-  
-      if (forcing_gabls4) then
-!read GABLS4 forcings
-      
-      fich_gabls4='gabls4_driver.nc'
-      
-       	
-      call read_gabls4(fich_gabls4,nlev_gabls4,nt_gabls4,nsol_gabls4,zz_gabls4,depth_sn_gabls4,ug_gabls4,vg_gabls4 &
-     & ,plev_gabls4,th_gabls4,t_gabls4,qv_gabls4,u_gabls4,v_gabls4,ht_gabls4,hq_gabls4,tg_gabls4,tsnow_gabls4,snow_dens_gabls4)
-
-      write(*,*) 'Forcing GABLS4 lu'
-
-!champs initiaux:
-      do k=1,nlev_gabls4
-         t_gabi(k)=t_gabls4(k)
-         qv_gabi(k)=qv_gabls4(k)
-         u_gabi(k)=u_gabls4(k)
-         v_gabi(k)=v_gabls4(k)
-         poub(k)=0.
-         ht_gabi(k)=ht_gabls4(k,1)
-         hq_gabi(k)=hq_gabls4(k,1)
-         ug_gabi(k)=ug_gabls4(k,1)
-         vg_gabi(k)=vg_gabls4(k,1)
-      enddo 
-  
-      omega(:)=0.      
-      omega2(:)=0.
-      rho(:)=0.
-! vertical interpolation using TOGA interpolation routine:
-!      write(*,*)'avant interp vert', t_proftwp
-!
-!     CALL interp_dice_time(daytime,day1,annee_ref
-!    i             ,year_ini_dice,day_ju_ini_dice,nt_dice,dt_dice
-!    i             ,nlev_dice,shf_dice,lhf_dice,lwup_dice,swup_dice
-!    i             ,tg_dice,ustar_dice,psurf_dice,ug_dice,vg_dice
-!    i             ,ht_dice,hq_dice,hu_dice,hv_dice,w_dice,omega_dice
-!    o             ,shf_prof,lhf_prof,lwup_prof,swup_prof,tg_prof
-!    o             ,ustar_prof,psurf_prof,ug_profd,vg_profd
-!    o             ,ht_profd,hq_profd,hu_profd,hv_profd,w_profd
-!    o             ,omega_profd)
-
-      CALL interp_dice_vertical(play,nlev_gabls4,nt_gabls4,plev_gabls4       &
-     &         ,t_gabi,qv_gabi,u_gabi,v_gabi,poub                  &
-     &         ,ht_gabi,hq_gabi,ug_gabi,vg_gabi,poub,poub          &
-     &         ,t_mod,qv_mod,u_mod,v_mod,o3_mod                    &
-     &         ,ht_mod,hq_mod,ug_mod,vg_mod,w_mod,omega_mod,mxcalc)
-
-! Les forcages GABLS4 ont l air d etre en K/S quoiqu en dise le fichier gabls4_driver.nc !? MPL 20141024
-!     ht_mod(:)=ht_mod(:)/86400.
-!     hq_mod(:)=hq_mod(:)/86400.
-
-! initial and boundary conditions :
-      write(*,*) 'SST initiale mxcalc: ',tsurf,mxcalc
-      do l = 1, llm
-! Ligne du dessous ?? decommenter si on lit theta au lieu de temp
-!      temp(l) = th_mod(l)*(play(l)/pzero)**rkappa 
-       temp(l) = t_mod(l) 
-       q(l,1) = qv_mod(l)
-       q(l,2) = 0.0
-!      print *,'read_forc: l,temp,q=',l,temp(l),q(l,1)
-       u(l) = u_mod(l)
-       v(l) = v_mod(l)
-       ug(l)=ug_mod(l)
-       vg(l)=vg_mod(l)
-       
-!
-!	tg=tsurf
-!       
-
-       print *,'***** tsurf=',tsurf
-       rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
-!      omega(l) = w_mod(l)*(-rg*rho(l))
-       omega(l) = omega_mod(l)
-       omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
-       
-    
-
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
-!on applique le forcage total au premier pas de temps
-!attention: signe different de toga
-!      d_t_adv(l) = alpha*omega(l)/rcpd+ht_mod(l)
-!forcage en th
-       d_t_adv(l) = ht_mod(l)
-       d_q_adv(l,1) = hq_mod(l)
-       d_q_adv(l,2) = 0.0
-       dt_cooling(l)=0.
-      enddo     
-
-!--------------- Residus forcages du cas Dice (a supprimer) MPL 20141024---------------
-! Le cas Dice doit etre force avec ustar mais on peut simplifier en forcant par 
-! le coefficient de trainee en surface cd**2=ustar*vent(k=1)
-! On commence ici a stocker ustar dans cdrag puis on terminera le calcul dans pbl_surface
-! MPL 05082013
-!     ust=ustar_dice(1)
-!     tg=tg_dice(1)
-!     print *,'ust= ',ust
-!     IF (tsurf .LE. 0.) THEN
-!      tsurf= tg_dice(1)
-!     ENDIF
-!     psurf= psurf_dice(1)
-!     solsw_in = (1.-albedo)/albedo*swup_dice(1)
-!     sollw_in = (0.7*RSIGMA*temp(1)**4)-lwup_dice(1)
-!     PRINT *,'1D_READ_FORC : solsw, sollw',solsw_in,sollw_in
-!--------------------------------------------------------------------------------------
-      endif !forcing_gabls4
-
-
-
-! Forcing from Arm_Cu case                   
-! For this case, ifa_armcu.txt contains sensible, latent heat fluxes
-! large scale advective forcing,radiative forcing 
-! and advective tendency of theta and qt to be applied 
-!---------------------------------------------------------------------
-
-      if (forcing_armcu) then
-! read armcu forcing :
-       write(*,*) 'Avant lecture Forcing Arm_Cu'
-      fich_armcu = './ifa_armcu.txt'
-      CALL read_armcu(fich_armcu,nlev_armcu,nt_armcu,                       &
-     & sens_armcu,flat_armcu,adv_theta_armcu,                               &
-     & rad_theta_armcu,adv_qt_armcu)
-       write(*,*) 'Forcing Arm_Cu lu'
-
-!----------------------------------------------------------------------
-! Read profiles from file: prof.inp.19 or prof.inp.40 
-! For this case, profiles are given for two vertical resolution
-! 19 or 40 levels
-!
-! Comment from: http://www.knmi.nl/samenw/eurocs/ARM/profiles.html
-! Note that the initial profiles contain no liquid water! 
-! (so potential temperature can be interpreted as liquid water 
-! potential temperature and water vapor as total water)
-! profiles are given at full levels
-!----------------------------------------------------------------------
-
-      call readprofile_armcu(nlev_max,kmax,height,play_mod,u_mod,           &
-     &           v_mod,theta_mod,t_mod,qv_mod,rv_mod,ap,bp)
-
-! time interpolation for initial conditions:
-      write(*,*) 'AVT 1ere INTERPOLATION: day,day1 = ',day,day1
-
-      print *,'Avant interp_armcu_time'
-      print *,'daytime=',daytime
-      print *,'day1=',day1
-      print *,'annee_ref=',annee_ref
-      print *,'year_ini_armcu=',year_ini_armcu
-      print *,'day_ju_ini_armcu=',day_ju_ini_armcu
-      print *,'nt_armcu=',nt_armcu
-      print *,'dt_armcu=',dt_armcu
-      print *,'nlev_armcu=',nlev_armcu
-      CALL interp_armcu_time(daytime,day1,annee_ref                         &
-     &            ,year_ini_armcu,day_ju_ini_armcu,nt_armcu,dt_armcu        &
-     &            ,nlev_armcu,sens_armcu,flat_armcu,adv_theta_armcu         &
-     &            ,rad_theta_armcu,adv_qt_armcu,sens_prof,flat_prof         &
-     &            ,adv_theta_prof,rad_theta_prof,adv_qt_prof)
-       write(*,*) 'Forcages interpoles dans temps'
-
-! No vertical interpolation if nlev imposed to 19 or 40
-! The vertical grid stops at 4000m # 600hPa
-      mxcalc=llm
-
-! initial and boundary conditions :
-!     tsurf = ts_prof
-! tsurf read in lmdz1d.def
-      write(*,*) 'Tsurf initiale: ',tsurf
-      do l = 1, llm
-       play(l)=play_mod(l)*100.
-       presnivs(l)=play(l)
-       zlay(l)=height(l)
-       temp(l) = t_mod(l)
-       teta(l)=theta_mod(l)
-       q(l,1) = qv_mod(l)/1000.
-! No liquid water in the initial profil
-       q(l,2) = 0.
-       u(l) = u_mod(l)
-       ug(l)= u_mod(l)
-       v(l) = v_mod(l)
-       vg(l)= v_mod(l)
-! Advective forcings are given in K or g/kg ... per HOUR
-!      IF(height(l).LT.1000) THEN
-!        d_t_adv(l) = (adv_theta_prof + rad_theta_prof)/3600.
-!        d_q_adv(l,1) = adv_qt_prof/1000./3600.
-!        d_q_adv(l,2) = 0.0
-!      ELSEIF (height(l).GE.1000.AND.height(l).LT.3000) THEN
-!        d_t_adv(l) = (adv_theta_prof + rad_theta_prof)*
-!    :               (1-(height(l)-1000.)/2000.)
-!        d_t_adv(l) = d_t_adv(l)/3600.
-!        d_q_adv(l,1) = adv_qt_prof*(1-(height(l)-1000.)/2000.)
-!        d_q_adv(l,1) = d_q_adv(l,1)/1000./3600.
-!        d_q_adv(l,2) = 0.0
-!      ELSE
-!        d_t_adv(l) = 0.0
-!        d_q_adv(l,1) = 0.0
-!        d_q_adv(l,2) = 0.0
-!      ENDIF
-      enddo
-! plev at half levels is given in proh.inp.19 or proh.inp.40 files
-      plev(1)= ap(llm+1)+bp(llm+1)*psurf
-      do l = 1, llm
-      plev(l+1) = ap(llm-l+1)+bp(llm-l+1)*psurf
-      print *,'Read_forc: l height play plev zlay temp',                    &
-     &   l,height(l),play(l),plev(l),zlay(l),temp(l)
-      enddo
-! For this case, fluxes are imposed
-       fsens=-1*sens_prof
-       flat=-1*flat_prof
-
-      endif ! forcing_armcu
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Forcing from transition case of Irina Sandu                  
-!---------------------------------------------------------------------
-
-      if (forcing_sandu) then
-       write(*,*) 'Avant lecture Forcing SANDU'
-
-! read sanduref forcing :
-      fich_sandu = './ifa_sanduref.txt'
-      CALL read_sandu(fich_sandu,nlev_sandu,nt_sandu,ts_sandu)
-
-       write(*,*) 'Forcing SANDU lu'
-
-!----------------------------------------------------------------------
-! Read profiles from file: prof.inp.001 
-!----------------------------------------------------------------------
-
-      call readprofile_sandu(nlev_max,kmax,height,plev_profs,t_profs,       &
-     &           thl_profs,q_profs,u_profs,v_profs,                         &
-     &           w_profs,omega_profs,o3mmr_profs)
-
-! time interpolation for initial conditions:
-      write(*,*) 'AVT 1ere INTERPOLATION: day,day1 = ',day,day1
-! ATTENTION, cet appel ne convient pas pour le cas SANDU !!
-! revoir 1DUTILS.h et les arguments
-
-      print *,'Avant interp_sandu_time'
-      print *,'daytime=',daytime
-      print *,'day1=',day1
-      print *,'annee_ref=',annee_ref
-      print *,'year_ini_sandu=',year_ini_sandu
-      print *,'day_ju_ini_sandu=',day_ju_ini_sandu
-      print *,'nt_sandu=',nt_sandu
-      print *,'dt_sandu=',dt_sandu
-      print *,'nlev_sandu=',nlev_sandu
-      CALL interp_sandu_time(daytime,day1,annee_ref                         &
-     &             ,year_ini_sandu,day_ju_ini_sandu,nt_sandu,dt_sandu       &
-     &             ,nlev_sandu                                              &
-     &             ,ts_sandu,ts_prof)
-
-! vertical interpolation:
-      print *,'Avant interp_vertical: nlev_sandu=',nlev_sandu
-      CALL interp_sandu_vertical(play,nlev_sandu,plev_profs                 &
-     &         ,t_profs,thl_profs,q_profs,u_profs,v_profs,w_profs           &
-     &         ,omega_profs,o3mmr_profs                                     &
-     &         ,t_mod,thl_mod,q_mod,u_mod,v_mod,w_mod                       &
-     &         ,omega_mod,o3mmr_mod,mxcalc)
-       write(*,*) 'Profil initial forcing SANDU interpole'
-
-! initial and boundary conditions :
-      tsurf = ts_prof
-      write(*,*) 'SST initiale: ',tsurf
-      do l = 1, llm
-       temp(l) = t_mod(l)
-       tetal(l)=thl_mod(l)
-       q(l,1) = q_mod(l)
-       q(l,2) = 0.0
-       u(l) = u_mod(l)
-       v(l) = v_mod(l)
-       w(l) = w_mod(l)
-       omega(l) = omega_mod(l)
-       omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
-!?       rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
-!?       omega2(l)=-rho(l)*omega(l)
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
-!      d_t_adv(l) = alpha*omega(l)/rcpd+vt_mod(l)
-!      d_q_adv(l,1) = vq_mod(l)
-       d_t_adv(l) = alpha*omega(l)/rcpd
-       d_q_adv(l,1) = 0.0
-       d_q_adv(l,2) = 0.0
-      enddo
-
-      endif ! forcing_sandu
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Forcing from Astex case
-!---------------------------------------------------------------------
-
-      if (forcing_astex) then
-       write(*,*) 'Avant lecture Forcing Astex'
-
-! read astex forcing :
-      fich_astex = './ifa_astex.txt'
-      CALL read_astex(fich_astex,nlev_astex,nt_astex,div_astex,ts_astex,    &
-     &  ug_astex,vg_astex,ufa_astex,vfa_astex)
-
-       write(*,*) 'Forcing Astex lu'
-
-!----------------------------------------------------------------------
-! Read profiles from file: prof.inp.001
-!----------------------------------------------------------------------
-
-      call readprofile_astex(nlev_max,kmax,height,plev_profa,t_profa,       &
-     &           thl_profa,qv_profa,ql_profa,qt_profa,u_profa,v_profa,      &
-     &           w_profa,tke_profa,o3mmr_profa)
-
-! time interpolation for initial conditions:
-      write(*,*) 'AVT 1ere INTERPOLATION: day,day1 = ',day,day1
-! ATTENTION, cet appel ne convient pas pour le cas SANDU !!
-! revoir 1DUTILS.h et les arguments
-
-      print *,'Avant interp_astex_time'
-      print *,'daytime=',daytime
-      print *,'day1=',day1
-      print *,'annee_ref=',annee_ref
-      print *,'year_ini_astex=',year_ini_astex
-      print *,'day_ju_ini_astex=',day_ju_ini_astex
-      print *,'nt_astex=',nt_astex
-      print *,'dt_astex=',dt_astex
-      print *,'nlev_astex=',nlev_astex
-      CALL interp_astex_time(daytime,day1,annee_ref                         &
-     &             ,year_ini_astex,day_ju_ini_astex,nt_astex,dt_astex       &
-     &             ,nlev_astex,div_astex,ts_astex,ug_astex,vg_astex         &
-     &             ,ufa_astex,vfa_astex,div_prof,ts_prof,ug_prof,vg_prof    &
-     &             ,ufa_prof,vfa_prof)
-
-! vertical interpolation:
-      print *,'Avant interp_vertical: nlev_astex=',nlev_astex
-      CALL interp_astex_vertical(play,nlev_astex,plev_profa                 &
-     &         ,t_profa,thl_profa,qv_profa,ql_profa,qt_profa                &
-     &         ,u_profa,v_profa,w_profa,tke_profa,o3mmr_profa               &
-     &         ,t_mod,thl_mod,qv_mod,ql_mod,qt_mod,u_mod,v_mod,w_mod        &
-     &         ,tke_mod,o3mmr_mod,mxcalc)
-       write(*,*) 'Profil initial forcing Astex interpole'
-
-! initial and boundary conditions :
-      tsurf = ts_prof
-      write(*,*) 'SST initiale: ',tsurf
-      do l = 1, llm
-       temp(l) = t_mod(l)
-       tetal(l)=thl_mod(l)
-       q(l,1) = qv_mod(l)
-       q(l,2) = ql_mod(l)
-       u(l) = u_mod(l)
-       v(l) = v_mod(l)
-       w(l) = w_mod(l)
-       omega(l) = w_mod(l)
-!      omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
-!      rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
-!      omega2(l)=-rho(l)*omega(l)
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
-!      d_t_adv(l) = alpha*omega(l)/rcpd+vt_mod(l)
-!      d_q_adv(l,1) = vq_mod(l)
-       d_t_adv(l) = alpha*omega(l)/rcpd
-       d_q_adv(l,1) = 0.0
-       d_q_adv(l,2) = 0.0
-      enddo
-
-      endif ! forcing_astex
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Forcing from standard case :
-!---------------------------------------------------------------------
-
-      if (forcing_case) then
-
-         write(*,*),'avant call read_1D_cas'
-         call read_1D_cas
-         write(*,*) 'Forcing read'
-
-!Time interpolation for initial conditions using TOGA interpolation routine
-         write(*,*) 'AVT 1ere INTERPOLATION: day,day1 = ',daytime,day1   
-      CALL interp_case_time(day,day1,annee_ref                                                              &
-!    &         ,year_ini_cas,day_ju_ini_cas,nt_cas,pdt_cas,nlev_cas                                         &
-     &         ,nt_cas,nlev_cas                                                                             &
-     &         ,ts_cas,plev_cas,t_cas,q_cas,u_cas,v_cas                                                     &
-     &         ,ug_cas,vg_cas,vitw_cas,du_cas,hu_cas,vu_cas                                                 &
-     &         ,dv_cas,hv_cas,vv_cas,dt_cas,ht_cas,vt_cas,dtrad_cas                                         &
-     &         ,dq_cas,hq_cas,vq_cas,lat_cas,sens_cas,ustar_cas                                             &
-     &         ,uw_cas,vw_cas,q1_cas,q2_cas                                                                 &
-     &         ,ts_prof_cas,plev_prof_cas,t_prof_cas,q_prof_cas,u_prof_cas,v_prof_cas                       &
-     &         ,ug_prof_cas,vg_prof_cas,vitw_prof_cas,du_prof_cas,hu_prof_cas,vu_prof_cas                   &
-     &         ,dv_prof_cas,hv_prof_cas,vv_prof_cas,dt_prof_cas,ht_prof_cas,vt_prof_cas,dtrad_prof_cas      &
-     &         ,dq_prof_cas,hq_prof_cas,vq_prof_cas,lat_prof_cas,sens_prof_cas,ustar_prof_cas               &
-     &         ,uw_prof_cas,vw_prof_cas,q1_prof_cas,q2_prof_cas)
-
-! vertical interpolation using TOGA interpolation routine:
-!      write(*,*)'avant interp vert', t_prof
-      CALL interp_case_vertical(play,nlev_cas,plev_prof_cas            &
-     &         ,t_prof_cas,q_prof_cas,u_prof_cas,v_prof_cas,ug_prof_cas,vg_prof_cas,vitw_prof_cas    &
-     &         ,du_prof_cas,hu_prof_cas,vu_prof_cas,dv_prof_cas,hv_prof_cas,vv_prof_cas           &
-     &         ,dt_prof_cas,ht_prof_cas,vt_prof_cas,dtrad_prof_cas,dq_prof_cas,hq_prof_cas,vq_prof_cas           &
-     &         ,t_mod_cas,q_mod_cas,u_mod_cas,v_mod_cas,ug_mod_cas,vg_mod_cas,w_mod_cas           &
-     &         ,du_mod_cas,hu_mod_cas,vu_mod_cas,dv_mod_cas,hv_mod_cas,vv_mod_cas               &
-     &         ,dt_mod_cas,ht_mod_cas,vt_mod_cas,dtrad_mod_cas,dq_mod_cas,hq_mod_cas,vq_mod_cas,mxcalc)
-!       write(*,*) 'Profil initial forcing case interpole',t_mod
-
-! initial and boundary conditions :
-!      tsurf = ts_prof_cas
-      ts_cur = ts_prof_cas 
-      psurf=plev_prof_cas(1)
-      write(*,*) 'SST initiale: ',tsurf
-      do l = 1, llm
-       temp(l) = t_mod_cas(l)
-       q(l,1) = q_mod_cas(l)
-       q(l,2) = 0.0
-       u(l) = u_mod_cas(l)
-       v(l) = v_mod_cas(l)
-       omega(l) = w_mod_cas(l)
-       omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
-
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
-!on applique le forcage total au premier pas de temps
-!attention: signe different de toga
-       d_t_adv(l) = alpha*omega(l)/rcpd+(ht_mod_cas(l)+vt_mod_cas(l))
-       d_q_adv(l,1) = (hq_mod_cas(l)+vq_mod_cas(l))
-       d_q_adv(l,2) = 0.0
-       d_u_adv(l) = (hu_mod_cas(l)+vu_mod_cas(l))
-! correction bug d_u -> d_v (MM+MPL 20170310)
-       d_v_adv(l) = (hv_mod_cas(l)+vv_mod_cas(l))
-      enddo     
-
-! In case fluxes are imposed
-       IF (ok_flux_surf) THEN
-       fsens=sens_prof_cas
-       flat=lat_prof_cas
-       ENDIF
-       IF (ok_prescr_ust) THEN
-       ust=ustar_prof_cas
-       print *,'ust=',ust
-       ENDIF
-
-      endif !forcing_case
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!---------------------------------------------------------------------
-! Forcing from standard case :
-!---------------------------------------------------------------------
-
-      if (forcing_case2) then
-
-         write(*,*),'avant call read2_1D_cas'
-         call read2_1D_cas
-         write(*,*) 'Forcing read'
+         write(*,*),'avant call read_SCM'
+         call read_SCM_cas
+         write(*,*) 'Forcing read' 
+	 print*,'PS ps_cas',ps_cas
 
 !Time interpolation for initial conditions using interpolation routine
          write(*,*) 'AVT 1ere INTERPOLATION: day,day1 = ',daytime,day1   
-        CALL interp2_case_time(daytime,day1,annee_ref                                       &
+        CALL interp_case_time_std(daytime,day1,annee_ref                                       &
 !    &       ,year_ini_cas,day_ju_ini_cas,nt_cas,pdt_cas,nlev_cas                           &
      &       ,nt_cas,nlev_cas                                                               &
      &       ,ts_cas,ps_cas,plev_cas,t_cas,th_cas,thv_cas,thl_cas,qv_cas,ql_cas,qi_cas      &
-     &       ,u_cas,v_cas,ug_cas,vg_cas,vitw_cas,omega_cas,du_cas,hu_cas,vu_cas             &
+     &       ,u_cas,v_cas,ug_cas,vg_cas                                                     &
+     &       ,temp_nudg_cas,qv_nudg_cas,u_nudg_cas,v_nudg_cas                               &
+     &       ,vitw_cas,omega_cas,du_cas,hu_cas,vu_cas                                       &
      &       ,dv_cas,hv_cas,vv_cas,dt_cas,ht_cas,vt_cas,dtrad_cas                           &
      &       ,dq_cas,hq_cas,vq_cas,dth_cas,hth_cas,vth_cas,lat_cas,sens_cas,ustar_cas       &
      &       ,uw_cas,vw_cas,q1_cas,q2_cas,tke_cas                                           &
 !
-     &       ,ts_prof_cas,plev_prof_cas,t_prof_cas,theta_prof_cas,thv_prof_cas  &
+     &       ,ts_prof_cas,ps_prof_cas,plev_prof_cas,t_prof_cas,theta_prof_cas,thv_prof_cas  &
      &       ,thl_prof_cas,qv_prof_cas,ql_prof_cas,qi_prof_cas                              &
-     &       ,u_prof_cas,v_prof_cas,ug_prof_cas,vg_prof_cas,vitw_prof_cas,omega_prof_cas    &
+     &       ,u_prof_cas,v_prof_cas,ug_prof_cas,vg_prof_cas                                 &
+     &       ,temp_nudg_prof_cas,qv_nudg_prof_cas,u_nudg_prof_cas,v_nudg_prof_cas           &
+     &       ,vitw_prof_cas,omega_prof_cas                                                  &
      &       ,du_prof_cas,hu_prof_cas,vu_prof_cas                                           &
      &       ,dv_prof_cas,hv_prof_cas,vv_prof_cas,dt_prof_cas,ht_prof_cas,vt_prof_cas       &
@@ -947,8 +49,11 @@
 ! vertical interpolation using interpolation routine:
 !      write(*,*)'avant interp vert', t_prof
-      CALL interp2_case_vertical(play,nlev_cas,plev_prof_cas                                              &
+      CALL interp2_case_vertical_std(play,nlev_cas,plev_prof_cas                                              &
      &         ,t_prof_cas,theta_prof_cas,thv_prof_cas,thl_prof_cas                                          &
      &         ,qv_prof_cas,ql_prof_cas,qi_prof_cas,u_prof_cas,v_prof_cas                                 &
-     &         ,ug_prof_cas,vg_prof_cas,vitw_prof_cas,omega_prof_cas                                      &
+     &         ,ug_prof_cas,vg_prof_cas                                                                   &
+     &       ,temp_nudg_prof_cas,qv_nudg_prof_cas,u_nudg_prof_cas,v_nudg_prof_cas                         &
+
+     &         ,vitw_prof_cas,omega_prof_cas                                                              &
      &         ,du_prof_cas,hu_prof_cas,vu_prof_cas,dv_prof_cas,hv_prof_cas,vv_prof_cas                   &
      &         ,dt_prof_cas,ht_prof_cas,vt_prof_cas,dtrad_prof_cas,dq_prof_cas,hq_prof_cas,vq_prof_cas    &
@@ -956,16 +61,16 @@
 !
      &         ,t_mod_cas,theta_mod_cas,thv_mod_cas,thl_mod_cas,qv_mod_cas,ql_mod_cas,qi_mod_cas          &
-     &         ,u_mod_cas,v_mod_cas,ug_mod_cas,vg_mod_cas,w_mod_cas,omega_mod_cas                         &
+     &         ,u_mod_cas,v_mod_cas,ug_mod_cas,vg_mod_cas                                                 &
+     &         ,temp_nudg_mod_cas,qv_nudg_mod_cas,u_nudg_mod_cas,v_nudg_mod_cas                           &
+     &         ,w_mod_cas,omega_mod_cas                                                                   &
      &         ,du_mod_cas,hu_mod_cas,vu_mod_cas,dv_mod_cas,hv_mod_cas,vv_mod_cas                         &
      &         ,dt_mod_cas,ht_mod_cas,vt_mod_cas,dtrad_mod_cas,dq_mod_cas,hq_mod_cas,vq_mod_cas           &
      &         ,dth_mod_cas,hth_mod_cas,vth_mod_cas,mxcalc)
 
-!       write(*,*) 'Profil initial forcing case interpole',t_mod
 
 ! initial and boundary conditions :
 !      tsurf = ts_prof_cas
+      psurf = ps_prof_cas
       ts_cur = ts_prof_cas 
-      psurf=plev_prof_cas(1)
-      write(*,*) 'SST initiale: ',tsurf
       do l = 1, llm
        temp(l) = t_mod_cas(l)
@@ -980,17 +85,17 @@
        omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
 
-       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
-!on applique le forcage total au premier pas de temps
-!attention: signe different de toga
-       d_t_adv(l) = alpha*omega(l)/rcpd+(ht_mod_cas(l)+vt_mod_cas(l))
-       d_t_adv(l) = alpha*omega(l)/rcpd+(ht_mod_cas(l)+vt_mod_cas(l))
-!      d_q_adv(l,1) = (hq_mod_cas(l)+vq_mod_cas(l))
-       d_q_adv(l,1) = dq_mod_cas(l)
+
+! On effectue la somme du forcage total et de la decomposition
+! horizontal/vertical en supposant que soit l'un soit l'autre
+! sont remplis mais jamais les deux
+
+       d_t_adv(l) = dt_mod_cas(l)+ht_mod_cas(l)+vt_mod_cas(l)
+       d_q_adv(l,1) = dq_mod_cas(l)+hq_mod_cas(l)+vq_mod_cas(l)
        d_q_adv(l,2) = 0.0
-!      d_u_adv(l) = (hu_mod_cas(l)+vu_mod_cas(l))
-       d_u_adv(l) = du_mod_cas(l)
-!      d_v_adv(l) = (hv_mod_cas(l)+vv_mod_cas(l))
-! correction bug d_u -> d_v (MM+MPL 20170310)
-       d_v_adv(l) = dv_mod_cas(l)
+       d_u_adv(l) = du_mod_cas(l)+hu_mod_cas(l)+vu_mod_cas(l)
+       d_v_adv(l) = dv_mod_cas(l)+hv_mod_cas(l)+vv_mod_cas(l)
+
+!print*,'d_t_adv ',d_t_adv(1:20)*86400
+
       enddo     
 
@@ -1006,5 +111,3 @@
        ENDIF
 
-      endif !forcing_case2
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-
+      endif !forcing_SCM
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/compar1d.h
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/compar1d.h	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/compar1d.h	(revision 3605)
@@ -42,5 +42,6 @@
       integer :: tadv, tadvv, tadvh, qadv, qadvv, qadvh, thadv, thadvv, thadvh, trad
       integer :: forc_omega, forc_u, forc_v, forc_w, forc_geo, forc_ustar
-      real    :: nudging_u, nudging_v, nudging_w, nudging_t, nudging_q
+      real    :: nudging_u, nudging_v, nudging_w, nudging_t, nudging_qv
+      real    :: p_nudging_u, p_nudging_v, p_nudging_w, p_nudging_t, p_nudging_qv
       common/com_par1d/                                                 &
      & nat_surf,tsurf,rugos,rugosh,                                     &
@@ -52,6 +53,7 @@
      & restart,ok_old_disvert,                                          &
      & tadv, tadvv, tadvh, qadv, qadvv, qadvh, thadv, thadvv, thadvh,   &
-     & trad, forc_omega, forc_w, forc_geo, forc_ustar,                  &
-     & nudging_u, nudging_v, nudging_t, nudging_q
+     & trad, forc_omega, forc_u, forc_v, forc_w, forc_geo, forc_ustar,  &
+     & nudging_u, nudging_v, nudging_t, nudging_qv, nudging_w,          &
+     & p_nudging_u, p_nudging_v, p_nudging_t, p_nudging_qv, p_nudging_w
 
 !$OMP THREADPRIVATE(/com_par1d/)
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/lmdz1d.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/lmdz1d.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/lmdz1d.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 !#ifdef CPP_1D
 !#include "../dyn3d/mod_const_mpi.F90"
@@ -6,1271 +9,20 @@
 
 
-      PROGRAM lmdz1d
+   PROGRAM lmdz1d
 
-   USE ioipsl, only: ju2ymds, ymds2ju, ioconf_calendar
-   USE phys_state_var_mod, ONLY : phys_state_var_init, phys_state_var_end, &
-       clwcon, detr_therm, &
-       qsol, fevap, z0m, z0h, agesno, &
-       du_gwd_rando, du_gwd_front, entr_therm, f0, fm_therm, &
-       falb_dir, falb_dif, &
-       ftsol, pbl_tke, pctsrf, radsol, rain_fall, snow_fall, ratqs, &
-       rnebcon, rugoro, sig1, w01, solaire_etat0, sollw, sollwdown, &
-       solsw, t_ancien, q_ancien, u_ancien, v_ancien, wake_cstar, &
-       wake_delta_pbl_TKE, delta_tsurf, wake_fip, wake_pe, &
-       wake_deltaq, wake_deltat, wake_s, wake_dens, &
-       zgam, zmax0, zmea, zpic, zsig, &
-       zstd, zthe, zval, ale_bl, ale_bl_trig, alp_bl, ql_ancien, qs_ancien, &
-       prlw_ancien, prsw_ancien, prw_ancien
-  
-   USE dimphy
-   USE surface_data, only : type_ocean,ok_veget
-   USE pbl_surface_mod, only : ftsoil, pbl_surface_init, &
-                                 pbl_surface_final
-   USE fonte_neige_mod, only : fonte_neige_init, fonte_neige_final 
+   USE ioipsl, only: getin
 
-   USE infotrac ! new
-   USE control_mod
-   USE indice_sol_mod
-   USE phyaqua_mod
-!  USE mod_1D_cases_read
-   USE mod_1D_cases_read2
-   USE mod_1D_amma_read
-   USE print_control_mod, ONLY: lunout, prt_level
-   USE iniphysiq_mod, ONLY: iniphysiq
-   USE mod_const_mpi, ONLY: comm_lmdz
-   USE physiq_mod, ONLY: physiq
-   USE comvert_mod, ONLY: presnivs, ap, bp, dpres,nivsig, nivsigs, pa, &
-                          preff, aps, bps, pseudoalt, scaleheight
-   USE temps_mod, ONLY: annee_ref, calend, day_end, day_ini, day_ref, &
-                        itau_dyn, itau_phy, start_time
+   INTEGER forcing_type
 
-      implicit none
-#include "dimensions.h"
-#include "YOMCST.h"
-!!#include "control.h"
-#include "clesphys.h"
-#include "dimsoil.h"
-!#include "indicesol.h"
+   CALL getin('forcing_type',forcing_type)
 
-#include "compar1d.h"
-#include "flux_arp.h"
-#include "date_cas.h"
-#include "tsoilnudge.h"
-#include "fcg_gcssold.h"
-!!!#include "fbforcing.h"
-#include "compbl.h"
+   IF (forcing_type==1000) THEN
+           CALL scm
+   ELSE
+           CALL old_lmdz1d
+   ENDIF
 
-!=====================================================================
-! DECLARATIONS
-!=====================================================================
+   END
 
-!---------------------------------------------------------------------
-!  Externals
-!---------------------------------------------------------------------
-      external fq_sat
-      real fq_sat
-
-!---------------------------------------------------------------------
-!  Arguments d' initialisations de la physique (USER DEFINE)
-!---------------------------------------------------------------------
-
-      integer, parameter :: ngrid=1
-      real :: zcufi    = 1.
-      real :: zcvfi    = 1.
-
-!-      real :: nat_surf
-!-      logical :: ok_flux_surf
-!-      real :: fsens
-!-      real :: flat
-!-      real :: tsurf
-!-      real :: rugos
-!-      real :: qsol(1:2)
-!-      real :: qsurf
-!-      real :: psurf
-!-      real :: zsurf
-!-      real :: albedo
-!-
-!-      real :: time     = 0.
-!-      real :: time_ini
-!-      real :: xlat 
-!-      real :: xlon 
-!-      real :: wtsurf 
-!-      real :: wqsurf 
-!-      real :: restart_runoff 
-!-      real :: xagesno 
-!-      real :: qsolinp 
-!-      real :: zpicinp 
-!-
-      real :: fnday 
-      real :: day, daytime 
-      real :: day1
-      real :: heure
-      integer :: jour
-      integer :: mois
-      integer :: an
- 
-!---------------------------------------------------------------------
-!  Declarations related to forcing and initial profiles 
-!---------------------------------------------------------------------
-
-        integer :: kmax = llm
-        integer llm700,nq1,nq2
-        INTEGER, PARAMETER :: nlev_max=1000, nqmx=1000
-        real timestep, frac
-        real height(nlev_max),tttprof(nlev_max),qtprof(nlev_max)
-        real  uprof(nlev_max),vprof(nlev_max),e12prof(nlev_max)
-        real  ugprof(nlev_max),vgprof(nlev_max),wfls(nlev_max)
-        real  dqtdxls(nlev_max),dqtdyls(nlev_max)
-        real  dqtdtls(nlev_max),thlpcar(nlev_max)
-        real  qprof(nlev_max,nqmx)
-
-!        integer :: forcing_type
-        logical :: forcing_les     = .false.
-        logical :: forcing_armcu   = .false.
-        logical :: forcing_rico    = .false.
-        logical :: forcing_radconv = .false.
-        logical :: forcing_toga    = .false.
-        logical :: forcing_twpice  = .false.
-        logical :: forcing_amma    = .false.
-        logical :: forcing_dice    = .false.
-        logical :: forcing_gabls4  = .false.
-
-        logical :: forcing_GCM2SCM = .false.
-        logical :: forcing_GCSSold = .false.
-        logical :: forcing_sandu   = .false.
-        logical :: forcing_astex   = .false.
-        logical :: forcing_fire    = .false.
-        logical :: forcing_case    = .false.
-        logical :: forcing_case2   = .false.
-        integer :: type_ts_forcing ! 0 = SST constant; 1 = SST read from a file
-!                                                            (cf read_tsurf1d.F)
-
-!vertical advection computation
-!       real d_t_z(llm), d_q_z(llm)
-!       real d_t_dyn_z(llm), dq_dyn_z(llm)
-!       real zz(llm)
-!       real zfact
-
-!flag forcings
-        logical :: nudge_wind=.true.
-        logical :: nudge_thermo=.false.
-        logical :: cptadvw=.true.
-!=====================================================================
-! DECLARATIONS FOR EACH CASE
-!=====================================================================
-!
-#include "1D_decl_cases.h"
-!
-!---------------------------------------------------------------------
-!  Declarations related to nudging
-!---------------------------------------------------------------------
-     integer :: nudge_max
-     parameter (nudge_max=9)
-     integer :: inudge_RHT=1
-     integer :: inudge_UV=2
-     logical :: nudge(nudge_max)
-     real :: t_targ(llm)
-     real :: rh_targ(llm)
-     real :: u_targ(llm)
-     real :: v_targ(llm)
-!
-!---------------------------------------------------------------------
-!  Declarations related to vertical discretization:
-!---------------------------------------------------------------------
-      real :: pzero=1.e5
-      real :: play (llm),zlay (llm),sig_s(llm),plev(llm+1)
-      real :: playd(llm),zlayd(llm),ap_amma(llm+1),bp_amma(llm+1)
-
-!---------------------------------------------------------------------
-!  Declarations related to variables
-!---------------------------------------------------------------------
-
-      real :: phi(llm)
-      real :: teta(llm),tetal(llm),temp(llm),u(llm),v(llm),w(llm)
-      REAL rot(1, llm) ! relative vorticity, in s-1
-      real :: rlat_rad(1),rlon_rad(1)
-      real :: omega(llm+1),omega2(llm),rho(llm+1)
-      real :: ug(llm),vg(llm),fcoriolis
-      real :: sfdt, cfdt
-      real :: du_phys(llm),dv_phys(llm),dt_phys(llm)
-      real :: dt_dyn(llm)
-      real :: dt_cooling(llm),d_t_adv(llm),d_t_nudge(llm)
-      real :: d_u_nudge(llm),d_v_nudge(llm)
-      real :: du_adv(llm),dv_adv(llm)
-      real :: du_age(llm),dv_age(llm)
-      real :: alpha
-      real :: ttt
-
-      REAL, ALLOCATABLE, DIMENSION(:,:):: q
-      REAL, ALLOCATABLE, DIMENSION(:,:):: dq
-      REAL, ALLOCATABLE, DIMENSION(:,:):: dq_dyn
-      REAL, ALLOCATABLE, DIMENSION(:,:):: d_q_adv
-      REAL, ALLOCATABLE, DIMENSION(:,:):: d_q_nudge
-!      REAL, ALLOCATABLE, DIMENSION(:):: d_th_adv
-
-!---------------------------------------------------------------------
-!  Initialization of surface variables
-!---------------------------------------------------------------------
-      real :: run_off_lic_0(1)
-      real :: fder(1),snsrf(1,nbsrf),qsurfsrf(1,nbsrf)
-      real :: tsoil(1,nsoilmx,nbsrf)
-!     real :: agesno(1,nbsrf)
-
-!---------------------------------------------------------------------
-!  Call to phyredem
-!---------------------------------------------------------------------
-      logical :: ok_writedem =.true.
-      real :: sollw_in = 0.
-      real :: solsw_in = 0.
-      
-!---------------------------------------------------------------------
-!  Call to physiq
-!---------------------------------------------------------------------
-      logical :: firstcall=.true.
-      logical :: lastcall=.false.
-      real :: phis(1)    = 0.0
-      real :: dpsrf(1)
-
-!---------------------------------------------------------------------
-!  Initializations of boundary conditions 
-!---------------------------------------------------------------------
-      integer, parameter :: yd = 360
-      real :: phy_nat (yd) = 0.0 ! 0=ocean libre,1=land,2=glacier,3=banquise
-      real :: phy_alb (yd)  ! Albedo land only (old value condsurf_jyg=0.3)
-      real :: phy_sst (yd)  ! SST (will not be used; cf read_tsurf1d.F)
-      real :: phy_bil (yd) = 1.0 ! Ne sert que pour les slab_ocean
-      real :: phy_rug (yd) ! Longueur rugosite utilisee sur land only
-      real :: phy_ice (yd) = 0.0 ! Fraction de glace
-      real :: phy_fter(yd) = 0.0 ! Fraction de terre
-      real :: phy_foce(yd) = 0.0 ! Fraction de ocean
-      real :: phy_fsic(yd) = 0.0 ! Fraction de glace
-      real :: phy_flic(yd) = 0.0 ! Fraction de glace
-
-!---------------------------------------------------------------------
-!  Fichiers et d'autres variables
-!---------------------------------------------------------------------
-      integer :: k,l,i,it=1,mxcalc
-      integer :: nsrf
-      integer jcode
-      INTEGER read_climoz 
-!
-      integer :: it_end ! iteration number of the last call
-!Al1
-      integer ecrit_slab_oc !1=ecrit,-1=lit,0=no file
-      data ecrit_slab_oc/-1/
-!
-!     if flag_inhib_forcing = 0, tendencies of forcing are added
-!                           <> 0, tendencies of forcing are not added
-      INTEGER :: flag_inhib_forcing = 0
-
-!=====================================================================
-! INITIALIZATIONS 
-!=====================================================================
-      du_phys(:)=0.
-      dv_phys(:)=0.
-      dt_phys(:)=0.
-      dt_dyn(:)=0.
-      dt_cooling(:)=0.
-      d_t_adv(:)=0.
-      d_t_nudge(:)=0.
-      d_u_nudge(:)=0.
-      d_v_nudge(:)=0.
-      du_adv(:)=0.
-      dv_adv(:)=0.
-      du_age(:)=0.
-      dv_age(:)=0.
-      
-! Initialization of Common turb_forcing
-       dtime_frcg = 0.
-       Turb_fcg_gcssold=.false.
-       hthturb_gcssold = 0.
-       hqturb_gcssold = 0.
-
-
-
-
-!---------------------------------------------------------------------
-! OPTIONS OF THE 1D SIMULATION (lmdz1d.def => unicol.def)
-!---------------------------------------------------------------------
-!Al1
-        call conf_unicol
-!Al1 moves this gcssold var from common fcg_gcssold to 
-        Turb_fcg_gcssold = xTurb_fcg_gcssold
-! --------------------------------------------------------------------
-        close(1)
-!Al1
-        write(*,*) 'lmdz1d.def lu => unicol.def'
-
-! forcing_type defines the way the SCM is forced:
-!forcing_type = 0 ==> forcing_les = .true.
-!             initial profiles from file prof.inp.001
-!             no forcing by LS convergence ; 
-!             surface temperature imposed ;
-!             radiative cooling may be imposed (iflag_radia=0 in physiq.def)
-!forcing_type = 1 ==> forcing_radconv = .true.
-!             idem forcing_type = 0, but the imposed radiative cooling 
-!             is set to 0 (hence, if iflag_radia=0 in physiq.def, 
-!             then there is no radiative cooling at all)
-!forcing_type = 2 ==> forcing_toga = .true.
-!             initial profiles from TOGA-COARE IFA files 
-!             LS convergence and SST imposed from TOGA-COARE IFA files 
-!forcing_type = 3 ==> forcing_GCM2SCM = .true.
-!             initial profiles from the GCM output
-!             LS convergence imposed from the GCM output
-!forcing_type = 4 ==> forcing_twpice = .true.
-!             initial profiles from TWP-ICE cdf file 
-!             LS convergence, omega and SST imposed from TWP-ICE files 
-!forcing_type = 5 ==> forcing_rico = .true.
-!             initial profiles from RICO files 
-!             LS convergence imposed from RICO files 
-!forcing_type = 6 ==> forcing_amma = .true.
-!             initial profiles from AMMA nc file 
-!             LS convergence, omega and surface fluxes imposed from AMMA file  
-!forcing_type = 7 ==> forcing_dice = .true.
-!             initial profiles and large scale forcings in dice_driver.nc
-!             Different stages: soil model alone, atm. model alone
-!             then both models coupled
-!forcing_type = 8 ==> forcing_gabls4 = .true.
-!             initial profiles and large scale forcings in gabls4_driver.nc
-!forcing_type >= 100 ==> forcing_case = .true.
-!             initial profiles and large scale forcings in cas.nc
-!             LS convergence, omega and SST imposed from CINDY-DYNAMO files 
-!             101=cindynamo
-!             102=bomex
-!forcing_type >= 100 ==> forcing_case2 = .true.
-!             temporary flag while all the 1D cases are not whith the same cas.nc forcing file
-!             103=arm_cu2 ie arm_cu with new forcing format
-!             104=rico2 ie rico with new forcing format
-!forcing_type = 40 ==> forcing_GCSSold = .true.
-!             initial profile from GCSS file
-!             LS convergence imposed from GCSS file
-!forcing_type = 50 ==> forcing_fire = .true.
-!             forcing from fire.nc
-!forcing_type = 59 ==> forcing_sandu = .true.
-!             initial profiles from sanduref file: see prof.inp.001
-!             SST varying with time and divergence constante: see ifa_sanduref.txt file
-!             Radiation has to be computed interactively
-!forcing_type = 60 ==> forcing_astex = .true.
-!             initial profiles from file: see prof.inp.001 
-!             SST,divergence,ug,vg,ufa,vfa varying with time : see ifa_astex.txt file
-!             Radiation has to be computed interactively
-!forcing_type = 61 ==> forcing_armcu = .true.
-!             initial profiles from file: see prof.inp.001 
-!             sensible and latent heat flux imposed: see ifa_arm_cu_1.txt
-!             large scale advective forcing & radiative tendencies applied below 1000m: see ifa_arm_cu_2.txt
-!             use geostrophic wind ug=10m/s vg=0m/s. Duration of the case 53100s 
-!             Radiation to be switched off
-!
-      if (forcing_type <=0) THEN
-       forcing_les = .true.
-      elseif (forcing_type .eq.1) THEN
-       forcing_radconv = .true.
-      elseif (forcing_type .eq.2) THEN
-       forcing_toga    = .true.
-      elseif (forcing_type .eq.3) THEN
-       forcing_GCM2SCM = .true.
-      elseif (forcing_type .eq.4) THEN
-       forcing_twpice = .true.
-      elseif (forcing_type .eq.5) THEN
-       forcing_rico = .true.
-      elseif (forcing_type .eq.6) THEN
-       forcing_amma = .true.
-      elseif (forcing_type .eq.7) THEN
-       forcing_dice = .true.
-      elseif (forcing_type .eq.8) THEN
-       forcing_gabls4 = .true.
-      elseif (forcing_type .eq.101) THEN ! Cindynamo starts 1-10-2011 0h
-       forcing_case = .true.
-       year_ini_cas=2011
-       mth_ini_cas=10
-       day_deb=1
-       heure_ini_cas=0.
-       pdt_cas=3*3600.         ! forcing frequency
-      elseif (forcing_type .eq.102) THEN ! Bomex starts 24-6-1969 0h
-       forcing_case = .true.
-       year_ini_cas=1969
-       mth_ini_cas=6
-       day_deb=24
-       heure_ini_cas=0.
-       pdt_cas=1800.         ! forcing frequency
-      elseif (forcing_type .eq.103) THEN ! Arm_cu starts 21-6-1997 11h30
-       forcing_case2 = .true.
-       year_ini_cas=1997
-       mth_ini_cas=6
-       day_deb=21
-       heure_ini_cas=11.5
-       pdt_cas=1800.         ! forcing frequency
-      elseif (forcing_type .eq.104) THEN ! rico starts 16-12-2004 0h
-       forcing_case2 = .true.
-       year_ini_cas=2004
-       mth_ini_cas=12
-       day_deb=16
-       heure_ini_cas=0.
-       pdt_cas=1800.         ! forcing frequency
-      elseif (forcing_type .eq.105) THEN ! bomex starts 16-12-2004 0h
-       forcing_case2 = .true.
-       year_ini_cas=1969
-       mth_ini_cas=6
-       day_deb=24
-       heure_ini_cas=0.
-       pdt_cas=1800.         ! forcing frequency
-      elseif (forcing_type .eq.106) THEN ! ayotte_24SC starts 6-11-1992 0h
-       forcing_case2 = .true.
-       year_ini_cas=1992
-       mth_ini_cas=11
-       day_deb=6
-       heure_ini_cas=10.
-       pdt_cas=86400.        ! forcing frequency
-      elseif (forcing_type .eq.40) THEN
-       forcing_GCSSold = .true.
-      elseif (forcing_type .eq.50) THEN
-       forcing_fire = .true.
-      elseif (forcing_type .eq.59) THEN
-       forcing_sandu   = .true.
-      elseif (forcing_type .eq.60) THEN
-       forcing_astex   = .true.
-      elseif (forcing_type .eq.61) THEN
-       forcing_armcu = .true.
-       IF(llm.NE.19.AND.llm.NE.40) stop 'Erreur nombre de niveaux !!'
-      else
-       write (*,*) 'ERROR : unknown forcing_type ', forcing_type
-       stop 'Forcing_type should be 0,1,2,3,4,5,6 or 40,59,60,61'
-      ENDIF
-      print*,"forcing type=",forcing_type
-
-! if type_ts_forcing=0, the surface temp of 1D simulation is constant in time
-! (specified by tsurf in lmdz1d.def); if type_ts_forcing=1, the surface temperature
-! varies in time according to a forcing (e.g. forcing_toga) and is passed to read_tsurf1d.F
-! through the common sst_forcing.
-
-        type_ts_forcing = 0
-        if (forcing_toga.or.forcing_sandu.or.forcing_astex .or. forcing_dice)                 &
-     &    type_ts_forcing = 1
-!
-! Initialization of the logical switch for nudging
-     jcode = iflag_nudge
-     do i = 1,nudge_max
-       nudge(i) = mod(jcode,10) .ge. 1
-       jcode = jcode/10
-     enddo
-!---------------------------------------------------------------------
-!  Definition of the run
-!---------------------------------------------------------------------
-
-      call conf_gcm( 99, .TRUE. )
-!-----------------------------------------------------------------------
-!   Choix du calendrier
-!   -------------------
-
-!      calend = 'earth_365d'
-      if (calend == 'earth_360d') then
-        call ioconf_calendar('360d')
-        write(*,*)'CALENDRIER CHOISI: Terrestre a 360 jours/an'
-      else if (calend == 'earth_365d') then
-        call ioconf_calendar('noleap')
-        write(*,*)'CALENDRIER CHOISI: Terrestre a 365 jours/an'
-      else if (calend == 'earth_366d') then
-        call ioconf_calendar('all_leap')
-        write(*,*)'CALENDRIER CHOISI: Terrestre bissextile'
-      else if (calend == 'gregorian') then
-        call ioconf_calendar('gregorian') ! not to be used by normal users
-        write(*,*)'CALENDRIER CHOISI: Gregorien'
-      else
-        write (*,*) 'ERROR : unknown calendar ', calend
-        stop 'calend should be 360d,earth_365d,earth_366d,gregorian'
-      endif
-!-----------------------------------------------------------------------
-!
-!c Date :
-!      La date est supposee donnee sous la forme [annee, numero du jour dans 
-!      l annee] ; l heure est donnee dans time_ini, lu dans lmdz1d.def.
-!      On appelle ymds2ju pour convertir [annee, jour] en [jour Julien].
-!      Le numero du jour est dans "day". L heure est traitee separement.
-!      La date complete est dans "daytime" (l'unite est le jour).
-      if (nday>0) then
-         fnday=nday
-      else
-         fnday=-nday/float(day_step)
-      endif
-      print *,'fnday=',fnday
-!     start_time doit etre en FRACTION DE JOUR
-      start_time=time_ini/24.
-
-! Special case for arm_cu which lasts less than one day : 53100s !! (MPL 20111026)
-      IF(forcing_type .EQ. 61) fnday=53100./86400.
-      IF(forcing_type .EQ. 103) fnday=53100./86400.
-! Special case for amma which lasts less than one day : 64800s !! (MPL 20120216)
-      IF(forcing_type .EQ. 6) fnday=64800./86400.
-!     IF(forcing_type .EQ. 6) fnday=50400./86400.
- IF(forcing_type .EQ. 8 ) fnday=129600./86400. 
-      annee_ref = anneeref
-      mois = 1
-      day_ref = dayref
-      heure = 0.
-      itau_dyn = 0
-      itau_phy = 0
-      call ymds2ju(annee_ref,mois,day_ref,heure,day)
-      day_ini = int(day)
-      day_end = day_ini + int(fnday)
-
-      IF (forcing_type .eq.2) THEN
-! Convert the initial date of Toga-Coare to Julian day
-      call ymds2ju                                                          &
-     & (year_ini_toga,mth_ini_toga,day_ini_toga,heure,day_ju_ini_toga)
-
-      ELSEIF (forcing_type .eq.4) THEN
-! Convert the initial date of TWPICE to Julian day
-      call ymds2ju                                                          &
-     & (year_ini_twpi,mth_ini_twpi,day_ini_twpi,heure_ini_twpi              &
-     & ,day_ju_ini_twpi)
-      ELSEIF (forcing_type .eq.6) THEN
-! Convert the initial date of AMMA to Julian day
-      call ymds2ju                                                          &
-     & (year_ini_amma,mth_ini_amma,day_ini_amma,heure_ini_amma              &
-     & ,day_ju_ini_amma)
-      ELSEIF (forcing_type .eq.7) THEN
-! Convert the initial date of DICE to Julian day
-      call ymds2ju                                                         &
-     & (year_ini_dice,mth_ini_dice,day_ini_dice,heure_ini_dice             & 
-     & ,day_ju_ini_dice)
- ELSEIF (forcing_type .eq.8 ) THEN
-! Convert the initial date of GABLS4 to Julian day
-      call ymds2ju                                                         &
-     & (year_ini_gabls4,mth_ini_gabls4,day_ini_gabls4,heure_ini_gabls4     & 
-     & ,day_ju_ini_gabls4)
-      ELSEIF (forcing_type .gt.100) THEN
-! Convert the initial date to Julian day
-      day_ini_cas=day_deb
-      print*,'time case',year_ini_cas,mth_ini_cas,day_ini_cas
-      call ymds2ju                                                         &
-     & (year_ini_cas,mth_ini_cas,day_ini_cas,heure_ini_cas*3600            &
-     & ,day_ju_ini_cas)
-      print*,'time case 2',day_ini_cas,day_ju_ini_cas
-      ELSEIF (forcing_type .eq.59) THEN
-! Convert the initial date of Sandu case to Julian day
-      call ymds2ju                                                          &
-     &   (year_ini_sandu,mth_ini_sandu,day_ini_sandu,                       &
-     &    time_ini*3600.,day_ju_ini_sandu)
-
-      ELSEIF (forcing_type .eq.60) THEN
-! Convert the initial date of Astex case to Julian day
-      call ymds2ju                                                          &
-     &   (year_ini_astex,mth_ini_astex,day_ini_astex,                        &
-     &    time_ini*3600.,day_ju_ini_astex)
-
-      ELSEIF (forcing_type .eq.61) THEN
-! Convert the initial date of Arm_cu case to Julian day
-      call ymds2ju                                                          &
-     & (year_ini_armcu,mth_ini_armcu,day_ini_armcu,heure_ini_armcu          &
-     & ,day_ju_ini_armcu)
-      ENDIF
-
-      IF (forcing_type .gt.100) THEN
-      daytime = day + heure_ini_cas/24. ! 1st day and initial time of the simulation 
-      ELSE
-      daytime = day + time_ini/24. ! 1st day and initial time of the simulation 
-      ENDIF
-! Print out the actual date of the beginning of the simulation :
-      call ju2ymds(daytime,year_print, month_print,day_print,sec_print)
-      print *,' Time of beginning : ',                                      &
-     &        year_print, month_print, day_print, sec_print
-
-!---------------------------------------------------------------------
-! Initialization of dimensions, geometry and initial state
-!---------------------------------------------------------------------
-!      call init_phys_lmdz(1,1,llm,1,(/1/)) ! job now done via iniphysiq
-!     but we still need to initialize dimphy module (klon,klev,etc.)  here.
-      call init_dimphy(1,llm)
-      call suphel
-      call infotrac_init 
-
-      if (nqtot>nqmx) STOP 'Augmenter nqmx dans lmdz1d.F'
-      allocate(q(llm,nqtot)) ; q(:,:)=0.
-      allocate(dq(llm,nqtot)) 
-      allocate(dq_dyn(llm,nqtot)) 
-      allocate(d_q_adv(llm,nqtot)) 
-      allocate(d_q_nudge(llm,nqtot)) 
-!      allocate(d_th_adv(llm)) 
-
-      q(:,:) = 0.
-      dq(:,:) = 0.
-      dq_dyn(:,:) = 0.
-      d_q_adv(:,:) = 0.
-      d_q_nudge(:,:) = 0.
-
-!
-!   No ozone climatology need be read in this pre-initialization
-!          (phys_state_var_init is called again in physiq)
-      read_climoz = 0
-!
-      call phys_state_var_init(read_climoz)
-
-      if (ngrid.ne.klon) then
-         print*,'stop in inifis'
-         print*,'Probleme de dimensions :'
-         print*,'ngrid = ',ngrid
-         print*,'klon  = ',klon
-         stop
-      endif
-!!!=====================================================================
-!!! Feedback forcing values for Gateaux differentiation (al1)
-!!!=====================================================================
-!!! Surface Planck forcing bracketing call radiation
-!!      surf_Planck = 0.
-!!      surf_Conv   = 0.
-!!      write(*,*) 'Gateaux-dif Planck,Conv:',surf_Planck,surf_Conv
-!!! a mettre dans le lmdz1d.def ou autre
-!!
-!!
-      qsol = qsolinp
-      qsurf = fq_sat(tsurf,psurf/100.)
-      day1= day_ini
-      time=daytime-day
-      ts_toga(1)=tsurf ! needed by read_tsurf1d.F
-      rho(1)=psurf/(rd*tsurf*(1.+(rv/rd-1.)*qsurf)) 
-
-!
-!! mpl et jyg le 22/08/2012 : 
-!!  pour que les cas a flux de surface imposes marchent
-      IF(.NOT.ok_flux_surf.or.max(abs(wtsurf),abs(wqsurf))>0.) THEN
-       fsens=-wtsurf*rcpd*rho(1)
-       flat=-wqsurf*rlvtt*rho(1)
-       print *,'Flux: ok_flux wtsurf wqsurf',ok_flux_surf,wtsurf,wqsurf
-      ENDIF
-      print*,'Flux sol ',fsens,flat
-!!      ok_flux_surf=.false.
-!!      fsens=-wtsurf*rcpd*rho(1)
-!!      flat=-wqsurf*rlvtt*rho(1)
-!!!!
-
-! Vertical discretization and pressure levels at half and mid levels:
-
-      pa   = 5e4
-!!      preff= 1.01325e5
-      preff = psurf
-      IF (ok_old_disvert) THEN
-        call disvert0(pa,preff,ap,bp,dpres,presnivs,nivsigs,nivsig)
-        print *,'On utilise disvert0'
-        aps(1:llm)=0.5*(ap(1:llm)+ap(2:llm+1))
-        bps(1:llm)=0.5*(bp(1:llm)+bp(2:llm+1))
-        scaleheight=8.
-        pseudoalt(1:llm)=-scaleheight*log(presnivs(1:llm)/preff)
-      ELSE
-        call disvert()
-        print *,'On utilise disvert'
-!       Nouvelle version disvert permettant d imposer ap,bp (modif L.Guez) MPL 18092012
-!       Dans ce cas, on lit ap,bp dans le fichier hybrid.txt
-      ENDIF
-
-      sig_s=presnivs/preff
-      plev =ap+bp*psurf
-      play = 0.5*(plev(1:llm)+plev(2:llm+1))
-      zlay=-rd*300.*log(play/psurf)/rg ! moved after reading profiles
-
-      IF (forcing_type .eq. 59) THEN
-! pour forcing_sandu, on cherche l'indice le plus proche de 700hpa#3000m
-      write(*,*) '***********************'
-      do l = 1, llm
-       write(*,*) 'l,play(l),presnivs(l): ',l,play(l),presnivs(l)
-       if (trouve_700 .and. play(l).le.70000) then
-         llm700=l
-         print *,'llm700,play=',llm700,play(l)/100.
-         trouve_700= .false.
-       endif
-      enddo
-      write(*,*) '***********************'
-      ENDIF
-
-!
-!=====================================================================
-! EVENTUALLY, READ FORCING DATA :
-!=====================================================================
-
-#include "1D_read_forc_cases.h"
-
-      if (forcing_GCM2SCM) then
-        write (*,*) 'forcing_GCM2SCM not yet implemented'
-        stop 'in initialization'
-      endif ! forcing_GCM2SCM
-
-      print*,'mxcalc=',mxcalc
-!     print*,'zlay=',zlay(mxcalc)
-      print*,'play=',play(mxcalc)
-
-!Al1 pour SST forced, appell?? depuis ocean_forced_noice
-      ts_cur = tsurf ! SST used in read_tsurf1d
-!=====================================================================
-! Initialisation de la physique : 
-!=====================================================================
-
-!  Rq: conf_phys.F90 lit tous les flags de physiq.def; conf_phys appele depuis physiq.F
-!
-! day_step, iphysiq lus dans gcm.def ci-dessus
-! timestep: calcule ci-dessous from rday et day_step
-! ngrid=1
-! llm: defini dans .../modipsl/modeles/LMDZ4/libf/grid/dimension
-! rday: defini dans suphel.F (86400.)
-! day_ini: lu dans run.def (dayref)
-! rlat_rad,rlon-rad: transformes en radian de rlat,rlon lus dans lmdz1d.def (en degres)
-! airefi,zcufi,zcvfi initialises au debut de ce programme
-! rday,ra,rg,rd,rcpd declares dans YOMCST.h et calcules dans suphel.F
-      day_step = float(nsplit_phys)*day_step/float(iphysiq)
-      write (*,*) 'Time step divided by nsplit_phys (=',nsplit_phys,')'
-      timestep =rday/day_step
-      dtime_frcg = timestep
-!
-      zcufi=airefi
-      zcvfi=airefi
-!
-      rlat_rad(1)=xlat*rpi/180.
-      rlon_rad(1)=xlon*rpi/180.
-
-     ! Ehouarn: iniphysiq requires arrays related to (3D) dynamics grid,
-     ! e.g. for cell boundaries, which are meaningless in 1D; so pad these 
-     ! with '0.' when necessary
-      call iniphysiq(iim,jjm,llm, &
-           1,comm_lmdz, &
-           rday,day_ini,timestep,  &
-           (/rlat_rad(1),0./),(/0./), &
-           (/0.,0./),(/rlon_rad(1),0./),  &
-           (/ (/airefi,0./),(/0.,0./) /), &
-           (/zcufi,0.,0.,0./), &
-           (/zcvfi,0./), &
-           ra,rg,rd,rcpd,1)
-      print*,'apres iniphysiq'
-
-! 2 PARAMETRES QUI DEVRAIENT ETRE LUS DANS run.def MAIS NE LE SONT PAS ICI:
-      co2_ppm= 330.0
-      solaire=1370.0
-
-! Ecriture du startphy avant le premier appel a la physique.
-! On le met juste avant pour avoir acces a tous les champs
-
-      if (ok_writedem) then
-
-!--------------------------------------------------------------------------
-! pbl_surface_init (called here) and pbl_surface_final (called by phyredem)
-! need : qsol fder snow qsurf evap rugos agesno ftsoil
-!--------------------------------------------------------------------------
-
-        type_ocean = "force"
-        run_off_lic_0(1) = restart_runoff 
-        call fonte_neige_init(run_off_lic_0)
-
-        fder=0.
-        snsrf(1,:)=snowmass ! masse de neige des sous surface
-        qsurfsrf(1,:)=qsurf ! humidite de l'air des sous surface
-        fevap=0.
-        z0m(1,:)=rugos     ! couverture de neige des sous surface
-        z0h(1,:)=rugosh    ! couverture de neige des sous surface
-        agesno  = xagesno
-        tsoil(:,:,:)=tsurf
-!------ AMMA 2e run avec modele sol et rayonnement actif (MPL 23052012)
-!       tsoil(1,1,1)=299.18
-!       tsoil(1,2,1)=300.08
-!       tsoil(1,3,1)=301.88
-!       tsoil(1,4,1)=305.48
-!       tsoil(1,5,1)=308.00
-!       tsoil(1,6,1)=308.00
-!       tsoil(1,7,1)=308.00
-!       tsoil(1,8,1)=308.00
-!       tsoil(1,9,1)=308.00
-!       tsoil(1,10,1)=308.00
-!       tsoil(1,11,1)=308.00
-!-----------------------------------------------------------------------
-        call pbl_surface_init(fder, snsrf, qsurfsrf, tsoil)
-
-!------------------ prepare limit conditions for limit.nc -----------------
-!--   Ocean force
-
-        print*,'avant phyredem'
-        pctsrf(1,:)=0.
-          if (nat_surf.eq.0.) then
-          pctsrf(1,is_oce)=1.
-          pctsrf(1,is_ter)=0.
-          pctsrf(1,is_lic)=0.
-          pctsrf(1,is_sic)=0.
-        else if (nat_surf .eq. 1) then 
-          pctsrf(1,is_oce)=0.
-          pctsrf(1,is_ter)=1.
-          pctsrf(1,is_lic)=0.
-          pctsrf(1,is_sic)=0.
-        else if (nat_surf .eq. 2) then 
-          pctsrf(1,is_oce)=0.
-          pctsrf(1,is_ter)=0.
-          pctsrf(1,is_lic)=1.
-          pctsrf(1,is_sic)=0.
-        else if (nat_surf .eq. 3) then 
-          pctsrf(1,is_oce)=0.
-          pctsrf(1,is_ter)=0.
-          pctsrf(1,is_lic)=0.
-          pctsrf(1,is_sic)=1.
-
-     end if
-
-
-        print*,'nat_surf,pctsrf(1,is_oce),pctsrf(1,is_ter)',nat_surf         &
-     &        ,pctsrf(1,is_oce),pctsrf(1,is_ter)
-
-        zmasq=pctsrf(1,is_ter)+pctsrf(1,is_lic)
-        zpic = zpicinp
-        ftsol=tsurf
-        nsw=6 ! on met le nb de bandes SW=6, pour initialiser
-              ! 6 albedo, mais on peut quand meme tourner avec
-              ! moins. Seules les 2 ou 4 premiers seront lus
-        falb_dir=albedo
-        falb_dif=albedo
-        rugoro=rugos 
-        t_ancien(1,:)=temp(:)
-        q_ancien(1,:)=q(:,1)
-        ql_ancien = 0.
-        qs_ancien = 0.
-        prlw_ancien = 0.
-        prsw_ancien = 0.
-        prw_ancien = 0.
-!jyg<
-!!        pbl_tke(:,:,:)=1.e-8
-        pbl_tke(:,:,:)=0.
-        pbl_tke(:,2,:)=1.e-2
-        PRINT *, ' pbl_tke dans lmdz1d '
-        if (prt_level .ge. 5) then 
-         DO nsrf = 1,4
-           PRINT *,'pbl_tke(1,:,',nsrf,') ',pbl_tke(1,:,nsrf)
-         ENDDO
-        end if
-
-!>jyg
-
-        rain_fall=0.
-        snow_fall=0.
-        solsw=0.
-        sollw=0.
-        sollwdown=rsigma*tsurf**4
-        radsol=0.
-        rnebcon=0.
-        ratqs=0.
-        clwcon=0.
-        zmax0 = 0.
-        zmea=0.
-        zstd=0.
-        zsig=0.
-        zgam=0.
-        zval=0. 
-        zthe=0. 
-        sig1=0.
-        w01=0.
-        wake_cstar = 0.
-        wake_deltaq = 0.
-        wake_deltat = 0.
-        wake_delta_pbl_TKE(:,:,:) = 0.
-        delta_tsurf = 0.
-        wake_fip = 0.
-        wake_pe = 0.
-        wake_s = 0.
-        wake_dens = 0.
-        ale_bl = 0.
-        ale_bl_trig = 0.
-        alp_bl = 0.
-        IF (ALLOCATED(du_gwd_rando)) du_gwd_rando = 0.
-        IF (ALLOCATED(du_gwd_front)) du_gwd_front = 0.
-        entr_therm = 0.
-        detr_therm = 0.
-        f0 = 0.
-        fm_therm = 0.
-        u_ancien(1,:)=u(:)
-        v_ancien(1,:)=v(:)
- 
-!------------------------------------------------------------------------
-! Make file containing restart for the physics (startphy.nc)
-!
-! NB: List of the variables to be written by phyredem (via put_field):
-! rlon,rlat,zmasq,pctsrf(:,is_ter),pctsrf(:,is_lic),pctsrf(:,is_oce)
-! pctsrf(:,is_sic),ftsol(:,nsrf),tsoil(:,isoil,nsrf),qsurf(:,nsrf)
-! qsol,falb_dir(:,nsrf),falb_dif(:,nsrf),evap(:,nsrf),snow(:,nsrf)
-! radsol,solsw,sollw, sollwdown,fder,rain_fall,snow_fall,frugs(:,nsrf)
-! agesno(:,nsrf),zmea,zstd,zsig,zgam,zthe,zpic,zval,rugoro
-! t_ancien,q_ancien,,frugs(:,is_oce),clwcon(:,1),rnebcon(:,1),ratqs(:,1)
-! run_off_lic_0,pbl_tke(:,1:klev,nsrf), zmax0,f0,sig1,w01
-! wake_deltat,wake_deltaq,wake_s,wake_dens,wake_cstar,
-! wake_fip,wake_delta_pbl_tke(:,1:klev,nsrf)
-!
-! NB2: The content of the startphy.nc file depends on some flags defined in
-! the ".def" files. However, since conf_phys is not called in lmdz1d.F90, these flags have 
-! to be set at some arbitratry convenient values.
-!------------------------------------------------------------------------
-!Al1 =============== restart option ==========================
-        if (.not.restart) then
-          iflag_pbl = 5
-          call phyredem ("startphy.nc")
-        else
-! (desallocations)
-        print*,'callin surf final'
-          call pbl_surface_final( fder, snsrf, qsurfsrf, tsoil)
-        print*,'after surf final'
-          CALL fonte_neige_final(run_off_lic_0)
-        endif
-
-        ok_writedem=.false.
-        print*,'apres phyredem'
-
-      endif ! ok_writedem
-      
-!------------------------------------------------------------------------
-! Make file containing boundary conditions (limit.nc) **Al1->restartdyn***
-! --------------------------------------------------
-! NB: List of the variables to be written in limit.nc 
-!     (by writelim.F, subroutine of 1DUTILS.h):
-!        phy_nat,phy_alb,phy_sst,phy_bil,phy_rug,phy_ice,
-!        phy_fter,phy_foce,phy_flic,phy_fsic)
-!------------------------------------------------------------------------
-      do i=1,yd
-        phy_nat(i)  = nat_surf
-        phy_alb(i)  = albedo
-        phy_sst(i)  = tsurf ! read_tsurf1d will be used instead
-        phy_rug(i)  = rugos
-        phy_fter(i) = pctsrf(1,is_ter)
-        phy_foce(i) = pctsrf(1,is_oce)
-        phy_fsic(i) = pctsrf(1,is_sic)
-        phy_flic(i) = pctsrf(1,is_lic)
-      enddo
-
-! fabrication de limit.nc
-      call writelim (1,phy_nat,phy_alb,phy_sst,phy_bil,phy_rug,             &
-     &               phy_ice,phy_fter,phy_foce,phy_flic,phy_fsic)
-
-
-      call phys_state_var_end
-!Al1
-      if (restart) then
-        print*,'call to restart dyn 1d'
-        Call dyn1deta0("start1dyn.nc",plev,play,phi,phis,presnivs,          &
-     &              u,v,temp,q,omega2)
-
-       print*,'fnday,annee_ref,day_ref,day_ini',                            &
-     &     fnday,annee_ref,day_ref,day_ini
-!**      call ymds2ju(annee_ref,mois,day_ini,heure,day)
-       day = day_ini
-       day_end = day_ini + nday
-       daytime = day + time_ini/24. ! 1st day and initial time of the simulation 
-
-! Print out the actual date of the beginning of the simulation :
-       call ju2ymds(daytime, an, mois, jour, heure)
-       print *,' Time of beginning : y m d h',an, mois,jour,heure/3600.
-
-       day = int(daytime)
-       time=daytime-day
-  
-       print*,'****** intialised fields from restart1dyn *******'
-       print*,'plev,play,phi,phis,presnivs,u,v,temp,q,omega2'
-       print*,'temp(1),q(1,1),u(1),v(1),plev(1),phis :'
-       print*,temp(1),q(1,1),u(1),v(1),plev(1),phis
-! raz for safety
-       do l=1,llm
-         dq_dyn(l,1) = 0.
-       enddo
-      endif
-!Al1 ================  end restart =================================
-      IF (ecrit_slab_oc.eq.1) then
-         open(97,file='div_slab.dat',STATUS='UNKNOWN')
-       elseif (ecrit_slab_oc.eq.0) then
-         open(97,file='div_slab.dat',STATUS='OLD')
-       endif
-!
-!---------------------------------------------------------------------
-!    Initialize target profile for RHT nudging if needed
-!---------------------------------------------------------------------
-      if (nudge(inudge_RHT)) then
-        call nudge_RHT_init(plev,play,temp,q(:,1),t_targ,rh_targ)
-      endif
-      if (nudge(inudge_UV)) then
-        call nudge_UV_init(plev,play,u,v,u_targ,v_targ)
-      endif
-!
-!=====================================================================
-       CALL iophys_ini
-! START OF THE TEMPORAL LOOP :
-!=====================================================================
-           
-      it_end = nint(fnday*day_step)
-!test JLD     it_end = 10
-      do while(it.le.it_end)
-
-       if (prt_level.ge.1) then
-         print*,'XXXXXXXXXXXXXXXXXXX ITAP,day,time=',                       &
-     &             it,day,time,it_end,day_step
-         print*,'PAS DE TEMPS ',timestep
-       endif
-!Al1 demande de restartphy.nc
-       if (it.eq.it_end) lastcall=.True.
-
-!---------------------------------------------------------------------
-! Interpolation of forcings in time and onto model levels
-!---------------------------------------------------------------------
-
-#include "1D_interp_cases.h"
-
-      if (forcing_GCM2SCM) then
-        write (*,*) 'forcing_GCM2SCM not yet implemented'
-        stop 'in time loop'
-      endif ! forcing_GCM2SCM
-
-!---------------------------------------------------------------------
-!  Geopotential :
-!---------------------------------------------------------------------
-
-        phi(1)=RD*temp(1)*(plev(1)-play(1))/(.5*(plev(1)+play(1)))
-        do l = 1, llm-1
-          phi(l+1)=phi(l)+RD*(temp(l)+temp(l+1))*                           &
-     &    (play(l)-play(l+1))/(play(l)+play(l+1))
-        enddo
-
-!---------------------------------------------------------------------
-! Listing output for debug prt_level>=1
-!---------------------------------------------------------------------
-       if (prt_level>=1) then
-         print *,' avant physiq : -------- day time ',day,time
-         write(*,*) 'firstcall,lastcall,phis',                               &
-     &               firstcall,lastcall,phis
-       end if
-       if (prt_level>=5) then
-         write(*,'(a10,2a4,4a13)') 'BEFOR1 IT=','it','l',                   &
-     &        'presniv','plev','play','phi'
-         write(*,'(a10,2i4,4f13.2)') ('BEFOR1 IT= ',it,l,                   &
-     &         presnivs(l),plev(l),play(l),phi(l),l=1,llm)
-         write(*,'(a11,2a4,a11,6a8)') 'BEFOR2','it','l',                    &
-     &         'presniv','u','v','temp','q1','q2','omega2'
-         write(*,'(a11,2i4,f11.2,5f8.2,e10.2)') ('BEFOR2 IT= ',it,l,         &
-     &   presnivs(l),u(l),v(l),temp(l),q(l,1),q(l,2),omega2(l),l=1,llm)
-       endif
-
-!---------------------------------------------------------------------
-!   Call physiq :
-!---------------------------------------------------------------------
-       call physiq(ngrid,llm, &
-                    firstcall,lastcall,timestep, &
-                    plev,play,phi,phis,presnivs, &
-                    u,v, rot, temp,q,omega2, &
-                    du_phys,dv_phys,dt_phys,dq,dpsrf)
-                firstcall=.false.
-
-!---------------------------------------------------------------------
-! Listing output for debug
-!---------------------------------------------------------------------
-        if (prt_level>=5) then
-          write(*,'(a11,2a4,4a13)') 'AFTER1 IT=','it','l',                  &
-     &        'presniv','plev','play','phi'
-          write(*,'(a11,2i4,4f13.2)') ('AFTER1 it= ',it,l,                  &
-     &    presnivs(l),plev(l),play(l),phi(l),l=1,llm)
-          write(*,'(a11,2a4,a11,6a8)') 'AFTER2','it','l',                   &
-     &         'presniv','u','v','temp','q1','q2','omega2'
-          write(*,'(a11,2i4,f11.2,5f8.2,e10.2)') ('AFTER2 it= ',it,l,       &
-     &    presnivs(l),u(l),v(l),temp(l),q(l,1),q(l,2),omega2(l),l=1,llm)
-          write(*,'(a11,2a4,a11,5a8)') 'AFTER3','it','l',                   &
-     &         'presniv','du_phys','dv_phys','dt_phys','dq1','dq2'    
-           write(*,'(a11,2i4,f11.2,5f8.2)') ('AFTER3 it= ',it,l,            &
-     &      presnivs(l),86400*du_phys(l),86400*dv_phys(l),                   &
-     &       86400*dt_phys(l),86400*dq(l,1),dq(l,2),l=1,llm)
-          write(*,*) 'dpsrf',dpsrf
-        endif
-!---------------------------------------------------------------------
-!   Add physical tendencies :
-!---------------------------------------------------------------------
-
-       fcoriolis=2.*sin(rpi*xlat/180.)*romega
-       if (forcing_radconv .or. forcing_fire) then
-         fcoriolis=0.0
-         dt_cooling=0.0
-         d_t_adv=0.0
-         d_q_adv=0.0
-       endif
-!      print*, 'calcul de fcoriolis ', fcoriolis
-
-       if (forcing_toga .or. forcing_GCSSold .or. forcing_twpice            &
-     &    .or.forcing_amma .or. forcing_type.eq.101) then
-         fcoriolis=0.0 ; ug=0. ; vg=0.
-       endif
-
-       if(forcing_rico) then
-          dt_cooling=0.
-       endif
-
-!CRio:Attention modif sp??cifique cas de Caroline
-      if (forcing_type==-1) then
-         fcoriolis=0.
-!Nudging
-        
-!on calcule dt_cooling
-        do l=1,llm
-        if (play(l).ge.20000.) then
-            dt_cooling(l)=-1.5/86400.
-        elseif ((play(l).ge.10000.).and.((play(l).lt.20000.))) then
-            dt_cooling(l)=-1.5/86400.*(play(l)-10000.)/(10000.)-1./86400.*(20000.-play(l))/10000.*(temp(l)-200.)
-        else
-            dt_cooling(l)=-1.*(temp(l)-200.)/86400.
-        endif
-        enddo
-
-      endif     
-!RC
-      if (forcing_sandu) then
-         ug(1:llm)=u_mod(1:llm)
-         vg(1:llm)=v_mod(1:llm)
-      endif
-
-      IF (prt_level >= 5) print*, 'fcoriolis, xlat,mxcalc ', &
-                                   fcoriolis, xlat,mxcalc
-
-!       print *,'u-ug=',u-ug
-
-!!!!!!!!!!!!!!!!!!!!!!!!
-! Geostrophic wind
-! Le calcul ci dessous est insuffisamment precis
-!      du_age(1:mxcalc)=fcoriolis*(v(1:mxcalc)-vg(1:mxcalc))
-!      dv_age(1:mxcalc)=-fcoriolis*(u(1:mxcalc)-ug(1:mxcalc))
-!!!!!!!!!!!!!!!!!!!!!!!!
-       sfdt = sin(0.5*fcoriolis*timestep)
-       cfdt = cos(0.5*fcoriolis*timestep)
-!       print *,'fcoriolis,sfdt,cfdt,timestep',fcoriolis,sfdt,cfdt,timestep
-!
-        du_age(1:mxcalc)= -2.*sfdt/timestep*                                &
-     &          (sfdt*(u(1:mxcalc)-ug(1:mxcalc)) -                          &
-     &           cfdt*(v(1:mxcalc)-vg(1:mxcalc))  )
-!!     : fcoriolis*(v(1:mxcalc)-vg(1:mxcalc))
-!
-       dv_age(1:mxcalc)= -2.*sfdt/timestep*                                 &
-     &          (cfdt*(u(1:mxcalc)-ug(1:mxcalc)) +                           &
-     &           sfdt*(v(1:mxcalc)-vg(1:mxcalc))  )
-!!     : -fcoriolis*(u(1:mxcalc)-ug(1:mxcalc))
-!
-!!!!!!!!!!!!!!!!!!!!!!!!
-!  Nudging
-!!!!!!!!!!!!!!!!!!!!!!!!
-      d_t_nudge(:) = 0.
-      d_q_nudge(:,:) = 0.
-      d_u_nudge(:) = 0.
-      d_v_nudge(:) = 0.
-      if (nudge(inudge_RHT)) then
-        call nudge_RHT(timestep,plev,play,t_targ,rh_targ,temp,q(:,1),     &
-    &                  d_t_nudge,d_q_nudge(:,1))
-      endif
-      if (nudge(inudge_UV)) then
-        call nudge_UV(timestep,plev,play,u_targ,v_targ,u,v,     &
-    &                  d_u_nudge,d_v_nudge)
-      endif
-!
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!         call  writefield_phy('dv_age' ,dv_age,llm)
-!         call  writefield_phy('du_age' ,du_age,llm)
-!         call  writefield_phy('du_phys' ,du_phys,llm)
-!         call  writefield_phy('u_tend' ,u,llm)
-!         call  writefield_phy('u_g' ,ug,llm)
-!
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!! Increment state variables
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-    IF (flag_inhib_forcing == 0) then ! if tendency of forcings should be added
-
-! pour les cas sandu et astex, on reclacule u,v,q,temp et teta dans 1D_nudge_sandu_astex.h
-! au dessus de 700hpa, on relaxe vers les profils initiaux
-      if (forcing_sandu .OR. forcing_astex) then
-#include "1D_nudge_sandu_astex.h"
-      else
-        u(1:mxcalc)=u(1:mxcalc) + timestep*(                                &
-     &              du_phys(1:mxcalc)                                       &
-     &             +du_age(1:mxcalc)+du_adv(1:mxcalc)                       &
-     &             +d_u_nudge(1:mxcalc) )            
-        v(1:mxcalc)=v(1:mxcalc) + timestep*(                                 &
-     &              dv_phys(1:mxcalc)                                       &
-     &             +dv_age(1:mxcalc)+dv_adv(1:mxcalc)                       &
-     &             +d_v_nudge(1:mxcalc) )
-        q(1:mxcalc,:)=q(1:mxcalc,:)+timestep*(                              &
-     &                dq(1:mxcalc,:)                                        &
-     &               +d_q_adv(1:mxcalc,:)                                   &
-     &               +d_q_nudge(1:mxcalc,:) )
-
-        if (prt_level.ge.3) then
-          print *,                                                          &
-     &    'physiq-> temp(1),dt_phys(1),d_t_adv(1),dt_cooling(1) ',         &
-     &              temp(1),dt_phys(1),d_t_adv(1),dt_cooling(1)
-           print* ,'dv_phys=',dv_phys
-           print* ,'dv_age=',dv_age
-           print* ,'dv_adv=',dv_adv
-           print* ,'d_v_nudge=',d_v_nudge
-           print*, v
-           print*, vg
-        endif
-
-        temp(1:mxcalc)=temp(1:mxcalc)+timestep*(                            &
-     &              dt_phys(1:mxcalc)                                       &
-     &             +d_t_adv(1:mxcalc)                                      &
-     &             +d_t_nudge(1:mxcalc)                                      &
-     &             +dt_cooling(1:mxcalc))  ! Taux de chauffage ou refroid.
-
-      endif  ! forcing_sandu or forcing_astex
-
-        teta=temp*(pzero/play)**rkappa
-!
-!---------------------------------------------------------------------
-!   Nudge soil temperature if requested
-!---------------------------------------------------------------------
-
-      IF (nudge_tsoil .AND. .NOT. lastcall) THEN
-       ftsoil(1,isoil_nudge,:) = ftsoil(1,isoil_nudge,:)                     &
-     &  -timestep/tau_soil_nudge*(ftsoil(1,isoil_nudge,:)-Tsoil_nudge)
-      ENDIF
-
-!---------------------------------------------------------------------
-!   Add large-scale tendencies (advection, etc) :
-!---------------------------------------------------------------------
-
-!cc nrlmd
-!cc        tmpvar=teta
-!cc        call advect_vert(llm,omega,timestep,tmpvar,plev)
-!cc
-!cc        teta(1:mxcalc)=tmpvar(1:mxcalc)
-!cc        tmpvar(:)=q(:,1)
-!cc        call advect_vert(llm,omega,timestep,tmpvar,plev)
-!cc        q(1:mxcalc,1)=tmpvar(1:mxcalc)
-!cc        tmpvar(:)=q(:,2)
-!cc        call advect_vert(llm,omega,timestep,tmpvar,plev)
-!cc        q(1:mxcalc,2)=tmpvar(1:mxcalc)
-
-   END IF ! end if tendency of tendency should be added
-
-!---------------------------------------------------------------------
-!   Air temperature :
-!---------------------------------------------------------------------        
-        if (lastcall) then
-          print*,'Pas de temps final ',it
-          call ju2ymds(daytime, an, mois, jour, heure)
-          print*,'a la date : a m j h',an, mois, jour ,heure/3600.
-        endif
-
-!  incremente day time
-!        print*,'daytime bef',daytime,1./day_step
-        daytime = daytime+1./day_step
-!Al1dbg
-        day = int(daytime+0.1/day_step)
-!        time = max(daytime-day,0.0)
-!Al1&jyg: correction de bug
-!cc        time = real(mod(it,day_step))/day_step
-        time = time_ini/24.+real(mod(it,day_step))/day_step
-!        print*,'daytime nxt time',daytime,time
-        it=it+1
-
-      enddo
-
-!Al1
-      if (ecrit_slab_oc.ne.-1) close(97)
-
-!Al1 Call to 1D equivalent of dynredem (an,mois,jour,heure ?)
-! -------------------------------------
-       call dyn1dredem("restart1dyn.nc",                                    &
-     &              plev,play,phi,phis,presnivs,                            &
-     &              u,v,temp,q,omega2)
-
-        CALL abort_gcm ('lmdz1d   ','The End  ',0)
-
-      end
 
 #include "1DUTILS.h"
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/mod_1D_cases_read2.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/mod_1D_cases_read2.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/mod_1D_cases_read2.F90	(revision 3605)
@@ -315,4 +315,160 @@
 END SUBROUTINE read2_1D_cas
 
+!**********************************************************************************************
+SUBROUTINE read_SCM_cas
+      implicit none
+
+#include "netcdf.inc"
+#include "date_cas.h"
+
+      INTEGER nid,rid,ierr
+      INTEGER ii,jj,timeid
+      REAL, ALLOCATABLE :: time_val(:)
+
+      print*,'ON EST VRAIMENT LA'
+      fich_cas='cas.nc'
+      print*,'fich_cas ',fich_cas
+      ierr = NF_OPEN(fich_cas,NF_NOWRITE,nid)
+      print*,'fich_cas,NF_NOWRITE,nid ',fich_cas,NF_NOWRITE,nid
+      if (ierr.NE.NF_NOERR) then
+         write(*,*) 'ERROR: GROS Pb opening forcings nc file '
+         write(*,*) NF_STRERROR(ierr)
+         stop ""
+      endif
+!.......................................................................
+      ierr=NF_INQ_DIMID(nid,'lat',rid)
+      IF (ierr.NE.NF_NOERR) THEN
+         print*, 'Oh probleme lecture dimension lat'
+      ENDIF
+      ierr=NF_INQ_DIMLEN(nid,rid,ii)
+      print*,'OK1 read2: nid,rid,lat',nid,rid,ii
+!.......................................................................
+      ierr=NF_INQ_DIMID(nid,'lon',rid)
+      IF (ierr.NE.NF_NOERR) THEN
+         print*, 'Oh probleme lecture dimension lon'
+      ENDIF
+      ierr=NF_INQ_DIMLEN(nid,rid,jj)
+      print*,'OK2 read2: nid,rid,lat',nid,rid,jj
+!.......................................................................
+      ierr=NF_INQ_DIMID(nid,'lev',rid)
+      IF (ierr.NE.NF_NOERR) THEN
+         print*, 'Oh probleme lecture dimension nlev'
+      ENDIF
+      ierr=NF_INQ_DIMLEN(nid,rid,nlev_cas)
+      print*,'OK3 read2: nid,rid,nlev_cas',nid,rid,nlev_cas
+      IF ( .NOT. ( nlev_cas > 10 .AND. nlev_cas < 1000 )) THEN
+              print*,'Valeur de nlev_cas peu probable'
+              STOP
+      ENDIF
+!.......................................................................
+      ierr=NF_INQ_DIMID(nid,'time',rid)
+      nt_cas=0
+      IF (ierr.NE.NF_NOERR) THEN
+        stop 'Oh probleme lecture dimension time'
+      ENDIF
+      ierr=NF_INQ_DIMLEN(nid,rid,nt_cas)
+      print*,'OK4 read2: nid,rid,nt_cas',nid,rid,nt_cas
+! Lecture de l'axe des temps
+      print*,'LECTURE DU TEMPS'
+      ierr=NF_INQ_VARID(nid,'time',timeid)
+         if(ierr/=NF_NOERR) then
+           print *,'Variable time manquante dans cas.nc:'
+           ierr=NF_NOERR
+         else
+                 allocate(time_val(nt_cas))
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,timeid,time_val)
+#else
+           ierr = NF_GET_VAR_REAL(nid,timeid,time_val)
+#endif
+           if(ierr/=NF_NOERR) then
+              print *,'Pb a la lecture de time cas.nc: '
+           endif
+   endif
+   IF (nt_cas>1) THEN
+           pdt_cas=time_val(2)-time_val(1)
+   ELSE
+           pdt_cas=0.
+   ENDIF
+
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!profils moyens:
+        allocate(plev_cas(nlev_cas,nt_cas),plevh_cas(nlev_cas+1))        
+        allocate(z_cas(nlev_cas,nt_cas),zh_cas(nlev_cas+1))
+        allocate(ap_cas(nlev_cas+1),bp_cas(nt_cas+1))
+        allocate(t_cas(nlev_cas,nt_cas),q_cas(nlev_cas,nt_cas),qv_cas(nlev_cas,nt_cas),ql_cas(nlev_cas,nt_cas), &
+             qi_cas(nlev_cas,nt_cas),rh_cas(nlev_cas,nt_cas))
+        allocate(th_cas(nlev_cas,nt_cas),thl_cas(nlev_cas,nt_cas),thv_cas(nlev_cas,nt_cas),rv_cas(nlev_cas,nt_cas))
+        allocate(u_cas(nlev_cas,nt_cas),v_cas(nlev_cas,nt_cas),vitw_cas(nlev_cas,nt_cas),omega_cas(nlev_cas,nt_cas))
+
+!forcing
+        allocate(ht_cas(nlev_cas,nt_cas),vt_cas(nlev_cas,nt_cas),dt_cas(nlev_cas,nt_cas),dtrad_cas(nlev_cas,nt_cas))
+        allocate(hq_cas(nlev_cas,nt_cas),vq_cas(nlev_cas,nt_cas),dq_cas(nlev_cas,nt_cas))
+        allocate(hth_cas(nlev_cas,nt_cas),vth_cas(nlev_cas,nt_cas),dth_cas(nlev_cas,nt_cas))
+        allocate(hr_cas(nlev_cas,nt_cas),vr_cas(nlev_cas,nt_cas),dr_cas(nlev_cas,nt_cas))
+        allocate(hu_cas(nlev_cas,nt_cas),vu_cas(nlev_cas,nt_cas),du_cas(nlev_cas,nt_cas))
+        allocate(hv_cas(nlev_cas,nt_cas),vv_cas(nlev_cas,nt_cas),dv_cas(nlev_cas,nt_cas))
+        allocate(ug_cas(nlev_cas,nt_cas))
+        allocate(vg_cas(nlev_cas,nt_cas))
+        allocate(lat_cas(nt_cas),sens_cas(nt_cas),ts_cas(nt_cas),ps_cas(nt_cas),ustar_cas(nt_cas),tke_cas(nt_cas))
+        allocate(uw_cas(nlev_cas,nt_cas),vw_cas(nlev_cas,nt_cas),q1_cas(nlev_cas,nt_cas),q2_cas(nlev_cas,nt_cas))
+
+
+
+!champs interpoles
+        allocate(plev_prof_cas(nlev_cas))
+        allocate(t_prof_cas(nlev_cas))
+        allocate(theta_prof_cas(nlev_cas))
+        allocate(thl_prof_cas(nlev_cas))
+        allocate(thv_prof_cas(nlev_cas))
+        allocate(q_prof_cas(nlev_cas))
+        allocate(qv_prof_cas(nlev_cas))
+        allocate(ql_prof_cas(nlev_cas))
+        allocate(qi_prof_cas(nlev_cas))
+        allocate(rh_prof_cas(nlev_cas))
+        allocate(rv_prof_cas(nlev_cas))
+        allocate(u_prof_cas(nlev_cas))
+        allocate(v_prof_cas(nlev_cas))
+        allocate(vitw_prof_cas(nlev_cas))
+        allocate(omega_prof_cas(nlev_cas))
+        allocate(ug_prof_cas(nlev_cas))
+        allocate(vg_prof_cas(nlev_cas))
+        allocate(ht_prof_cas(nlev_cas))
+        allocate(hth_prof_cas(nlev_cas))
+        allocate(hq_prof_cas(nlev_cas))
+        allocate(hu_prof_cas(nlev_cas))
+        allocate(hv_prof_cas(nlev_cas))
+        allocate(vt_prof_cas(nlev_cas))
+        allocate(vth_prof_cas(nlev_cas))
+        allocate(vq_prof_cas(nlev_cas))
+        allocate(vu_prof_cas(nlev_cas))
+        allocate(vv_prof_cas(nlev_cas))
+        allocate(dt_prof_cas(nlev_cas))
+        allocate(dth_prof_cas(nlev_cas))
+        allocate(dtrad_prof_cas(nlev_cas))
+        allocate(dq_prof_cas(nlev_cas))
+        allocate(du_prof_cas(nlev_cas))
+        allocate(dv_prof_cas(nlev_cas))
+        allocate(uw_prof_cas(nlev_cas))
+        allocate(vw_prof_cas(nlev_cas))
+        allocate(q1_prof_cas(nlev_cas))
+        allocate(q2_prof_cas(nlev_cas))
+
+        print*,'Allocations OK'
+        call read_SCM (nid,nlev_cas,nt_cas,                                                                     &
+     &     ap_cas,bp_cas,z_cas,plev_cas,zh_cas,plevh_cas,t_cas,th_cas,thv_cas,thl_cas,qv_cas,                    &
+     &     ql_cas,qi_cas,rh_cas,rv_cas,u_cas,v_cas,vitw_cas,omega_cas,ug_cas,vg_cas,du_cas,hu_cas,vu_cas,        &
+     &     dv_cas,hv_cas,vv_cas,dt_cas,ht_cas,vt_cas,dq_cas,hq_cas,vq_cas,dth_cas,hth_cas,vth_cas,               &
+     &     dr_cas,hr_cas,vr_cas,dtrad_cas,sens_cas,lat_cas,ts_cas,ps_cas,ustar_cas,tke_cas,                      &
+     &     uw_cas,vw_cas,q1_cas,q2_cas,orog_cas,albedo_cas,emiss_cas,t_skin_cas,q_skin_cas,mom_rough,heat_rough, &
+     &     o3_cas,rugos_cas,clay_cas,sand_cas)
+        print*,'Read2 cas OK'
+        do ii=1,nlev_cas
+        print*,'apres read2_cas, plev_cas=',ii,plev_cas(ii,1)
+        enddo
+
+
+END SUBROUTINE read_SCM_cas
 
 
@@ -685,6 +841,239 @@
 !-----------------------------------------------------------------------
 
+
          return 
          end subroutine read2_cas
+
+!======================================================================
+      subroutine read_SCM(nid,nlevel,ntime,                                       &
+     &     ap,bp,zz,pp,zzh,pph,temp,theta,thv,thl,qv,ql,qi,rh,rv,u,v,vitw,omega,ug,vg,&
+     &     du,hu,vu,dv,hv,vv,dt,ht,vt,dq,hq,vq,                                    &
+     &     dth,hth,vth,dr,hr,vr,dtrad,sens,flat,ts,ps,ustar,tke,uw,vw,q1,q2,       &
+     &     orog_cas,albedo_cas,emiss_cas,t_skin_cas,q_skin_cas,mom_rough,          &
+     &     heat_rough,o3_cas,rugos_cas,clay_cas,sand_cas)
+
+!program reading forcing of the case study
+      implicit none
+#include "netcdf.inc"
+
+      integer ntime,nlevel,k,t
+
+      real ap(nlevel+1),bp(nlevel+1)
+      real zz(nlevel,ntime),zzh(nlevel+1)
+      real pp(nlevel,ntime),pph(nlevel+1)
+!profils initiaux
+      real temp0(nlevel),qv0(nlevel),ql0(nlevel),qi0(nlevel),u0(nlevel),v0(nlevel),tke0(nlevel)
+      real pp0(nlevel)    
+      real temp(nlevel,ntime),qv(nlevel,ntime),ql(nlevel,ntime),qi(nlevel,ntime),rh(nlevel,ntime)
+      real theta(nlevel,ntime),thv(nlevel,ntime),thl(nlevel,ntime),rv(nlevel,ntime)
+      real u(nlevel,ntime),v(nlevel,ntime),tke(nlevel,ntime)
+      real ug(nlevel,ntime),vg(nlevel,ntime)
+      real vitw(nlevel,ntime),omega(nlevel,ntime)
+      real du(nlevel,ntime),hu(nlevel,ntime),vu(nlevel,ntime)
+      real dv(nlevel,ntime),hv(nlevel,ntime),vv(nlevel,ntime)
+      real dt(nlevel,ntime),ht(nlevel,ntime),vt(nlevel,ntime)
+      real dtrad(nlevel,ntime)
+      real dq(nlevel,ntime),hq(nlevel,ntime),vq(nlevel,ntime)
+      real dth(nlevel,ntime),hth(nlevel,ntime),vth(nlevel,ntime),hthl(nlevel,ntime)
+      real dr(nlevel,ntime),hr(nlevel,ntime),vr(nlevel,ntime)
+      real flat(ntime),sens(ntime),ustar(ntime)
+      real uw(nlevel,ntime),vw(nlevel,ntime),q1(nlevel,ntime),q2(nlevel,ntime)
+      real ts(ntime),ps(ntime)
+      real orog_cas,albedo_cas,emiss_cas,t_skin_cas,q_skin_cas,mom_rough,heat_rough,o3_cas,rugos_cas,clay_cas,sand_cas
+      real apbp(nlevel+1),resul(nlevel,ntime),resul1(nlevel),resul2(ntime),resul3
+
+
+      integer nid, ierr,ierr1,ierr2,rid,i
+      integer nbvar3d
+      parameter(nbvar3d=70)
+      integer var3didin(nbvar3d),missing_var(nbvar3d)
+      character*13 name_var(1:nbvar3d)
+      data name_var/'coor_par_a','coor_par_b','height_h','pressure_h',&
+     &'temp','qv','ql','qi','u','v','tke','pressure',&
+     &'w','omega','ug','vg','uadv','uadvh','uadvv','vadv','vadvh','vadvv','tadv','tadvh','tadvv',&
+     &'qvadv','qvadvh','qvadvv','thadv','thadvh','thadvv','thladvh','radv','radvh','radvv','radcool','q1','q2','ustress','vstress', &
+     'rh',&
+     &'height_f','pressure_forc','tempt','theta','thv','thl','qvt','qlt','qit','rv','ut','vt','tket',&
+     &'sfc_sens_flx','sfc_lat_flx','ts','ps','ustar',&
+     &'orog','albedo','emiss','t_skin','q_skin','mom_rough','heat_rough','o3','rugos','clay','sand'/
+      do i=1,nbvar3d
+        missing_var(i)=0.
+      enddo
+
+!-----------------------------------------------------------------------
+
+     print*,'ON EST LA'
+       do i=1,nbvar3d
+         ierr=NF_INQ_VARID(nid,name_var(i),var3didin(i)) 
+         if(ierr/=NF_NOERR) then
+           print *,'Variable manquante dans cas.nc:',i,name_var(i)
+           ierr=NF_NOERR
+           missing_var(i)=1
+         else
+!-----------------------------------------------------------------------
+           if(i.LE.4) then     ! Lecture des coord pression en (nlevelp1,lat,lon)
+#ifdef NC_DOUBLE
+           ierr = NF_GET_VAR_DOUBLE(nid,var3didin(i),apbp)
+#else
+           ierr = NF_GET_VAR_REAL(nid,var3didin(i),apbp)
+#endif
+           print *,'read2_cas(apbp), on a lu ',i,name_var(i)
+           if(ierr/=NF_NOERR) then
+              print *,'Pb a la lecture de cas.nc: ',name_var(i)
+              stop "getvarup"
+           endif
+!-----------------------------------------------------------------------
+           else if(i.gt.4.and.i.LE.12) then   ! Lecture des variables en (time,nlevel,lat,lon)
+#ifdef NC_DOUBLE
+           ierr = NF_GET_VAR_DOUBLE(nid,var3didin(i),resul1)
+#else
+           ierr = NF_GET_VAR_REAL(nid,var3didin(i),resul1)
+#endif
+           print *,'read2_cas(resul1), on a lu ',i,name_var(i)
+           if(ierr/=NF_NOERR) then
+              print *,'Pb a la lecture de cas.nc: ',name_var(i)
+              stop "getvarup"
+           endif
+         print*,'Lecture de la variable #i ',i,name_var(i),minval(resul1),maxval(resul1)
+!-----------------------------------------------------------------------
+           else if(i.gt.12.and.i.LE.54) then   ! Lecture des variables en (time,nlevel,lat,lon)
+#ifdef NC_DOUBLE
+           ierr = NF_GET_VAR_DOUBLE(nid,var3didin(i),resul)
+#else
+           ierr = NF_GET_VAR_REAL(nid,var3didin(i),resul)
+#endif
+           print *,'read2_cas(resul), on a lu ',i,name_var(i)
+           if(ierr/=NF_NOERR) then
+              print *,'Pb a la lecture de cas.nc: ',name_var(i)
+              stop "getvarup"
+           endif
+         print*,'Lecture de la variable #i ',i,name_var(i),minval(resul),maxval(resul)
+!-----------------------------------------------------------------------
+           else if (i.gt.54.and.i.LE.65) then   ! Lecture des variables en (time,lat,lon)
+#ifdef NC_DOUBLE
+           ierr = NF_GET_VAR_DOUBLE(nid,var3didin(i),resul2)
+#else
+           ierr = NF_GET_VAR_REAL(nid,var3didin(i),resul2)
+#endif
+           print *,'read2_cas(resul2), on a lu ',i,name_var(i)
+           if(ierr/=NF_NOERR) then
+              print *,'Pb a la lecture de cas.nc: ',name_var(i)
+              stop "getvarup"
+           endif
+         print*,'Lecture de la variable #i  ',i,name_var(i),minval(resul2),maxval(resul2)
+!-----------------------------------------------------------------------
+           else     ! Lecture des constantes (lat,lon)
+#ifdef NC_DOUBLE
+           ierr = NF_GET_VAR_DOUBLE(nid,var3didin(i),resul3)
+#else
+           ierr = NF_GET_VAR_REAL(nid,var3didin(i),resul3)
+#endif
+           print *,'read2_cas(resul3), on a lu ',i,name_var(i)
+           if(ierr/=NF_NOERR) then
+              print *,'Pb a la lecture de cas.nc: ',name_var(i)
+              stop "getvarup"
+           endif
+         print*,'Lecture de la variable #i ',i,name_var(i),resul3
+           endif
+         endif
+!-----------------------------------------------------------------------
+         select case(i)
+         !case(1) ; ap=apbp       ! donnees indexees en nlevel+1
+         ! case(2) ; bp=apbp
+           case(3) ; zzh=apbp
+           case(4) ; pph=apbp
+           case(5) ; temp0=resul1    ! donnees initiales
+           case(6) ; qv0=resul1
+           case(7) ; ql0=resul1
+           case(8) ; qi0=resul1
+           case(9) ; u0=resul1
+           case(10) ; v0=resul1
+           case(11) ; tke0=resul1
+           case(12) ; pp0=resul1
+           case(13) ; vitw=resul    ! donnees indexees en nlevel,time
+           case(14) ; omega=resul
+           case(15) ; ug=resul
+           case(16) ; vg=resul
+           case(17) ; du=resul
+           case(18) ; hu=resul
+           case(19) ; vu=resul
+           case(20) ; dv=resul
+           case(21) ; hv=resul
+           case(22) ; vv=resul
+           case(23) ; dt=resul
+           case(24) ; ht=resul
+           case(25) ; vt=resul
+           case(26) ; dq=resul
+           case(27) ; hq=resul
+           case(28) ; vq=resul
+           case(29) ; dth=resul
+           case(30) ; hth=resul
+           case(31) ; vth=resul
+           case(32) ; hthl=resul
+           case(33) ; dr=resul
+           case(34) ; hr=resul
+           case(35) ; vr=resul
+           case(36) ; dtrad=resul
+           case(37) ; q1=resul
+           case(38) ; q2=resul
+           case(39) ; uw=resul
+           case(40) ; vw=resul
+           case(41) ; rh=resul
+           case(42) ; zz=resul      ! donnees en time,nlevel pour profil initial
+           case(43) ; pp=resul
+           case(44) ; temp=resul
+           case(45) ; theta=resul
+           case(46) ; thv=resul
+           case(47) ; thl=resul
+           case(48) ; qv=resul
+           case(49) ; ql=resul
+           case(50) ; qi=resul
+           case(51) ; rv=resul
+           case(52) ; u=resul
+           case(53) ; v=resul
+           case(54) ; tke=resul
+           case(55) ; sens=resul2   ! donnees indexees en time
+           case(56) ; flat=resul2
+           case(57) ; ts=resul2
+           case(58) ; ps=resul2
+           case(59) ; ustar=resul2
+           case(60) ; orog_cas=resul3      ! constantes
+           case(61) ; albedo_cas=resul3
+           case(62) ; emiss_cas=resul3
+           case(63) ; t_skin_cas=resul3
+           case(64) ; q_skin_cas=resul3
+           case(65) ; mom_rough=resul3
+           case(66) ; heat_rough=resul3
+           case(67) ; o3_cas=resul3        
+           case(68) ; rugos_cas=resul3
+           case(69) ; clay_cas=resul3
+           case(70) ; sand_cas=resul3
+         end select
+         resul=0.
+         resul1=0.
+         resul2=0.
+         resul3=0.
+       enddo
+         print*,'Lecture de la variable APRES ,sens ',minval(sens),maxval(sens)
+         print*,'Lecture de la variable APRES ,flat ',minval(flat),maxval(flat)
+
+!CR:ATTENTION EN ATTENTE DE REGLER LA QUESTION DU PAS DE TEMPS INITIAL
+       do t=1,ntime
+          do k=1,nlevel
+             temp(k,t)=temp0(k)
+             qv(k,t)=qv0(k)
+             ql(k,t)=ql0(k)
+             qi(k,t)=qi0(k)
+             u(k,t)=u0(k)
+             v(k,t)=v0(k)
+             tke(k,t)=tke0(k)
+          enddo
+       enddo
+!-----------------------------------------------------------------------
+
+         return 
+         end subroutine read_SCM
+!======================================================================
+
 !======================================================================
         SUBROUTINE interp_case_time2(day,day1,annee_ref                &
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/mod_1D_cases_read_std.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/mod_1D_cases_read_std.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/mod_1D_cases_read_std.F90	(revision 3605)
@@ -0,0 +1,1067 @@
+!
+! $Id: mod_1D_cases_read.F90 2373 2015-10-13 17:28:01Z jyg $
+!
+MODULE mod_1D_cases_read_std
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!Declarations specifiques au cas standard
+        character*80 :: fich_cas
+! Discr?tisation 
+        integer nlev_cas, nt_cas
+
+
+!profils environnementaux
+        real, allocatable::  plev_cas(:,:),plevh_cas(:)
+        real, allocatable::  ap_cas(:),bp_cas(:)
+
+        real, allocatable::  z_cas(:,:),zh_cas(:)
+        real, allocatable::  t_cas(:,:),q_cas(:,:),qv_cas(:,:),ql_cas(:,:),qi_cas(:,:),rh_cas(:,:)
+        real, allocatable::  th_cas(:,:),thv_cas(:,:),thl_cas(:,:),rv_cas(:,:)
+        real, allocatable::  u_cas(:,:),v_cas(:,:),vitw_cas(:,:),omega_cas(:,:)
+
+!forcing
+        real, allocatable::  ht_cas(:,:),vt_cas(:,:),dt_cas(:,:),dtrad_cas(:,:)
+        real, allocatable::  hth_cas(:,:),vth_cas(:,:),dth_cas(:,:)
+        real, allocatable::  hq_cas(:,:),vq_cas(:,:),dq_cas(:,:)
+        real, allocatable::  hr_cas(:,:),vr_cas(:,:),dr_cas(:,:)
+        real, allocatable::  hu_cas(:,:),vu_cas(:,:),du_cas(:,:)
+        real, allocatable::  hv_cas(:,:),vv_cas(:,:),dv_cas(:,:)
+        real, allocatable::  ug_cas(:,:),vg_cas(:,:)
+        real, allocatable::  temp_nudg_cas(:,:),qv_nudg_cas(:,:),u_nudg_cas(:,:),v_nudg_cas(:,:)
+        real, allocatable::  lat_cas(:),sens_cas(:),ts_cas(:),ps_cas(:),ustar_cas(:)
+        real, allocatable::  uw_cas(:,:),vw_cas(:,:),q1_cas(:,:),q2_cas(:,:),tke_cas(:)
+
+!champs interpoles
+        real, allocatable::  plev_prof_cas(:)
+        real, allocatable::  t_prof_cas(:)
+        real, allocatable::  theta_prof_cas(:)
+        real, allocatable::  thl_prof_cas(:)
+        real, allocatable::  thv_prof_cas(:)
+        real, allocatable::  q_prof_cas(:)
+        real, allocatable::  qv_prof_cas(:)
+        real, allocatable::  ql_prof_cas(:)
+        real, allocatable::  qi_prof_cas(:)
+        real, allocatable::  rh_prof_cas(:)
+        real, allocatable::  rv_prof_cas(:)
+        real, allocatable::  u_prof_cas(:)
+        real, allocatable::  v_prof_cas(:)        
+        real, allocatable::  vitw_prof_cas(:)
+        real, allocatable::  omega_prof_cas(:)
+        real, allocatable::  ug_prof_cas(:)
+        real, allocatable::  vg_prof_cas(:)
+        real, allocatable::  temp_nudg_prof_cas(:),qv_nudg_prof_cas(:),u_nudg_prof_cas(:),v_nudg_prof_cas(:)
+        real, allocatable::  ht_prof_cas(:)
+        real, allocatable::  hth_prof_cas(:)
+        real, allocatable::  hq_prof_cas(:)
+        real, allocatable::  vt_prof_cas(:)
+        real, allocatable::  vth_prof_cas(:)
+        real, allocatable::  vq_prof_cas(:)
+        real, allocatable::  dt_prof_cas(:)
+        real, allocatable::  dth_prof_cas(:)
+        real, allocatable::  dtrad_prof_cas(:)
+        real, allocatable::  dq_prof_cas(:)
+        real, allocatable::  hu_prof_cas(:)
+        real, allocatable::  hv_prof_cas(:)
+        real, allocatable::  vu_prof_cas(:)
+        real, allocatable::  vv_prof_cas(:)
+        real, allocatable::  du_prof_cas(:)
+        real, allocatable::  dv_prof_cas(:)
+        real, allocatable::  uw_prof_cas(:)
+        real, allocatable::  vw_prof_cas(:)
+        real, allocatable::  q1_prof_cas(:)
+        real, allocatable::  q2_prof_cas(:)
+
+
+        real lat_prof_cas,sens_prof_cas,ts_prof_cas,ps_prof_cas,ustar_prof_cas,tke_prof_cas
+        real o3_cas,orog_cas,albedo_cas,emiss_cas,t_skin_cas,q_skin_cas,mom_rough,heat_rough,rugos_cas,sand_cas,clay_cas
+      
+
+
+CONTAINS
+
+
+!**********************************************************************************************
+SUBROUTINE read_SCM_cas
+      implicit none
+
+#include "netcdf.inc"
+#include "date_cas.h"
+
+      INTEGER nid,rid,ierr
+      INTEGER ii,jj,timeid
+      REAL, ALLOCATABLE :: time_val(:)
+
+      print*,'ON EST VRAIMENT LA'
+      fich_cas='cas.nc'
+      print*,'fich_cas ',fich_cas
+      ierr = NF_OPEN(fich_cas,NF_NOWRITE,nid)
+      print*,'fich_cas,NF_NOWRITE,nid ',fich_cas,NF_NOWRITE,nid
+      if (ierr.NE.NF_NOERR) then
+         write(*,*) 'ERROR: GROS Pb opening forcings nc file '
+         write(*,*) NF_STRERROR(ierr)
+         stop ""
+      endif
+!.......................................................................
+      ierr=NF_INQ_DIMID(nid,'lat',rid)
+      IF (ierr.NE.NF_NOERR) THEN
+         print*, 'Oh probleme lecture dimension lat'
+      ENDIF
+      ierr=NF_INQ_DIMLEN(nid,rid,ii)
+      print*,'OK1 read2: nid,rid,lat',nid,rid,ii
+!.......................................................................
+      ierr=NF_INQ_DIMID(nid,'lon',rid)
+      IF (ierr.NE.NF_NOERR) THEN
+         print*, 'Oh probleme lecture dimension lon'
+      ENDIF
+      ierr=NF_INQ_DIMLEN(nid,rid,jj)
+      print*,'OK2 read2: nid,rid,lat',nid,rid,jj
+!.......................................................................
+      ierr=NF_INQ_DIMID(nid,'lev',rid)
+      IF (ierr.NE.NF_NOERR) THEN
+         print*, 'Oh probleme lecture dimension nlev'
+      ENDIF
+      ierr=NF_INQ_DIMLEN(nid,rid,nlev_cas)
+      print*,'OK3 read2: nid,rid,nlev_cas',nid,rid,nlev_cas
+      IF ( .NOT. ( nlev_cas > 10 .AND. nlev_cas < 1000 )) THEN
+              print*,'Valeur de nlev_cas peu probable'
+              STOP
+      ENDIF
+!.......................................................................
+      ierr=NF_INQ_DIMID(nid,'time',rid)
+      nt_cas=0
+      IF (ierr.NE.NF_NOERR) THEN
+        stop 'Oh probleme lecture dimension time'
+      ENDIF
+      ierr=NF_INQ_DIMLEN(nid,rid,nt_cas)
+      print*,'OK4 read2: nid,rid,nt_cas',nid,rid,nt_cas
+! Lecture de l'axe des temps
+      print*,'LECTURE DU TEMPS'
+      ierr=NF_INQ_VARID(nid,'time',timeid)
+         if(ierr/=NF_NOERR) then
+           print *,'Variable time manquante dans cas.nc:'
+           ierr=NF_NOERR
+         else
+                 allocate(time_val(nt_cas))
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,timeid,time_val)
+#else
+           ierr = NF_GET_VAR_REAL(nid,timeid,time_val)
+#endif
+           if(ierr/=NF_NOERR) then
+              print *,'Pb a la lecture de time cas.nc: '
+           endif
+   endif
+   IF (nt_cas>1) THEN
+           pdt_cas=time_val(2)-time_val(1)
+   ELSE
+           pdt_cas=0.
+   ENDIF
+
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!profils moyens:
+        allocate(plev_cas(nlev_cas,nt_cas),plevh_cas(nlev_cas+1))        
+        allocate(z_cas(nlev_cas,nt_cas),zh_cas(nlev_cas+1))
+        allocate(ap_cas(nlev_cas+1),bp_cas(nt_cas+1))
+        allocate(t_cas(nlev_cas,nt_cas),q_cas(nlev_cas,nt_cas),qv_cas(nlev_cas,nt_cas),ql_cas(nlev_cas,nt_cas), &
+             qi_cas(nlev_cas,nt_cas),rh_cas(nlev_cas,nt_cas))
+        allocate(th_cas(nlev_cas,nt_cas),thl_cas(nlev_cas,nt_cas),thv_cas(nlev_cas,nt_cas),rv_cas(nlev_cas,nt_cas))
+        allocate(u_cas(nlev_cas,nt_cas),v_cas(nlev_cas,nt_cas),vitw_cas(nlev_cas,nt_cas),omega_cas(nlev_cas,nt_cas))
+
+!forcing
+        allocate(ht_cas(nlev_cas,nt_cas),vt_cas(nlev_cas,nt_cas),dt_cas(nlev_cas,nt_cas),dtrad_cas(nlev_cas,nt_cas))
+        allocate(hq_cas(nlev_cas,nt_cas),vq_cas(nlev_cas,nt_cas),dq_cas(nlev_cas,nt_cas))
+        allocate(hth_cas(nlev_cas,nt_cas),vth_cas(nlev_cas,nt_cas),dth_cas(nlev_cas,nt_cas))
+        allocate(hr_cas(nlev_cas,nt_cas),vr_cas(nlev_cas,nt_cas),dr_cas(nlev_cas,nt_cas))
+        allocate(hu_cas(nlev_cas,nt_cas),vu_cas(nlev_cas,nt_cas),du_cas(nlev_cas,nt_cas))
+        allocate(hv_cas(nlev_cas,nt_cas),vv_cas(nlev_cas,nt_cas),dv_cas(nlev_cas,nt_cas))
+        allocate(ug_cas(nlev_cas,nt_cas),vg_cas(nlev_cas,nt_cas))
+        allocate(temp_nudg_cas(nlev_cas,nt_cas),qv_nudg_cas(nlev_cas,nt_cas))
+        allocate(u_nudg_cas(nlev_cas,nt_cas),v_nudg_cas(nlev_cas,nt_cas))
+        allocate(lat_cas(nt_cas),sens_cas(nt_cas),ts_cas(nt_cas),ps_cas(nt_cas),ustar_cas(nt_cas),tke_cas(nt_cas))
+        allocate(uw_cas(nlev_cas,nt_cas),vw_cas(nlev_cas,nt_cas),q1_cas(nlev_cas,nt_cas),q2_cas(nlev_cas,nt_cas))
+
+
+
+!champs interpoles
+        allocate(plev_prof_cas(nlev_cas))
+        allocate(t_prof_cas(nlev_cas))
+        allocate(theta_prof_cas(nlev_cas))
+        allocate(thl_prof_cas(nlev_cas))
+        allocate(thv_prof_cas(nlev_cas))
+        allocate(q_prof_cas(nlev_cas))
+        allocate(qv_prof_cas(nlev_cas))
+        allocate(ql_prof_cas(nlev_cas))
+        allocate(qi_prof_cas(nlev_cas))
+        allocate(rh_prof_cas(nlev_cas))
+        allocate(rv_prof_cas(nlev_cas))
+        allocate(u_prof_cas(nlev_cas))
+        allocate(v_prof_cas(nlev_cas))
+        allocate(vitw_prof_cas(nlev_cas))
+        allocate(omega_prof_cas(nlev_cas))
+        allocate(ug_prof_cas(nlev_cas))
+        allocate(vg_prof_cas(nlev_cas))
+        allocate(temp_nudg_prof_cas(nlev_cas),qv_nudg_prof_cas(nlev_cas))
+        allocate(u_nudg_prof_cas(nlev_cas),v_nudg_prof_cas(nlev_cas))
+        allocate(ht_prof_cas(nlev_cas))
+        allocate(hth_prof_cas(nlev_cas))
+        allocate(hq_prof_cas(nlev_cas))
+        allocate(hu_prof_cas(nlev_cas))
+        allocate(hv_prof_cas(nlev_cas))
+        allocate(vt_prof_cas(nlev_cas))
+        allocate(vth_prof_cas(nlev_cas))
+        allocate(vq_prof_cas(nlev_cas))
+        allocate(vu_prof_cas(nlev_cas))
+        allocate(vv_prof_cas(nlev_cas))
+        allocate(dt_prof_cas(nlev_cas))
+        allocate(dth_prof_cas(nlev_cas))
+        allocate(dtrad_prof_cas(nlev_cas))
+        allocate(dq_prof_cas(nlev_cas))
+        allocate(du_prof_cas(nlev_cas))
+        allocate(dv_prof_cas(nlev_cas))
+        allocate(uw_prof_cas(nlev_cas))
+        allocate(vw_prof_cas(nlev_cas))
+        allocate(q1_prof_cas(nlev_cas))
+        allocate(q2_prof_cas(nlev_cas))
+
+        print*,'Allocations OK'
+        CALL read_SCM (nid,nlev_cas,nt_cas,                                                                     &
+     &     ap_cas,bp_cas,z_cas,plev_cas,zh_cas,plevh_cas,t_cas,th_cas,thv_cas,thl_cas,qv_cas,                   &
+     &     ql_cas,qi_cas,rh_cas,rv_cas,u_cas,v_cas,vitw_cas,omega_cas,ug_cas,vg_cas,                            &
+     &     temp_nudg_cas,qv_nudg_cas,u_nudg_cas,v_nudg_cas,                                                     &
+     &     du_cas,hu_cas,vu_cas,                                                                                &
+     &     dv_cas,hv_cas,vv_cas,dt_cas,ht_cas,vt_cas,dq_cas,hq_cas,vq_cas,dth_cas,hth_cas,vth_cas,               &
+     &     dr_cas,hr_cas,vr_cas,dtrad_cas,sens_cas,lat_cas,ts_cas,ps_cas,ustar_cas,tke_cas,                      &
+     &     uw_cas,vw_cas,q1_cas,q2_cas,orog_cas,albedo_cas,emiss_cas,t_skin_cas,q_skin_cas,mom_rough,heat_rough, &
+     &     o3_cas,rugos_cas,clay_cas,sand_cas)
+        print*,'read_SCM cas OK'
+        do ii=1,nlev_cas
+        print*,'apres read2_SCM, plev_cas=',ii,plev_cas(ii,1)
+        !print*,'apres read_SCM, plev_cas=',ii,omega_cas(ii,nt_cas/2+1)
+        enddo
+
+
+END SUBROUTINE read_SCM_cas
+
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+SUBROUTINE deallocate2_1D_cases
+!profils environnementaux:
+        deallocate(plev_cas,plevh_cas)
+        
+        deallocate(z_cas,zh_cas)
+        deallocate(ap_cas,bp_cas)
+        deallocate(t_cas,q_cas,qv_cas,ql_cas,qi_cas,rh_cas)
+        deallocate(th_cas,thl_cas,thv_cas,rv_cas)
+        deallocate(u_cas,v_cas,vitw_cas,omega_cas)
+        
+!forcing
+        deallocate(ht_cas,vt_cas,dt_cas,dtrad_cas)
+        deallocate(hq_cas,vq_cas,dq_cas)
+        deallocate(hth_cas,vth_cas,dth_cas)
+        deallocate(hr_cas,vr_cas,dr_cas)
+        deallocate(hu_cas,vu_cas,du_cas)
+        deallocate(hv_cas,vv_cas,dv_cas)
+        deallocate(ug_cas)
+        deallocate(vg_cas)
+        deallocate(lat_cas,sens_cas,ts_cas,ps_cas,ustar_cas,tke_cas,uw_cas,vw_cas,q1_cas,q2_cas)
+
+!champs interpoles
+        deallocate(plev_prof_cas)
+        deallocate(t_prof_cas)
+        deallocate(theta_prof_cas)
+        deallocate(thl_prof_cas)
+        deallocate(thv_prof_cas)
+        deallocate(q_prof_cas)
+        deallocate(qv_prof_cas)
+        deallocate(ql_prof_cas)
+        deallocate(qi_prof_cas)
+        deallocate(rh_prof_cas)
+        deallocate(rv_prof_cas)
+        deallocate(u_prof_cas)
+        deallocate(v_prof_cas)
+        deallocate(vitw_prof_cas)
+        deallocate(omega_prof_cas)
+        deallocate(ug_prof_cas)
+        deallocate(vg_prof_cas)
+        deallocate(temp_nudg_prof_cas,qv_nudg_prof_cas,u_nudg_prof_cas,v_nudg_prof_cas)
+        deallocate(ht_prof_cas)
+        deallocate(hq_prof_cas)
+        deallocate(hu_prof_cas)
+        deallocate(hv_prof_cas)
+        deallocate(vt_prof_cas)
+        deallocate(vq_prof_cas)
+        deallocate(vu_prof_cas)
+        deallocate(vv_prof_cas)
+        deallocate(dt_prof_cas)
+        deallocate(dtrad_prof_cas)
+        deallocate(dq_prof_cas)
+        deallocate(du_prof_cas)
+        deallocate(dv_prof_cas)
+        deallocate(t_prof_cas)
+        deallocate(u_prof_cas)
+        deallocate(v_prof_cas)
+        deallocate(uw_prof_cas)
+        deallocate(vw_prof_cas)
+        deallocate(q1_prof_cas)
+        deallocate(q2_prof_cas)
+
+END SUBROUTINE deallocate2_1D_cases
+
+
+!=====================================================================
+      SUBROUTINE read_SCM(nid,nlevel,ntime,                                       &
+     &     ap,bp,zz,pp,zzh,pph,temp,theta,thv,thl,qv,ql,qi,rh,rv,u,v,vitw,omega,ug,vg,&
+     &     temp_nudg,qv_nudg,u_nudg,v_nudg,                                        &
+     &     du,hu,vu,dv,hv,vv,dt,ht,vt,dq,hq,vq,                                    &
+     &     dth,hth,vth,dr,hr,vr,dtrad,sens,flat,ts,ps,ustar,tke,uw,vw,q1,q2,       &
+     &     orog_cas,albedo_cas,emiss_cas,t_skin_cas,q_skin_cas,mom_rough,          &
+     &     heat_rough,o3_cas,rugos_cas,clay_cas,sand_cas)
+
+!program reading forcing of the case study
+      implicit none
+#include "netcdf.inc"
+#include "compar1d.h"
+
+      integer ntime,nlevel,k,t
+
+      real ap(nlevel+1),bp(nlevel+1)
+      real zz(nlevel,ntime),zzh(nlevel+1)
+      real pp(nlevel,ntime),pph(nlevel+1)
+!profils initiaux
+      real temp0(nlevel),qv0(nlevel),ql0(nlevel),qi0(nlevel),u0(nlevel),v0(nlevel),tke0(nlevel)
+      real pp0(nlevel)    
+      real temp(nlevel,ntime),qv(nlevel,ntime),ql(nlevel,ntime),qi(nlevel,ntime),rh(nlevel,ntime)
+      real theta(nlevel,ntime),thv(nlevel,ntime),thl(nlevel,ntime),rv(nlevel,ntime)
+      real u(nlevel,ntime),v(nlevel,ntime),tke(nlevel,ntime)
+      real temp_nudg(nlevel,ntime),qv_nudg(nlevel,ntime),u_nudg(nlevel,ntime),v_nudg(nlevel,ntime)
+      real ug(nlevel,ntime),vg(nlevel,ntime)
+      real vitw(nlevel,ntime),omega(nlevel,ntime)
+      real du(nlevel,ntime),hu(nlevel,ntime),vu(nlevel,ntime)
+      real dv(nlevel,ntime),hv(nlevel,ntime),vv(nlevel,ntime)
+      real dt(nlevel,ntime),ht(nlevel,ntime),vt(nlevel,ntime)
+      real dtrad(nlevel,ntime)
+      real dq(nlevel,ntime),hq(nlevel,ntime),vq(nlevel,ntime)
+      real dth(nlevel,ntime),hth(nlevel,ntime),vth(nlevel,ntime),hthl(nlevel,ntime)
+      real dr(nlevel,ntime),hr(nlevel,ntime),vr(nlevel,ntime)
+      real flat(ntime),sens(ntime),ustar(ntime)
+      real uw(nlevel,ntime),vw(nlevel,ntime),q1(nlevel,ntime),q2(nlevel,ntime)
+      real ts(ntime),ps(ntime)
+      real orog_cas,albedo_cas,emiss_cas,t_skin_cas,q_skin_cas,mom_rough,heat_rough,o3_cas,rugos_cas,clay_cas,sand_cas
+      real apbp(nlevel+1),resul(nlevel,ntime),resul1(nlevel),resul2(ntime),resul3
+
+
+      integer nid, ierr,ierr1,ierr2,rid,i
+      integer nbvar3d
+      parameter(nbvar3d=74)
+      integer var3didin(nbvar3d),missing_var(nbvar3d)
+      character*13 name_var(1:nbvar3d)
+
+
+      data name_var/ &
+     ! coordonnees pression (n+1 niveaux) #4
+     & 'coor_par_a','coor_par_b','height_h','pressure_h',& ! #1-#4
+     ! coordonnees pression (n niveaux) #8
+     &'temp','qv','ql','qi','u','v','tke','pressure',& ! #5-#12
+     ! coordonnees pression + temps #42
+     &'w','omega','ug','vg','uadv','uadvh','uadvv','vadv','vadvh','vadvv','tadv','tadvh','tadvv',& !  #13 - #25
+     &'qvadv','qvadvh','qvadvv','thadv','thadvh','thadvv','thladvh',                             & ! #26 - #33
+     & 'radv','radvh','radvv','radcool','q1','q2','ustress','vstress',                           & ! #34 - #41
+     & 'rh','temp_nudg','qv_nudg','u_nudg','v_nudg',&
+     &'height_f','pressure_forc','tempt','theta','thv','thl','qvt','qlt','qit','rv','ut','vt','tket',&
+     ! coordonnees temps #12
+     &'sfc_sens_flx','sfc_lat_flx','ts','ps','ustar',&
+     &'orog','albedo','emiss','t_skin','q_skin','mom_rough','heat_rough',&
+     ! scalaires #4
+     &'o3','rugos','clay','sand'/
+
+      do i=1,nbvar3d
+        missing_var(i)=0.
+      enddo
+
+!-----------------------------------------------------------------------
+
+       do i=1,nbvar3d
+         ierr=NF_INQ_VARID(nid,name_var(i),var3didin(i)) 
+         if(ierr/=NF_NOERR) then
+           print *,'Variable manquante dans cas.nc:',i,name_var(i)
+           ierr=NF_NOERR
+           missing_var(i)=1
+         else
+
+!-----------------------------------------------------------------------
+! Activation de quelques cles en fonction des variables disponibles
+!-----------------------------------------------------------------------
+if ( 1 == 1 ) THEN
+            if ( name_var(i) == 'temp_nudg' .and. nint(nudging_t)==0) stop 'Nudging inconsistency temp'
+            if ( name_var(i) == 'qv_nudg' .and. nint(nudging_qv)==0) stop 'Nudging inconsistency qv'
+            if ( name_var(i) == 'u_nudg' .and. nint(nudging_u)==0) stop 'Nudging inconsistency u'
+            if ( name_var(i) == 'v_nudg' .and. nint(nudging_u)==0) stop 'Nudging inconsistency v'
+    ELSE
+             print*,'GUIDAGE : CONSISTENCY CHECK DEACTIVATED FOR TESTS of SANDU/REF'
+    ENDIF
+
+!-----------------------------------------------------------------------
+           if(i.LE.4) then     ! Lecture des coord pression en (nlevelp1,lat,lon)
+#ifdef NC_DOUBLE
+           ierr = NF_GET_VAR_DOUBLE(nid,var3didin(i),apbp)
+#else
+           ierr = NF_GET_VAR_REAL(nid,var3didin(i),apbp)
+#endif
+           print *,'read2_cas(apbp), on a lu ',i,name_var(i)
+           if(ierr/=NF_NOERR) then
+              print *,'Pb a la lecture de cas.nc: ',name_var(i)
+              stop "getvarup"
+           endif
+!-----------------------------------------------------------------------
+           else if(i.gt.4.and.i.LE.12) then   ! Lecture des variables en (time,nlevel,lat,lon)
+#ifdef NC_DOUBLE
+           ierr = NF_GET_VAR_DOUBLE(nid,var3didin(i),resul1)
+#else
+           ierr = NF_GET_VAR_REAL(nid,var3didin(i),resul1)
+#endif
+           print *,'read2_cas(resul1), on a lu ',i,name_var(i)
+           if(ierr/=NF_NOERR) then
+              print *,'Pb a la lecture de cas.nc: ',name_var(i)
+              stop "getvarup"
+           endif
+         print*,'Lecture de la variable #i ',i,name_var(i),minval(resul1),maxval(resul1)
+!-----------------------------------------------------------------------
+           else if(i.gt.12.and.i.LE.54) then   ! Lecture des variables en (time,nlevel,lat,lon)
+#ifdef NC_DOUBLE
+           ierr = NF_GET_VAR_DOUBLE(nid,var3didin(i),resul)
+#else
+           ierr = NF_GET_VAR_REAL(nid,var3didin(i),resul)
+#endif
+           print *,'read2_cas(resul), on a lu ',i,name_var(i)
+           if(ierr/=NF_NOERR) then
+              print *,'Pb a la lecture de cas.nc: ',name_var(i)
+              stop "getvarup"
+           endif
+
+         print*,'Lecture de la variable #i ',i,name_var(i),minval(resul),maxval(resul)
+!-----------------------------------------------------------------------
+           else if (i.gt.54.and.i.LE.65) then   ! Lecture des variables en (time,lat,lon)
+#ifdef NC_DOUBLE
+           ierr = NF_GET_VAR_DOUBLE(nid,var3didin(i),resul2)
+#else
+           ierr = NF_GET_VAR_REAL(nid,var3didin(i),resul2)
+#endif
+           print *,'read2_cas(resul2), on a lu ',i,name_var(i)
+           if(ierr/=NF_NOERR) then
+              print *,'Pb a la lecture de cas.nc: ',name_var(i)
+              stop "getvarup"
+           endif
+         print*,'Lecture de la variable #i  ',i,name_var(i),minval(resul2),maxval(resul2)
+!-----------------------------------------------------------------------
+           else     ! Lecture des constantes (lat,lon)
+#ifdef NC_DOUBLE
+           ierr = NF_GET_VAR_DOUBLE(nid,var3didin(i),resul3)
+#else
+           ierr = NF_GET_VAR_REAL(nid,var3didin(i),resul3)
+#endif
+           print *,'read2_cas(resul3), on a lu ',i,name_var(i)
+           if(ierr/=NF_NOERR) then
+              print *,'Pb a la lecture de cas.nc: ',name_var(i)
+              stop "getvarup"
+           endif
+         print*,'Lecture de la variable #i ',i,name_var(i),resul3
+           endif
+         endif
+!-----------------------------------------------------------------------
+         select case(i)
+         !case(1) ; ap=apbp       ! donnees indexees en nlevel+1
+         ! case(2) ; bp=apbp
+           case(3) ; zzh=apbp
+           case(4) ; pph=apbp
+           case(5) ; temp0=resul1    ! donnees initiales
+           case(6) ; qv0=resul1
+           case(7) ; ql0=resul1
+           case(8) ; qi0=resul1
+           case(9) ; u0=resul1
+           case(10) ; v0=resul1
+           case(11) ; tke0=resul1
+           case(12) ; pp0=resul1
+           case(13) ; vitw=resul    ! donnees indexees en nlevel,time
+           case(14) ; omega=resul
+           case(15) ; ug=resul
+           case(16) ; vg=resul
+           case(17) ; du=resul
+           case(18) ; hu=resul
+           case(19) ; vu=resul
+           case(20) ; dv=resul
+           case(21) ; hv=resul
+           case(22) ; vv=resul
+           case(23) ; dt=resul
+           case(24) ; ht=resul
+           case(25) ; vt=resul
+           case(26) ; dq=resul
+           case(27) ; hq=resul
+           case(28) ; vq=resul
+           case(29) ; dth=resul
+           case(30) ; hth=resul
+           case(31) ; vth=resul
+           case(32) ; hthl=resul
+           case(33) ; dr=resul
+           case(34) ; hr=resul
+           case(35) ; vr=resul
+           case(36) ; dtrad=resul
+           case(37) ; q1=resul
+           case(38) ; q2=resul
+           case(39) ; uw=resul
+           case(40) ; vw=resul
+           case(41) ; rh=resul
+           case(42) ; temp_nudg=resul
+           case(43) ; qv_nudg=resul
+           case(44) ; u_nudg=resul
+           case(45) ; v_nudg=resul
+           case(46) ; zz=resul      ! donnees en time,nlevel pour profil initial
+           case(47) ; pp=resul
+           case(48) ; temp=resul
+           case(49) ; theta=resul
+           case(50) ; thv=resul
+           case(51) ; thl=resul
+           case(52) ; qv=resul
+           case(53) ; ql=resul
+           case(54) ; qi=resul
+           case(55) ; rv=resul
+           case(56) ; u=resul
+           case(57) ; v=resul
+           case(58) ; tke=resul
+           case(59) ; sens=resul2   ! donnees indexees en time
+           case(60) ; flat=resul2
+           case(61) ; ts=resul2
+           case(62) ; ps=resul2
+           case(63) ; ustar=resul2
+           case(64) ; orog_cas=resul3      ! constantes
+           case(65) ; albedo_cas=resul3
+           case(66) ; emiss_cas=resul3
+           case(67) ; t_skin_cas=resul3
+           case(68) ; q_skin_cas=resul3
+           case(69) ; mom_rough=resul3
+           case(70) ; heat_rough=resul3
+           case(71) ; o3_cas=resul3        
+           case(72) ; rugos_cas=resul3
+           case(73) ; clay_cas=resul3
+           case(74) ; sand_cas=resul3
+         end select
+         resul=0.
+         resul1=0.
+         resul2=0.
+         resul3=0.
+       enddo
+         print*,'Lecture de la variable APRES ,sens ',minval(sens),maxval(sens)
+         print*,'Lecture de la variable APRES ,flat ',minval(flat),maxval(flat)
+
+!CR:ATTENTION EN ATTENTE DE REGLER LA QUESTION DU PAS DE TEMPS INITIAL
+       do t=1,ntime
+          do k=1,nlevel
+             temp(k,t)=temp0(k)
+             qv(k,t)=qv0(k)
+             ql(k,t)=ql0(k)
+             qi(k,t)=qi0(k)
+             u(k,t)=u0(k)
+             v(k,t)=v0(k)
+             tke(k,t)=tke0(k)
+          enddo
+       enddo
+       !!!! TRAVAIL : EN FONCTION DES DECISIONS SUR LA SPECIFICATION DE W
+       !!!omega=-vitw*pres*rg/(rd*temp)
+!-----------------------------------------------------------------------
+
+         return 
+         END SUBROUTINE read_SCM
+!======================================================================
+
+!======================================================================
+
+!**********************************************************************************************
+        SUBROUTINE interp_case_time_std(day,day1,annee_ref                           &
+!    &         ,year_cas,day_cas,nt_cas,pdt_forc,nlev_cas                         &
+     &         ,nt_cas,nlev_cas                                                   &
+     &         ,ts_cas,ps_cas,plev_cas,t_cas,theta_cas,thv_cas,thl_cas            &
+     &         ,qv_cas,ql_cas,qi_cas,u_cas,v_cas                                  &
+     &         ,ug_cas,vg_cas,temp_nudg_cas,qv_nudg_cas,u_nudg_cas,v_nudg_cas     &
+     &         ,vitw_cas,omega_cas,du_cas,hu_cas,vu_cas             &
+     &         ,dv_cas,hv_cas,vv_cas,dt_cas,ht_cas,vt_cas,dtrad_cas               &
+     &         ,dq_cas,hq_cas,vq_cas,dth_cas,hth_cas,vth_cas                      &
+     &         ,lat_cas,sens_cas,ustar_cas                                        &
+     &         ,uw_cas,vw_cas,q1_cas,q2_cas,tke_cas                               &
+!
+     &         ,ts_prof_cas,ps_prof_cas,plev_prof_cas,t_prof_cas,theta_prof_cas               &
+     &         ,thv_prof_cas,thl_prof_cas,qv_prof_cas,ql_prof_cas,qi_prof_cas     &
+     &         ,u_prof_cas,v_prof_cas,ug_prof_cas,vg_prof_cas                     &
+     &         ,temp_nudg_prof_cas,qv_nudg_prof_cas,u_nudg_prof_cas,v_nudg_prof_cas     &
+     &         ,vitw_prof_cas,omega_prof_cas,du_prof_cas,hu_prof_cas,vu_prof_cas  &
+     &         ,dv_prof_cas,hv_prof_cas,vv_prof_cas,dt_prof_cas                   &
+     &         ,ht_prof_cas,vt_prof_cas,dtrad_prof_cas,dq_prof_cas                &
+     &         ,hq_prof_cas,vq_prof_cas,dth_prof_cas,hth_prof_cas,vth_prof_cas    &
+     &         ,lat_prof_cas,sens_prof_cas                                        &
+     &         ,ustar_prof_cas,uw_prof_cas,vw_prof_cas,q1_prof_cas,q2_prof_cas,tke_prof_cas)
+          
+
+        implicit none
+
+!---------------------------------------------------------------------------------------
+! Time interpolation of a 2D field to the timestep corresponding to day
+!
+! day: current julian day (e.g. 717538.2)
+! day1: first day of the simulation
+! nt_cas: total nb of data in the forcing 
+! pdt_cas: total time interval (in sec) between 2 forcing data
+!---------------------------------------------------------------------------------------
+
+#include "compar1d.h"
+#include "date_cas.h"
+
+! inputs:
+        integer annee_ref
+        integer nt_cas,nlev_cas
+        real day, day1,day_cas
+        real ts_cas(nt_cas),ps_cas(nt_cas)
+        real plev_cas(nlev_cas,nt_cas)
+        real t_cas(nlev_cas,nt_cas),theta_cas(nlev_cas,nt_cas),thv_cas(nlev_cas,nt_cas),thl_cas(nlev_cas,nt_cas)
+        real qv_cas(nlev_cas,nt_cas),ql_cas(nlev_cas,nt_cas),qi_cas(nlev_cas,nt_cas)
+        real u_cas(nlev_cas,nt_cas),v_cas(nlev_cas,nt_cas)
+        real ug_cas(nlev_cas,nt_cas),vg_cas(nlev_cas,nt_cas)
+        real temp_nudg_cas(nlev_cas,nt_cas),qv_nudg_cas(nlev_cas,nt_cas)
+        real u_nudg_cas(nlev_cas,nt_cas),v_nudg_cas(nlev_cas,nt_cas)
+
+        real vitw_cas(nlev_cas,nt_cas),omega_cas(nlev_cas,nt_cas)
+        real du_cas(nlev_cas,nt_cas),hu_cas(nlev_cas,nt_cas),vu_cas(nlev_cas,nt_cas)
+        real dv_cas(nlev_cas,nt_cas),hv_cas(nlev_cas,nt_cas),vv_cas(nlev_cas,nt_cas)
+        real dt_cas(nlev_cas,nt_cas),ht_cas(nlev_cas,nt_cas),vt_cas(nlev_cas,nt_cas)
+        real dth_cas(nlev_cas,nt_cas),hth_cas(nlev_cas,nt_cas),vth_cas(nlev_cas,nt_cas)
+        real dtrad_cas(nlev_cas,nt_cas)
+        real dq_cas(nlev_cas,nt_cas),hq_cas(nlev_cas,nt_cas),vq_cas(nlev_cas,nt_cas)
+        real lat_cas(nt_cas),sens_cas(nt_cas),tke_cas(nt_cas)
+        real ustar_cas(nt_cas),uw_cas(nlev_cas,nt_cas),vw_cas(nlev_cas,nt_cas)
+        real q1_cas(nlev_cas,nt_cas),q2_cas(nlev_cas,nt_cas)
+
+! outputs:
+        real plev_prof_cas(nlev_cas)
+        real t_prof_cas(nlev_cas),theta_prof_cas(nlev_cas),thl_prof_cas(nlev_cas),thv_prof_cas(nlev_cas)
+        real qv_prof_cas(nlev_cas),ql_prof_cas(nlev_cas),qi_prof_cas(nlev_cas)
+        real u_prof_cas(nlev_cas),v_prof_cas(nlev_cas)
+        real ug_prof_cas(nlev_cas),vg_prof_cas(nlev_cas)
+        real temp_nudg_prof_cas(nlev_cas),qv_nudg_prof_cas(nlev_cas)
+        real u_nudg_prof_cas(nlev_cas),v_nudg_prof_cas(nlev_cas)
+
+        real vitw_prof_cas(nlev_cas),omega_prof_cas(nlev_cas)
+        real du_prof_cas(nlev_cas),hu_prof_cas(nlev_cas),vu_prof_cas(nlev_cas)
+        real dv_prof_cas(nlev_cas),hv_prof_cas(nlev_cas),vv_prof_cas(nlev_cas)
+        real dt_prof_cas(nlev_cas),ht_prof_cas(nlev_cas),vt_prof_cas(nlev_cas)
+        real dth_prof_cas(nlev_cas),hth_prof_cas(nlev_cas),vth_prof_cas(nlev_cas)
+        real dtrad_prof_cas(nlev_cas)
+        real dq_prof_cas(nlev_cas),hq_prof_cas(nlev_cas),vq_prof_cas(nlev_cas)
+        real lat_prof_cas,sens_prof_cas,tke_prof_cas,ts_prof_cas,ps_prof_cas,ustar_prof_cas
+        real uw_prof_cas(nlev_cas),vw_prof_cas(nlev_cas),q1_prof_cas(nlev_cas),q2_prof_cas(nlev_cas)
+! local:
+        integer it_cas1, it_cas2,k
+        real timeit,time_cas1,time_cas2,frac
+
+
+        print*,'Check time',day1,day_ju_ini_cas,day_deb+1,pdt_cas
+!       do k=1,nlev_cas
+!       print*,'debut de interp2_case_time, plev_cas=',k,plev_cas(k,1)
+!       enddo
+
+! On teste si la date du cas AMMA est correcte.
+! C est pour memoire car en fait les fichiers .def
+! sont censes etre corrects.
+! A supprimer a terme (MPL 20150623)
+!     if ((forcing_type.eq.10).and.(1.eq.0)) then
+! Check that initial day of the simulation consistent with AMMA case:
+!      if (annee_ref.ne.2006) then
+!       print*,'Pour AMMA, annee_ref doit etre 2006'
+!       print*,'Changer annee_ref dans run.def'
+!       stop
+!      endif
+!      if (annee_ref.eq.2006 .and. day1.lt.day_cas) then
+!       print*,'AMMA a debute le 10 juillet 2006',day1,day_cas
+!       print*,'Changer dayref dans run.def'
+!       stop
+!      endif
+!      if (annee_ref.eq.2006 .and. day1.gt.day_cas+1) then
+!       print*,'AMMA a fini le 11 juillet'
+!       print*,'Changer dayref ou nday dans run.def'
+!       stop
+!      endif
+!      endif
+
+! Determine timestep relative to the 1st day:
+!       timeit=(day-day1)*86400.
+!       if (annee_ref.eq.1992) then
+!        timeit=(day-day_cas)*86400.
+!       else
+!        timeit=(day+61.-1.)*86400. ! 61 days between Nov01 and Dec31 1992
+!       endif
+      timeit=(day-day_ju_ini_cas)*86400
+      print *,'day=',day
+      print *,'day_ju_ini_cas=',day_ju_ini_cas
+      print *,'pdt_cas=',pdt_cas
+      print *,'timeit=',timeit
+      print *,'nt_cas=',nt_cas
+
+! Determine the closest observation times:
+!       it_cas1=INT(timeit/pdt_cas)+1
+!       it_cas2=it_cas1 + 1
+!       time_cas1=(it_cas1-1)*pdt_cas
+!       time_cas2=(it_cas2-1)*pdt_cas
+
+       it_cas1=INT(timeit/pdt_cas)+1
+       IF (it_cas1 .EQ. nt_cas) THEN
+       it_cas2=it_cas1 
+       ELSE
+       it_cas2=it_cas1 + 1
+       ENDIF
+       time_cas1=(it_cas1-1)*pdt_cas
+       time_cas2=(it_cas2-1)*pdt_cas
+!     print *,'timeit,pdt_cas,nt_cas=',timeit,pdt_cas,nt_cas
+!     print *,'it_cas1,it_cas2,time_cas1,time_cas2=',it_cas1,it_cas2,time_cas1,time_cas2
+
+       if (it_cas1 .gt. nt_cas) then 
+        write(*,*) 'PB-stop: day, day_ju_ini_cas,it_cas1, it_cas2, timeit: '            &
+     &        ,day,day_ju_ini_cas,it_cas1,it_cas2,timeit
+        stop
+       endif
+
+! time interpolation:
+       IF (it_cas1 .EQ. it_cas2) THEN
+          frac=0.
+       ELSE
+          frac=(time_cas2-timeit)/(time_cas2-time_cas1)
+          frac=max(frac,0.0)
+       ENDIF
+
+       lat_prof_cas = lat_cas(it_cas2)                                   &
+     &          -frac*(lat_cas(it_cas2)-lat_cas(it_cas1)) 
+       sens_prof_cas = sens_cas(it_cas2)                                 &
+     &          -frac*(sens_cas(it_cas2)-sens_cas(it_cas1))
+       tke_prof_cas = tke_cas(it_cas2)                                   &
+     &          -frac*(tke_cas(it_cas2)-tke_cas(it_cas1))
+       ts_prof_cas = ts_cas(it_cas2)                                     &
+     &          -frac*(ts_cas(it_cas2)-ts_cas(it_cas1))
+       ps_prof_cas = ps_cas(it_cas2)                                     &
+     &          -frac*(ps_cas(it_cas2)-ps_cas(it_cas1))
+       ustar_prof_cas = ustar_cas(it_cas2)                               &
+     &          -frac*(ustar_cas(it_cas2)-ustar_cas(it_cas1))
+
+       do k=1,nlev_cas
+        plev_prof_cas(k) = plev_cas(k,it_cas2)                           &     
+     &          -frac*(plev_cas(k,it_cas2)-plev_cas(k,it_cas1))
+        t_prof_cas(k) = t_cas(k,it_cas2)                                 &        
+     &          -frac*(t_cas(k,it_cas2)-t_cas(k,it_cas1))
+        !print *,'k,frac,plev_cas1,plev_cas2=',k,frac,plev_cas(k,it_cas1),plev_cas(k,it_cas2)
+        theta_prof_cas(k) = theta_cas(k,it_cas2)                         &                      
+     &          -frac*(theta_cas(k,it_cas2)-theta_cas(k,it_cas1))
+        thv_prof_cas(k) = thv_cas(k,it_cas2)                             &          
+     &          -frac*(thv_cas(k,it_cas2)-thv_cas(k,it_cas1))
+        thl_prof_cas(k) = thl_cas(k,it_cas2)                             &              
+     &          -frac*(thl_cas(k,it_cas2)-thl_cas(k,it_cas1))
+        qv_prof_cas(k) = qv_cas(k,it_cas2)                               &
+     &          -frac*(qv_cas(k,it_cas2)-qv_cas(k,it_cas1))
+        ql_prof_cas(k) = ql_cas(k,it_cas2)                               &
+     &          -frac*(ql_cas(k,it_cas2)-ql_cas(k,it_cas1))
+        qi_prof_cas(k) = qi_cas(k,it_cas2)                               &
+     &          -frac*(qi_cas(k,it_cas2)-qi_cas(k,it_cas1))
+        u_prof_cas(k) = u_cas(k,it_cas2)                                 &
+     &          -frac*(u_cas(k,it_cas2)-u_cas(k,it_cas1))
+        v_prof_cas(k) = v_cas(k,it_cas2)                                 &
+     &          -frac*(v_cas(k,it_cas2)-v_cas(k,it_cas1))
+        ug_prof_cas(k) = ug_cas(k,it_cas2)                               &
+     &          -frac*(ug_cas(k,it_cas2)-ug_cas(k,it_cas1))
+        vg_prof_cas(k) = vg_cas(k,it_cas2)                               &
+     &          -frac*(vg_cas(k,it_cas2)-vg_cas(k,it_cas1))
+        temp_nudg_prof_cas(k) = temp_nudg_cas(k,it_cas2)                    &
+     &          -frac*(temp_nudg_cas(k,it_cas2)-temp_nudg_cas(k,it_cas1))
+        qv_nudg_prof_cas(k) = qv_nudg_cas(k,it_cas2)                        &
+     &          -frac*(qv_nudg_cas(k,it_cas2)-qv_nudg_cas(k,it_cas1))
+        u_nudg_prof_cas(k) = u_nudg_cas(k,it_cas2)                          &
+     &          -frac*(u_nudg_cas(k,it_cas2)-u_nudg_cas(k,it_cas1))
+        v_nudg_prof_cas(k) = v_nudg_cas(k,it_cas2)                          &
+     &          -frac*(v_nudg_cas(k,it_cas2)-v_nudg_cas(k,it_cas1))
+        vitw_prof_cas(k) = vitw_cas(k,it_cas2)                           &
+     &          -frac*(vitw_cas(k,it_cas2)-vitw_cas(k,it_cas1))
+        omega_prof_cas(k) = omega_cas(k,it_cas2)                         &
+     &          -frac*(omega_cas(k,it_cas2)-omega_cas(k,it_cas1))
+        du_prof_cas(k) = du_cas(k,it_cas2)                               &
+     &          -frac*(du_cas(k,it_cas2)-du_cas(k,it_cas1))
+        hu_prof_cas(k) = hu_cas(k,it_cas2)                               &
+     &          -frac*(hu_cas(k,it_cas2)-hu_cas(k,it_cas1))
+        vu_prof_cas(k) = vu_cas(k,it_cas2)                               &
+     &          -frac*(vu_cas(k,it_cas2)-vu_cas(k,it_cas1))
+        dv_prof_cas(k) = dv_cas(k,it_cas2)                               &
+     &          -frac*(dv_cas(k,it_cas2)-dv_cas(k,it_cas1))
+        hv_prof_cas(k) = hv_cas(k,it_cas2)                               &
+     &          -frac*(hv_cas(k,it_cas2)-hv_cas(k,it_cas1))
+        vv_prof_cas(k) = vv_cas(k,it_cas2)                               &
+     &          -frac*(vv_cas(k,it_cas2)-vv_cas(k,it_cas1))
+        dt_prof_cas(k) = dt_cas(k,it_cas2)                               &
+     &          -frac*(dt_cas(k,it_cas2)-dt_cas(k,it_cas1))
+        ht_prof_cas(k) = ht_cas(k,it_cas2)                               &
+     &          -frac*(ht_cas(k,it_cas2)-ht_cas(k,it_cas1))
+        vt_prof_cas(k) = vt_cas(k,it_cas2)                               &
+     &          -frac*(vt_cas(k,it_cas2)-vt_cas(k,it_cas1))
+        dth_prof_cas(k) = dth_cas(k,it_cas2)                             &
+     &          -frac*(dth_cas(k,it_cas2)-dth_cas(k,it_cas1))
+        hth_prof_cas(k) = hth_cas(k,it_cas2)                             &
+     &          -frac*(hth_cas(k,it_cas2)-hth_cas(k,it_cas1))
+        vth_prof_cas(k) = vth_cas(k,it_cas2)                             &
+     &          -frac*(vth_cas(k,it_cas2)-vth_cas(k,it_cas1))
+        dtrad_prof_cas(k) = dtrad_cas(k,it_cas2)                         &
+     &          -frac*(dtrad_cas(k,it_cas2)-dtrad_cas(k,it_cas1))
+        dq_prof_cas(k) = dq_cas(k,it_cas2)                               &
+     &          -frac*(dq_cas(k,it_cas2)-dq_cas(k,it_cas1))
+        hq_prof_cas(k) = hq_cas(k,it_cas2)                               &
+     &          -frac*(hq_cas(k,it_cas2)-hq_cas(k,it_cas1))
+        vq_prof_cas(k) = vq_cas(k,it_cas2)                               &
+     &          -frac*(vq_cas(k,it_cas2)-vq_cas(k,it_cas1))
+       uw_prof_cas(k) = uw_cas(k,it_cas2)                                &
+     &          -frac*(uw_cas(k,it_cas2)-uw_cas(k,it_cas1))
+       vw_prof_cas(k) = vw_cas(k,it_cas2)                                &
+     &          -frac*(vw_cas(k,it_cas2)-vw_cas(k,it_cas1))
+       q1_prof_cas(k) = q1_cas(k,it_cas2)                                &
+     &          -frac*(q1_cas(k,it_cas2)-q1_cas(k,it_cas1))
+       q2_prof_cas(k) = q2_cas(k,it_cas2)                                &
+     &          -frac*(q2_cas(k,it_cas2)-q2_cas(k,it_cas1))
+        enddo
+
+        return
+        END SUBROUTINE interp_case_time_std
+
+!**********************************************************************************************
+!=====================================================================
+       SUBROUTINE interp2_case_vertical_std(play,nlev_cas,plev_prof_cas                                &
+     &         ,t_prof_cas,th_prof_cas,thv_prof_cas,thl_prof_cas                                       &
+     &         ,qv_prof_cas,ql_prof_cas,qi_prof_cas,u_prof_cas,v_prof_cas                              &
+     &         ,ug_prof_cas,vg_prof_cas                                                                &
+     &         ,temp_nudg_prof_cas,qv_nudg_prof_cas,u_nudg_prof_cas,v_nudg_prof_cas                    &
+     &         ,vitw_prof_cas,omega_prof_cas                                                           &
+     &         ,du_prof_cas,hu_prof_cas,vu_prof_cas,dv_prof_cas,hv_prof_cas,vv_prof_cas                &
+     &         ,dt_prof_cas,ht_prof_cas,vt_prof_cas,dtrad_prof_cas,dq_prof_cas,hq_prof_cas,vq_prof_cas &
+     &         ,dth_prof_cas,hth_prof_cas,vth_prof_cas                                                 &
+!
+     &         ,t_mod_cas,theta_mod_cas,thv_mod_cas,thl_mod_cas                                        &
+     &         ,qv_mod_cas,ql_mod_cas,qi_mod_cas,u_mod_cas,v_mod_cas                                   &
+     &         ,ug_mod_cas,vg_mod_cas                                                                  &
+     &         ,temp_nudg_mod_cas,qv_nudg_mod_cas,u_nudg_mod_cas,v_nudg_mod_cas                        &
+     &         ,w_mod_cas,omega_mod_cas                                                                &
+     &         ,du_mod_cas,hu_mod_cas,vu_mod_cas,dv_mod_cas,hv_mod_cas,vv_mod_cas                      &
+     &         ,dt_mod_cas,ht_mod_cas,vt_mod_cas,dtrad_mod_cas,dq_mod_cas,hq_mod_cas,vq_mod_cas        &
+     &         ,dth_mod_cas,hth_mod_cas,vth_mod_cas,mxcalc)
+ 
+       implicit none
+ 
+#include "YOMCST.h"
+#include "dimensions.h"
+
+!-------------------------------------------------------------------------
+! Vertical interpolation of generic case forcing data onto mod_casel levels
+!-------------------------------------------------------------------------
+ 
+       integer nlevmax
+       parameter (nlevmax=41)
+       integer nlev_cas,mxcalc
+!       real play(llm), plev_prof(nlevmax) 
+!       real t_prof(nlevmax),q_prof(nlevmax)
+!       real u_prof(nlevmax),v_prof(nlevmax), w_prof(nlevmax)
+!       real ht_prof(nlevmax),vt_prof(nlevmax)
+!       real hq_prof(nlevmax),vq_prof(nlevmax)
+ 
+       real play(llm), plev_prof_cas(nlev_cas) 
+       real t_prof_cas(nlev_cas),th_prof_cas(nlev_cas),thv_prof_cas(nlev_cas),thl_prof_cas(nlev_cas)
+       real qv_prof_cas(nlev_cas),ql_prof_cas(nlev_cas),qi_prof_cas(nlev_cas)
+       real u_prof_cas(nlev_cas),v_prof_cas(nlev_cas)
+       real ug_prof_cas(nlev_cas),vg_prof_cas(nlev_cas), vitw_prof_cas(nlev_cas),omega_prof_cas(nlev_cas)
+       real temp_nudg_prof_cas(nlev_cas),qv_nudg_prof_cas(nlev_cas)
+       real u_nudg_prof_cas(nlev_cas),v_nudg_prof_cas(nlev_cas)
+
+       real du_prof_cas(nlev_cas),hu_prof_cas(nlev_cas),vu_prof_cas(nlev_cas)
+       real dv_prof_cas(nlev_cas),hv_prof_cas(nlev_cas),vv_prof_cas(nlev_cas)
+       real dt_prof_cas(nlev_cas),ht_prof_cas(nlev_cas),vt_prof_cas(nlev_cas),dtrad_prof_cas(nlev_cas)
+       real dth_prof_cas(nlev_cas),hth_prof_cas(nlev_cas),vth_prof_cas(nlev_cas)
+       real dq_prof_cas(nlev_cas),hq_prof_cas(nlev_cas),vq_prof_cas(nlev_cas)
+ 
+       real t_mod_cas(llm),theta_mod_cas(llm),thv_mod_cas(llm),thl_mod_cas(llm)
+       real qv_mod_cas(llm),ql_mod_cas(llm),qi_mod_cas(llm)
+       real u_mod_cas(llm),v_mod_cas(llm)
+       real ug_mod_cas(llm),vg_mod_cas(llm), w_mod_cas(llm),omega_mod_cas(llm)
+       real temp_nudg_mod_cas(llm),qv_nudg_mod_cas(llm)
+       real u_nudg_mod_cas(llm),v_nudg_mod_cas(llm)
+       real du_mod_cas(llm),hu_mod_cas(llm),vu_mod_cas(llm)
+       real dv_mod_cas(llm),hv_mod_cas(llm),vv_mod_cas(llm)
+       real dt_mod_cas(llm),ht_mod_cas(llm),vt_mod_cas(llm),dtrad_mod_cas(llm)
+       real dth_mod_cas(llm),hth_mod_cas(llm),vth_mod_cas(llm)
+       real dq_mod_cas(llm),hq_mod_cas(llm),vq_mod_cas(llm)
+ 
+       integer l,k,k1,k2
+       real frac,frac1,frac2,fact
+ 
+!       do l = 1, llm
+!       print *,'debut interp2, play=',l,play(l)
+!       enddo
+!      do l = 1, nlev_cas
+!      print *,'debut interp2, plev_prof_cas=',l,play(l),plev_prof_cas(l)
+!      enddo
+
+       do l = 1, llm
+
+        if (play(l).ge.plev_prof_cas(nlev_cas)) then
+ 
+        mxcalc=l
+!        print *,'debut interp2, mxcalc=',mxcalc
+         k1=0
+         k2=0
+
+         if (play(l).le.plev_prof_cas(1)) then
+
+         do k = 1, nlev_cas-1
+          if (play(l).le.plev_prof_cas(k).and. play(l).gt.plev_prof_cas(k+1)) then
+            k1=k
+            k2=k+1
+          endif
+         enddo
+
+         if (k1.eq.0 .or. k2.eq.0) then
+          write(*,*) 'PB! k1, k2 = ',k1,k2
+          write(*,*) 'l,play(l) = ',l,play(l)/100
+         do k = 1, nlev_cas-1
+          write(*,*) 'k,plev_prof_cas(k) = ',k,plev_prof_cas(k)/100
+         enddo
+         endif
+
+         frac = (plev_prof_cas(k2)-play(l))/(plev_prof_cas(k2)-plev_prof_cas(k1))
+         t_mod_cas(l)= t_prof_cas(k2) - frac*(t_prof_cas(k2)-t_prof_cas(k1))
+         theta_mod_cas(l)= th_prof_cas(k2) - frac*(th_prof_cas(k2)-th_prof_cas(k1))
+         if(theta_mod_cas(l).NE.0) t_mod_cas(l)= theta_mod_cas(l)*(play(l)/100000.)**(RD/RCPD)
+         thv_mod_cas(l)= thv_prof_cas(k2) - frac*(thv_prof_cas(k2)-thv_prof_cas(k1))
+         thl_mod_cas(l)= thl_prof_cas(k2) - frac*(thl_prof_cas(k2)-thl_prof_cas(k1))
+         qv_mod_cas(l)= qv_prof_cas(k2) - frac*(qv_prof_cas(k2)-qv_prof_cas(k1))
+         ql_mod_cas(l)= ql_prof_cas(k2) - frac*(ql_prof_cas(k2)-ql_prof_cas(k1))
+         qi_mod_cas(l)= qi_prof_cas(k2) - frac*(qi_prof_cas(k2)-qi_prof_cas(k1))
+         u_mod_cas(l)= u_prof_cas(k2) - frac*(u_prof_cas(k2)-u_prof_cas(k1))
+         v_mod_cas(l)= v_prof_cas(k2) - frac*(v_prof_cas(k2)-v_prof_cas(k1))
+         ug_mod_cas(l)= ug_prof_cas(k2) - frac*(ug_prof_cas(k2)-ug_prof_cas(k1))
+         vg_mod_cas(l)= vg_prof_cas(k2) - frac*(vg_prof_cas(k2)-vg_prof_cas(k1))
+         temp_nudg_mod_cas(l)= temp_nudg_prof_cas(k2) - frac*(temp_nudg_prof_cas(k2)-temp_nudg_prof_cas(k1))
+         qv_nudg_mod_cas(l)= qv_nudg_prof_cas(k2) - frac*(qv_nudg_prof_cas(k2)-qv_nudg_prof_cas(k1))
+         u_nudg_mod_cas(l)= u_nudg_prof_cas(k2) - frac*(u_nudg_prof_cas(k2)-u_nudg_prof_cas(k1))
+         v_nudg_mod_cas(l)= v_nudg_prof_cas(k2) - frac*(v_nudg_prof_cas(k2)-v_nudg_prof_cas(k1))
+         w_mod_cas(l)= vitw_prof_cas(k2) - frac*(vitw_prof_cas(k2)-vitw_prof_cas(k1))
+         omega_mod_cas(l)= omega_prof_cas(k2) - frac*(omega_prof_cas(k2)-omega_prof_cas(k1))
+         du_mod_cas(l)= du_prof_cas(k2) - frac*(du_prof_cas(k2)-du_prof_cas(k1))
+         hu_mod_cas(l)= hu_prof_cas(k2) - frac*(hu_prof_cas(k2)-hu_prof_cas(k1))
+         vu_mod_cas(l)= vu_prof_cas(k2) - frac*(vu_prof_cas(k2)-vu_prof_cas(k1))
+         dv_mod_cas(l)= dv_prof_cas(k2) - frac*(dv_prof_cas(k2)-dv_prof_cas(k1))
+         hv_mod_cas(l)= hv_prof_cas(k2) - frac*(hv_prof_cas(k2)-hv_prof_cas(k1))
+         vv_mod_cas(l)= vv_prof_cas(k2) - frac*(vv_prof_cas(k2)-vv_prof_cas(k1))
+         dt_mod_cas(l)= dt_prof_cas(k2) - frac*(dt_prof_cas(k2)-dt_prof_cas(k1))
+         ht_mod_cas(l)= ht_prof_cas(k2) - frac*(ht_prof_cas(k2)-ht_prof_cas(k1))
+         vt_mod_cas(l)= vt_prof_cas(k2) - frac*(vt_prof_cas(k2)-vt_prof_cas(k1))
+         dth_mod_cas(l)= dth_prof_cas(k2) - frac*(dth_prof_cas(k2)-dth_prof_cas(k1))
+         hth_mod_cas(l)= hth_prof_cas(k2) - frac*(hth_prof_cas(k2)-hth_prof_cas(k1))
+         vth_mod_cas(l)= vth_prof_cas(k2) - frac*(vth_prof_cas(k2)-vth_prof_cas(k1))
+         dq_mod_cas(l)= dq_prof_cas(k2) - frac*(dq_prof_cas(k2)-dq_prof_cas(k1))
+         hq_mod_cas(l)= hq_prof_cas(k2) - frac*(hq_prof_cas(k2)-hq_prof_cas(k1))
+         vq_mod_cas(l)= vq_prof_cas(k2) - frac*(vq_prof_cas(k2)-vq_prof_cas(k1))
+         dtrad_mod_cas(l)= dtrad_prof_cas(k2) - frac*(dtrad_prof_cas(k2)-dtrad_prof_cas(k1))
+     
+         else !play>plev_prof_cas(1)
+
+         k1=1
+         k2=2
+         print *,'interp2_vert, k1,k2=',plev_prof_cas(k1),plev_prof_cas(k2)
+         frac1 = (play(l)-plev_prof_cas(k2))/(plev_prof_cas(k1)-plev_prof_cas(k2))
+         frac2 = (play(l)-plev_prof_cas(k1))/(plev_prof_cas(k1)-plev_prof_cas(k2))
+         t_mod_cas(l)= frac1*t_prof_cas(k1) - frac2*t_prof_cas(k2)
+         theta_mod_cas(l)= frac1*th_prof_cas(k1) - frac2*th_prof_cas(k2)
+         if(theta_mod_cas(l).NE.0) t_mod_cas(l)= theta_mod_cas(l)*(play(l)/100000.)**(RD/RCPD)
+         thv_mod_cas(l)= frac1*thv_prof_cas(k1) - frac2*thv_prof_cas(k2)
+         thl_mod_cas(l)= frac1*thl_prof_cas(k1) - frac2*thl_prof_cas(k2)
+         qv_mod_cas(l)= frac1*qv_prof_cas(k1) - frac2*qv_prof_cas(k2)
+         ql_mod_cas(l)= frac1*ql_prof_cas(k1) - frac2*ql_prof_cas(k2)
+         qi_mod_cas(l)= frac1*qi_prof_cas(k1) - frac2*qi_prof_cas(k2)
+         u_mod_cas(l)= frac1*u_prof_cas(k1) - frac2*u_prof_cas(k2)
+         v_mod_cas(l)= frac1*v_prof_cas(k1) - frac2*v_prof_cas(k2)
+         ug_mod_cas(l)= frac1*ug_prof_cas(k1) - frac2*ug_prof_cas(k2)
+         vg_mod_cas(l)= frac1*vg_prof_cas(k1) - frac2*vg_prof_cas(k2)
+         temp_nudg_mod_cas(l)= frac1*temp_nudg_prof_cas(k1) - frac2*temp_nudg_prof_cas(k2)
+         qv_nudg_mod_cas(l)= frac1*qv_nudg_prof_cas(k1) - frac2*qv_nudg_prof_cas(k2)
+         u_nudg_mod_cas(l)= frac1*u_nudg_prof_cas(k1) - frac2*u_nudg_prof_cas(k2)
+         v_nudg_mod_cas(l)= frac1*v_nudg_prof_cas(k1) - frac2*v_nudg_prof_cas(k2)
+         w_mod_cas(l)= frac1*vitw_prof_cas(k1) - frac2*vitw_prof_cas(k2)
+         omega_mod_cas(l)= frac1*omega_prof_cas(k1) - frac2*omega_prof_cas(k2)
+         du_mod_cas(l)= frac1*du_prof_cas(k1) - frac2*du_prof_cas(k2)
+         hu_mod_cas(l)= frac1*hu_prof_cas(k1) - frac2*hu_prof_cas(k2)
+         vu_mod_cas(l)= frac1*vu_prof_cas(k1) - frac2*vu_prof_cas(k2)
+         dv_mod_cas(l)= frac1*dv_prof_cas(k1) - frac2*dv_prof_cas(k2)
+         hv_mod_cas(l)= frac1*hv_prof_cas(k1) - frac2*hv_prof_cas(k2)
+         vv_mod_cas(l)= frac1*vv_prof_cas(k1) - frac2*vv_prof_cas(k2)
+         dt_mod_cas(l)= frac1*dt_prof_cas(k1) - frac2*dt_prof_cas(k2)
+         ht_mod_cas(l)= frac1*ht_prof_cas(k1) - frac2*ht_prof_cas(k2)
+         vt_mod_cas(l)= frac1*vt_prof_cas(k1) - frac2*vt_prof_cas(k2)
+         dth_mod_cas(l)= frac1*dth_prof_cas(k1) - frac2*dth_prof_cas(k2)
+         hth_mod_cas(l)= frac1*hth_prof_cas(k1) - frac2*hth_prof_cas(k2)
+         vth_mod_cas(l)= frac1*vth_prof_cas(k1) - frac2*vth_prof_cas(k2)
+         dq_mod_cas(l)= frac1*dq_prof_cas(k1) - frac2*dq_prof_cas(k2)
+         hq_mod_cas(l)= frac1*hq_prof_cas(k1) - frac2*hq_prof_cas(k2)
+         vq_mod_cas(l)= frac1*vq_prof_cas(k1) - frac2*vq_prof_cas(k2)
+         dtrad_mod_cas(l)= frac1*dtrad_prof_cas(k1) - frac2*dtrad_prof_cas(k2)
+
+         endif ! play.le.plev_prof_cas(1)
+
+        else ! above max altitude of forcing file
+ 
+!jyg
+         fact=20.*(plev_prof_cas(nlev_cas)-play(l))/plev_prof_cas(nlev_cas) !jyg
+         fact = max(fact,0.)                                           !jyg
+         fact = exp(-fact)                                             !jyg
+         t_mod_cas(l)= t_prof_cas(nlev_cas)                            !jyg
+         theta_mod_cas(l)= th_prof_cas(nlev_cas)                       !jyg
+         thv_mod_cas(l)= thv_prof_cas(nlev_cas)                        !jyg
+         thl_mod_cas(l)= thl_prof_cas(nlev_cas)                        !jyg
+         qv_mod_cas(l)= qv_prof_cas(nlev_cas)*fact                     !jyg
+         ql_mod_cas(l)= ql_prof_cas(nlev_cas)*fact                     !jyg
+         qi_mod_cas(l)= qi_prof_cas(nlev_cas)*fact                     !jyg
+         u_mod_cas(l)= u_prof_cas(nlev_cas)*fact                       !jyg
+         v_mod_cas(l)= v_prof_cas(nlev_cas)*fact                       !jyg
+         ug_mod_cas(l)= ug_prof_cas(nlev_cas)                          !jyg
+         vg_mod_cas(l)= vg_prof_cas(nlev_cas)                          !jyg
+         temp_nudg_mod_cas(l)= temp_nudg_prof_cas(nlev_cas)                          !jyg
+         qv_nudg_mod_cas(l)= qv_nudg_prof_cas(nlev_cas)                          !jyg
+         u_nudg_mod_cas(l)= u_nudg_prof_cas(nlev_cas)                          !jyg
+         v_nudg_mod_cas(l)= v_nudg_prof_cas(nlev_cas)                          !jyg
+         thv_mod_cas(l)= thv_prof_cas(nlev_cas)                        !jyg
+         w_mod_cas(l)= 0.0                                             !jyg
+         omega_mod_cas(l)= 0.0                                         !jyg
+         du_mod_cas(l)= du_prof_cas(nlev_cas)*fact 
+         hu_mod_cas(l)= hu_prof_cas(nlev_cas)*fact                     !jyg
+         vu_mod_cas(l)= vu_prof_cas(nlev_cas)*fact                     !jyg
+         dv_mod_cas(l)= dv_prof_cas(nlev_cas)*fact
+         hv_mod_cas(l)= hv_prof_cas(nlev_cas)*fact                     !jyg
+         vv_mod_cas(l)= vv_prof_cas(nlev_cas)*fact                     !jyg
+         dt_mod_cas(l)= dt_prof_cas(nlev_cas) 
+         ht_mod_cas(l)= ht_prof_cas(nlev_cas)                          !jyg
+         vt_mod_cas(l)= vt_prof_cas(nlev_cas)                          !jyg
+         dth_mod_cas(l)= dth_prof_cas(nlev_cas) 
+         hth_mod_cas(l)= hth_prof_cas(nlev_cas)                        !jyg
+         vth_mod_cas(l)= vth_prof_cas(nlev_cas)                        !jyg
+         dq_mod_cas(l)= dq_prof_cas(nlev_cas)*fact 
+         hq_mod_cas(l)= hq_prof_cas(nlev_cas)*fact                     !jyg
+         vq_mod_cas(l)= vq_prof_cas(nlev_cas)*fact                     !jyg
+         dtrad_mod_cas(l)= dtrad_prof_cas(nlev_cas)*fact               !jyg
+ 
+        endif ! play
+ 
+       enddo ! l
+
+          return
+          end
+!***************************************************************************** 
+
+
+
+
+
+END MODULE mod_1D_cases_read_std
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/old_1DUTILS_read_interp.h
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/old_1DUTILS_read_interp.h	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/old_1DUTILS_read_interp.h	(revision 3605)
@@ -0,0 +1,3380 @@
+!======================================================================
+      SUBROUTINE read_togacoare(fich_toga,nlev_toga,nt_toga                     &
+     &             ,ts_toga,plev_toga,t_toga,q_toga,u_toga,v_toga,w_toga        &
+     &             ,ht_toga,vt_toga,hq_toga,vq_toga)
+      implicit none
+
+!-------------------------------------------------------------------------
+! Read TOGA-COARE forcing data 
+!-------------------------------------------------------------------------
+
+      integer nlev_toga,nt_toga
+      real ts_toga(nt_toga),plev_toga(nlev_toga,nt_toga)
+      real t_toga(nlev_toga,nt_toga),q_toga(nlev_toga,nt_toga)
+      real u_toga(nlev_toga,nt_toga),v_toga(nlev_toga,nt_toga)
+      real w_toga(nlev_toga,nt_toga)
+      real ht_toga(nlev_toga,nt_toga),vt_toga(nlev_toga,nt_toga)
+      real hq_toga(nlev_toga,nt_toga),vq_toga(nlev_toga,nt_toga)
+      character*80 fich_toga
+
+      integer k,ip
+      real bid
+
+      integer iy,im,id,ih
+      
+       real plev_min
+
+       plev_min = 55.  ! pas de tendance de vap. d eau au-dessus de 55 hPa
+
+      open(21,file=trim(fich_toga),form='formatted')
+      read(21,'(a)') 
+      do ip = 1, nt_toga
+      read(21,'(a)') 
+      read(21,'(a)') 
+      read(21,223) iy, im, id, ih, bid, ts_toga(ip), bid,bid,bid,bid
+      read(21,'(a)') 
+      read(21,'(a)') 
+
+       do k = 1, nlev_toga
+         read(21,230) plev_toga(k,ip), t_toga(k,ip), q_toga(k,ip)          &
+     &       ,u_toga(k,ip), v_toga(k,ip), w_toga(k,ip)                     &
+     &       ,ht_toga(k,ip), vt_toga(k,ip), hq_toga(k,ip), vq_toga(k,ip)
+
+! conversion in SI units:
+         t_toga(k,ip)=t_toga(k,ip)+273.15     ! K
+         q_toga(k,ip)=q_toga(k,ip)*0.001      ! kg/kg
+         w_toga(k,ip)=w_toga(k,ip)*100./3600. ! Pa/s
+! no water vapour tendency above 55 hPa
+         if (plev_toga(k,ip) .lt. plev_min) then
+          q_toga(k,ip) = 0.
+          hq_toga(k,ip) = 0.
+          vq_toga(k,ip) =0.
+         endif
+       enddo
+
+         ts_toga(ip)=ts_toga(ip)+273.15       ! K
+       enddo
+       close(21)
+
+  223 format(4i3,6f8.2)
+  230 format(6f9.3,4e11.3)
+
+          return
+          end
+
+!-------------------------------------------------------------------------
+      SUBROUTINE read_sandu(fich_sandu,nlev_sandu,nt_sandu,ts_sandu)
+      implicit none
+
+!-------------------------------------------------------------------------
+! Read I.SANDU case forcing data
+!-------------------------------------------------------------------------
+
+      integer nlev_sandu,nt_sandu
+      real ts_sandu(nt_sandu)
+      character*80 fich_sandu
+
+      integer ip
+      integer iy,im,id,ih
+
+      real plev_min
+
+      print*,'nlev_sandu',nlev_sandu
+      plev_min = 55000.  ! pas de tendance de vap. d eau au-dessus de 55 hPa
+
+      open(21,file=trim(fich_sandu),form='formatted')
+      read(21,'(a)')
+      do ip = 1, nt_sandu
+      read(21,'(a)')
+      read(21,'(a)')
+      read(21,223) iy, im, id, ih, ts_sandu(ip)
+      print *,'ts=',iy,im,id,ih,ip,ts_sandu(ip)
+      enddo
+      close(21)
+
+  223 format(4i3,f8.2)
+
+          return
+          end
+
+!=====================================================================
+!-------------------------------------------------------------------------
+      SUBROUTINE read_astex(fich_astex,nlev_astex,nt_astex,div_astex,      &
+     & ts_astex,ug_astex,vg_astex,ufa_astex,vfa_astex)
+      implicit none
+
+!-------------------------------------------------------------------------
+! Read Astex case forcing data
+!-------------------------------------------------------------------------
+
+      integer nlev_astex,nt_astex
+      real div_astex(nt_astex),ts_astex(nt_astex),ug_astex(nt_astex)
+      real vg_astex(nt_astex),ufa_astex(nt_astex),vfa_astex(nt_astex)
+      character*80 fich_astex
+
+      integer ip
+      integer iy,im,id,ih
+
+       real plev_min
+
+      print*,'nlev_astex',nlev_astex
+       plev_min = 55000.  ! pas de tendance de vap. d eau au-dessus de 55 hPa
+
+      open(21,file=trim(fich_astex),form='formatted')
+      read(21,'(a)')
+      read(21,'(a)')
+      do ip = 1, nt_astex
+      read(21,'(a)')
+      read(21,'(a)')
+      read(21,223) iy, im, id, ih, div_astex(ip),ts_astex(ip),             &
+     &ug_astex(ip),vg_astex(ip),ufa_astex(ip),vfa_astex(ip)
+      ts_astex(ip)=ts_astex(ip)+273.15
+      print *,'ts=',iy,im,id,ih,ip,div_astex(ip),ts_astex(ip),             &
+     &ug_astex(ip),vg_astex(ip),ufa_astex(ip),vg_astex(ip)
+      enddo
+      close(21)
+
+  223 format(4i3,e13.2,f7.2,f7.3,f7.2,f7.3,f7.2)
+
+          return
+          end
+!=====================================================================
+      subroutine read_twpice(fich_twpice,nlevel,ntime                       &
+     &     ,T_srf,plev,T,q,u,v,omega                                       &
+     &     ,T_adv_h,T_adv_v,q_adv_h,q_adv_v)
+
+!program reading forcings of the TWP-ICE experiment
+
+!      use netcdf
+
+      implicit none
+
+#include "netcdf.inc"
+
+      integer ntime,nlevel
+      integer l,k
+      character*80 :: fich_twpice
+      real*8 time(ntime)
+      real*8 lat, lon, alt, phis
+      real*8 lev(nlevel)
+      real*8 plev(nlevel,ntime)
+
+      real*8 T(nlevel,ntime)
+      real*8 q(nlevel,ntime),u(nlevel,ntime)
+      real*8 v(nlevel,ntime)
+      real*8 omega(nlevel,ntime), div(nlevel,ntime)
+      real*8 T_adv_h(nlevel,ntime)
+      real*8 T_adv_v(nlevel,ntime), q_adv_h(nlevel,ntime)
+      real*8 q_adv_v(nlevel,ntime)
+      real*8 s(nlevel,ntime), s_adv_h(nlevel,ntime)
+      real*8 s_adv_v(nlevel,ntime)
+      real*8 p_srf_aver(ntime), p_srf_center(ntime)
+      real*8 T_srf(ntime)
+
+      integer nid, ierr
+      integer nbvar3d
+      parameter(nbvar3d=20)
+      integer var3didin(nbvar3d)
+
+      ierr = NF_OPEN(fich_twpice,NF_NOWRITE,nid)
+      if (ierr.NE.NF_NOERR) then
+         write(*,*) 'ERROR: Pb opening forcings cdf file '
+         write(*,*) NF_STRERROR(ierr)
+         stop ""
+      endif
+
+      ierr=NF_INQ_VARID(nid,"lat",var3didin(1))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'lat'
+         endif
+      
+       ierr=NF_INQ_VARID(nid,"lon",var3didin(2))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'lon'
+         endif
+
+       ierr=NF_INQ_VARID(nid,"alt",var3didin(3))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'alt'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"phis",var3didin(4))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'phis'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"T",var3didin(5))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'T'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"q",var3didin(6))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'q'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"u",var3didin(7))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'u'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"v",var3didin(8))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'v'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"omega",var3didin(9))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'omega'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"div",var3didin(10))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'div'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"T_adv_h",var3didin(11))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'T_adv_h'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"T_adv_v",var3didin(12))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'T_adv_v'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"q_adv_h",var3didin(13))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'q_adv_h'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"q_adv_v",var3didin(14))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'q_adv_v'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"s",var3didin(15))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 's'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"s_adv_h",var3didin(16))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 's_adv_h'
+         endif
+    
+      ierr=NF_INQ_VARID(nid,"s_adv_v",var3didin(17))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 's_adv_v'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"p_srf_aver",var3didin(18))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'p_srf_aver'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"p_srf_center",var3didin(19))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'p_srf_center'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"T_srf",var3didin(20))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'T_srf'
+         endif
+
+!dimensions lecture
+      call catchaxis(nid,ntime,nlevel,time,lev,ierr)
+
+!pressure 
+       do l=1,ntime
+       do k=1,nlevel
+          plev(k,l)=lev(k)
+       enddo
+       enddo
+          
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(1),lat)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(1),lat)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!         write(*,*)'lecture lat ok',lat
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(2),lon)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(2),lon)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!         write(*,*)'lecture lon ok',lon
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(3),alt)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(3),alt)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture alt ok',alt
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(4),phis)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(4),phis)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture phis ok',phis
+          
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(5),T)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(5),T)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!         write(*,*)'lecture T ok'
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(6),q)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(6),q)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!         write(*,*)'lecture q ok'
+!q in kg/kg
+       do l=1,ntime
+       do k=1,nlevel
+          q(k,l)=q(k,l)/1000.
+       enddo
+       enddo
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(7),u)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(7),u)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!         write(*,*)'lecture u ok'
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(8),v)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(8),v)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!         write(*,*)'lecture v ok'
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(9),omega)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(9),omega)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!         write(*,*)'lecture omega ok'
+!omega in mb/hour
+       do l=1,ntime
+       do k=1,nlevel
+          omega(k,l)=omega(k,l)*100./3600.
+       enddo
+       enddo
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(10),div)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(10),div)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!         write(*,*)'lecture div ok'
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(11),T_adv_h)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(11),T_adv_h)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!         write(*,*)'lecture T_adv_h ok'
+!T adv in K/s
+       do l=1,ntime
+       do k=1,nlevel
+          T_adv_h(k,l)=T_adv_h(k,l)/3600.
+       enddo
+       enddo
+
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(12),T_adv_v)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(12),T_adv_v)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!         write(*,*)'lecture T_adv_v ok'
+!T adv in K/s
+       do l=1,ntime
+       do k=1,nlevel
+          T_adv_v(k,l)=T_adv_v(k,l)/3600.
+       enddo
+       enddo
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(13),q_adv_h)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(13),q_adv_h)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!         write(*,*)'lecture q_adv_h ok'
+!q adv in kg/kg/s
+       do l=1,ntime
+       do k=1,nlevel
+          q_adv_h(k,l)=q_adv_h(k,l)/1000./3600.
+       enddo
+       enddo
+
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(14),q_adv_v)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(14),q_adv_v)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!         write(*,*)'lecture q_adv_v ok'
+!q adv in kg/kg/s
+       do l=1,ntime
+       do k=1,nlevel
+          q_adv_v(k,l)=q_adv_v(k,l)/1000./3600.
+       enddo
+       enddo
+
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(15),s)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(15),s)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(16),s_adv_h)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(16),s_adv_h)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(17),s_adv_v)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(17),s_adv_v)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(18),p_srf_aver)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(18),p_srf_aver)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(19),p_srf_center)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(19),p_srf_center)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(20),T_srf)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(20),T_srf)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!         write(*,*)'lecture T_srf ok', T_srf
+
+         return 
+         end subroutine read_twpice
+!=====================================================================
+         subroutine catchaxis(nid,ttm,llm,time,lev,ierr)
+
+!         use netcdf
+
+         implicit none
+#include "netcdf.inc"
+         integer nid,ttm,llm
+         real*8 time(ttm)
+         real*8 lev(llm)
+         integer ierr
+
+         integer timevar,levvar
+         integer timelen,levlen
+         integer timedimin,levdimin
+
+! Control & lecture on dimensions
+! ===============================
+         ierr=NF_INQ_DIMID(nid,"time",timedimin)
+         ierr=NF_INQ_VARID(nid,"time",timevar)
+         if (ierr.NE.NF_NOERR) then
+            write(*,*) 'ERROR: Field <time> is missing'
+            stop ""  
+         endif
+         ierr=NF_INQ_DIMLEN(nid,timedimin,timelen)
+
+         ierr=NF_INQ_DIMID(nid,"lev",levdimin)
+         ierr=NF_INQ_VARID(nid,"lev",levvar)
+         if (ierr.NE.NF_NOERR) then
+             write(*,*) 'ERROR: Field <lev> is lacking'
+             stop "" 
+         endif
+         ierr=NF_INQ_DIMLEN(nid,levdimin,levlen)
+
+         if((timelen/=ttm).or.(levlen/=llm)) then
+            write(*,*) 'ERROR: Not the good lenght for axis'
+            write(*,*) 'longitude: ',timelen,ttm+1
+            write(*,*) 'latitude: ',levlen,llm
+            stop ""  
+         endif
+
+!#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,timevar,time)
+         ierr = NF_GET_VAR_DOUBLE(nid,levvar,lev)
+!#else
+!        ierr = NF_GET_VAR_REAL(nid,timevar,time)
+!        ierr = NF_GET_VAR_REAL(nid,levvar,lev)
+!#endif
+
+       return
+       end
+!=====================================================================
+
+       SUBROUTINE interp_sandu_vertical(play,nlev_sandu,plev_prof          &
+     &         ,t_prof,thl_prof,q_prof,u_prof,v_prof,w_prof                &
+     &         ,omega_prof,o3mmr_prof                                      &
+     &         ,t_mod,thl_mod,q_mod,u_mod,v_mod,w_mod                      &
+     &         ,omega_mod,o3mmr_mod,mxcalc)
+
+       implicit none
+
+#include "dimensions.h"
+
+!-------------------------------------------------------------------------
+! Vertical interpolation of SANDUREF forcing data onto model levels
+!-------------------------------------------------------------------------
+
+       integer nlevmax
+       parameter (nlevmax=41)
+       integer nlev_sandu,mxcalc
+!       real play(llm), plev_prof(nlevmax)
+!       real t_prof(nlevmax),q_prof(nlevmax)
+!       real u_prof(nlevmax),v_prof(nlevmax), w_prof(nlevmax)
+!       real ht_prof(nlevmax),vt_prof(nlevmax)
+!       real hq_prof(nlevmax),vq_prof(nlevmax)
+
+       real play(llm), plev_prof(nlev_sandu)
+       real t_prof(nlev_sandu),thl_prof(nlev_sandu),q_prof(nlev_sandu)
+       real u_prof(nlev_sandu),v_prof(nlev_sandu), w_prof(nlev_sandu)
+       real omega_prof(nlev_sandu),o3mmr_prof(nlev_sandu)
+
+       real t_mod(llm),thl_mod(llm),q_mod(llm)
+       real u_mod(llm),v_mod(llm), w_mod(llm)
+       real omega_mod(llm),o3mmr_mod(llm)
+
+       integer l,k,k1,k2
+       real frac,frac1,frac2,fact
+
+       do l = 1, llm
+
+        if (play(l).ge.plev_prof(nlev_sandu)) then
+
+        mxcalc=l
+         k1=0
+         k2=0
+
+         if (play(l).le.plev_prof(1)) then
+
+         do k = 1, nlev_sandu-1
+          if (play(l).le.plev_prof(k).and. play(l).gt.plev_prof(k+1)) then
+            k1=k
+            k2=k+1
+          endif
+         enddo
+
+         if (k1.eq.0 .or. k2.eq.0) then
+          write(*,*) 'PB! k1, k2 = ',k1,k2
+          write(*,*) 'l,play(l) = ',l,play(l)/100
+         do k = 1, nlev_sandu-1
+          write(*,*) 'k,plev_prof(k) = ',k,plev_prof(k)/100
+         enddo
+         endif
+
+         frac = (plev_prof(k2)-play(l))/(plev_prof(k2)-plev_prof(k1))
+         t_mod(l)= t_prof(k2) - frac*(t_prof(k2)-t_prof(k1))
+         thl_mod(l)= thl_prof(k2) - frac*(thl_prof(k2)-thl_prof(k1))
+         q_mod(l)= q_prof(k2) - frac*(q_prof(k2)-q_prof(k1))
+         u_mod(l)= u_prof(k2) - frac*(u_prof(k2)-u_prof(k1))
+         v_mod(l)= v_prof(k2) - frac*(v_prof(k2)-v_prof(k1))
+         w_mod(l)= w_prof(k2) - frac*(w_prof(k2)-w_prof(k1))
+         omega_mod(l)=omega_prof(k2)-frac*(omega_prof(k2)-omega_prof(k1))
+         o3mmr_mod(l)=o3mmr_prof(k2)-frac*(o3mmr_prof(k2)-o3mmr_prof(k1))
+
+         else !play>plev_prof(1)
+
+         k1=1
+         k2=2
+         frac1 = (play(l)-plev_prof(k2))/(plev_prof(k1)-plev_prof(k2))
+         frac2 = (play(l)-plev_prof(k1))/(plev_prof(k1)-plev_prof(k2))
+         t_mod(l)= frac1*t_prof(k1) - frac2*t_prof(k2)
+         thl_mod(l)= frac1*thl_prof(k1) - frac2*thl_prof(k2)
+         q_mod(l)= frac1*q_prof(k1) - frac2*q_prof(k2)
+         u_mod(l)= frac1*u_prof(k1) - frac2*u_prof(k2)
+         v_mod(l)= frac1*v_prof(k1) - frac2*v_prof(k2)
+         w_mod(l)= frac1*w_prof(k1) - frac2*w_prof(k2)
+         omega_mod(l)= frac1*omega_prof(k1) - frac2*omega_prof(k2)
+         o3mmr_mod(l)= frac1*o3mmr_prof(k1) - frac2*o3mmr_prof(k2)
+
+         endif ! play.le.plev_prof(1)
+
+        else ! above max altitude of forcing file
+
+!jyg
+         fact=20.*(plev_prof(nlev_sandu)-play(l))/plev_prof(nlev_sandu) !jyg
+         fact = max(fact,0.)                                           !jyg
+         fact = exp(-fact)                                             !jyg
+         t_mod(l)= t_prof(nlev_sandu)                                   !jyg
+         thl_mod(l)= thl_prof(nlev_sandu)                                   !jyg
+         q_mod(l)= q_prof(nlev_sandu)*fact                              !jyg
+         u_mod(l)= u_prof(nlev_sandu)*fact                              !jyg
+         v_mod(l)= v_prof(nlev_sandu)*fact                              !jyg
+         w_mod(l)= w_prof(nlev_sandu)*fact                              !jyg
+         omega_mod(l)= omega_prof(nlev_sandu)*fact                      !jyg
+         o3mmr_mod(l)= o3mmr_prof(nlev_sandu)*fact                      !jyg
+
+        endif ! play
+
+       enddo ! l
+
+       do l = 1,llm
+!      print *,'t_mod(l),thl_mod(l),q_mod(l),u_mod(l),v_mod(l) ',
+!    $        l,t_mod(l),thl_mod(l),q_mod(l),u_mod(l),v_mod(l)
+       enddo
+
+          return
+          end
+!=====================================================================
+       SUBROUTINE interp_astex_vertical(play,nlev_astex,plev_prof          &
+     &         ,t_prof,thl_prof,qv_prof,ql_prof,qt_prof,u_prof,v_prof      &
+     &         ,w_prof,tke_prof,o3mmr_prof                                 &
+     &         ,t_mod,thl_mod,qv_mod,ql_mod,qt_mod,u_mod,v_mod,w_mod       &
+     &         ,tke_mod,o3mmr_mod,mxcalc)
+
+       implicit none
+
+#include "dimensions.h"
+
+!-------------------------------------------------------------------------
+! Vertical interpolation of Astex forcing data onto model levels
+!-------------------------------------------------------------------------
+
+       integer nlevmax
+       parameter (nlevmax=41)
+       integer nlev_astex,mxcalc
+!       real play(llm), plev_prof(nlevmax)
+!       real t_prof(nlevmax),qv_prof(nlevmax)
+!       real u_prof(nlevmax),v_prof(nlevmax), w_prof(nlevmax)
+!       real ht_prof(nlevmax),vt_prof(nlevmax)
+!       real hq_prof(nlevmax),vq_prof(nlevmax)
+
+       real play(llm), plev_prof(nlev_astex)
+       real t_prof(nlev_astex),thl_prof(nlev_astex),qv_prof(nlev_astex)
+       real u_prof(nlev_astex),v_prof(nlev_astex), w_prof(nlev_astex)
+       real o3mmr_prof(nlev_astex),ql_prof(nlev_astex)
+       real qt_prof(nlev_astex),tke_prof(nlev_astex)
+
+       real t_mod(llm),thl_mod(llm),qv_mod(llm)
+       real u_mod(llm),v_mod(llm), w_mod(llm),tke_mod(llm)
+       real o3mmr_mod(llm),ql_mod(llm),qt_mod(llm)
+
+       integer l,k,k1,k2
+       real frac,frac1,frac2,fact
+
+       do l = 1, llm
+
+        if (play(l).ge.plev_prof(nlev_astex)) then
+
+        mxcalc=l
+         k1=0
+         k2=0
+
+         if (play(l).le.plev_prof(1)) then
+
+         do k = 1, nlev_astex-1
+          if (play(l).le.plev_prof(k).and. play(l).gt.plev_prof(k+1)) then
+            k1=k
+            k2=k+1
+          endif
+         enddo
+
+         if (k1.eq.0 .or. k2.eq.0) then
+          write(*,*) 'PB! k1, k2 = ',k1,k2
+          write(*,*) 'l,play(l) = ',l,play(l)/100
+         do k = 1, nlev_astex-1
+          write(*,*) 'k,plev_prof(k) = ',k,plev_prof(k)/100
+         enddo
+         endif
+
+         frac = (plev_prof(k2)-play(l))/(plev_prof(k2)-plev_prof(k1))
+         t_mod(l)= t_prof(k2) - frac*(t_prof(k2)-t_prof(k1))
+         thl_mod(l)= thl_prof(k2) - frac*(thl_prof(k2)-thl_prof(k1))
+         qv_mod(l)= qv_prof(k2) - frac*(qv_prof(k2)-qv_prof(k1))
+         ql_mod(l)= ql_prof(k2) - frac*(ql_prof(k2)-ql_prof(k1))
+         qt_mod(l)= qt_prof(k2) - frac*(qt_prof(k2)-qt_prof(k1))
+         u_mod(l)= u_prof(k2) - frac*(u_prof(k2)-u_prof(k1))
+         v_mod(l)= v_prof(k2) - frac*(v_prof(k2)-v_prof(k1))
+         w_mod(l)= w_prof(k2) - frac*(w_prof(k2)-w_prof(k1))
+         tke_mod(l)= tke_prof(k2) - frac*(tke_prof(k2)-tke_prof(k1))
+         o3mmr_mod(l)=o3mmr_prof(k2)-frac*(o3mmr_prof(k2)-o3mmr_prof(k1))
+
+         else !play>plev_prof(1)
+
+         k1=1
+         k2=2
+         frac1 = (play(l)-plev_prof(k2))/(plev_prof(k1)-plev_prof(k2))
+         frac2 = (play(l)-plev_prof(k1))/(plev_prof(k1)-plev_prof(k2))
+         t_mod(l)= frac1*t_prof(k1) - frac2*t_prof(k2)
+         thl_mod(l)= frac1*thl_prof(k1) - frac2*thl_prof(k2)
+         qv_mod(l)= frac1*qv_prof(k1) - frac2*qv_prof(k2)
+         ql_mod(l)= frac1*ql_prof(k1) - frac2*ql_prof(k2)
+         qt_mod(l)= frac1*qt_prof(k1) - frac2*qt_prof(k2)
+         u_mod(l)= frac1*u_prof(k1) - frac2*u_prof(k2)
+         v_mod(l)= frac1*v_prof(k1) - frac2*v_prof(k2)
+         w_mod(l)= frac1*w_prof(k1) - frac2*w_prof(k2)
+         tke_mod(l)= frac1*tke_prof(k1) - frac2*tke_prof(k2)
+         o3mmr_mod(l)= frac1*o3mmr_prof(k1) - frac2*o3mmr_prof(k2)
+
+         endif ! play.le.plev_prof(1)
+
+        else ! above max altitude of forcing file
+
+!jyg
+         fact=20.*(plev_prof(nlev_astex)-play(l))/plev_prof(nlev_astex) !jyg
+         fact = max(fact,0.)                                           !jyg
+         fact = exp(-fact)                                             !jyg
+         t_mod(l)= t_prof(nlev_astex)                                   !jyg
+         thl_mod(l)= thl_prof(nlev_astex)                                   !jyg
+         qv_mod(l)= qv_prof(nlev_astex)*fact                              !jyg
+         ql_mod(l)= ql_prof(nlev_astex)*fact                              !jyg
+         qt_mod(l)= qt_prof(nlev_astex)*fact                              !jyg
+         u_mod(l)= u_prof(nlev_astex)*fact                              !jyg
+         v_mod(l)= v_prof(nlev_astex)*fact                              !jyg
+         w_mod(l)= w_prof(nlev_astex)*fact                              !jyg
+         tke_mod(l)= tke_prof(nlev_astex)*fact                              !jyg
+         o3mmr_mod(l)= o3mmr_prof(nlev_astex)*fact                      !jyg
+
+        endif ! play
+
+       enddo ! l
+
+       do l = 1,llm
+!      print *,'t_mod(l),thl_mod(l),qv_mod(l),u_mod(l),v_mod(l) ',
+!    $        l,t_mod(l),thl_mod(l),qv_mod(l),u_mod(l),v_mod(l)
+       enddo
+
+          return
+          end
+
+!======================================================================
+      SUBROUTINE read_rico(fich_rico,nlev_rico,ps_rico,play                &
+     &             ,ts_rico,t_rico,q_rico,u_rico,v_rico,w_rico             &
+     &             ,dth_dyn,dqh_dyn)
+      implicit none
+
+!-------------------------------------------------------------------------
+! Read RICO forcing data 
+!-------------------------------------------------------------------------
+#include "dimensions.h"
+
+
+      integer nlev_rico
+      real ts_rico,ps_rico
+      real t_rico(llm),q_rico(llm)
+      real u_rico(llm),v_rico(llm)
+      real w_rico(llm)
+      real dth_dyn(llm)
+      real dqh_dyn(llm)
+      
+
+      real play(llm),zlay(llm)
+     
+
+      real prico(nlev_rico),zrico(nlev_rico)
+
+      character*80 fich_rico
+
+      integer k,l
+
+      
+      print*,fich_rico
+      open(21,file=trim(fich_rico),form='formatted')
+        do k=1,llm
+      zlay(k)=0.
+         enddo
+      
+        read(21,*) ps_rico,ts_rico
+        prico(1)=ps_rico
+        zrico(1)=0.0
+      do l=2,nlev_rico
+        read(21,*) k,prico(l),zrico(l)
+      enddo
+       close(21)
+
+      do k=1,llm
+        do l=1,80
+          if(prico(l)>play(k)) then
+              if(play(k)>prico(l+1)) then
+                zlay(k)=zrico(l)+(play(k)-prico(l)) *                      &
+     &              (zrico(l+1)-zrico(l))/(prico(l+1)-prico(l))
+              else 
+                zlay(k)=zrico(l)+(play(k)-prico(80))*                      &
+     &              (zrico(81)-zrico(80))/(prico(81)-prico(80))
+              endif
+          endif
+        enddo
+        print*,k,zlay(k)
+        ! U
+        if(0 < zlay(k) .and. zlay(k) < 4000) then
+          u_rico(k)=-9.9 + (-1.9 + 9.9)*zlay(k)/4000
+        elseif(4000 < zlay(k) .and. zlay(k) < 12000) then
+       u_rico(k)=  -1.9 + (30.0 + 1.9) /                                   &
+     &          (12000 - 4000) * (zlay(k) - 4000)
+        elseif(12000 < zlay(k) .and. zlay(k) < 13000) then
+          u_rico(k)=30.0
+        elseif(13000 < zlay(k) .and. zlay(k) < 20000) then
+          u_rico(k)=30.0 - (30.0) /                                        &
+     & (20000 - 13000) * (zlay(k) - 13000)
+        else
+          u_rico(k)=0.0
+        endif
+
+!Q_v
+        if(0 < zlay(k) .and. zlay(k) < 740) then
+          q_rico(k)=16.0 + (13.8 - 16.0) / (740) * zlay(k)
+        elseif(740 < zlay(k) .and. zlay(k) < 3260) then
+          q_rico(k)=13.8 + (2.4 - 13.8) /                                   &
+     &          (3260 - 740) * (zlay(k) - 740)
+        elseif(3260 < zlay(k) .and. zlay(k) < 4000) then
+          q_rico(k)=2.4 + (1.8 - 2.4) /                                    &
+     &               (4000 - 3260) * (zlay(k) - 3260)
+        elseif(4000 < zlay(k) .and. zlay(k) < 9000) then
+          q_rico(k)=1.8 + (0 - 1.8) /                                      &
+     &             (9000 - 4000) * (zlay(k) - 4000)
+        else
+          q_rico(k)=0.0
+        endif
+
+!T
+        if(0 < zlay(k) .and. zlay(k) < 740) then
+          t_rico(k)=299.2 + (292.0 - 299.2) / (740) * zlay(k)
+        elseif(740 < zlay(k) .and. zlay(k) < 4000) then
+          t_rico(k)=292.0 + (278.0 - 292.0) /                              &                       
+     &       (4000 - 740) * (zlay(k) - 740)
+        elseif(4000 < zlay(k) .and. zlay(k) < 15000) then
+          t_rico(k)=278.0 + (203.0 - 278.0) /                              &
+     &       (15000 - 4000) * (zlay(k) - 4000)
+        elseif(15000 < zlay(k) .and. zlay(k) < 17500) then
+          t_rico(k)=203.0 + (194.0 - 203.0) /                              & 
+     &       (17500 - 15000)* (zlay(k) - 15000)
+        elseif(17500 < zlay(k) .and. zlay(k) < 20000) then
+          t_rico(k)=194.0 + (206.0 - 194.0) /                              &
+     &       (20000 - 17500)* (zlay(k) - 17500)
+        elseif(20000 < zlay(k) .and. zlay(k) < 60000) then
+          t_rico(k)=206.0 + (270.0 - 206.0) /                              & 
+     &        (60000 - 20000)* (zlay(k) - 20000)
+        endif
+
+! W
+        if(0 < zlay(k) .and. zlay(k) < 2260 ) then
+          w_rico(k)=- (0.005/2260) * zlay(k)
+        elseif(2260 < zlay(k) .and. zlay(k) < 4000 ) then
+          w_rico(k)=- 0.005
+        elseif(4000 < zlay(k) .and. zlay(k) < 5000 ) then
+       w_rico(k)=- 0.005 + (0.005/ (5000 - 4000)) * (zlay(k) - 4000)
+        else
+          w_rico(k)=0.0
+        endif
+
+! dThrz+dTsw0+dTlw0
+        if(0 < zlay(k) .and. zlay(k) < 4000) then
+          dth_dyn(k)=- 2.51 / 86400 + (-2.18 + 2.51 )/                     &
+     &               (86400*4000) * zlay(k)
+        elseif(4000 < zlay(k) .and. zlay(k) < 5000) then
+          dth_dyn(k)=- 2.18 / 86400 + ( 2.18 ) /                           &
+     &           (86400*(5000 - 4000)) * (zlay(k) - 4000)
+        else
+          dth_dyn(k)=0.0
+        endif
+! dQhrz
+        if(0 < zlay(k) .and. zlay(k) < 3000) then
+          dqh_dyn(k)=-1.0 / 86400 + (0.345 + 1.0)/                         &
+     &                    (86400*3000) * (zlay(k))
+        elseif(3000 < zlay(k) .and. zlay(k) < 4000) then
+          dqh_dyn(k)=0.345 / 86400
+        elseif(4000 < zlay(k) .and. zlay(k) < 5000) then
+          dqh_dyn(k)=0.345 / 86400 +                                       &
+     &   (-0.345)/(86400 * (5000 - 4000)) * (zlay(k)-4000)
+        else
+          dqh_dyn(k)=0.0
+        endif
+
+!?        if(play(k)>6e4) then
+!?          ratqs0(1,k)=ratqsbas*(plev(1)-play(k))/(plev(1)-6e4)
+!?        elseif((play(k)>3e4).and.(play(k)<6e4)) then
+!?          ratqs0(1,k)=ratqsbas+(ratqshaut-ratqsbas)&
+!?                          *(6e4-play(k))/(6e4-3e4)
+!?        else
+!?          ratqs0(1,k)=ratqshaut
+!?        endif
+
+      enddo
+
+      do k=1,llm
+      q_rico(k)=q_rico(k)/1e3 
+      dqh_dyn(k)=dqh_dyn(k)/1e3
+      v_rico(k)=-3.8
+      enddo
+
+          return
+          end
+
+!======================================================================
+        SUBROUTINE interp_sandu_time(day,day1,annee_ref                    &
+     &             ,year_ini_sandu,day_ini_sandu,nt_sandu,dt_sandu         &
+     &             ,nlev_sandu,ts_sandu,ts_prof)
+        implicit none
+
+!---------------------------------------------------------------------------------------
+! Time interpolation of a 2D field to the timestep corresponding to day
+!
+! day: current julian day (e.g. 717538.2)
+! day1: first day of the simulation
+! nt_sandu: total nb of data in the forcing (e.g. 13 for Sanduref)
+! dt_sandu: total time interval (in sec) between 2 forcing data (e.g. 6h for Sanduref)
+!---------------------------------------------------------------------------------------
+! inputs:
+        integer annee_ref
+        integer nt_sandu,nlev_sandu
+        integer year_ini_sandu
+        real day, day1,day_ini_sandu,dt_sandu
+        real ts_sandu(nt_sandu)
+! outputs:
+        real ts_prof
+! local:
+        integer it_sandu1, it_sandu2
+        real timeit,time_sandu1,time_sandu2,frac
+! Check that initial day of the simulation consistent with SANDU period:
+       if (annee_ref.ne.2006 ) then
+        print*,'Pour SANDUREF, annee_ref doit etre 2006 '
+        print*,'Changer annee_ref dans run.def'
+        stop
+       endif
+!      if (annee_ref.eq.2006 .and. day1.lt.day_ini_sandu) then
+!       print*,'SANDUREF debute le 15 Juillet 2006 (jour julien=196)'
+!       print*,'Changer dayref dans run.def'
+!       stop
+!      endif
+
+! Determine timestep relative to the 1st day of TOGA-COARE:
+!       timeit=(day-day1)*86400.
+!       if (annee_ref.eq.1992) then
+!        timeit=(day-day_ini_sandu)*86400.
+!       else
+!        timeit=(day+61.-1.)*86400. ! 61 days between Nov01 and Dec31 1992
+!       endif
+      timeit=(day-day_ini_sandu)*86400
+
+! Determine the closest observation times:
+       it_sandu1=INT(timeit/dt_sandu)+1
+       it_sandu2=it_sandu1 + 1
+       time_sandu1=(it_sandu1-1)*dt_sandu
+       time_sandu2=(it_sandu2-1)*dt_sandu
+       print *,'timeit day day_ini_sandu',timeit,day,day_ini_sandu
+       print *,'it_sandu1,it_sandu2,time_sandu1,time_sandu2',              &
+     &          it_sandu1,it_sandu2,time_sandu1,time_sandu2
+
+       if (it_sandu1 .ge. nt_sandu) then
+        write(*,*) 'PB-stop: day, it_sandu1, it_sandu2, timeit: '          &
+     &        ,day,it_sandu1,it_sandu2,timeit/86400.
+        stop
+       endif
+
+! time interpolation:
+       frac=(time_sandu2-timeit)/(time_sandu2-time_sandu1)
+       frac=max(frac,0.0)
+
+       ts_prof = ts_sandu(it_sandu2)                                       &
+     &          -frac*(ts_sandu(it_sandu2)-ts_sandu(it_sandu1))
+
+         print*,                                                           &
+     &'day,annee_ref,day_ini_sandu,timeit,it_sandu1,it_sandu2,SST:',       &
+     &day,annee_ref,day_ini_sandu,timeit/86400.,it_sandu1,                  &
+     &it_sandu2,ts_prof
+
+        return
+        END
+!=====================================================================
+!-------------------------------------------------------------------------
+      SUBROUTINE read_armcu(fich_armcu,nlev_armcu,nt_armcu,                &
+     & sens,flat,adv_theta,rad_theta,adv_qt)
+      implicit none
+
+!-------------------------------------------------------------------------
+! Read ARM_CU case forcing data
+!-------------------------------------------------------------------------
+
+      integer nlev_armcu,nt_armcu
+      real sens(nt_armcu),flat(nt_armcu)
+      real adv_theta(nt_armcu),rad_theta(nt_armcu),adv_qt(nt_armcu)
+      character*80 fich_armcu
+
+      integer ip
+
+      integer iy,im,id,ih,in
+
+      print*,'nlev_armcu',nlev_armcu
+
+      open(21,file=trim(fich_armcu),form='formatted')
+      read(21,'(a)')
+      do ip = 1, nt_armcu
+      read(21,'(a)')
+      read(21,'(a)')
+      read(21,223) iy, im, id, ih, in, sens(ip),flat(ip),                  &
+     &             adv_theta(ip),rad_theta(ip),adv_qt(ip)
+      print *,'forcages=',iy,im,id,ih,in, sens(ip),flat(ip),               &
+     &             adv_theta(ip),rad_theta(ip),adv_qt(ip)
+      enddo
+      close(21)
+
+  223 format(5i3,5f8.3)
+
+          return
+          end
+
+!=====================================================================
+       SUBROUTINE interp_toga_vertical(play,nlev_toga,plev_prof            &
+     &         ,t_prof,q_prof,u_prof,v_prof,w_prof                         &
+     &         ,ht_prof,vt_prof,hq_prof,vq_prof                            &
+     &         ,t_mod,q_mod,u_mod,v_mod,w_mod                              &
+     &         ,ht_mod,vt_mod,hq_mod,vq_mod,mxcalc)
+ 
+       implicit none
+ 
+#include "dimensions.h"
+
+!-------------------------------------------------------------------------
+! Vertical interpolation of TOGA-COARE forcing data onto model levels
+!-------------------------------------------------------------------------
+ 
+       integer nlevmax
+       parameter (nlevmax=41)
+       integer nlev_toga,mxcalc
+!       real play(llm), plev_prof(nlevmax) 
+!       real t_prof(nlevmax),q_prof(nlevmax)
+!       real u_prof(nlevmax),v_prof(nlevmax), w_prof(nlevmax)
+!       real ht_prof(nlevmax),vt_prof(nlevmax)
+!       real hq_prof(nlevmax),vq_prof(nlevmax)
+ 
+       real play(llm), plev_prof(nlev_toga) 
+       real t_prof(nlev_toga),q_prof(nlev_toga)
+       real u_prof(nlev_toga),v_prof(nlev_toga), w_prof(nlev_toga)
+       real ht_prof(nlev_toga),vt_prof(nlev_toga)
+       real hq_prof(nlev_toga),vq_prof(nlev_toga)
+ 
+       real t_mod(llm),q_mod(llm)
+       real u_mod(llm),v_mod(llm), w_mod(llm)
+       real ht_mod(llm),vt_mod(llm)
+       real hq_mod(llm),vq_mod(llm)
+ 
+       integer l,k,k1,k2
+       real frac,frac1,frac2,fact
+ 
+       do l = 1, llm
+
+        if (play(l).ge.plev_prof(nlev_toga)) then
+ 
+        mxcalc=l
+         k1=0
+         k2=0
+
+         if (play(l).le.plev_prof(1)) then
+
+         do k = 1, nlev_toga-1
+          if (play(l).le.plev_prof(k).and. play(l).gt.plev_prof(k+1)) then
+            k1=k
+            k2=k+1
+          endif
+         enddo
+
+         if (k1.eq.0 .or. k2.eq.0) then
+          write(*,*) 'PB! k1, k2 = ',k1,k2
+          write(*,*) 'l,play(l) = ',l,play(l)/100
+         do k = 1, nlev_toga-1
+          write(*,*) 'k,plev_prof(k) = ',k,plev_prof(k)/100
+         enddo
+         endif
+
+         frac = (plev_prof(k2)-play(l))/(plev_prof(k2)-plev_prof(k1))
+         t_mod(l)= t_prof(k2) - frac*(t_prof(k2)-t_prof(k1))
+         q_mod(l)= q_prof(k2) - frac*(q_prof(k2)-q_prof(k1))
+         u_mod(l)= u_prof(k2) - frac*(u_prof(k2)-u_prof(k1))
+         v_mod(l)= v_prof(k2) - frac*(v_prof(k2)-v_prof(k1))
+         w_mod(l)= w_prof(k2) - frac*(w_prof(k2)-w_prof(k1))
+         ht_mod(l)= ht_prof(k2) - frac*(ht_prof(k2)-ht_prof(k1))
+         vt_mod(l)= vt_prof(k2) - frac*(vt_prof(k2)-vt_prof(k1))
+         hq_mod(l)= hq_prof(k2) - frac*(hq_prof(k2)-hq_prof(k1))
+         vq_mod(l)= vq_prof(k2) - frac*(vq_prof(k2)-vq_prof(k1))
+     
+         else !play>plev_prof(1)
+
+         k1=1
+         k2=2
+         frac1 = (play(l)-plev_prof(k2))/(plev_prof(k1)-plev_prof(k2))
+         frac2 = (play(l)-plev_prof(k1))/(plev_prof(k1)-plev_prof(k2))
+         t_mod(l)= frac1*t_prof(k1) - frac2*t_prof(k2)
+         q_mod(l)= frac1*q_prof(k1) - frac2*q_prof(k2)
+         u_mod(l)= frac1*u_prof(k1) - frac2*u_prof(k2)
+         v_mod(l)= frac1*v_prof(k1) - frac2*v_prof(k2)
+         w_mod(l)= frac1*w_prof(k1) - frac2*w_prof(k2)
+         ht_mod(l)= frac1*ht_prof(k1) - frac2*ht_prof(k2)
+         vt_mod(l)= frac1*vt_prof(k1) - frac2*vt_prof(k2)
+         hq_mod(l)= frac1*hq_prof(k1) - frac2*hq_prof(k2)
+         vq_mod(l)= frac1*vq_prof(k1) - frac2*vq_prof(k2)
+
+         endif ! play.le.plev_prof(1)
+
+        else ! above max altitude of forcing file
+ 
+!jyg
+         fact=20.*(plev_prof(nlev_toga)-play(l))/plev_prof(nlev_toga) !jyg
+         fact = max(fact,0.)                                           !jyg
+         fact = exp(-fact)                                             !jyg
+         t_mod(l)= t_prof(nlev_toga)                                   !jyg
+         q_mod(l)= q_prof(nlev_toga)*fact                              !jyg
+         u_mod(l)= u_prof(nlev_toga)*fact                              !jyg
+         v_mod(l)= v_prof(nlev_toga)*fact                              !jyg
+         w_mod(l)= 0.0                                                 !jyg
+         ht_mod(l)= ht_prof(nlev_toga)                                 !jyg
+         vt_mod(l)= vt_prof(nlev_toga)                                 !jyg
+         hq_mod(l)= hq_prof(nlev_toga)*fact                            !jyg
+         vq_mod(l)= vq_prof(nlev_toga)*fact                            !jyg
+ 
+        endif ! play
+ 
+       enddo ! l
+
+!       do l = 1,llm
+!       print *,'t_mod(l),q_mod(l),ht_mod(l),hq_mod(l) ',
+!     $        l,t_mod(l),q_mod(l),ht_mod(l),hq_mod(l)
+!       enddo
+ 
+          return
+          end
+ 
+!=====================================================================
+       SUBROUTINE interp_case_vertical(play,nlev_cas,plev_prof_cas            &
+     &         ,t_prof_cas,q_prof_cas,u_prof_cas,v_prof_cas,ug_prof_cas,vg_prof_cas,vitw_prof_cas                         &
+     &         ,du_prof_cas,hu_prof_cas,vu_prof_cas,dv_prof_cas,hv_prof_cas,vv_prof_cas           &
+     &         ,dt_prof_cas,ht_prof_cas,vt_prof_cas,dtrad_prof_cas,dq_prof_cas,hq_prof_cas,vq_prof_cas                            &
+     &         ,t_mod_cas,q_mod_cas,u_mod_cas,v_mod_cas,ug_mod_cas,vg_mod_cas,w_mod_cas                              &
+     &         ,du_mod_cas,hu_mod_cas,vu_mod_cas,dv_mod_cas,hv_mod_cas,vv_mod_cas               &
+     &         ,dt_mod_cas,ht_mod_cas,vt_mod_cas,dtrad_mod_cas,dq_mod_cas,hq_mod_cas,vq_mod_cas,mxcalc)
+ 
+       implicit none
+ 
+#include "dimensions.h"
+
+!-------------------------------------------------------------------------
+! Vertical interpolation of TOGA-COARE forcing data onto mod_casel levels
+!-------------------------------------------------------------------------
+ 
+       integer nlevmax
+       parameter (nlevmax=41)
+       integer nlev_cas,mxcalc
+!       real play(llm), plev_prof(nlevmax) 
+!       real t_prof(nlevmax),q_prof(nlevmax)
+!       real u_prof(nlevmax),v_prof(nlevmax), w_prof(nlevmax)
+!       real ht_prof(nlevmax),vt_prof(nlevmax)
+!       real hq_prof(nlevmax),vq_prof(nlevmax)
+ 
+       real play(llm), plev_prof_cas(nlev_cas) 
+       real t_prof_cas(nlev_cas),q_prof_cas(nlev_cas)
+       real u_prof_cas(nlev_cas),v_prof_cas(nlev_cas)
+       real ug_prof_cas(nlev_cas),vg_prof_cas(nlev_cas), vitw_prof_cas(nlev_cas)
+       real du_prof_cas(nlev_cas),hu_prof_cas(nlev_cas),vu_prof_cas(nlev_cas)
+       real dv_prof_cas(nlev_cas),hv_prof_cas(nlev_cas),vv_prof_cas(nlev_cas)
+       real dt_prof_cas(nlev_cas),ht_prof_cas(nlev_cas),vt_prof_cas(nlev_cas),dtrad_prof_cas(nlev_cas)
+       real dq_prof_cas(nlev_cas),hq_prof_cas(nlev_cas),vq_prof_cas(nlev_cas)
+ 
+       real t_mod_cas(llm),q_mod_cas(llm)
+       real u_mod_cas(llm),v_mod_cas(llm)
+       real ug_mod_cas(llm),vg_mod_cas(llm), w_mod_cas(llm)
+       real du_mod_cas(llm),hu_mod_cas(llm),vu_mod_cas(llm)
+       real dv_mod_cas(llm),hv_mod_cas(llm),vv_mod_cas(llm)
+       real dt_mod_cas(llm),ht_mod_cas(llm),vt_mod_cas(llm),dtrad_mod_cas(llm)
+       real dq_mod_cas(llm),hq_mod_cas(llm),vq_mod_cas(llm)
+ 
+       integer l,k,k1,k2
+       real frac,frac1,frac2,fact
+ 
+       do l = 1, llm
+
+        if (play(l).ge.plev_prof_cas(nlev_cas)) then
+ 
+        mxcalc=l
+         k1=0
+         k2=0
+
+         if (play(l).le.plev_prof_cas(1)) then
+
+         do k = 1, nlev_cas-1
+          if (play(l).le.plev_prof_cas(k).and. play(l).gt.plev_prof_cas(k+1)) then
+            k1=k
+            k2=k+1
+          endif
+         enddo
+
+         if (k1.eq.0 .or. k2.eq.0) then
+          write(*,*) 'PB! k1, k2 = ',k1,k2
+          write(*,*) 'l,play(l) = ',l,play(l)/100
+         do k = 1, nlev_cas-1
+          write(*,*) 'k,plev_prof_cas(k) = ',k,plev_prof_cas(k)/100
+         enddo
+         endif
+
+         frac = (plev_prof_cas(k2)-play(l))/(plev_prof_cas(k2)-plev_prof_cas(k1))
+         t_mod_cas(l)= t_prof_cas(k2) - frac*(t_prof_cas(k2)-t_prof_cas(k1))
+         q_mod_cas(l)= q_prof_cas(k2) - frac*(q_prof_cas(k2)-q_prof_cas(k1))
+         u_mod_cas(l)= u_prof_cas(k2) - frac*(u_prof_cas(k2)-u_prof_cas(k1))
+         v_mod_cas(l)= v_prof_cas(k2) - frac*(v_prof_cas(k2)-v_prof_cas(k1))
+         ug_mod_cas(l)= ug_prof_cas(k2) - frac*(ug_prof_cas(k2)-ug_prof_cas(k1))
+         vg_mod_cas(l)= vg_prof_cas(k2) - frac*(vg_prof_cas(k2)-vg_prof_cas(k1))
+         w_mod_cas(l)= vitw_prof_cas(k2) - frac*(vitw_prof_cas(k2)-vitw_prof_cas(k1))
+         du_mod_cas(l)= du_prof_cas(k2) - frac*(du_prof_cas(k2)-du_prof_cas(k1))
+         hu_mod_cas(l)= hu_prof_cas(k2) - frac*(hu_prof_cas(k2)-hu_prof_cas(k1))
+         vu_mod_cas(l)= vu_prof_cas(k2) - frac*(vu_prof_cas(k2)-vu_prof_cas(k1))
+         dv_mod_cas(l)= dv_prof_cas(k2) - frac*(dv_prof_cas(k2)-dv_prof_cas(k1))
+         hv_mod_cas(l)= hv_prof_cas(k2) - frac*(hv_prof_cas(k2)-hv_prof_cas(k1))
+         vv_mod_cas(l)= vv_prof_cas(k2) - frac*(vv_prof_cas(k2)-vv_prof_cas(k1))
+         dt_mod_cas(l)= dt_prof_cas(k2) - frac*(dt_prof_cas(k2)-dt_prof_cas(k1))
+         ht_mod_cas(l)= ht_prof_cas(k2) - frac*(ht_prof_cas(k2)-ht_prof_cas(k1))
+         vt_mod_cas(l)= vt_prof_cas(k2) - frac*(vt_prof_cas(k2)-vt_prof_cas(k1))
+         dq_mod_cas(l)= dq_prof_cas(k2) - frac*(dq_prof_cas(k2)-dq_prof_cas(k1))
+         hq_mod_cas(l)= hq_prof_cas(k2) - frac*(hq_prof_cas(k2)-hq_prof_cas(k1))
+         vq_mod_cas(l)= vq_prof_cas(k2) - frac*(vq_prof_cas(k2)-vq_prof_cas(k1))
+         dtrad_mod_cas(l)= dtrad_prof_cas(k2) - frac*(dtrad_prof_cas(k2)-dtrad_prof_cas(k1))
+     
+         else !play>plev_prof_cas(1)
+
+         k1=1
+         k2=2
+         frac1 = (play(l)-plev_prof_cas(k2))/(plev_prof_cas(k1)-plev_prof_cas(k2))
+         frac2 = (play(l)-plev_prof_cas(k1))/(plev_prof_cas(k1)-plev_prof_cas(k2))
+         t_mod_cas(l)= frac1*t_prof_cas(k1) - frac2*t_prof_cas(k2)
+         q_mod_cas(l)= frac1*q_prof_cas(k1) - frac2*q_prof_cas(k2)
+         u_mod_cas(l)= frac1*u_prof_cas(k1) - frac2*u_prof_cas(k2)
+         v_mod_cas(l)= frac1*v_prof_cas(k1) - frac2*v_prof_cas(k2)
+         ug_mod_cas(l)= frac1*ug_prof_cas(k1) - frac2*ug_prof_cas(k2)
+         vg_mod_cas(l)= frac1*vg_prof_cas(k1) - frac2*vg_prof_cas(k2)
+         w_mod_cas(l)= frac1*vitw_prof_cas(k1) - frac2*vitw_prof_cas(k2)
+         du_mod_cas(l)= frac1*du_prof_cas(k1) - frac2*du_prof_cas(k2)
+         hu_mod_cas(l)= frac1*hu_prof_cas(k1) - frac2*hu_prof_cas(k2)
+         vu_mod_cas(l)= frac1*vu_prof_cas(k1) - frac2*vu_prof_cas(k2)
+         dv_mod_cas(l)= frac1*dv_prof_cas(k1) - frac2*dv_prof_cas(k2)
+         hv_mod_cas(l)= frac1*hv_prof_cas(k1) - frac2*hv_prof_cas(k2)
+         vv_mod_cas(l)= frac1*vv_prof_cas(k1) - frac2*vv_prof_cas(k2)
+         dt_mod_cas(l)= frac1*dt_prof_cas(k1) - frac2*dt_prof_cas(k2)
+         ht_mod_cas(l)= frac1*ht_prof_cas(k1) - frac2*ht_prof_cas(k2)
+         vt_mod_cas(l)= frac1*vt_prof_cas(k1) - frac2*vt_prof_cas(k2)
+         dq_mod_cas(l)= frac1*dq_prof_cas(k1) - frac2*dq_prof_cas(k2)
+         hq_mod_cas(l)= frac1*hq_prof_cas(k1) - frac2*hq_prof_cas(k2)
+         vq_mod_cas(l)= frac1*vq_prof_cas(k1) - frac2*vq_prof_cas(k2)
+         dtrad_mod_cas(l)= frac1*dtrad_prof_cas(k1) - frac2*dtrad_prof_cas(k2)
+
+         endif ! play.le.plev_prof_cas(1)
+
+        else ! above max altitude of forcing file
+ 
+!jyg
+         fact=20.*(plev_prof_cas(nlev_cas)-play(l))/plev_prof_cas(nlev_cas) !jyg
+         fact = max(fact,0.)                                           !jyg
+         fact = exp(-fact)                                             !jyg
+         t_mod_cas(l)= t_prof_cas(nlev_cas)                                   !jyg
+         q_mod_cas(l)= q_prof_cas(nlev_cas)*fact                              !jyg
+         u_mod_cas(l)= u_prof_cas(nlev_cas)*fact                              !jyg
+         v_mod_cas(l)= v_prof_cas(nlev_cas)*fact                              !jyg
+         ug_mod_cas(l)= ug_prof_cas(nlev_cas)*fact                              !jyg
+         vg_mod_cas(l)= vg_prof_cas(nlev_cas)*fact                              !jyg
+         w_mod_cas(l)= 0.0                                                 !jyg
+         du_mod_cas(l)= du_prof_cas(nlev_cas)*fact 
+         hu_mod_cas(l)= hu_prof_cas(nlev_cas)*fact                            !jyg
+         vu_mod_cas(l)= vu_prof_cas(nlev_cas)*fact                            !jyg
+         dv_mod_cas(l)= dv_prof_cas(nlev_cas)*fact 
+         hv_mod_cas(l)= hv_prof_cas(nlev_cas)*fact                            !jyg
+         vv_mod_cas(l)= vv_prof_cas(nlev_cas)*fact                            !jyg
+         dt_mod_cas(l)= dt_prof_cas(nlev_cas) 
+         ht_mod_cas(l)= ht_prof_cas(nlev_cas)                                 !jyg
+         vt_mod_cas(l)= vt_prof_cas(nlev_cas)                                 !jyg
+         dq_mod_cas(l)= dq_prof_cas(nlev_cas)*fact 
+         hq_mod_cas(l)= hq_prof_cas(nlev_cas)*fact                            !jyg
+         vq_mod_cas(l)= vq_prof_cas(nlev_cas)*fact                            !jyg
+         dtrad_mod_cas(l)= dtrad_prof_cas(nlev_cas)*fact                      !jyg
+ 
+        endif ! play
+ 
+       enddo ! l
+
+!       do l = 1,llm
+!       print *,'t_mod_cas(l),q_mod_cas(l),ht_mod_cas(l),hq_mod_cas(l) ',
+!     $        l,t_mod_cas(l),q_mod_cas(l),ht_mod_cas(l),hq_mod_cas(l)
+!       enddo
+ 
+          return
+          end
+!***************************************************************************** 
+!=====================================================================
+       SUBROUTINE interp_dice_vertical(play,nlev_dice,nt_dice,plev_prof   &
+     &         ,th_prof,qv_prof,u_prof,v_prof,o3_prof                     &
+     &         ,ht_prof,hq_prof,hu_prof,hv_prof,w_prof,omega_prof         &
+     &         ,th_mod,qv_mod,u_mod,v_mod,o3_mod                          &
+     &         ,ht_mod,hq_mod,hu_mod,hv_mod,w_mod,omega_mod,mxcalc)
+ 
+       implicit none
+ 
+#include "dimensions.h"
+
+!-------------------------------------------------------------------------
+! Vertical interpolation of Dice forcing data onto model levels
+!-------------------------------------------------------------------------
+ 
+       integer nlevmax
+       parameter (nlevmax=41)
+       integer nlev_dice,mxcalc,nt_dice
+ 
+       real play(llm), plev_prof(nlev_dice) 
+       real th_prof(nlev_dice),qv_prof(nlev_dice)
+       real u_prof(nlev_dice),v_prof(nlev_dice) 
+       real o3_prof(nlev_dice)
+       real ht_prof(nlev_dice),hq_prof(nlev_dice)
+       real hu_prof(nlev_dice),hv_prof(nlev_dice)
+       real w_prof(nlev_dice),omega_prof(nlev_dice)
+ 
+       real th_mod(llm),qv_mod(llm)
+       real u_mod(llm),v_mod(llm), o3_mod(llm)
+       real ht_mod(llm),hq_mod(llm)
+       real hu_mod(llm),hv_mod(llm),w_mod(llm),omega_mod(llm)
+ 
+       integer l,k,k1,k2,kp
+       real aa,frac,frac1,frac2,fact
+ 
+       do l = 1, llm
+
+        if (play(l).ge.plev_prof(nlev_dice)) then
+ 
+        mxcalc=l
+         k1=0
+         k2=0
+
+         if (play(l).le.plev_prof(1)) then
+
+         do k = 1, nlev_dice-1
+          if (play(l).le.plev_prof(k) .and. play(l).gt.plev_prof(k+1)) then
+            k1=k
+            k2=k+1
+          endif
+         enddo
+
+         if (k1.eq.0 .or. k2.eq.0) then
+          write(*,*) 'PB! k1, k2 = ',k1,k2
+          write(*,*) 'l,play(l) = ',l,play(l)/100
+         do k = 1, nlev_dice-1
+          write(*,*) 'k,plev_prof(k) = ',k,plev_prof(k)/100
+         enddo
+         endif
+
+         frac = (plev_prof(k2)-play(l))/(plev_prof(k2)-plev_prof(k1))
+         th_mod(l)= th_prof(k2) - frac*(th_prof(k2)-th_prof(k1))
+         qv_mod(l)= qv_prof(k2) - frac*(qv_prof(k2)-qv_prof(k1))
+         u_mod(l)= u_prof(k2) - frac*(u_prof(k2)-u_prof(k1))
+         v_mod(l)= v_prof(k2) - frac*(v_prof(k2)-v_prof(k1))
+         o3_mod(l)= o3_prof(k2) - frac*(o3_prof(k2)-o3_prof(k1))
+         ht_mod(l)= ht_prof(k2) - frac*(ht_prof(k2)-ht_prof(k1))
+         hq_mod(l)= hq_prof(k2) - frac*(hq_prof(k2)-hq_prof(k1))
+         hu_mod(l)= hu_prof(k2) - frac*(hu_prof(k2)-hu_prof(k1))
+         hv_mod(l)= hv_prof(k2) - frac*(hv_prof(k2)-hv_prof(k1))
+         w_mod(l)= w_prof(k2) - frac*(w_prof(k2)-w_prof(k1))
+         omega_mod(l)= omega_prof(k2) - frac*(omega_prof(k2)-omega_prof(k1))
+     
+         else !play>plev_prof(1)
+
+         k1=1
+         k2=2
+         frac1 = (play(l)-plev_prof(k2))/(plev_prof(k1)-plev_prof(k2))
+         frac2 = (play(l)-plev_prof(k1))/(plev_prof(k1)-plev_prof(k2))
+         th_mod(l)= frac1*th_prof(k1) - frac2*th_prof(k2)
+         qv_mod(l)= frac1*qv_prof(k1) - frac2*qv_prof(k2)
+         u_mod(l)= frac1*u_prof(k1) - frac2*u_prof(k2)
+         v_mod(l)= frac1*v_prof(k1) - frac2*v_prof(k2)
+         o3_mod(l)= frac1*o3_prof(k1) - frac2*o3_prof(k2)
+         ht_mod(l)= frac1*ht_prof(k1) - frac2*ht_prof(k2)
+         hq_mod(l)= frac1*hq_prof(k1) - frac2*hq_prof(k2)
+         hu_mod(l)= frac1*hu_prof(k1) - frac2*hu_prof(k2)
+         hv_mod(l)= frac1*hv_prof(k1) - frac2*hv_prof(k2)
+         w_mod(l)= frac1*w_prof(k1) - frac2*w_prof(k2)
+         omega_mod(l)= frac1*omega_prof(k1) - frac2*omega_prof(k2)
+
+         endif ! play.le.plev_prof(1)
+
+        else ! above max altitude of forcing file
+ 
+!jyg
+         fact=20.*(plev_prof(nlev_dice)-play(l))/plev_prof(nlev_dice) !jyg
+         fact = max(fact,0.)                                           !jyg
+         fact = exp(-fact)                                             !jyg
+         th_mod(l)= th_prof(nlev_dice)                                 !jyg
+         qv_mod(l)= qv_prof(nlev_dice)*fact                            !jyg
+         u_mod(l)= u_prof(nlev_dice)*fact                              !jyg
+         v_mod(l)= v_prof(nlev_dice)*fact                              !jyg
+         o3_mod(l)= o3_prof(nlev_dice)*fact                            !jyg
+         ht_mod(l)= ht_prof(nlev_dice)                                 !jyg
+         hq_mod(l)= hq_prof(nlev_dice)*fact                            !jyg
+         hu_mod(l)= hu_prof(nlev_dice)                                 !jyg
+         hv_mod(l)= hv_prof(nlev_dice)                                 !jyg
+         w_mod(l)= 0.                                                  !jyg
+         omega_mod(l)= 0.                                              !jyg
+ 
+        endif ! play
+ 
+       enddo ! l
+
+!       do l = 1,llm
+!       print *,'t_mod(l),q_mod(l),ht_mod(l),hq_mod(l) ',
+!     $        l,t_mod(l),q_mod(l),ht_mod(l),hq_mod(l)
+!       enddo
+ 
+          return
+          end
+
+!======================================================================
+        SUBROUTINE interp_astex_time(day,day1,annee_ref                    &
+     &             ,year_ini_astex,day_ini_astex,nt_astex,dt_astex         &
+     &             ,nlev_astex,div_astex,ts_astex,ug_astex,vg_astex        &
+     &             ,ufa_astex,vfa_astex,div_prof,ts_prof,ug_prof,vg_prof   &
+     &             ,ufa_prof,vfa_prof)
+        implicit none
+
+!---------------------------------------------------------------------------------------
+! Time interpolation of a 2D field to the timestep corresponding to day
+!
+! day: current julian day (e.g. 717538.2)
+! day1: first day of the simulation
+! nt_astex: total nb of data in the forcing (e.g. 41 for Astex)
+! dt_astex: total time interval (in sec) between 2 forcing data (e.g. 1h for Astex)
+!---------------------------------------------------------------------------------------
+
+! inputs:
+        integer annee_ref
+        integer nt_astex,nlev_astex
+        integer year_ini_astex
+        real day, day1,day_ini_astex,dt_astex
+        real div_astex(nt_astex),ts_astex(nt_astex),ug_astex(nt_astex)
+        real vg_astex(nt_astex),ufa_astex(nt_astex),vfa_astex(nt_astex)
+! outputs:
+        real div_prof,ts_prof,ug_prof,vg_prof,ufa_prof,vfa_prof
+! local:
+        integer it_astex1, it_astex2
+        real timeit,time_astex1,time_astex2,frac
+
+! Check that initial day of the simulation consistent with ASTEX period:
+       if (annee_ref.ne.1992 ) then
+        print*,'Pour Astex, annee_ref doit etre 1992 '
+        print*,'Changer annee_ref dans run.def'
+        stop
+       endif
+       if (annee_ref.eq.1992 .and. day1.lt.day_ini_astex) then
+        print*,'Astex debute le 13 Juin 1992 (jour julien=165)'
+        print*,'Changer dayref dans run.def'
+        stop
+       endif
+
+! Determine timestep relative to the 1st day of TOGA-COARE:
+!       timeit=(day-day1)*86400.
+!       if (annee_ref.eq.1992) then
+!        timeit=(day-day_ini_astex)*86400.
+!       else
+!        timeit=(day+2.-1.)*86400. ! 2 days between Jun13 and Jun15 1992
+!       endif
+      timeit=(day-day_ini_astex)*86400
+
+! Determine the closest observation times:
+       it_astex1=INT(timeit/dt_astex)+1
+       it_astex2=it_astex1 + 1
+       time_astex1=(it_astex1-1)*dt_astex
+       time_astex2=(it_astex2-1)*dt_astex
+       print *,'timeit day day_ini_astex',timeit,day,day_ini_astex
+       print *,'it_astex1,it_astex2,time_astex1,time_astex2',              &
+     &          it_astex1,it_astex2,time_astex1,time_astex2
+
+       if (it_astex1 .ge. nt_astex) then
+        write(*,*) 'PB-stop: day, it_astex1, it_astex2, timeit: '          &
+     &        ,day,it_astex1,it_astex2,timeit/86400.
+        stop
+       endif
+
+! time interpolation:
+       frac=(time_astex2-timeit)/(time_astex2-time_astex1)
+       frac=max(frac,0.0)
+
+       div_prof = div_astex(it_astex2)                                     &
+     &          -frac*(div_astex(it_astex2)-div_astex(it_astex1))
+       ts_prof = ts_astex(it_astex2)                                        &
+     &          -frac*(ts_astex(it_astex2)-ts_astex(it_astex1))
+       ug_prof = ug_astex(it_astex2)                                       &
+     &          -frac*(ug_astex(it_astex2)-ug_astex(it_astex1))
+       vg_prof = vg_astex(it_astex2)                                       &
+     &          -frac*(vg_astex(it_astex2)-vg_astex(it_astex1))
+       ufa_prof = ufa_astex(it_astex2)                                     &
+     &          -frac*(ufa_astex(it_astex2)-ufa_astex(it_astex1))
+       vfa_prof = vfa_astex(it_astex2)                                     &
+     &          -frac*(vfa_astex(it_astex2)-vfa_astex(it_astex1))
+
+         print*,                                                           &
+     &'day,annee_ref,day_ini_astex,timeit,it_astex1,it_astex2,SST:',       &
+     &day,annee_ref,day_ini_astex,timeit/86400.,it_astex1,                 &
+     &it_astex2,div_prof,ts_prof,ug_prof,vg_prof,ufa_prof,vfa_prof 
+
+        return
+        END
+
+!======================================================================
+        SUBROUTINE interp_toga_time(day,day1,annee_ref                     &
+     &             ,year_ini_toga,day_ini_toga,nt_toga,dt_toga,nlev_toga   &
+     &             ,ts_toga,plev_toga,t_toga,q_toga,u_toga,v_toga,w_toga   &
+     &             ,ht_toga,vt_toga,hq_toga,vq_toga                        &
+     &             ,ts_prof,plev_prof,t_prof,q_prof,u_prof,v_prof,w_prof   &
+     &             ,ht_prof,vt_prof,hq_prof,vq_prof)
+        implicit none
+
+!---------------------------------------------------------------------------------------
+! Time interpolation of a 2D field to the timestep corresponding to day
+!
+! day: current julian day (e.g. 717538.2)
+! day1: first day of the simulation
+! nt_toga: total nb of data in the forcing (e.g. 480 for TOGA-COARE)
+! dt_toga: total time interval (in sec) between 2 forcing data (e.g. 6h for TOGA-COARE)
+!---------------------------------------------------------------------------------------
+
+#include "compar1d.h"
+
+! inputs:
+        integer annee_ref
+        integer nt_toga,nlev_toga
+        integer year_ini_toga
+        real day, day1,day_ini_toga,dt_toga
+        real ts_toga(nt_toga)
+        real plev_toga(nlev_toga,nt_toga),t_toga(nlev_toga,nt_toga)
+        real q_toga(nlev_toga,nt_toga),u_toga(nlev_toga,nt_toga)
+        real v_toga(nlev_toga,nt_toga),w_toga(nlev_toga,nt_toga)
+        real ht_toga(nlev_toga,nt_toga),vt_toga(nlev_toga,nt_toga)
+        real hq_toga(nlev_toga,nt_toga),vq_toga(nlev_toga,nt_toga)
+! outputs:
+        real ts_prof
+        real plev_prof(nlev_toga),t_prof(nlev_toga)
+        real q_prof(nlev_toga),u_prof(nlev_toga)
+        real v_prof(nlev_toga),w_prof(nlev_toga)
+        real ht_prof(nlev_toga),vt_prof(nlev_toga)
+        real hq_prof(nlev_toga),vq_prof(nlev_toga)
+! local:
+        integer it_toga1, it_toga2,k
+        real timeit,time_toga1,time_toga2,frac
+
+
+        if (forcing_type.eq.2) then
+! Check that initial day of the simulation consistent with TOGA-COARE period:
+       if (annee_ref.ne.1992 .and. annee_ref.ne.1993) then
+        print*,'Pour TOGA-COARE, annee_ref doit etre 1992 ou 1993'
+        print*,'Changer annee_ref dans run.def'
+        stop
+       endif
+       if (annee_ref.eq.1992 .and. day1.lt.day_ini_toga) then
+        print*,'TOGA-COARE a debute le 1er Nov 1992 (jour julien=306)'
+        print*,'Changer dayref dans run.def'
+        stop
+       endif
+       if (annee_ref.eq.1993 .and. day1.gt.day_ini_toga+119) then
+        print*,'TOGA-COARE a fini le 28 Feb 1993 (jour julien=59)'
+        print*,'Changer dayref ou nday dans run.def'
+        stop
+       endif
+
+       else if (forcing_type.eq.4) then
+
+! Check that initial day of the simulation consistent with TWP-ICE period:
+       if (annee_ref.ne.2006) then
+        print*,'Pour TWP-ICE, annee_ref doit etre 2006'
+        print*,'Changer annee_ref dans run.def'
+        stop
+       endif
+       if (annee_ref.eq.2006 .and. day1.lt.day_ini_toga) then
+        print*,'TWP-ICE a debute le 17 Jan 2006 (jour julien=17)'
+        print*,'Changer dayref dans run.def'
+        stop
+       endif
+       if (annee_ref.eq.2006 .and. day1.gt.day_ini_toga+26) then
+        print*,'TWP-ICE a fini le 12 Feb 2006 (jour julien=43)'
+        print*,'Changer dayref ou nday dans run.def'
+        stop
+       endif
+
+       endif
+
+! Determine timestep relative to the 1st day of TOGA-COARE:
+!       timeit=(day-day1)*86400.
+!       if (annee_ref.eq.1992) then
+!        timeit=(day-day_ini_toga)*86400.
+!       else
+!        timeit=(day+61.-1.)*86400. ! 61 days between Nov01 and Dec31 1992
+!       endif
+      timeit=(day-day_ini_toga)*86400
+
+! Determine the closest observation times:
+       it_toga1=INT(timeit/dt_toga)+1
+       it_toga2=it_toga1 + 1
+       time_toga1=(it_toga1-1)*dt_toga
+       time_toga2=(it_toga2-1)*dt_toga
+
+       if (it_toga1 .ge. nt_toga) then
+        write(*,*) 'PB-stop: day, it_toga1, it_toga2, timeit: '            &
+     &        ,day,it_toga1,it_toga2,timeit/86400.
+        stop
+       endif
+
+! time interpolation:
+       frac=(time_toga2-timeit)/(time_toga2-time_toga1)
+       frac=max(frac,0.0)
+
+       ts_prof = ts_toga(it_toga2)                                         &
+     &          -frac*(ts_toga(it_toga2)-ts_toga(it_toga1))
+
+!        print*,
+!     :'day,annee_ref,day_ini_toga,timeit,it_toga1,it_toga2,SST:',
+!     :day,annee_ref,day_ini_toga,timeit/86400.,it_toga1,it_toga2,ts_prof
+
+       do k=1,nlev_toga
+        plev_prof(k) = 100.*(plev_toga(k,it_toga2)                         &
+     &          -frac*(plev_toga(k,it_toga2)-plev_toga(k,it_toga1)))
+        t_prof(k) = t_toga(k,it_toga2)                                     &
+     &          -frac*(t_toga(k,it_toga2)-t_toga(k,it_toga1))
+        q_prof(k) = q_toga(k,it_toga2)                                     &
+     &          -frac*(q_toga(k,it_toga2)-q_toga(k,it_toga1))
+        u_prof(k) = u_toga(k,it_toga2)                                     &
+     &          -frac*(u_toga(k,it_toga2)-u_toga(k,it_toga1))
+        v_prof(k) = v_toga(k,it_toga2)                                     &
+     &          -frac*(v_toga(k,it_toga2)-v_toga(k,it_toga1))
+        w_prof(k) = w_toga(k,it_toga2)                                     &
+     &          -frac*(w_toga(k,it_toga2)-w_toga(k,it_toga1))
+        ht_prof(k) = ht_toga(k,it_toga2)                                   &
+     &          -frac*(ht_toga(k,it_toga2)-ht_toga(k,it_toga1))
+        vt_prof(k) = vt_toga(k,it_toga2)                                   &
+     &          -frac*(vt_toga(k,it_toga2)-vt_toga(k,it_toga1))
+        hq_prof(k) = hq_toga(k,it_toga2)                                   &
+     &          -frac*(hq_toga(k,it_toga2)-hq_toga(k,it_toga1))
+        vq_prof(k) = vq_toga(k,it_toga2)                                   &
+     &          -frac*(vq_toga(k,it_toga2)-vq_toga(k,it_toga1))
+        enddo
+
+        return
+        END
+
+!======================================================================
+        SUBROUTINE interp_dice_time(day,day1,annee_ref                    &
+     &             ,year_ini_dice,day_ini_dice,nt_dice,dt_dice            &
+     &             ,nlev_dice,shf_dice,lhf_dice,lwup_dice,swup_dice       &
+     &             ,tg_dice,ustar_dice,psurf_dice,ug_dice,vg_dice         &
+     &             ,ht_dice,hq_dice,hu_dice,hv_dice,w_dice,omega_dice     &
+     &             ,shf_prof,lhf_prof,lwup_prof,swup_prof,tg_prof         &
+     &             ,ustar_prof,psurf_prof,ug_prof,vg_prof                 &
+     &             ,ht_prof,hq_prof,hu_prof,hv_prof,w_prof,omega_prof)
+        implicit none
+
+!---------------------------------------------------------------------------------------
+! Time interpolation of a 2D field to the timestep corresponding to day
+!
+! day: current julian day (e.g. 717538.2)
+! day1: first day of the simulation
+! nt_dice: total nb of data in the forcing (e.g. 145 for Dice)
+! dt_dice: total time interval (in sec) between 2 forcing data (e.g. 30min. for Dice)
+!---------------------------------------------------------------------------------------
+
+#include "compar1d.h"
+
+! inputs:
+        integer annee_ref
+        integer nt_dice,nlev_dice
+        integer year_ini_dice
+        real day, day1,day_ini_dice,dt_dice
+        real shf_dice(nt_dice),lhf_dice(nt_dice),lwup_dice(nt_dice)
+        real swup_dice(nt_dice),tg_dice(nt_dice),ustar_dice(nt_dice)
+        real psurf_dice(nt_dice),ug_dice(nt_dice),vg_dice(nt_dice)
+        real ht_dice(nlev_dice,nt_dice),hq_dice(nlev_dice,nt_dice)
+        real hu_dice(nlev_dice,nt_dice),hv_dice(nlev_dice,nt_dice)
+        real w_dice(nlev_dice,nt_dice),omega_dice(nlev_dice,nt_dice)
+! outputs:
+        real tg_prof,shf_prof,lhf_prof,lwup_prof,swup_prof
+        real ustar_prof,psurf_prof,ug_prof,vg_prof
+        real ht_prof(nlev_dice),hq_prof(nlev_dice)
+        real hu_prof(nlev_dice),hv_prof(nlev_dice)
+        real w_prof(nlev_dice),omega_prof(nlev_dice)
+! local:
+        integer it_dice1, it_dice2,k
+        real timeit,time_dice1,time_dice2,frac
+
+
+        if (forcing_type.eq.7) then
+! Check that initial day of the simulation consistent with Dice period:
+       print *,'annee_ref=',annee_ref
+       print *,'day1=',day1
+       print *,'day_ini_dice=',day_ini_dice
+       if (annee_ref.ne.1999) then
+        print*,'Pour Dice, annee_ref doit etre 1999'
+        print*,'Changer annee_ref dans run.def'
+        stop
+       endif
+       if (annee_ref.eq.1999 .and. day1.gt.day_ini_dice) then
+        print*,'Dice a debute le 23 Oct 1999 (jour julien=296)'
+        print*,'Changer dayref dans run.def',day1,day_ini_dice
+        stop
+       endif
+       if (annee_ref.eq.1999 .and. day1.gt.day_ini_dice+2) then
+        print*,'Dice a fini le 25 Oct 1999 (jour julien=298)'
+        print*,'Changer dayref ou nday dans run.def',day1,day_ini_dice
+        stop
+       endif
+
+       endif
+
+! Determine timestep relative to the 1st day of TOGA-COARE:
+!       timeit=(day-day1)*86400.
+!       if (annee_ref.eq.1992) then
+!        timeit=(day-day_ini_dice)*86400.
+!       else
+!        timeit=(day+61.-1.)*86400. ! 61 days between Nov01 and Dec31 1992
+!       endif
+      timeit=(day-day_ini_dice)*86400
+
+! Determine the closest observation times:
+       it_dice1=INT(timeit/dt_dice)+1
+       it_dice2=it_dice1 + 1
+       time_dice1=(it_dice1-1)*dt_dice
+       time_dice2=(it_dice2-1)*dt_dice
+
+       if (it_dice1 .ge. nt_dice) then
+        write(*,*) 'PB-stop: day, it_dice1, it_dice2, timeit: ',day,it_dice1,it_dice2,timeit/86400.
+        stop
+       endif
+
+! time interpolation:
+       frac=(time_dice2-timeit)/(time_dice2-time_dice1)
+       frac=max(frac,0.0)
+
+       shf_prof = shf_dice(it_dice2)-frac*(shf_dice(it_dice2)-shf_dice(it_dice1))
+       lhf_prof = lhf_dice(it_dice2)-frac*(lhf_dice(it_dice2)-lhf_dice(it_dice1))
+       lwup_prof = lwup_dice(it_dice2)-frac*(lwup_dice(it_dice2)-lwup_dice(it_dice1))
+       swup_prof = swup_dice(it_dice2)-frac*(swup_dice(it_dice2)-swup_dice(it_dice1))
+       tg_prof = tg_dice(it_dice2)-frac*(tg_dice(it_dice2)-tg_dice(it_dice1))
+       ustar_prof = ustar_dice(it_dice2)-frac*(ustar_dice(it_dice2)-ustar_dice(it_dice1))
+       psurf_prof = psurf_dice(it_dice2)-frac*(psurf_dice(it_dice2)-psurf_dice(it_dice1))
+       ug_prof = ug_dice(it_dice2)-frac*(ug_dice(it_dice2)-ug_dice(it_dice1))
+       vg_prof = vg_dice(it_dice2)-frac*(vg_dice(it_dice2)-vg_dice(it_dice1))
+
+!        print*,
+!     :'day,annee_ref,day_ini_dice,timeit,it_dice1,it_dice2,SST:',
+!     :day,annee_ref,day_ini_dice,timeit/86400.,it_dice1,it_dice2,ts_prof
+
+       do k=1,nlev_dice
+        ht_prof(k) = ht_dice(k,it_dice2)-frac*(ht_dice(k,it_dice2)-ht_dice(k,it_dice1))
+        hq_prof(k) = hq_dice(k,it_dice2)-frac*(hq_dice(k,it_dice2)-hq_dice(k,it_dice1))
+        hu_prof(k) = hu_dice(k,it_dice2)-frac*(hu_dice(k,it_dice2)-hu_dice(k,it_dice1))
+        hv_prof(k) = hv_dice(k,it_dice2)-frac*(hv_dice(k,it_dice2)-hv_dice(k,it_dice1))
+        w_prof(k) = w_dice(k,it_dice2)-frac*(w_dice(k,it_dice2)-w_dice(k,it_dice1))
+        omega_prof(k) = omega_dice(k,it_dice2)-frac*(omega_dice(k,it_dice2)-omega_dice(k,it_dice1))
+        enddo
+
+        return
+        END
+
+!======================================================================
+        SUBROUTINE interp_gabls4_time(day,day1,annee_ref                              &
+     &             ,year_ini_gabls4,day_ini_gabls4,nt_gabls4,dt_gabls4,nlev_gabls4    &
+     &             ,ug_gabls4,vg_gabls4,ht_gabls4,hq_gabls4,tg_gabls4                          &
+     &             ,ug_prof,vg_prof,ht_prof,hq_prof,tg_prof)
+        implicit none
+
+!---------------------------------------------------------------------------------------
+! Time interpolation of a 2D field to the timestep corresponding to day
+!
+! day: current julian day 
+! day1: first day of the simulation
+! nt_gabls4: total nb of data in the forcing (e.g. 37 for gabls4)
+! dt_gabls4: total time interval (in sec) between 2 forcing data (e.g. 60min. for gabls4)
+!---------------------------------------------------------------------------------------
+
+#include "compar1d.h"
+
+! inputs:
+        integer annee_ref
+        integer nt_gabls4,nlev_gabls4
+        integer year_ini_gabls4
+        real day, day1,day_ini_gabls4,dt_gabls4
+        real ug_gabls4(nlev_gabls4,nt_gabls4),vg_gabls4(nlev_gabls4,nt_gabls4)
+        real ht_gabls4(nlev_gabls4,nt_gabls4),hq_gabls4(nlev_gabls4,nt_gabls4)
+        real tg_gabls4(nt_gabls4), tg_prof
+! outputs:
+        real ug_prof(nlev_gabls4),vg_prof(nlev_gabls4)
+        real ht_prof(nlev_gabls4),hq_prof(nlev_gabls4)
+! local:
+        integer it_gabls41, it_gabls42,k
+        real timeit,time_gabls41,time_gabls42,frac
+
+
+
+! Check that initial day of the simulation consistent with gabls4 period:
+       if (forcing_type.eq.8 ) then
+       print *,'annee_ref=',annee_ref
+       print *,'day1=',day1
+       print *,'day_ini_gabls4=',day_ini_gabls4
+       if (annee_ref.ne.2009) then
+        print*,'Pour gabls4, annee_ref doit etre 2009'
+        print*,'Changer annee_ref dans run.def'
+        stop
+       endif
+       if (annee_ref.eq.2009 .and. day1.gt.day_ini_gabls4) then
+        print*,'gabls4 a debute le 11 dec 2009 (jour julien=345)'
+        print*,'Changer dayref dans run.def',day1,day_ini_gabls4
+        stop
+       endif
+       if (annee_ref.eq.2009 .and. day1.gt.day_ini_gabls4+2) then
+        print*,'gabls4 a fini le 12 dec 2009 (jour julien=346)'
+        print*,'Changer dayref ou nday dans run.def',day1,day_ini_gabls4
+        stop
+       endif
+       endif
+
+      timeit=(day-day_ini_gabls4)*86400
+       print *,'day,day_ini_gabls4=',day,day_ini_gabls4
+       print *,'nt_gabls4,dt,timeit=',nt_gabls4,dt_gabls4,timeit
+
+! Determine the closest observation times:
+       it_gabls41=INT(timeit/dt_gabls4)+1
+       it_gabls42=it_gabls41 + 1
+       time_gabls41=(it_gabls41-1)*dt_gabls4
+       time_gabls42=(it_gabls42-1)*dt_gabls4
+
+       if (it_gabls41 .ge. nt_gabls4) then
+        write(*,*) 'PB-stop: day, it_gabls41, it_gabls42, timeit: ',day,it_gabls41,it_gabls42,timeit/86400.
+        stop
+       endif
+
+! time interpolation:
+       frac=(time_gabls42-timeit)/(time_gabls42-time_gabls41)
+       frac=max(frac,0.0)
+
+
+       do k=1,nlev_gabls4
+        ug_prof(k) = ug_gabls4(k,it_gabls42)-frac*(ug_gabls4(k,it_gabls42)-ug_gabls4(k,it_gabls41))
+        vg_prof(k) = vg_gabls4(k,it_gabls42)-frac*(vg_gabls4(k,it_gabls42)-vg_gabls4(k,it_gabls41))
+        ht_prof(k) = ht_gabls4(k,it_gabls42)-frac*(ht_gabls4(k,it_gabls42)-ht_gabls4(k,it_gabls41))
+        hq_prof(k) = hq_gabls4(k,it_gabls42)-frac*(hq_gabls4(k,it_gabls42)-hq_gabls4(k,it_gabls41))
+        enddo
+        tg_prof=tg_gabls4(it_gabls42)-frac*(tg_gabls4(it_gabls42)-tg_gabls4(it_gabls41))
+        return
+        END
+
+!======================================================================
+        SUBROUTINE interp_armcu_time(day,day1,annee_ref                    &
+     &             ,year_ini_armcu,day_ini_armcu,nt_armcu,dt_armcu         &
+     &             ,nlev_armcu,fs_armcu,fl_armcu,at_armcu,rt_armcu         &
+     &             ,aqt_armcu,fs_prof,fl_prof,at_prof,rt_prof,aqt_prof)
+        implicit none
+
+!---------------------------------------------------------------------------------------
+! Time interpolation of a 2D field to the timestep corresponding to day
+!
+! day: current julian day (e.g. 717538.2)
+! day1: first day of the simulation
+! nt_armcu: total nb of data in the forcing (e.g. 31 for armcu)
+! dt_armcu: total time interval (in sec) between 2 forcing data (e.g. 1/2h for armcu)
+! fs= sensible flux
+! fl= latent flux
+! at,rt,aqt= advective and radiative tendencies
+!---------------------------------------------------------------------------------------
+
+! inputs:
+        integer annee_ref
+        integer nt_armcu,nlev_armcu
+        integer year_ini_armcu
+        real day, day1,day_ini_armcu,dt_armcu
+        real fs_armcu(nt_armcu),fl_armcu(nt_armcu),at_armcu(nt_armcu)
+        real rt_armcu(nt_armcu),aqt_armcu(nt_armcu)
+! outputs:
+        real fs_prof,fl_prof,at_prof,rt_prof,aqt_prof
+! local:
+        integer it_armcu1, it_armcu2,k
+        real timeit,time_armcu1,time_armcu2,frac
+
+! Check that initial day of the simulation consistent with ARMCU period:
+       if (annee_ref.ne.1997 ) then
+        print*,'Pour ARMCU, annee_ref doit etre 1997 '
+        print*,'Changer annee_ref dans run.def'
+        stop
+       endif
+
+      timeit=(day-day_ini_armcu)*86400
+
+! Determine the closest observation times:
+       it_armcu1=INT(timeit/dt_armcu)+1
+       it_armcu2=it_armcu1 + 1
+       time_armcu1=(it_armcu1-1)*dt_armcu
+       time_armcu2=(it_armcu2-1)*dt_armcu
+       print *,'timeit day day_ini_armcu',timeit,day,day_ini_armcu
+       print *,'it_armcu1,it_armcu2,time_armcu1,time_armcu2',              &
+     &          it_armcu1,it_armcu2,time_armcu1,time_armcu2
+
+       if (it_armcu1 .ge. nt_armcu) then
+        write(*,*) 'PB-stop: day, it_armcu1, it_armcu2, timeit: '          &
+     &        ,day,it_armcu1,it_armcu2,timeit/86400.
+        stop
+       endif
+
+! time interpolation:
+       frac=(time_armcu2-timeit)/(time_armcu2-time_armcu1)
+       frac=max(frac,0.0)
+
+       fs_prof = fs_armcu(it_armcu2)                                       &
+     &          -frac*(fs_armcu(it_armcu2)-fs_armcu(it_armcu1))
+       fl_prof = fl_armcu(it_armcu2)                                       &
+     &          -frac*(fl_armcu(it_armcu2)-fl_armcu(it_armcu1))
+       at_prof = at_armcu(it_armcu2)                                       &
+     &          -frac*(at_armcu(it_armcu2)-at_armcu(it_armcu1))
+       rt_prof = rt_armcu(it_armcu2)                                       &
+     &          -frac*(rt_armcu(it_armcu2)-rt_armcu(it_armcu1))
+       aqt_prof = aqt_armcu(it_armcu2)                                       &
+     &          -frac*(aqt_armcu(it_armcu2)-aqt_armcu(it_armcu1))
+
+         print*,                                                           &
+     &'day,annee_ref,day_ini_armcu,timeit,it_armcu1,it_armcu2,SST:',       &
+     &day,annee_ref,day_ini_armcu,timeit/86400.,it_armcu1,                 &
+     &it_armcu2,fs_prof,fl_prof,at_prof,rt_prof,aqt_prof
+
+        return
+        END
+
+!=====================================================================
+      subroutine readprofiles(nlev_max,kmax,ntrac,height,                  &
+     &           thlprof,qtprof,uprof,                                     &
+     &           vprof,e12prof,ugprof,vgprof,                              &
+     &           wfls,dqtdxls,dqtdyls,dqtdtls,                             &
+     &           thlpcar,tracer,nt1,nt2)
+      implicit none
+
+        integer nlev_max,kmax,kmax2,ntrac
+        logical :: llesread = .true.
+
+        real height(nlev_max),thlprof(nlev_max),qtprof(nlev_max),          &
+     &       uprof(nlev_max),vprof(nlev_max),e12prof(nlev_max),            &
+     &       ugprof(nlev_max),vgprof(nlev_max),wfls(nlev_max),             &
+     &       dqtdxls(nlev_max),dqtdyls(nlev_max),dqtdtls(nlev_max),        &
+     &           thlpcar(nlev_max),tracer(nlev_max,ntrac)
+
+        real height1(nlev_max)
+
+        integer, parameter :: ilesfile=1
+        integer :: ierr,k,itrac,nt1,nt2
+
+        if(.not.(llesread)) return
+
+       open (ilesfile,file='prof.inp.001',status='old',iostat=ierr)
+        if (ierr /= 0) stop 'ERROR:Prof.inp does not exist'
+        read (ilesfile,*) kmax
+        do k=1,kmax
+          read (ilesfile,*) height1(k),thlprof(k),qtprof (k),               &
+     &                      uprof (k),vprof  (k),e12prof(k)
+        enddo
+        close(ilesfile)
+
+       open(ilesfile,file='lscale.inp.001',status='old',iostat=ierr)
+        if (ierr /= 0) stop 'ERROR:Lscale.inp does not exist'
+        read (ilesfile,*) kmax2
+        if (kmax .ne. kmax2) then
+          print *, 'fichiers prof.inp et lscale.inp incompatibles :'
+          print *, 'nbre de niveaux : ',kmax,' et ',kmax2
+          stop 'lecture profiles'
+        endif
+        do k=1,kmax
+          read (ilesfile,*) height(k),ugprof(k),vgprof(k),wfls(k),         &
+     &                      dqtdxls(k),dqtdyls(k),dqtdtls(k),thlpcar(k)
+        end do
+        do k=1,kmax
+          if (height(k) .ne. height1(k)) then
+            print *, 'fichiers prof.inp et lscale.inp incompatibles :'
+            print *, 'les niveaux different : ',k,height1(k), height(k)
+            stop
+          endif
+        end do
+        close(ilesfile)
+
+       open(ilesfile,file='trac.inp.001',status='old',iostat=ierr)
+        if (ierr /= 0) then
+            print*,'WARNING : trac.inp does not exist'
+        else
+        read (ilesfile,*) kmax2,nt1,nt2
+        if (nt2>ntrac) then
+          stop 'Augmenter le nombre de traceurs dans traceur.def'
+        endif
+        if (kmax .ne. kmax2) then
+          print *, 'fichiers prof.inp et lscale.inp incompatibles :'
+          print *, 'nbre de niveaux : ',kmax,' et ',kmax2
+          stop 'lecture profiles'
+        endif
+        do k=1,kmax
+          read (ilesfile,*) height(k),(tracer(k,itrac),itrac=nt1,nt2)
+        end do
+        close(ilesfile)
+        endif
+
+        return
+        end
+!======================================================================
+      subroutine readprofile_sandu(nlev_max,kmax,height,pprof,tprof,       &
+     &       thlprof,qprof,uprof,vprof,wprof,omega,o3mmr)
+!======================================================================
+      implicit none
+
+        integer nlev_max,kmax
+        logical :: llesread = .true.
+
+        real height(nlev_max),pprof(nlev_max),tprof(nlev_max)
+        real thlprof(nlev_max)
+        real qprof(nlev_max),uprof(nlev_max),vprof(nlev_max)
+        real wprof(nlev_max),omega(nlev_max),o3mmr(nlev_max)
+
+        integer, parameter :: ilesfile=1
+        integer :: k,ierr
+
+        if(.not.(llesread)) return
+
+       open (ilesfile,file='prof.inp.001',status='old',iostat=ierr)
+        if (ierr /= 0) stop 'ERROR:Prof.inp does not exist'
+        read (ilesfile,*) kmax
+        do k=1,kmax
+          read (ilesfile,*) height(k),pprof(k),  tprof(k),thlprof(k),      &
+     &                      qprof (k),uprof(k),  vprof(k),  wprof(k),      &
+     &                      omega (k),o3mmr(k)
+        enddo
+        close(ilesfile)
+
+        return
+        end
+
+!======================================================================
+      subroutine readprofile_astex(nlev_max,kmax,height,pprof,tprof,       &
+     &    thlprof,qvprof,qlprof,qtprof,uprof,vprof,wprof,tkeprof,o3mmr)
+!======================================================================
+      implicit none
+
+        integer nlev_max,kmax
+        logical :: llesread = .true.
+
+        real height(nlev_max),pprof(nlev_max),tprof(nlev_max),             &
+     &  thlprof(nlev_max),qlprof(nlev_max),qtprof(nlev_max),               &
+     &  qvprof(nlev_max),uprof(nlev_max),vprof(nlev_max),                  &
+     &  wprof(nlev_max),tkeprof(nlev_max),o3mmr(nlev_max)
+
+        integer, parameter :: ilesfile=1
+        integer :: ierr,k
+
+        if(.not.(llesread)) return
+
+       open (ilesfile,file='prof.inp.001',status='old',iostat=ierr)
+        if (ierr /= 0) stop 'ERROR:Prof.inp does not exist'
+        read (ilesfile,*) kmax
+        do k=1,kmax
+          read (ilesfile,*) height(k),pprof(k),  tprof(k),thlprof(k),      &
+     &                qvprof (k),qlprof (k),qtprof (k),                    &
+     &                uprof(k),  vprof(k),  wprof(k),tkeprof(k),o3mmr(k)
+        enddo
+        close(ilesfile)
+
+        return
+        end
+
+
+
+!======================================================================
+      subroutine readprofile_armcu(nlev_max,kmax,height,pprof,uprof,       &
+     &       vprof,thetaprof,tprof,qvprof,rvprof,aprof,bprof)
+!======================================================================
+      implicit none
+
+        integer nlev_max,kmax
+        logical :: llesread = .true.
+
+        real height(nlev_max),pprof(nlev_max),tprof(nlev_max)
+        real thetaprof(nlev_max),rvprof(nlev_max)
+        real qvprof(nlev_max),uprof(nlev_max),vprof(nlev_max)
+        real aprof(nlev_max+1),bprof(nlev_max+1)
+
+        integer, parameter :: ilesfile=1
+        integer, parameter :: ifile=2
+        integer :: ierr,jtot,k
+
+        if(.not.(llesread)) return
+
+! Read profiles at full levels
+       IF(nlev_max.EQ.19) THEN
+       open (ilesfile,file='prof.inp.19',status='old',iostat=ierr)
+       print *,'On ouvre prof.inp.19'
+       ELSE
+       open (ilesfile,file='prof.inp.40',status='old',iostat=ierr)
+       print *,'On ouvre prof.inp.40'
+       ENDIF
+        if (ierr /= 0) stop 'ERROR:Prof.inp does not exist'
+        read (ilesfile,*) kmax
+        do k=1,kmax
+          read (ilesfile,*) height(k)    ,pprof(k),  uprof(k), vprof(k),   &
+     &                      thetaprof(k) ,tprof(k), qvprof(k),rvprof(k)
+        enddo
+        close(ilesfile)
+
+! Vertical coordinates half levels for eta-coordinates (plev = alpha + beta * psurf) 
+       IF(nlev_max.EQ.19) THEN
+       open (ifile,file='proh.inp.19',status='old',iostat=ierr)
+       print *,'On ouvre proh.inp.19'
+       if (ierr /= 0) stop 'ERROR:Proh.inp.19 does not exist'
+       ELSE
+       open (ifile,file='proh.inp.40',status='old',iostat=ierr)
+       print *,'On ouvre proh.inp.40'
+       if (ierr /= 0) stop 'ERROR:Proh.inp.40 does not exist'
+       ENDIF
+        read (ifile,*) kmax
+        do k=1,kmax
+          read (ifile,*) jtot,aprof(k),bprof(k)
+        enddo
+        close(ifile)
+
+        return
+        end
+
+!=====================================================================
+      subroutine read_fire(fich_fire,nlevel,ntime                          &
+     &     ,zz,thl,qt,u,v,tke                                              &
+     &     ,ug,vg,wls,dqtdx,dqtdy,dqtdt,thl_rad)
+
+!program reading forcings of the FIRE case study
+
+
+      implicit none
+
+#include "netcdf.inc"
+
+      integer ntime,nlevel
+      character*80 :: fich_fire
+      real*8 zz(nlevel)
+
+      real*8 thl(nlevel)
+      real*8 qt(nlevel),u(nlevel)
+      real*8 v(nlevel),tke(nlevel)
+      real*8 ug(nlevel,ntime),vg(nlevel,ntime),wls(nlevel,ntime)
+      real*8 dqtdx(nlevel,ntime),dqtdy(nlevel,ntime)
+      real*8 dqtdt(nlevel,ntime),thl_rad(nlevel,ntime)
+
+      integer nid, ierr
+      integer nbvar3d
+      parameter(nbvar3d=30)
+      integer var3didin(nbvar3d)
+
+      ierr = NF_OPEN(fich_fire,NF_NOWRITE,nid)
+      if (ierr.NE.NF_NOERR) then
+         write(*,*) 'ERROR: Pb opening forcings nc file '
+         write(*,*) NF_STRERROR(ierr)
+         stop ""
+      endif
+
+
+       ierr=NF_INQ_VARID(nid,"zz",var3didin(1)) 
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'lev'
+         endif
+
+
+      ierr=NF_INQ_VARID(nid,"thetal",var3didin(2))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'temp'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"qt",var3didin(3))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'qv'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"u",var3didin(4))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'u'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"v",var3didin(5))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'v'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"tke",var3didin(6))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'tke'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"ugeo",var3didin(7))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'ug'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"vgeo",var3didin(8))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'vg'
+         endif
+      
+      ierr=NF_INQ_VARID(nid,"wls",var3didin(9))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'wls'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"dqtdx",var3didin(10))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'dqtdx'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"dqtdy",var3didin(11))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'dqtdy'
+      endif
+
+      ierr=NF_INQ_VARID(nid,"dqtdt",var3didin(12))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'dqtdt'
+      endif
+
+      ierr=NF_INQ_VARID(nid,"thl_rad",var3didin(13))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'thl_rad'
+      endif
+!dimensions lecture
+!      call catchaxis(nid,ntime,nlevel,time,z,ierr)
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(1),zz)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(1),zz)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture z ok',zz
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(2),thl)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(2),thl)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture thl ok',thl
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(3),qt)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(3),qt)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture qt ok',qt
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(4),u)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(4),u)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture u ok',u
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(5),v)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(5),v)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture v ok',v
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(6),tke)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(6),tke)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture tke ok',tke
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(7),ug)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(7),ug)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture ug ok',ug
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(8),vg)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(8),vg)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture vg ok',vg
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(9),wls)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(9),wls)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture wls ok',wls
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(10),dqtdx)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(10),dqtdx)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture dqtdx ok',dqtdx
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(11),dqtdy)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(11),dqtdy)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture dqtdy ok',dqtdy
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(12),dqtdt)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(12),dqtdt)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture dqtdt ok',dqtdt
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(13),thl_rad)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(13),thl_rad)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture thl_rad ok',thl_rad
+
+         return 
+         end subroutine read_fire
+!=====================================================================
+      subroutine read_dice(fich_dice,nlevel,ntime                         &
+     &     ,zz,pres,t,qv,u,v,o3                                          &
+     &     ,shf,lhf,lwup,swup,tg,ustar,psurf,ug,vg                        &
+     &     ,hadvt,hadvq,hadvu,hadvv,w,omega)
+
+!program reading initial profils and forcings of the Dice case study
+
+
+      implicit none
+
+#include "netcdf.inc"
+#include "YOMCST.h"
+
+      integer ntime,nlevel
+      integer l,k
+      character*80 :: fich_dice
+      real*8 time(ntime)
+      real*8 zz(nlevel)
+
+      real*8 th(nlevel),pres(nlevel),t(nlevel)
+      real*8 qv(nlevel),u(nlevel),v(nlevel),o3(nlevel)
+      real*8 shf(ntime),lhf(ntime),lwup(ntime),swup(ntime),tg(ntime)
+      real*8 ustar(ntime),psurf(ntime),ug(ntime),vg(ntime)
+      real*8 hadvt(nlevel,ntime),hadvq(nlevel,ntime),hadvu(nlevel,ntime)
+      real*8 hadvv(nlevel,ntime),w(nlevel,ntime),omega(nlevel,ntime)
+      real*8 pzero
+
+      integer nid, ierr
+      integer nbvar3d
+      parameter(nbvar3d=30)
+      integer var3didin(nbvar3d)
+
+      pzero=100000.
+      ierr = NF_OPEN(fich_dice,NF_NOWRITE,nid)
+      if (ierr.NE.NF_NOERR) then
+         write(*,*) 'ERROR: Pb opening forcings nc file '
+         write(*,*) NF_STRERROR(ierr)
+         stop ""
+      endif
+
+
+       ierr=NF_INQ_VARID(nid,"height",var3didin(1)) 
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'height'
+         endif
+
+       ierr=NF_INQ_VARID(nid,"pf",var3didin(11)) 
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'pf'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"theta",var3didin(12))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'theta'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"qv",var3didin(13))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'qv'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"u",var3didin(14))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'u'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"v",var3didin(15))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'v'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"o3mmr",var3didin(16))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'o3'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"shf",var3didin(2))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'shf'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"lhf",var3didin(3))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'lhf'
+         endif
+      
+      ierr=NF_INQ_VARID(nid,"lwup",var3didin(4))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'lwup'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"swup",var3didin(5))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'dqtdx'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"Tg",var3didin(6))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'Tg'
+      endif
+
+      ierr=NF_INQ_VARID(nid,"ustar",var3didin(7))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'ustar'
+      endif
+
+      ierr=NF_INQ_VARID(nid,"psurf",var3didin(8))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'psurf'
+      endif
+
+      ierr=NF_INQ_VARID(nid,"Ug",var3didin(9))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'Ug'
+      endif
+
+      ierr=NF_INQ_VARID(nid,"Vg",var3didin(10))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'Vg'
+      endif
+
+      ierr=NF_INQ_VARID(nid,"hadvT",var3didin(17))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'hadvT'
+      endif
+
+      ierr=NF_INQ_VARID(nid,"hadvq",var3didin(18))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'hadvq'
+      endif
+
+      ierr=NF_INQ_VARID(nid,"hadvu",var3didin(19))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'hadvu'
+      endif
+
+      ierr=NF_INQ_VARID(nid,"hadvv",var3didin(20))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'hadvv'
+      endif
+
+      ierr=NF_INQ_VARID(nid,"w",var3didin(21))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'w'
+      endif
+
+      ierr=NF_INQ_VARID(nid,"omega",var3didin(22))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'omega'
+      endif
+!dimensions lecture
+!      call catchaxis(nid,ntime,nlevel,time,z,ierr)
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(1),zz)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(1),zz)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture zz ok',zz
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(11),pres)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(11),pres)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture pres ok',pres
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(12),th)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(12),th)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture th ok',th
+           do k=1,nlevel
+             t(k)=th(k)*(pres(k)/pzero)**rkappa
+           enddo
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(13),qv)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(13),qv)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture qv ok',qv
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(14),u)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(14),u)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture u ok',u
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(15),v)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(15),v)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture v ok',v
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(16),o3)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(16),o3)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture o3 ok',o3
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(2),shf)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(2),shf)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture shf ok',shf
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(3),lhf)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(3),lhf)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture lhf ok',lhf
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(4),lwup)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(4),lwup)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture lwup ok',lwup
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(5),swup)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(5),swup)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture swup ok',swup
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(6),tg)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(6),tg)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture tg ok',tg
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(7),ustar)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(7),ustar)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture ustar ok',ustar
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(8),psurf)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(8),psurf)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture psurf ok',psurf
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(9),ug)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(9),ug)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture ug ok',ug
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(10),vg)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(10),vg)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture vg ok',vg
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(17),hadvt)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(17),hadvt)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture hadvt ok',hadvt
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(18),hadvq)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(18),hadvq)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture hadvq ok',hadvq
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(19),hadvu)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(19),hadvu)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture hadvu ok',hadvu
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(20),hadvv)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(20),hadvv)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture hadvv ok',hadvv
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(21),w)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(21),w)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture w ok',w
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(22),omega)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(22),omega)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+!          write(*,*)'lecture omega ok',omega
+
+         return 
+         end subroutine read_dice
+!=====================================================================
+      subroutine read_gabls4(fich_gabls4,nlevel,ntime,nsol                    &
+     &     ,zz,depth_sn,ug,vg,pf,th,t,qv,u,v,hadvt,hadvq,tg,tsnow,snow_dens)
+
+!program reading initial profils and forcings of the Gabls4 case study
+
+
+      implicit none
+
+#include "netcdf.inc"
+
+      integer ntime,nlevel,nsol
+      integer l,k
+      character*80 :: fich_gabls4
+      real*8 time(ntime)
+
+!  ATTENTION: visiblement quand on lit gabls4_driver.nc on recupere les donnees 
+! dans un ordre inverse par rapport a la convention LMDZ
+! ==> il faut tout inverser  (MPL 20141024)
+! les variables indexees "_i" sont celles qui sont lues dans gabls4_driver.nc
+      real*8 zz_i(nlevel),th_i(nlevel),pf_i(nlevel),t_i(nlevel)
+      real*8 qv_i(nlevel),u_i(nlevel),v_i(nlevel),ug_i(nlevel,ntime),vg_i(nlevel,ntime)
+      real*8 hadvt_i(nlevel,ntime),hadvq_i(nlevel,ntime)
+
+      real*8 zz(nlevel),th(nlevel),pf(nlevel),t(nlevel)
+      real*8 qv(nlevel),u(nlevel),v(nlevel),ug(nlevel,ntime),vg(nlevel,ntime)
+      real*8 hadvt(nlevel,ntime),hadvq(nlevel,ntime)
+
+      real*8 depth_sn(nsol),tsnow(nsol),snow_dens(nsol)
+      real*8 tg(ntime)
+      integer nid, ierr
+      integer nbvar3d
+      parameter(nbvar3d=30)
+      integer var3didin(nbvar3d)
+
+      ierr = NF_OPEN(fich_gabls4,NF_NOWRITE,nid)
+      if (ierr.NE.NF_NOERR) then
+         write(*,*) 'ERROR: Pb opening forcings nc file '
+         write(*,*) NF_STRERROR(ierr)
+         stop ""
+      endif
+
+
+       ierr=NF_INQ_VARID(nid,"height",var3didin(1)) 
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'height'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"depth_sn",var3didin(2))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'depth_sn'
+      endif
+
+      ierr=NF_INQ_VARID(nid,"Ug",var3didin(3))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'Ug'
+      endif
+
+      ierr=NF_INQ_VARID(nid,"Vg",var3didin(4))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'Vg'
+      endif
+       ierr=NF_INQ_VARID(nid,"pf",var3didin(5)) 
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'pf'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"theta",var3didin(6))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'theta'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"tempe",var3didin(7))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'tempe'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"qv",var3didin(8))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'qv'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"u",var3didin(9))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'u'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"v",var3didin(10))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'v'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"hadvT",var3didin(11))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'hadvt'
+         endif
+
+      ierr=NF_INQ_VARID(nid,"hadvQ",var3didin(12))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'hadvq'
+      endif
+
+      ierr=NF_INQ_VARID(nid,"Tsnow",var3didin(14))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'tsnow'
+      endif
+
+      ierr=NF_INQ_VARID(nid,"snow_density",var3didin(15))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'snow_density'
+      endif
+
+      ierr=NF_INQ_VARID(nid,"Tg",var3didin(16))
+         if(ierr/=NF_NOERR) then
+           write(*,*) NF_STRERROR(ierr)
+           stop 'Tg'
+      endif
+
+
+!dimensions lecture
+!      call catchaxis(nid,ntime,nlevel,time,z,ierr)
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(1),zz_i)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(1),zz_i)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(2),depth_sn)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(2),depth_sn)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(3),ug_i)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(3),ug_i)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(4),vg_i)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(4),vg_i)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(5),pf_i)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(5),pf_i)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(6),th_i)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(6),th_i)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(7),t_i)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(7),t_i)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(8),qv_i)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(8),qv_i)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(9),u_i)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(9),u_i)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(10),v_i)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(10),v_i)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(11),hadvt_i)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(11),hadvt_i)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(12),hadvq_i)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(12),hadvq_i)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(14),tsnow)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(14),tsnow)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+ 
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(15),snow_dens)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(15),snow_dens)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+
+#ifdef NC_DOUBLE
+         ierr = NF_GET_VAR_DOUBLE(nid,var3didin(16),tg)
+#else
+         ierr = NF_GET_VAR_REAL(nid,var3didin(16),tg)
+#endif
+         if(ierr/=NF_NOERR) then
+            write(*,*) NF_STRERROR(ierr)
+            stop "getvarup"
+         endif
+
+! On remet les variables lues dans le bon ordre des niveaux (MPL 20141024)
+         do k=1,nlevel
+           zz(k)=zz_i(nlevel+1-k)
+           ug(k,:)=ug_i(nlevel+1-k,:)
+           vg(k,:)=vg_i(nlevel+1-k,:)
+           pf(k)=pf_i(nlevel+1-k)
+           print *,'pf=',pf(k)
+           th(k)=th_i(nlevel+1-k)
+           t(k)=t_i(nlevel+1-k)
+           qv(k)=qv_i(nlevel+1-k)
+           u(k)=u_i(nlevel+1-k)
+           v(k)=v_i(nlevel+1-k)
+           hadvt(k,:)=hadvt_i(nlevel+1-k,:)
+           hadvq(k,:)=hadvq_i(nlevel+1-k,:)
+         enddo
+         return 
+ end subroutine read_gabls4
+!=====================================================================
+
+!     Reads CIRC input files      
+
+      SUBROUTINE read_circ(nlev_circ,cf,lwp,iwp,reliq,reice,t,z,p,pm,h2o,o3,sza)
+      
+      parameter (ncm_1=49180)
+#include "YOMCST.h"
+
+      real albsfc(ncm_1), albsfc_w(ncm_1)
+      real cf(nlev_circ), icefra(nlev_circ), deice(nlev_circ), &
+           reliq(nlev_circ), reice(nlev_circ), lwp(nlev_circ), iwp(nlev_circ)
+      real t(nlev_circ+1), z(nlev_circ+1), dz(nlev_circ), p(nlev_circ+1)
+      real aer_beta(nlev_circ), waer(nlev_circ), gaer(nlev_circ)
+      real pm(nlev_circ), tm(nlev_circ), h2o(nlev_circ), o3(nlev_circ)
+      real co2(nlev_circ), n2o(nlev_circ), co(nlev_circ), ch4(nlev_circ), &
+           o2(nlev_circ), ccl4(nlev_circ), f11(nlev_circ), f12(nlev_circ)
+!     za= zenital angle
+!     sza= cosinus angle zenital
+      real wavn(ncm_1), ssf(ncm_1),za,sza
+      integer nlev
+
+
+!     Open the files
+
+      open (11, file='Tsfc_sza_nlev_case.txt', status='old')
+      open (12, file='level_input_case.txt', status='old')
+      open (13, file='layer_input_case.txt', status='old')
+      open (14, file='aerosol_input_case.txt', status='old')
+      open (15, file='cloud_input_case.txt', status='old')
+      open (16, file='sfcalbedo_input_case.txt', status='old')
+      
+!     Read scalar information
+      do iskip=1,5
+         read (11, *)
+      enddo
+      read (11, '(i8)') nlev
+      read (11, '(f10.2)') tsfc
+      read (11, '(f10.2)') za
+      read (11, '(f10.4)') sw_dn_toa
+      sza=cos(za/180.*RPI)
+      print *,'nlev,tsfc,sza,sw_dn_toa,RPI',nlev,tsfc,sza,sw_dn_toa,RPI
+      close(11)
+
+!     Read level information
+      read (12, *)
+      do il=1,nlev
+         read (12, 302) ilev, z(il), p(il), t(il)
+         z(il)=z(il)*1000.    ! z donne en km
+         p(il)=p(il)*100.     ! p donne en mb
+      enddo
+302   format (i8, f8.3, 2f9.2)
+      close(12)
+
+!     Read layer information (midpoint values)
+      do iskip=1,3
+         read (13, *)
+      enddo
+      do il=1,nlev-1
+         read (13, 303) ilev,pm(il),tm(il),h2o(il),co2(il),o3(il), &
+                        n2o(il),co(il),ch4(il),o2(il),ccl4(il), &
+                        f11(il),f12(il)
+         pm(il)=pm(il)*100.
+      enddo
+303   format (i8, 2f9.2, 10(2x,e13.7))      
+      close(13)
+      
+!     Read aerosol layer information
+      do iskip=1,3
+         read (14, *)
+      enddo
+      read (14, '(f10.2)') aer_alpha
+      read (14, *)
+      read (14, *)
+      do il=1,nlev-1
+         read (14, 304) ilev, aer_beta(il), waer(il), gaer(il)
+      enddo
+304   format (i8, f9.5, 2f8.3)
+      close(14)
+      
+!     Read cloud information
+      do iskip=1,3
+         read (15, *)
+      enddo
+      do il=1,nlev-1
+         read (15, 305) ilev, cf(il), lwp(il), iwp(il), reliq(il), reice(il)
+         lwp(il)=lwp(il)/1000.          ! lwp donne en g/kg
+         iwp(il)=iwp(il)/1000.          ! iwp donne en g/kg
+         reliq(il)=reliq(il)/1000000.   ! reliq donne en microns
+         reice(il)=reice(il)/1000000.   ! reice donne en microns
+      enddo
+305   format (i8, f8.3, 4f9.2)
+      close(15)
+
+!     Read surface albedo (weighted & unweighted) and spectral solar irradiance
+      do iskip=1,6
+         read (16, *)
+      enddo
+      do icm_1=1,ncm_1
+         read (16, 306) wavn(icm_1), albsfc(icm_1), albsfc_w(icm_1), ssf(icm_1)
+      enddo
+306   format(f10.1, 2f12.5, f14.8)
+      close(16)
+ 
+      return 
+      end subroutine read_circ
+!=====================================================================
+!     Reads RTMIP input files      
+
+      SUBROUTINE read_rtmip(nlev_rtmip,play,plev,t,h2o,o3)
+      
+#include "YOMCST.h"
+
+      real t(nlev_rtmip), pt(nlev_rtmip),pb(nlev_rtmip),h2o(nlev_rtmip), o3(nlev_rtmip)
+      real temp(nlev_rtmip), play(nlev_rtmip),ovap(nlev_rtmip), oz(nlev_rtmip),plev(nlev_rtmip+1)
+      integer nlev
+
+
+!     Open the files
+
+      open (11, file='low_resolution_profile.txt', status='old')
+      
+!     Read level information
+      read (11, *)
+      do il=1,nlev_rtmip
+         read (11, 302) pt(il), pb(il), t(il),h2o(il),o3(il)
+      enddo
+      do il=1,nlev_rtmip
+         play(il)=pt(nlev_rtmip-il+1)*100.     ! p donne en mb
+         temp(il)=t(nlev_rtmip-il+1)
+         ovap(il)=h2o(nlev_rtmip-il+1)
+         oz(il)=o3(nlev_rtmip-il+1)
+      enddo
+      do il=1,39
+         plev(il)=play(il)+(play(il+1)-play(il))/2.
+         print *,'il p t ovap oz=',il,plev(il),temp(il),ovap(il),oz(il)
+      enddo
+      plev(41)=101300.
+302   format (e16.10,3x,e16.10,3x,e16.10,3x,e12.6,3x,e12.6)
+      close(12)
+ 
+      return 
+      end subroutine read_rtmip
+!=====================================================================
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/old_1D_decl_cases.h
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/old_1D_decl_cases.h	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/old_1D_decl_cases.h	(revision 3605)
@@ -0,0 +1,293 @@
+#include "netcdf.inc"
+
+! Declarations specifiques au cas Toga
+        character*80 :: fich_toga
+!        integer nlev_prof
+!        parameter (nlev_prof = 41)
+        integer nlev_toga, nt_toga
+        parameter (nlev_toga=41, nt_toga=480)
+        integer year_ini_toga, day_ini_toga, mth_ini_toga
+        real day_ju_ini_toga   ! Julian day of toga coare first day
+        parameter (year_ini_toga=1992) 
+        parameter (mth_ini_toga=11)
+        parameter (day_ini_toga=1)  !  1erNov1992
+        real dt_toga
+        parameter (dt_toga=6.*3600.)
+!!
+        integer year_print, month_print, day_print
+        real    sec_print
+!!
+        real ts_toga(nt_toga)
+        real plev_toga(nlev_toga,nt_toga),w_toga(nlev_toga,nt_toga)
+        real t_toga(nlev_toga,nt_toga),q_toga(nlev_toga,nt_toga)
+        real u_toga(nlev_toga,nt_toga),v_toga(nlev_toga,nt_toga)
+        real ht_toga(nlev_toga,nt_toga),vt_toga(nlev_toga,nt_toga)
+        real hq_toga(nlev_toga,nt_toga),vq_toga(nlev_toga,nt_toga)
+
+        real ts_prof
+        real plev_prof(nlev_toga),w_prof(nlev_toga)
+        real t_prof(nlev_toga),q_prof(nlev_toga)
+        real u_prof(nlev_toga),v_prof(nlev_toga)
+        real ht_prof(nlev_toga),vt_prof(nlev_toga)
+        real hq_prof(nlev_toga),vq_prof(nlev_toga)
+
+        real w_mod(llm), t_mod(llm),q_mod(llm)
+        real u_mod(llm),v_mod(llm), ht_mod(llm),vt_mod(llm),ug_mod(llm),vg_mod(llm)
+        real hq_mod(llm),vq_mod(llm),qv_mod(llm),ql_mod(llm),qt_mod(llm)
+        real th_mod(llm)
+
+        real ts_cur
+        common /sst_forcing/ts_cur ! also in read_tsurf1d.F
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+! Declarations specifiques au cas RICO
+        character*80 :: fich_rico
+        integer nlev_rico
+
+        parameter (nlev_rico=81)
+        real ts_rico,ps_rico
+        real w_rico(llm)
+        real t_rico(llm),q_rico(llm)
+        real u_rico(llm),v_rico(llm)
+        real dth_rico(llm)
+        real dqh_rico(llm)
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+! Declarations specifiques au cas TWPice
+        character*80 :: fich_twpice
+        integer nlev_twpi, nt_twpi
+        parameter (nlev_twpi=40, nt_twpi=215)
+        integer year_ini_twpi, day_ini_twpi, mth_ini_twpi
+        real heure_ini_twpi
+        real day_ju_ini_twpi   ! Julian day of twpice first day
+        parameter (year_ini_twpi=2006) 
+        parameter (mth_ini_twpi=1)
+        parameter (day_ini_twpi=17)  ! 17 = 17Jan2006
+        parameter (heure_ini_twpi=10800.) !3h en secondes
+        real dt_twpi
+        parameter (dt_twpi=3.*3600.)
+
+        real ts_twpi(nt_twpi)
+        real plev_twpi(nlev_twpi,nt_twpi),w_twpi(nlev_twpi,nt_twpi)
+        real t_twpi(nlev_twpi,nt_twpi),q_twpi(nlev_twpi,nt_twpi)
+        real u_twpi(nlev_twpi,nt_twpi),v_twpi(nlev_twpi,nt_twpi)
+        real ht_twpi(nlev_twpi,nt_twpi),vt_twpi(nlev_twpi,nt_twpi)
+        real hq_twpi(nlev_twpi,nt_twpi),vq_twpi(nlev_twpi,nt_twpi)
+
+        real ts_proftwp
+        real plev_proftwp(nlev_twpi),w_proftwp(nlev_twpi)
+        real t_proftwp(nlev_twpi),q_proftwp(nlev_twpi)
+        real u_proftwp(nlev_twpi),v_proftwp(nlev_twpi)
+        real ht_proftwp(nlev_twpi),vt_proftwp(nlev_twpi)
+        real hq_proftwp(nlev_twpi),vq_proftwp(nlev_twpi)
+
+
+
+!Declarations specifiques au cas FIRE
+        character*80 :: fich_fire
+        integer nlev_fire, nt_fire
+        parameter (nlev_fire=120, nt_fire=1)  
+        integer year_ini_fire, day_ini_fire, mth_ini_fire
+        real heure_ini_fire
+        parameter (year_ini_fire=1987) 
+        parameter (mth_ini_fire=7)
+        parameter (day_ini_fire=14)  ! 14 = 14Juil1987
+        parameter (heure_ini_fire=0.) !0h en secondes
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!Declarations specifiques au cas GABLS4   (MPL 20141023)
+        character*80 :: fich_gabls4
+        integer nlev_gabls4, nt_gabls4, nsol_gabls4
+        parameter (nlev_gabls4=90, nt_gabls4=37, nsol_gabls4=19)  
+        integer year_ini_gabls4, day_ini_gabls4, mth_ini_gabls4
+        real heure_ini_gabls4
+        real day_ju_ini_gabls4   ! Julian day of gabls4 first day
+        parameter (year_ini_gabls4=2009) 
+        parameter (mth_ini_gabls4=12)
+        parameter (day_ini_gabls4=11)  ! 11 = 11 decembre 2009
+        parameter (heure_ini_gabls4=0.) !0UTC en secondes
+        real dt_gabls4
+        parameter (dt_gabls4=3600.) ! 1 forcage ttes les heures
+
+!profils initiaux:
+        real plev_gabls4(nlev_gabls4)
+        real zz_gabls4(nlev_gabls4)
+        real th_gabls4(nlev_gabls4),t_gabls4(nlev_gabls4),qv_gabls4(nlev_gabls4)
+        real u_gabls4(nlev_gabls4), v_gabls4(nlev_gabls4)
+        real depth_sn_gabls4(nsol_gabls4),tsnow_gabls4(nsol_gabls4),snow_dens_gabls4(nsol_gabls4)
+        real t_gabi(nlev_gabls4),qv_gabi(nlev_gabls4)
+        real u_gabi(nlev_gabls4), v_gabi(nlev_gabls4),ug_gabi(nlev_gabls4), vg_gabi(nlev_gabls4)
+        real ht_gabi(nlev_gabls4),hq_gabi(nlev_gabls4),poub(nlev_gabls4)
+        
+!forcings
+        real ht_gabls4(nlev_gabls4,nt_gabls4),hq_gabls4(nlev_gabls4,nt_gabls4)
+        real ug_gabls4(nlev_gabls4,nt_gabls4),vg_gabls4(nlev_gabls4,nt_gabls4)
+        real tg_gabls4(nt_gabls4)
+        real ht_profg(nlev_gabls4),hq_profg(nlev_gabls4)
+        real ug_profg(nlev_gabls4),vg_profg(nlev_gabls4)
+        real tg_profg
+         
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+!Declarations specifiques au cas DICE     (MPL 02072013)
+        character*80 :: fich_dice
+        integer nlev_dice, nt_dice
+        parameter (nlev_dice=70, nt_dice=145)  
+        integer year_ini_dice, day_ini_dice, mth_ini_dice
+        real heure_ini_dice
+        real day_ju_ini_dice   ! Julian day of dice first day
+        parameter (year_ini_dice=1999) 
+        parameter (mth_ini_dice=10)
+        parameter (day_ini_dice=23)  ! 23 = 23 october 1999
+        parameter (heure_ini_dice=68400.) !19UTC en secondes
+        real dt_dice
+        parameter (dt_dice=0.5*3600.) ! 1 forcage ttes les demi-heures
+
+!profils initiaux:
+        real plev_dice(nlev_dice)
+        
+        real zz_dice(nlev_dice)
+        real t_dice(nlev_dice),qv_dice(nlev_dice)
+        real u_dice(nlev_dice), v_dice(nlev_dice),o3_dice(nlev_dice)
+        real ht_dice(nlev_dice,nt_dice)
+        real hq_dice(nlev_dice,nt_dice), hu_dice(nlev_dice,nt_dice)
+        real hv_dice(nlev_dice,nt_dice)
+        real w_dice(nlev_dice,nt_dice),omega_dice(nlev_dice,nt_dice)
+        real o3_mod(llm),hu_mod(llm),hv_mod(llm)
+        real t_dicei(nlev_dice),qv_dicei(nlev_dice)
+        real u_dicei(nlev_dice), v_dicei(nlev_dice),o3_dicei(nlev_dice)
+        real ht_dicei(nlev_dice)
+        real hq_dicei(nlev_dice), hu_dicei(nlev_dice)
+        real hv_dicei(nlev_dice)
+        real w_dicei(nlev_dice),omega_dicei(nlev_dice)
+
+        
+!forcings
+        real shf_dice(nt_dice),lhf_dice(nt_dice)
+        real lwup_dice(nt_dice),swup_dice(nt_dice)
+        real tg_dice(nt_dice),ustar_dice(nt_dice),psurf_dice(nt_dice)
+        real ug_dice(nt_dice),vg_dice(nt_dice)
+
+        real shf_prof,lhf_prof,lwup_prof,swup_prof,tg_prof
+        real ustar_prof,psurf_prof,cdrag
+        real ht_profd(nlev_dice),hq_profd(nlev_dice),hu_profd(nlev_dice)
+        real hv_profd(nlev_dice),w_profd(nlev_dice)
+        real omega_profd(nlev_dice),ug_profd,vg_profd
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+! Declarations specifiques au cas GCSSold
+        character*80 :: fich_gcssold_ctl
+        character*80 :: fich_gcssold_dat
+        real  ht_gcssold(llm),hq_gcssold(llm),hw_gcssold(llm)
+        real  hu_gcssold(llm)
+        real  hv_gcssold(llm)
+        real  hthturb_gcssold(llm)
+        real  hqturb_gcssold(llm)
+        real  Ts_gcssold
+        real  dtime_frcg
+        logical :: Turb_fcg_gcssold
+
+        common /turb_forcing/                                                   &
+     &  dtime_frcg,hthturb_gcssold, hqturb_gcssold,Turb_fcg_gcssold
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+! Declarations specifiques au cas Arm_cu
+        character*80 :: fich_armcu
+
+
+        integer nlev_armcu, nt_armcu
+        parameter (nlev_armcu=40, nt_armcu=31)
+        integer year_ini_armcu, day_ini_armcu, mth_ini_armcu
+        real  heure_ini_armcu
+        real day_ju_ini_armcu                                ! Julian day of armcu case first day
+        parameter (year_ini_armcu=1997) 
+        parameter (mth_ini_armcu=6)
+        parameter (day_ini_armcu=21)  ! 172 = 21 juin 1997
+        parameter (heure_ini_armcu=41400)   ! 11:30 en secondes
+        real dt_armcu
+        parameter (dt_armcu=1.*1800.)   ! forcages donnes ttes les demi-heures par ifa_armcu.txt
+        real sens_armcu(nt_armcu),flat_armcu(nt_armcu)
+        real adv_theta_armcu(nt_armcu),rad_theta_armcu(nt_armcu)
+        real adv_qt_armcu(nt_armcu)
+        real theta_mod(llm),rv_mod(llm),play_mod(llm)
+! profc comme "profil armcu"
+        
+! forcages interpoles dans le temps
+        real adv_theta_prof,rad_theta_prof,adv_qt_prof
+        real sens_prof,flat_prof,fact
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+! declarations specifiques au cas Sandu
+        character*80 :: fich_sandu
+!        integer nlev_prof
+!        parameter (nlev_prof = 41)
+        integer nlev_sandu, nt_sandu
+        parameter (nlev_sandu=87, nt_sandu=13)
+        integer year_ini_sandu, day_ini_sandu, mth_ini_sandu
+        real day_ju_ini_sandu                                ! Julian day of sandu case first day
+        parameter (year_ini_sandu=2006)
+        parameter (mth_ini_sandu=7)
+        parameter (day_ini_sandu=15)  ! 196 = 15 juillet 2006
+        real dt_sandu, tau_sandu
+        logical  :: trouve_700=.true.
+        parameter (dt_sandu=6.*3600.)   ! forcages donnes ttes les 6 heures par ifa_sandu.txt
+        parameter (tau_sandu=30000*3600.)  ! temps de relaxation u,v,thetal,qt vers profil init et au dessus 700hPa
+!!
+        real ts_sandu(nt_sandu)
+! profs comme "profil sandu"
+        real plev_profs(nlev_sandu)
+        real t_profs(nlev_sandu),thl_profs(nlev_sandu)
+        real q_profs(nlev_sandu)
+        real u_profs(nlev_sandu),v_profs(nlev_sandu),w_profs(nlev_sandu)
+        real omega_profs(nlev_sandu),o3mmr_profs(nlev_sandu)
+
+        real, dimension(llm) :: relax_u,relax_v,relax_thl
+        real, dimension(llm,2) :: relax_q
+
+        real thl_mod(llm),omega_mod(llm),o3mmr_mod(llm),tke_mod(llm)
+!vertical advection computation
+        real d_t_z(llm),d_th_z(llm), d_q_z(llm)
+        real d_t_dyn_z(llm),d_th_dyn_z(llm), d_q_dyn_z(llm)
+        real d_u_z(llm),d_v_z(llm)
+        real d_u_dyn(llm),d_v_dyn(llm)
+        real d_u_dyn_z(llm),d_v_dyn_z(llm)
+        real d_u_adv(llm),d_v_adv(llm)
+        real zz(llm)
+        real zfact
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+! Declarations specifiques au cas Astex
+        character*80 :: fich_astex
+        integer nlev_astex, nt_astex
+        parameter (nlev_astex=34, nt_astex=49)
+        integer year_ini_astex, day_ini_astex, mth_ini_astex
+        real day_ju_ini_astex                                ! Julian day of astex case first day
+        parameter (year_ini_astex=1992)
+        parameter (mth_ini_astex=6)
+        parameter (day_ini_astex=13)  ! 165 = 13 juin 1992
+        real dt_astex
+        parameter (dt_astex=3600.)    ! forcages donnes ttes les heures par ifa_astex.txt
+        real ts_astex(nt_astex),div_astex(nt_astex),ug_astex(nt_astex)
+        real vg_astex(nt_astex),ufa_astex(nt_astex),vfa_astex(nt_astex)
+        real div_prof,ug_prof,vg_prof,ufa_prof,vfa_prof
+! profa comme "profil astex"
+        real plev_profa(nlev_astex)
+        real t_profa(nlev_astex),thl_profa(nlev_astex)
+        real qv_profa(nlev_astex),ql_profa(nlev_astex)
+        real qt_profa(nlev_astex),o3mmr_profa(nlev_astex)
+        real u_profa(nlev_astex),v_profa(nlev_astex),w_profa(nlev_astex)
+        real tke_profa(nlev_astex)
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!Declarations specifiques au cas standard
+
+        real w_mod_cas(llm), t_mod_cas(llm),q_mod_cas(llm)
+        real theta_mod_cas(llm),thl_mod_cas(llm),thv_mod_cas(llm)
+        real qv_mod_cas(llm),ql_mod_cas(llm),qi_mod_cas(llm)
+        real ug_mod_cas(llm),vg_mod_cas(llm)
+        real u_mod_cas(llm),v_mod_cas(llm)
+        real omega_mod_cas(llm)
+        real ht_mod_cas(llm),vt_mod_cas(llm),dt_mod_cas(llm),dtrad_mod_cas(llm)
+        real hth_mod_cas(llm),vth_mod_cas(llm),dth_mod_cas(llm)
+        real hq_mod_cas(llm),vq_mod_cas(llm),dq_mod_cas(llm)
+        real hu_mod_cas(llm),vu_mod_cas(llm),du_mod_cas(llm)
+        real hv_mod_cas(llm),vv_mod_cas(llm),dv_mod_cas(llm)
+        integer day_ini_cas
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/old_1D_interp_cases.h
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/old_1D_interp_cases.h	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/old_1D_interp_cases.h	(revision 3605)
@@ -0,0 +1,1032 @@
+!
+! $Id: 1D_interp_cases.h 3537 2019-06-19 08:29:16Z fhourdin $
+!
+!---------------------------------------------------------------------
+! Forcing_LES case: constant dq_dyn
+!---------------------------------------------------------------------
+      if (forcing_LES) then
+        DO l = 1,llm
+          d_q_adv(l,1) = dq_dyn(l,1)
+        ENDDO
+      endif ! forcing_LES
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Interpolation forcing in time and onto model levels
+!---------------------------------------------------------------------
+      if (forcing_GCSSold) then
+
+       call get_uvd(it,timestep,fich_gcssold_ctl,fich_gcssold_dat,              &
+     &               ht_gcssold,hq_gcssold,hw_gcssold,                          &
+     &               hu_gcssold,hv_gcssold,                                     &
+     &               hthturb_gcssold,hqturb_gcssold,Ts_gcssold,                 &
+     &               imp_fcg_gcssold,ts_fcg_gcssold,                            &
+     &               Tp_fcg_gcssold,Turb_fcg_gcssold)
+       if (prt_level.ge.1) then
+         print *,' get_uvd -> hqturb_gcssold ',it,hqturb_gcssold
+       endif
+! large-scale forcing :
+!!!      tsurf = ts_gcssold
+      do l = 1, llm
+!       u(l) = hu_gcssold(l) !  on prescrit le vent
+!       v(l) = hv_gcssold(l)    !  on prescrit le vent
+!       omega(l) = hw_gcssold(l)
+!       rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
+!       omega2(l)=-rho(l)*omega(l)
+       omega(l) = hw_gcssold(l)
+       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+       d_t_adv(l) = ht_gcssold(l)
+       d_q_adv(l,1) = hq_gcssold(l)
+       dt_cooling(l) = 0.0
+      enddo
+
+      endif ! forcing_GCSSold
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Interpolation Toga forcing 
+!---------------------------------------------------------------------
+      if (forcing_toga) then
+
+       if (prt_level.ge.1) then
+        print*,                                                             &
+     & '#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/dt_toga=',     &
+     &    day,day1,(day-day1)*86400.,(day-day1)*86400/dt_toga
+       endif
+
+! time interpolation:
+        CALL interp_toga_time(daytime,day1,annee_ref                        &
+     &             ,year_ini_toga,day_ju_ini_toga,nt_toga,dt_toga           &
+     &             ,nlev_toga,ts_toga,plev_toga,t_toga,q_toga,u_toga        &
+     &             ,v_toga,w_toga,ht_toga,vt_toga,hq_toga,vq_toga           &
+     &             ,ts_prof,plev_prof,t_prof,q_prof,u_prof,v_prof,w_prof    &
+     &             ,ht_prof,vt_prof,hq_prof,vq_prof)
+
+        if (type_ts_forcing.eq.1) ts_cur = ts_prof ! SST used in read_tsurf1d
+
+! vertical interpolation:
+      CALL interp_toga_vertical(play,nlev_toga,plev_prof                    &
+     &         ,t_prof,q_prof,u_prof,v_prof,w_prof                          &
+     &         ,ht_prof,vt_prof,hq_prof,vq_prof                             &
+     &         ,t_mod,q_mod,u_mod,v_mod,w_mod                               &
+     &         ,ht_mod,vt_mod,hq_mod,vq_mod,mxcalc)
+
+! large-scale forcing :
+      tsurf = ts_prof
+      do l = 1, llm
+       u(l) = u_mod(l) ! sb: on prescrit le vent
+       v(l) = v_mod(l) ! sb: on prescrit le vent
+!       omega(l) = w_prof(l)
+!       rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
+!       omega2(l)=-rho(l)*omega(l)
+       omega(l) = w_mod(l)
+       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+       d_t_adv(l) = alpha*omega(l)/rcpd-(ht_mod(l)+vt_mod(l))
+       d_q_adv(l,1) = -(hq_mod(l)+vq_mod(l))
+       dt_cooling(l) = 0.0
+      enddo
+
+      endif ! forcing_toga
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+! Interpolation DICE forcing 
+!---------------------------------------------------------------------
+      if (forcing_dice) then
+
+       if (prt_level.ge.1) then
+        print*,'#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/dt_dice=',&
+     &    day,day1,(day-day1)*86400.,(day-day1)*86400/dt_dice
+       endif
+
+! time interpolation:
+      CALL interp_dice_time(daytime,day1,annee_ref                    &
+     &             ,year_ini_dice,day_ju_ini_dice,nt_dice,dt_dice     & 
+     &             ,nlev_dice,shf_dice,lhf_dice,lwup_dice,swup_dice   &
+     &             ,tg_dice,ustar_dice,psurf_dice,ug_dice,vg_dice     &
+     &             ,ht_dice,hq_dice,hu_dice,hv_dice,w_dice,omega_dice &
+     &             ,shf_prof,lhf_prof,lwup_prof,swup_prof,tg_prof     &
+     &             ,ustar_prof,psurf_prof,ug_profd,vg_profd           &
+     &             ,ht_profd,hq_profd,hu_profd,hv_profd,w_profd       &
+     &             ,omega_profd)
+!     do l = 1, llm
+!     print *,'llm l omega_profd',llm,l,omega_profd(l)
+!     enddo
+
+        if (type_ts_forcing.eq.1) ts_cur = tg_prof ! SST used in read_tsurf1d
+
+! vertical interpolation:
+      CALL interp_dice_vertical(play,nlev_dice,nt_dice,plev_dice        &
+     &         ,t_dice,qv_dice,u_dice,v_dice,o3_dice                   &
+     &         ,ht_profd,hq_profd,hu_profd,hv_profd,w_profd,omega_profd &
+     &         ,t_mod,qv_mod,u_mod,v_mod,o3_mod                        &
+     &         ,ht_mod,hq_mod,hu_mod,hv_mod,w_mod,omega_mod,mxcalc)
+!     do l = 1, llm
+!      print *,'llm l omega_mod',llm,l,omega_mod(l)
+!     enddo
+
+! Les forcages DICE sont donnes /jour et non /seconde !
+      ht_mod(:)=ht_mod(:)/86400.
+      hq_mod(:)=hq_mod(:)/86400.
+      hu_mod(:)=hu_mod(:)/86400.
+      hv_mod(:)=hv_mod(:)/86400.
+
+!calcul de l'advection verticale a partir du omega (repris cas TWPICE, MPL 05082013)
+!Calcul des gradients verticaux
+!initialisation
+      d_t_z(:)=0.
+      d_q_z(:)=0.
+      d_u_z(:)=0.
+      d_v_z(:)=0.
+      DO l=2,llm-1
+       d_t_z(l)=(temp(l+1)-temp(l-1))/(play(l+1)-play(l-1))
+       d_q_z(l)=(q(l+1,1)-q(l-1,1)) /(play(l+1)-play(l-1))
+       d_u_z(l)=(u(l+1)-u(l-1))/(play(l+1)-play(l-1))
+       d_v_z(l)=(v(l+1)-v(l-1))/(play(l+1)-play(l-1))
+      ENDDO
+      d_t_z(1)=d_t_z(2)
+      d_q_z(1)=d_q_z(2)
+!     d_u_z(1)=u(2)/(play(2)-psurf)/5.
+!     d_v_z(1)=v(2)/(play(2)-psurf)/5.
+      d_u_z(1)=0.
+      d_v_z(1)=0.
+      d_t_z(llm)=d_t_z(llm-1)
+      d_q_z(llm)=d_q_z(llm-1)
+      d_u_z(llm)=d_u_z(llm-1)
+      d_v_z(llm)=d_v_z(llm-1)
+
+!Calcul de l advection verticale: 
+! utiliser omega (Pa/s) et non w (m/s) !! MP 20131108
+      d_t_dyn_z(:)=omega_mod(:)*d_t_z(:)
+      d_q_dyn_z(:)=omega_mod(:)*d_q_z(:)
+      d_u_dyn_z(:)=omega_mod(:)*d_u_z(:)
+      d_v_dyn_z(:)=omega_mod(:)*d_v_z(:)
+
+! large-scale forcing :
+!     tsurf = tg_prof    MPL 20130925 commente
+      psurf = psurf_prof
+! For this case, fluxes are imposed
+      fsens=-1*shf_prof
+      flat=-1*lhf_prof
+      ust=ustar_prof
+      tg=tg_prof
+      print *,'ust= ',ust
+      do l = 1, llm
+       ug(l)= ug_profd
+       vg(l)= vg_profd
+!       omega(l) = w_prof(l)
+!      rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
+!       omega2(l)=-rho(l)*omega(l)
+!      omega(l) = w_mod(l)*(-rg*rho(l))
+       omega(l) = omega_mod(l)
+       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+       d_t_adv(l) = alpha*omega(l)/rcpd+ht_mod(l)-d_t_dyn_z(l)
+       d_q_adv(l,1) = hq_mod(l)-d_q_dyn_z(l)
+       d_u_adv(l) = hu_mod(l)-d_u_dyn_z(l)
+       d_v_adv(l) = hv_mod(l)-d_v_dyn_z(l)
+       dt_cooling(l) = 0.0
+      enddo
+
+      endif ! forcing_dice
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+! Interpolation gabls4 forcing 
+!---------------------------------------------------------------------
+      if (forcing_gabls4 ) then
+
+       if (prt_level.ge.1) then
+        print*,'#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/dt_gabls4=',&
+     &    day,day1,(day-day1)*86400.,(day-day1)*86400/dt_gabls4
+       endif
+
+! time interpolation:
+      CALL interp_gabls4_time(daytime,day1,annee_ref                                     &
+     &             ,year_ini_gabls4,day_ju_ini_gabls4,nt_gabls4,dt_gabls4,nlev_gabls4  & 
+     &             ,ug_gabls4,vg_gabls4,ht_gabls4,hq_gabls4,tg_gabls4                            &
+     &             ,ug_profg,vg_profg,ht_profg,hq_profg,tg_profg)
+
+        if (type_ts_forcing.eq.1) ts_cur = tg_prof ! SST used in read_tsurf1d
+
+! vertical interpolation:
+! on re-utilise le programme interp_dice_vertical: les transformations sur 
+! plev_gabls4,th_gabls4,qv_gabls4,u_gabls4,v_gabls4 ne sont pas prises en compte.
+! seules celles sur ht_profg,hq_profg,ug_profg,vg_profg sont prises en compte.
+
+      CALL interp_dice_vertical(play,nlev_gabls4,nt_gabls4,plev_gabls4         &
+!    &         ,t_gabls4,qv_gabls4,u_gabls4,v_gabls4,poub            &
+     &         ,poub,poub,poub,poub,poub                             &
+     &         ,ht_profg,hq_profg,ug_profg,vg_profg,poub,poub        &
+     &         ,t_mod,qv_mod,u_mod,v_mod,o3_mod                      &
+     &         ,ht_mod,hq_mod,ug_mod,vg_mod,w_mod,omega_mod,mxcalc)
+
+      do l = 1, llm
+       ug(l)= ug_mod(l)
+       vg(l)= vg_mod(l)
+       d_t_adv(l)=ht_mod(l)
+       d_q_adv(l,1)=hq_mod(l)
+      enddo
+
+      endif ! forcing_gabls4
+!---------------------------------------------------------------------
+
+!---------------------------------------------------------------------
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Interpolation forcing TWPice
+!---------------------------------------------------------------------
+      if (forcing_twpice) then
+
+        print*,                                                             &
+     & '#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/dt_twpi=',     &
+     &    daytime,day1,(daytime-day1)*86400.,                               &
+     &    (daytime-day1)*86400/dt_twpi
+
+! time interpolation:
+        CALL interp_toga_time(daytime,day1,annee_ref                        &
+     &       ,year_ini_twpi,day_ju_ini_twpi,nt_twpi,dt_twpi,nlev_twpi       &
+     &       ,ts_twpi,plev_twpi,t_twpi,q_twpi,u_twpi,v_twpi,w_twpi          &
+     &       ,ht_twpi,vt_twpi,hq_twpi,vq_twpi                               &
+     &       ,ts_proftwp,plev_proftwp,t_proftwp,q_proftwp,u_proftwp         &
+     &       ,v_proftwp,w_proftwp                                           &
+     &       ,ht_proftwp,vt_proftwp,hq_proftwp,vq_proftwp)
+
+! vertical interpolation:
+      CALL interp_toga_vertical(play,nlev_twpi,plev_proftwp                 &
+     &         ,t_proftwp,q_proftwp,u_proftwp,v_proftwp,w_proftwp           &
+     &         ,ht_proftwp,vt_proftwp,hq_proftwp,vq_proftwp                 &
+     &         ,t_mod,q_mod,u_mod,v_mod,w_mod                               &
+     &         ,ht_mod,vt_mod,hq_mod,vq_mod,mxcalc)
+
+
+!calcul de l'advection verticale a partir du omega
+!Calcul des gradients verticaux
+!initialisation
+      d_t_z(:)=0.
+      d_q_z(:)=0.
+      d_t_dyn_z(:)=0.
+      d_q_dyn_z(:)=0.
+      DO l=2,llm-1
+       d_t_z(l)=(temp(l+1)-temp(l-1))/(play(l+1)-play(l-1))
+       d_q_z(l)=(q(l+1,1)-q(l-1,1))/(play(l+1)-play(l-1))
+      ENDDO
+      d_t_z(1)=d_t_z(2)
+      d_q_z(1)=d_q_z(2)
+      d_t_z(llm)=d_t_z(llm-1)
+      d_q_z(llm)=d_q_z(llm-1)
+
+!Calcul de l advection verticale
+      d_t_dyn_z(:)=w_mod(:)*d_t_z(:)
+      d_q_dyn_z(:)=w_mod(:)*d_q_z(:)
+
+!wind nudging above 500m with a 2h time scale
+        do l=1,llm
+        if (nudge_wind) then
+!           if (phi(l).gt.5000.) then
+        if (phi(l).gt.0.) then
+        u(l)=u(l)+timestep*(u_mod(l)-u(l))/(2.*3600.)
+        v(l)=v(l)+timestep*(v_mod(l)-v(l))/(2.*3600.)
+           endif    
+        else
+        u(l) = u_mod(l) 
+        v(l) = v_mod(l)
+        endif
+        enddo
+
+!CR:nudging of q and theta with a 6h time scale above 15km
+        if (nudge_thermo) then
+        do l=1,llm
+           zz(l)=phi(l)/9.8
+           if ((zz(l).le.16000.).and.(zz(l).gt.15000.)) then
+             zfact=(zz(l)-15000.)/1000.
+        q(l,1)=q(l,1)+timestep*(q_mod(l)-q(l,1))/(6.*3600.)*zfact
+        temp(l)=temp(l)+timestep*(t_mod(l)-temp(l))/(6.*3600.)*zfact
+           else if (zz(l).gt.16000.) then 
+        q(l,1)=q(l,1)+timestep*(q_mod(l)-q(l,1))/(6.*3600.)
+        temp(l)=temp(l)+timestep*(t_mod(l)-temp(l))/(6.*3600.)
+           endif
+        enddo    
+        endif
+
+      do l = 1, llm
+       omega(l) = w_mod(l)
+       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+!calcul de l'advection totale
+        if (cptadvw) then
+        d_t_adv(l) = alpha*omega(l)/rcpd+ht_mod(l)-d_t_dyn_z(l)
+!        print*,'temp vert adv',l,ht_mod(l),vt_mod(l),-d_t_dyn_z(l)
+        d_q_adv(l,1) = hq_mod(l)-d_q_dyn_z(l)
+!        print*,'q vert adv',l,hq_mod(l),vq_mod(l),-d_q_dyn_z(l)
+        else
+        d_t_adv(l) = alpha*omega(l)/rcpd+(ht_mod(l)+vt_mod(l))
+        d_q_adv(l,1) = (hq_mod(l)+vq_mod(l))
+        endif
+       dt_cooling(l) = 0.0
+      enddo
+
+      endif ! forcing_twpice
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Interpolation forcing AMMA
+!---------------------------------------------------------------------
+
+       if (forcing_amma) then
+
+        print*,                                                             &
+     & '#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/dt_amma=',     &
+     &    daytime,day1,(daytime-day1)*86400.,                               &
+     &    (daytime-day1)*86400/dt_amma
+
+! time interpolation using TOGA interpolation routine
+        CALL interp_amma_time(daytime,day1,annee_ref                        &
+     &       ,year_ini_amma,day_ju_ini_amma,nt_amma,dt_amma,nlev_amma       &
+     &       ,vitw_amma,ht_amma,hq_amma,lat_amma,sens_amma                  &
+     &       ,vitw_profamma,ht_profamma,hq_profamma,lat_profamma            &
+     &       ,sens_profamma)
+
+      print*,'apres interpolation temporelle AMMA'
+
+      do k=1,nlev_amma
+         th_profamma(k)=0.
+         q_profamma(k)=0.
+         u_profamma(k)=0.
+         v_profamma(k)=0.
+         vt_profamma(k)=0.
+         vq_profamma(k)=0.
+       enddo
+! vertical interpolation using TOGA interpolation routine:
+!      write(*,*)'avant interp vert', t_proftwp
+      CALL interp_toga_vertical(play,nlev_amma,plev_amma                      &
+     &         ,th_profamma,q_profamma,u_profamma,v_profamma                 &
+     &         ,vitw_profamma                                               &
+     &         ,ht_profamma,vt_profamma,hq_profamma,vq_profamma             &
+     &         ,t_mod,q_mod,u_mod,v_mod,w_mod                               &
+     &         ,ht_mod,vt_mod,hq_mod,vq_mod,mxcalc)
+       write(*,*) 'Profil initial forcing AMMA interpole'
+
+
+!calcul de l'advection verticale a partir du omega
+!Calcul des gradients verticaux
+!initialisation
+      do l=1,llm
+      d_t_z(l)=0.
+      d_q_z(l)=0.
+      enddo
+
+      DO l=2,llm-1
+       d_t_z(l)=(temp(l+1)-temp(l-1))/(play(l+1)-play(l-1))
+       d_q_z(l)=(q(l+1,1)-q(l-1,1))/(play(l+1)-play(l-1))
+      ENDDO
+      d_t_z(1)=d_t_z(2)
+      d_q_z(1)=d_q_z(2)
+      d_t_z(llm)=d_t_z(llm-1)
+      d_q_z(llm)=d_q_z(llm-1)
+
+
+      do l = 1, llm
+       rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
+       omega(l) = w_mod(l)*(-rg*rho(l))
+       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+!calcul de l'advection totale
+!        d_t_adv(l) = alpha*omega(l)/rcpd+ht_mod(l)-omega(l)*d_t_z(l)
+!attention: on impose dth
+        d_t_adv(l) = alpha*omega(l)/rcpd+                                  &
+     &         ht_mod(l)*(play(l)/pzero)**rkappa-omega(l)*d_t_z(l)
+!        d_t_adv(l) = 0.
+!        print*,'temp vert adv',l,ht_mod(l),vt_mod(l),-d_t_dyn_z(l)
+        d_q_adv(l,1) = hq_mod(l)-omega(l)*d_q_z(l)
+!        d_q_adv(l,1) = 0.
+!        print*,'q vert adv',l,hq_mod(l),vq_mod(l),-d_q_dyn_z(l)
+   
+       dt_cooling(l) = 0.0
+      enddo
+
+
+!     ok_flux_surf=.false.
+      fsens=-1.*sens_profamma
+      flat=-1.*lat_profamma
+
+      endif ! forcing_amma
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Interpolation forcing Rico
+!---------------------------------------------------------------------
+      if (forcing_rico) then
+!      call lstendH(llm,omega,dt_dyn,dq_dyn,du_dyn, dv_dyn,q,temp,u,v,play)
+       call lstendH(llm,nqtot,omega,dt_dyn,dq_dyn,q,temp,u,v,play)
+
+        do l=1,llm
+       d_t_adv(l) =  (dth_rico(l) +  dt_dyn(l))
+       d_q_adv(l,1) = (dqh_rico(l) +  dq_dyn(l,1))
+       d_q_adv(l,2) = 0.
+        enddo
+      endif  ! forcing_rico
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Interpolation forcing Arm_cu
+!---------------------------------------------------------------------
+      if (forcing_armcu) then
+
+        print*,                                                             &
+     & '#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/dt_armcu=',    &
+     &    day,day1,(day-day1)*86400.,(day-day1)*86400/dt_armcu
+
+! time interpolation:
+! ATTENTION, cet appel ne convient pas pour TOGA !!
+! revoir 1DUTILS.h et les arguments
+      CALL interp_armcu_time(daytime,day1,annee_ref                         &
+     &            ,year_ini_armcu,day_ju_ini_armcu,nt_armcu,dt_armcu        &
+     &            ,nlev_armcu,sens_armcu,flat_armcu,adv_theta_armcu          &
+     &            ,rad_theta_armcu,adv_qt_armcu,sens_prof,flat_prof         &
+     &            ,adv_theta_prof,rad_theta_prof,adv_qt_prof)
+
+! vertical interpolation:
+! No vertical interpolation if nlev imposed to 19 or 40
+
+! For this case, fluxes are imposed
+       fsens=-1*sens_prof
+       flat=-1*flat_prof
+
+! Advective forcings are given in K or g/kg ... BY HOUR
+      do l = 1, llm
+       ug(l)= u_mod(l)
+       vg(l)= v_mod(l)
+       IF((phi(l)/RG).LT.1000) THEN
+         d_t_adv(l) = (adv_theta_prof + rad_theta_prof)/3600.
+         d_q_adv(l,1) = adv_qt_prof/1000./3600.
+         d_q_adv(l,2) = 0.0
+!        print *,'INF1000: phi dth dq1 dq2',
+!    :  phi(l)/RG,d_t_adv(l),d_q_adv(l,1),d_q_adv(l,2)
+       ELSEIF ((phi(l)/RG).GE.1000.AND.(phi(l)/RG).lt.3000) THEN
+         fact=((phi(l)/RG)-1000.)/2000.
+         fact=1-fact
+         d_t_adv(l) = (adv_theta_prof + rad_theta_prof)*fact/3600.
+         d_q_adv(l,1) = adv_qt_prof*fact/1000./3600.
+         d_q_adv(l,2) = 0.0
+!        print *,'SUP1000: phi fact dth dq1 dq2',
+!    :  phi(l)/RG,fact,d_t_adv(l),d_q_adv(l,1),d_q_adv(l,2)
+       ELSE
+         d_t_adv(l) = 0.0
+         d_q_adv(l,1) = 0.0
+         d_q_adv(l,2) = 0.0
+!        print *,'SUP3000: phi dth dq1 dq2',
+!    :  phi(l)/RG,d_t_adv(l),d_q_adv(l,1),d_q_adv(l,2)
+       ENDIF
+      dt_cooling(l) = 0.0  
+!     print *,'Interp armcu: phi dth dq1 dq2',
+!    :  l,phi(l),d_t_adv(l),d_q_adv(l,1),d_q_adv(l,2)
+      enddo
+      endif ! forcing_armcu
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Interpolation forcing in time and onto model levels
+!---------------------------------------------------------------------
+      if (forcing_sandu) then
+
+        print*,                                                             &
+     & '#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/dt_sandu=',    &
+     &    day,day1,(day-day1)*86400.,(day-day1)*86400/dt_sandu 
+
+! time interpolation:
+! ATTENTION, cet appel ne convient pas pour TOGA !!
+! revoir 1DUTILS.h et les arguments
+      CALL interp_sandu_time(daytime,day1,annee_ref                         &
+     &             ,year_ini_sandu,day_ju_ini_sandu,nt_sandu,dt_sandu       &
+     &             ,nlev_sandu                                              &
+     &             ,ts_sandu,ts_prof)
+
+        if (type_ts_forcing.eq.1) ts_cur = ts_prof ! SST used in read_tsurf1d
+
+! vertical interpolation:
+      CALL interp_sandu_vertical(play,nlev_sandu,plev_profs                 &
+     &         ,t_profs,thl_profs,q_profs,u_profs,v_profs,w_profs           &
+     &         ,omega_profs,o3mmr_profs                                     &
+     &         ,t_mod,thl_mod,q_mod,u_mod,v_mod,w_mod                       &
+     &         ,omega_mod,o3mmr_mod,mxcalc)
+!calcul de l'advection verticale
+!Calcul des gradients verticaux
+!initialisation
+      d_t_z(:)=0.
+      d_q_z(:)=0.
+      d_t_dyn_z(:)=0.
+      d_q_dyn_z(:)=0.
+! schema centre
+!     DO l=2,llm-1
+!      d_t_z(l)=(temp(l+1)-temp(l-1))
+!    &          /(play(l+1)-play(l-1))
+!      d_q_z(l)=(q(l+1,1)-q(l-1,1))
+!    &          /(play(l+1)-play(l-1))
+! schema amont
+      DO l=2,llm-1
+       d_t_z(l)=(temp(l+1)-temp(l))/(play(l+1)-play(l))
+       d_q_z(l)=(q(l+1,1)-q(l,1))/(play(l+1)-play(l))
+!     print *,'l temp2 temp0 play2 play0 omega_mod',
+!    & temp(l+1),temp(l-1),play(l+1),play(l-1),omega_mod(l)
+      ENDDO
+      d_t_z(1)=d_t_z(2)
+      d_q_z(1)=d_q_z(2)
+      d_t_z(llm)=d_t_z(llm-1)
+      d_q_z(llm)=d_q_z(llm-1)
+
+!  calcul de l advection verticale
+! Confusion w (m/s) et omega (Pa/s) !!
+      d_t_dyn_z(:)=omega_mod(:)*d_t_z(:)
+      d_q_dyn_z(:)=omega_mod(:)*d_q_z(:)
+!     do l=1,llm
+!      print *,'d_t_dyn omega_mod d_t_z d_q_dyn d_q_z',
+!    :l,d_t_dyn_z(l),omega_mod(l),d_t_z(l),d_q_dyn_z(l),d_q_z(l)
+!     enddo
+
+
+! large-scale forcing : pour le cas Sandu ces forcages sont la SST
+! et une divergence constante -> profil de omega
+      tsurf = ts_prof
+      write(*,*) 'SST suivante: ',tsurf
+      do l = 1, llm
+       omega(l) = omega_mod(l)
+       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+!
+!      d_t_adv(l) = 0.0
+!      d_q_adv(l,1) = 0.0
+!CR:test advection=0
+!calcul de l'advection verticale
+        d_t_adv(l) = alpha*omega(l)/rcpd-d_t_dyn_z(l)
+!        print*,'temp adv',l,-d_t_dyn_z(l)
+        d_q_adv(l,1) = -d_q_dyn_z(l)
+!        print*,'q adv',l,-d_q_dyn_z(l)
+       dt_cooling(l) = 0.0
+      enddo
+      endif ! forcing_sandu
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Interpolation forcing in time and onto model levels
+!---------------------------------------------------------------------
+      if (forcing_astex) then
+
+        print*,                                                             &
+     & '#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/dt_astex=',    &
+     &    day,day1,(day-day1)*86400.,(day-day1)*86400/dt_astex
+
+! time interpolation:
+! ATTENTION, cet appel ne convient pas pour TOGA !!
+! revoir 1DUTILS.h et les arguments
+      CALL interp_astex_time(daytime,day1,annee_ref                         &
+     &             ,year_ini_astex,day_ju_ini_astex,nt_astex,dt_astex       &
+     &             ,nlev_astex,div_astex,ts_astex,ug_astex,vg_astex         &
+     &             ,ufa_astex,vfa_astex,div_prof,ts_prof,ug_prof,vg_prof    &
+     &             ,ufa_prof,vfa_prof)
+
+        if (type_ts_forcing.eq.1) ts_cur = ts_prof ! SST used in read_tsurf1d
+
+! vertical interpolation:
+      CALL interp_astex_vertical(play,nlev_astex,plev_profa                 &
+     &         ,t_profa,thl_profa,qv_profa,ql_profa,qt_profa                &
+     &         ,u_profa,v_profa,w_profa,tke_profa,o3mmr_profa               &
+     &         ,t_mod,thl_mod,qv_mod,ql_mod,qt_mod,u_mod,v_mod,w_mod        &
+     &         ,tke_mod,o3mmr_mod,mxcalc)
+!calcul de l'advection verticale
+!Calcul des gradients verticaux
+!initialisation
+      d_t_z(:)=0.
+      d_q_z(:)=0.
+      d_t_dyn_z(:)=0.
+      d_q_dyn_z(:)=0.
+! schema centre
+!     DO l=2,llm-1
+!      d_t_z(l)=(temp(l+1)-temp(l-1))
+!    &          /(play(l+1)-play(l-1))
+!      d_q_z(l)=(q(l+1,1)-q(l-1,1))
+!    &          /(play(l+1)-play(l-1))
+! schema amont
+      DO l=2,llm-1
+       d_t_z(l)=(temp(l+1)-temp(l))/(play(l+1)-play(l))
+       d_q_z(l)=(q(l+1,1)-q(l,1))/(play(l+1)-play(l))
+!     print *,'l temp2 temp0 play2 play0 omega_mod',
+!    & temp(l+1),temp(l-1),play(l+1),play(l-1),omega_mod(l)
+      ENDDO
+      d_t_z(1)=d_t_z(2)
+      d_q_z(1)=d_q_z(2)
+      d_t_z(llm)=d_t_z(llm-1)
+      d_q_z(llm)=d_q_z(llm-1)
+
+!  calcul de l advection verticale
+! Confusion w (m/s) et omega (Pa/s) !!
+      d_t_dyn_z(:)=w_mod(:)*d_t_z(:)
+      d_q_dyn_z(:)=w_mod(:)*d_q_z(:)
+!     do l=1,llm
+!      print *,'d_t_dyn omega_mod d_t_z d_q_dyn d_q_z',
+!    :l,d_t_dyn_z(l),omega_mod(l),d_t_z(l),d_q_dyn_z(l),d_q_z(l)
+!     enddo
+
+
+! large-scale forcing : pour le cas Astex ces forcages sont la SST
+! la divergence,ug,vg,ufa,vfa
+      tsurf = ts_prof
+      write(*,*) 'SST suivante: ',tsurf
+      do l = 1, llm
+       omega(l) = w_mod(l)
+       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+!
+!      d_t_adv(l) = 0.0
+!      d_q_adv(l,1) = 0.0
+!CR:test advection=0
+!calcul de l'advection verticale
+        d_t_adv(l) = alpha*omega(l)/rcpd-d_t_dyn_z(l)
+!        print*,'temp adv',l,-d_t_dyn_z(l)
+        d_q_adv(l,1) = -d_q_dyn_z(l)
+!        print*,'q adv',l,-d_q_dyn_z(l)
+       dt_cooling(l) = 0.0
+      enddo
+      endif ! forcing_astex
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Interpolation forcing standard case
+!---------------------------------------------------------------------
+      if (forcing_case) then
+
+         print*,'FORCING CASE forcing_case'
+
+        print*,                                                             &
+     & '#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/pdt_cas=',     &
+     &    daytime,day1,(daytime-day1)*86400.,                               &
+     &    (daytime-day1)*86400/pdt_cas
+
+! time interpolation:
+        CALL interp_case_time(daytime,day1,annee_ref                                        &
+!    &       ,year_ini_cas,day_ju_ini_cas,nt_cas,pdt_cas,nlev_cas                           &
+     &       ,nt_cas,nlev_cas                                                               &
+     &       ,ts_cas,plev_cas,t_cas,q_cas,u_cas,v_cas,ug_cas,vg_cas                         &
+     &       ,vitw_cas,du_cas,hu_cas,vu_cas                                                 &
+     &       ,dv_cas,hv_cas,vv_cas,dt_cas,ht_cas,vt_cas,dtrad_cas                           &
+     &       ,dq_cas,hq_cas,vq_cas,lat_cas,sens_cas,ustar_cas                               &
+     &       ,uw_cas,vw_cas,q1_cas,q2_cas                                                   &
+     &       ,ts_prof_cas,plev_prof_cas,t_prof_cas,q_prof_cas,u_prof_cas,v_prof_cas         &
+     &       ,ug_prof_cas,vg_prof_cas,vitw_prof_cas,du_prof_cas,hu_prof_cas,vu_prof_cas     &
+     &       ,dv_prof_cas,hv_prof_cas,vv_prof_cas,dt_prof_cas,ht_prof_cas,vt_prof_cas       &
+     &       ,dtrad_prof_cas,dq_prof_cas,hq_prof_cas,vq_prof_cas,lat_prof_cas               &
+     &       ,sens_prof_cas,ustar_prof_cas,uw_prof_cas,vw_prof_cas,q1_prof_cas,q2_prof_cas)
+
+             ts_cur = ts_prof_cas 
+             psurf=plev_prof_cas(1)
+
+! vertical interpolation:
+      CALL interp_case_vertical(play,nlev_cas,plev_prof_cas            &
+     &         ,t_prof_cas,q_prof_cas,u_prof_cas,v_prof_cas,ug_prof_cas,vg_prof_cas,vitw_prof_cas                         &
+     &         ,du_prof_cas,hu_prof_cas,vu_prof_cas,dv_prof_cas,hv_prof_cas,vv_prof_cas           &
+     &         ,dt_prof_cas,ht_prof_cas,vt_prof_cas,dtrad_prof_cas,dq_prof_cas,hq_prof_cas,vq_prof_cas           &
+     &         ,t_mod_cas,q_mod_cas,u_mod_cas,v_mod_cas,ug_mod_cas,vg_mod_cas,w_mod_cas                              &
+     &         ,du_mod_cas,hu_mod_cas,vu_mod_cas,dv_mod_cas,hv_mod_cas,vv_mod_cas               &
+     &         ,dt_mod_cas,ht_mod_cas,vt_mod_cas,dtrad_mod_cas,dq_mod_cas,hq_mod_cas,vq_mod_cas,mxcalc)
+
+
+!calcul de l'advection verticale a partir du omega
+!Calcul des gradients verticaux
+!initialisation
+      d_t_z(:)=0.
+      d_q_z(:)=0.
+      d_u_z(:)=0.
+      d_v_z(:)=0.
+      d_t_dyn_z(:)=0.
+      d_q_dyn_z(:)=0.
+      d_u_dyn_z(:)=0.
+      d_v_dyn_z(:)=0.
+      DO l=2,llm-1
+       d_t_z(l)=(temp(l+1)-temp(l-1))/(play(l+1)-play(l-1))
+       d_q_z(l)=(q(l+1,1)-q(l-1,1))/(play(l+1)-play(l-1))
+       d_u_z(l)=(u(l+1)-u(l-1))/(play(l+1)-play(l-1))
+       d_v_z(l)=(v(l+1)-v(l-1))/(play(l+1)-play(l-1))
+      ENDDO
+      d_t_z(1)=d_t_z(2)
+      d_q_z(1)=d_q_z(2)
+      d_u_z(1)=d_u_z(2)
+      d_v_z(1)=d_v_z(2)
+      d_t_z(llm)=d_t_z(llm-1)
+      d_q_z(llm)=d_q_z(llm-1)
+      d_u_z(llm)=d_u_z(llm-1)
+      d_v_z(llm)=d_v_z(llm-1)
+
+!Calcul de l advection verticale
+
+      d_t_dyn_z(:)=w_mod_cas(:)*d_t_z(:)
+
+      d_q_dyn_z(:)=w_mod_cas(:)*d_q_z(:)
+      d_u_dyn_z(:)=w_mod_cas(:)*d_u_z(:)
+      d_v_dyn_z(:)=w_mod_cas(:)*d_v_z(:)
+
+!wind nudging 
+      if (nudge_u.gt.0.) then
+        do l=1,llm
+           u(l)=u(l)+timestep*(u_mod_cas(l)-u(l))/(nudge_u)
+        enddo
+      else
+        do l=1,llm
+        u(l) = u_mod_cas(l) 
+        enddo
+      endif
+
+      if (nudge_v.gt.0.) then
+        do l=1,llm
+           v(l)=v(l)+timestep*(v_mod_cas(l)-v(l))/(nudge_v)
+        enddo
+      else
+        do l=1,llm
+        v(l) = v_mod_cas(l) 
+        enddo
+      endif
+
+      if (nudge_w.gt.0.) then
+        do l=1,llm
+           w(l)=w(l)+timestep*(w_mod_cas(l)-w(l))/(nudge_w)
+        enddo
+      else
+        do l=1,llm
+        w(l) = w_mod_cas(l) 
+        enddo
+      endif
+
+!nudging of q and temp 
+      if (nudge_t.gt.0.) then
+        do l=1,llm
+           temp(l)=temp(l)+timestep*(t_mod_cas(l)-temp(l))/(nudge_t)
+        enddo
+      endif
+      if (nudge_q.gt.0.) then
+        do l=1,llm
+           q(l,1)=q(l,1)+timestep*(q_mod_cas(l)-q(l,1))/(nudge_q)
+        enddo
+      endif
+
+      do l = 1, llm
+       omega(l) = w_mod_cas(l)  ! juste car w_mod_cas en Pa/s (MPL 20170310)
+       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+
+!calcul advection
+        if ((tend_u.eq.1).and.(tend_w.eq.0)) then
+           d_u_adv(l)=du_mod_cas(l)
+        else if ((tend_u.eq.1).and.(tend_w.eq.1)) then
+           d_u_adv(l)=hu_mod_cas(l)-d_u_dyn_z(l)
+        endif
+
+        if ((tend_v.eq.1).and.(tend_w.eq.0)) then
+           d_v_adv(l)=dv_mod_cas(l)
+        else if ((tend_v.eq.1).and.(tend_w.eq.1)) then
+           d_v_adv(l)=hv_mod_cas(l)-d_v_dyn_z(l)
+        endif
+
+        if ((tend_t.eq.1).and.(tend_w.eq.0)) then
+!           d_t_adv(l)=alpha*omega(l)/rcpd+dt_mod_cas(l)
+           d_t_adv(l)=alpha*omega(l)/rcpd-dt_mod_cas(l)
+        else if ((tend_t.eq.1).and.(tend_w.eq.1)) then
+!           d_t_adv(l)=alpha*omega(l)/rcpd+ht_mod_cas(l)-d_t_dyn_z(l)
+           d_t_adv(l)=alpha*omega(l)/rcpd-ht_mod_cas(l)-d_t_dyn_z(l)
+        endif
+
+        if ((tend_q.eq.1).and.(tend_w.eq.0)) then
+!           d_q_adv(l,1)=dq_mod_cas(l)
+           d_q_adv(l,1)=-1*dq_mod_cas(l)
+        else if ((tend_q.eq.1).and.(tend_w.eq.1)) then
+!           d_q_adv(l,1)=hq_mod_cas(l)-d_q_dyn_z(l)
+           d_q_adv(l,1)=-1*hq_mod_cas(l)-d_q_dyn_z(l)
+        endif
+         
+        if (tend_rayo.eq.1) then
+           dt_cooling(l) = dtrad_mod_cas(l)
+!          print *,'dt_cooling=',dt_cooling(l)
+        else
+           dt_cooling(l) = 0.0
+        endif
+      enddo
+
+! Faut-il multiplier par -1 ? (MPL 20160713)
+      IF(ok_flux_surf) THEN
+       fsens=sens_prof_cas
+       flat=lat_prof_cas
+      ENDIF
+!
+      IF (ok_prescr_ust) THEN
+       ust=ustar_prof_cas
+       print *,'ust=',ust
+      ENDIF
+      endif ! forcing_case
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Interpolation forcing standard case
+!---------------------------------------------------------------------
+      if (forcing_case2 .OR. forcing_SCM) then
+
+         print*,'FORCING CASE forcing_case2'
+        print*,                                                             &
+     & '#### ITAP,day,day1,(day-day1)*86400,(day-day1)*86400/pdt_cas=',     &
+     &    daytime,day1,(daytime-day1)*86400.,                               &
+     &    (daytime-day1)*86400/pdt_cas
+
+! time interpolation:
+        CALL interp2_case_time(daytime,day1,annee_ref                                       &
+!    &       ,year_ini_cas,day_ju_ini_cas,nt_cas,pdt_cas,nlev_cas                           &
+     &       ,nt_cas,nlev_cas                                                               &
+     &       ,ts_cas,ps_cas,plev_cas,t_cas,th_cas,thv_cas,thl_cas,qv_cas,ql_cas,qi_cas      &
+     &       ,u_cas,v_cas,ug_cas,vg_cas,vitw_cas,omega_cas,du_cas,hu_cas,vu_cas             &
+     &       ,dv_cas,hv_cas,vv_cas,dt_cas,ht_cas,vt_cas,dtrad_cas                           &
+     &       ,dq_cas,hq_cas,vq_cas,dth_cas,hth_cas,vth_cas,lat_cas,sens_cas,ustar_cas       &
+     &       ,uw_cas,vw_cas,q1_cas,q2_cas,tke_cas                                           &
+!
+     &       ,ts_prof_cas,plev_prof_cas,t_prof_cas,theta_prof_cas,thv_prof_cas  &
+     &       ,thl_prof_cas,qv_prof_cas,ql_prof_cas,qi_prof_cas                              &
+     &       ,u_prof_cas,v_prof_cas,ug_prof_cas,vg_prof_cas,vitw_prof_cas,omega_prof_cas    &
+     &       ,du_prof_cas,hu_prof_cas,vu_prof_cas                                           &
+     &       ,dv_prof_cas,hv_prof_cas,vv_prof_cas,dt_prof_cas,ht_prof_cas,vt_prof_cas       &
+     &       ,dtrad_prof_cas,dq_prof_cas,hq_prof_cas,vq_prof_cas                            &
+     &       ,dth_prof_cas,hth_prof_cas,vth_prof_cas,lat_prof_cas                           &
+     &       ,sens_prof_cas,ustar_prof_cas,uw_prof_cas,vw_prof_cas,q1_prof_cas,q2_prof_cas,tke_prof_cas)
+
+             ts_cur = ts_prof_cas 
+!            psurf=plev_prof_cas(1)
+             psurf=ps_prof_cas
+
+! vertical interpolation:
+      CALL interp2_case_vertical(play,nlev_cas,plev_prof_cas                                              &
+     &         ,t_prof_cas,theta_prof_cas,thv_prof_cas,thl_prof_cas                                          &
+     &         ,qv_prof_cas,ql_prof_cas,qi_prof_cas,u_prof_cas,v_prof_cas                                 &
+     &         ,ug_prof_cas,vg_prof_cas,vitw_prof_cas,omega_prof_cas                                      &
+     &         ,du_prof_cas,hu_prof_cas,vu_prof_cas,dv_prof_cas,hv_prof_cas,vv_prof_cas                   &
+     &         ,dt_prof_cas,ht_prof_cas,vt_prof_cas,dtrad_prof_cas,dq_prof_cas,hq_prof_cas,vq_prof_cas    &
+     &         ,dth_prof_cas,hth_prof_cas,vth_prof_cas                                                    &
+!
+     &         ,t_mod_cas,theta_mod_cas,thv_mod_cas,thl_mod_cas,qv_mod_cas,ql_mod_cas,qi_mod_cas          &
+     &         ,u_mod_cas,v_mod_cas,ug_mod_cas,vg_mod_cas,w_mod_cas,omega_mod_cas                         &
+     &         ,du_mod_cas,hu_mod_cas,vu_mod_cas,dv_mod_cas,hv_mod_cas,vv_mod_cas                         &
+     &         ,dt_mod_cas,ht_mod_cas,vt_mod_cas,dtrad_mod_cas,dq_mod_cas,hq_mod_cas,vq_mod_cas           &
+     &         ,dth_mod_cas,hth_mod_cas,vth_mod_cas,mxcalc)
+
+
+      DO l=1,llm
+      teta(l)=temp(l)*(100000./play(l))**(rd/rcpd)
+      ENDDO
+!calcul de l'advection verticale a partir du omega
+!Calcul des gradients verticaux
+!initialisation
+      d_t_z(:)=0.
+      d_th_z(:)=0.
+      d_q_z(:)=0.
+      d_u_z(:)=0.
+      d_v_z(:)=0.
+      d_t_dyn_z(:)=0.
+      d_th_dyn_z(:)=0.
+      d_q_dyn_z(:)=0.
+      d_u_dyn_z(:)=0.
+      d_v_dyn_z(:)=0.
+      DO l=2,llm-1
+       d_t_z(l)=(temp(l+1)-temp(l-1))/(play(l+1)-play(l-1))
+       d_th_z(l)=(teta(l+1)-teta(l-1))/(play(l+1)-play(l-1))
+       d_q_z(l)=(q(l+1,1)-q(l-1,1))/(play(l+1)-play(l-1))
+       d_u_z(l)=(u(l+1)-u(l-1))/(play(l+1)-play(l-1))
+       d_v_z(l)=(v(l+1)-v(l-1))/(play(l+1)-play(l-1))
+      ENDDO
+      d_t_z(1)=d_t_z(2)
+      d_th_z(1)=d_th_z(2)
+      d_q_z(1)=d_q_z(2)
+      d_u_z(1)=d_u_z(2)
+      d_v_z(1)=d_v_z(2)
+      d_t_z(llm)=d_t_z(llm-1)
+      d_th_z(llm)=d_th_z(llm-1)
+      d_q_z(llm)=d_q_z(llm-1)
+      d_u_z(llm)=d_u_z(llm-1)
+      d_v_z(llm)=d_v_z(llm-1)
+
+!Calcul de l advection verticale
+! Modif w_mod_cas -> omega_mod_cas (MM+MPL 20170310)
+      d_t_dyn_z(:)=omega_mod_cas(:)*d_t_z(:)
+      d_th_dyn_z(:)=omega_mod_cas(:)*d_th_z(:)
+      d_q_dyn_z(:)=omega_mod_cas(:)*d_q_z(:)
+      d_u_dyn_z(:)=omega_mod_cas(:)*d_u_z(:)
+      d_v_dyn_z(:)=omega_mod_cas(:)*d_v_z(:)
+
+!geostrophic wind 
+      if (forc_geo.eq.1) then
+        do l=1,llm
+        ug(l) = ug_mod_cas(l) 
+        vg(l) = vg_mod_cas(l) 
+        enddo
+      endif
+!wind nudging 
+      if (nudging_u.gt.0.) then
+        do l=1,llm
+           u(l)=u(l)+timestep*(u_mod_cas(l)-u(l))/(nudge_u)
+        enddo
+!     else
+!       do l=1,llm
+!          u(l) = u_mod_cas(l) 
+!       enddo
+      endif
+
+      if (nudging_v.gt.0.) then
+        do l=1,llm
+           v(l)=v(l)+timestep*(v_mod_cas(l)-v(l))/(nudge_v)
+        enddo
+!     else
+!       do l=1,llm
+!          v(l) = v_mod_cas(l) 
+!       enddo
+      endif
+
+      if (nudging_w.gt.0.) then
+        do l=1,llm
+           w(l)=w(l)+timestep*(w_mod_cas(l)-w(l))/(nudge_w)
+        enddo
+ !    else
+ !      do l=1,llm
+ !         w(l) = w_mod_cas(l) 
+ !      enddo
+      endif
+
+!nudging of q and temp 
+      if (nudging_t.gt.0.) then
+        do l=1,llm
+           temp(l)=temp(l)+timestep*(t_mod_cas(l)-temp(l))/(nudge_t)
+        enddo
+      endif
+      if (nudging_qv.gt.0.) then
+        do l=1,llm
+           q(l,1)=q(l,1)+timestep*(q_mod_cas(l)-q(l,1))/(nudge_q)
+        enddo
+      endif
+
+      do l = 1, llm
+! Modif w_mod_cas -> omega_mod_cas (MM+MPL 20170309)
+       omega(l) = omega_mod_cas(l)
+       omega2(l)= omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+
+!calcul advections
+        if ((forc_u.eq.1).and.(forc_w.eq.0)) then
+           d_u_adv(l)=du_mod_cas(l)
+        else if ((forc_u.eq.1).and.(forc_w.eq.1)) then
+           d_u_adv(l)=hu_mod_cas(l)-d_u_dyn_z(l)
+        endif
+
+        if ((forc_v.eq.1).and.(forc_w.eq.0)) then
+           d_v_adv(l)=dv_mod_cas(l)
+        else if ((forc_v.eq.1).and.(forc_w.eq.1)) then
+           d_v_adv(l)=hv_mod_cas(l)-d_v_dyn_z(l)
+        endif
+
+! Puisque dth a ete converti en dt, on traite de la meme facon 
+! les flags tadv et thadv
+        if ((tadv.eq.1.or.thadv.eq.1) .and. (forc_w.eq.0)) then
+!          d_t_adv(l)=alpha*omega(l)/rcpd-dt_mod_cas(l)
+           d_t_adv(l)=alpha*omega(l)/rcpd+dt_mod_cas(l)
+        else if ((tadv.eq.1.or.thadv.eq.1) .and. (forc_w.eq.1)) then
+!          d_t_adv(l)=alpha*omega(l)/rcpd-ht_mod_cas(l)-d_t_dyn_z(l)
+           d_t_adv(l)=alpha*omega(l)/rcpd+ht_mod_cas(l)-d_t_dyn_z(l)
+        endif
+
+!       if ((thadv.eq.1) .and. (forc_w.eq.0)) then
+!          d_t_adv(l)=alpha*omega(l)/rcpd-dth_mod_cas(l)
+!          d_t_adv(l)=alpha*omega(l)/rcpd+dth_mod_cas(l)
+!       else if ((thadv.eq.1) .and. (forc_w.eq.1)) then
+!          d_t_adv(l)=alpha*omega(l)/rcpd-hth_mod_cas(l)-d_t_dyn_z(l)
+!          d_t_adv(l)=alpha*omega(l)/rcpd+hth_mod_cas(l)-d_t_dyn_z(l)
+!       endif
+
+        if ((qadv.eq.1) .and. (forc_w.eq.0)) then
+           d_q_adv(l,1)=dq_mod_cas(l)
+!          d_q_adv(l,1)=-1*dq_mod_cas(l)
+        else if ((qadv.eq.1) .and. (forc_w.eq.1)) then
+           d_q_adv(l,1)=hq_mod_cas(l)-d_q_dyn_z(l)
+!          d_q_adv(l,1)=-1*hq_mod_cas(l)-d_q_dyn_z(l)
+        endif
+         
+        if (trad.eq.1) then
+           tend_rayo=1
+           dt_cooling(l) = dtrad_mod_cas(l)
+!          print *,'dt_cooling=',dt_cooling(l)
+        else
+           dt_cooling(l) = 0.0
+        endif
+      enddo
+
+! Faut-il multiplier par -1 ? (MPL 20160713)
+      IF(ok_flux_surf) THEN
+       fsens=-1.*sens_prof_cas
+       flat=-1.*lat_prof_cas
+       print *,'1D_interp: sens,flat',fsens,flat
+      ENDIF
+!
+      IF (ok_prescr_ust) THEN
+       ust=ustar_prof_cas
+       print *,'ust=',ust
+      ENDIF
+      endif ! forcing_case2
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/old_1D_read_forc_cases.h
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/old_1D_read_forc_cases.h	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/old_1D_read_forc_cases.h	(revision 3605)
@@ -0,0 +1,1106 @@
+!
+! $Id: 1D_read_forc_cases.h 3537 2019-06-19 08:29:16Z fhourdin $
+!
+!----------------------------------------------------------------------
+! forcing_les = .T. : Impose a constant cooling 
+! forcing_radconv = .T. : Pure radiative-convective equilibrium:
+!----------------------------------------------------------------------
+
+
+      nq1=0
+      nq2=0
+
+      if (forcing_les .or. forcing_radconv                                      &
+     &    .or. forcing_GCSSold .or. forcing_fire) then
+
+      if (forcing_fire) then
+!----------------------------------------------------------------------
+!read fire forcings from fire.nc
+!----------------------------------------------------------------------
+      fich_fire='fire.nc'
+      call read_fire(fich_fire,nlev_fire,nt_fire                                &
+     &     ,height,tttprof,qtprof,uprof,vprof,e12prof                           &
+     &     ,ugprof,vgprof,wfls,dqtdxls                                          &
+     &     ,dqtdyls,dqtdtls,thlpcar)
+      write(*,*) 'Forcing FIRE lu'
+      kmax=120            ! nombre de niveaux dans les profils et forcages
+      else 
+!----------------------------------------------------------------------
+! Read profiles from files: prof.inp.001 and lscale.inp.001
+! (repris de readlesfiles)
+!----------------------------------------------------------------------
+
+      call readprofiles(nlev_max,kmax,nqtot,height,                             &
+     &           tttprof,qtprof,uprof,vprof,                                    &
+     &           e12prof,ugprof,vgprof,                                         &
+     &           wfls,dqtdxls,dqtdyls,dqtdtls,                                  &
+     &           thlpcar,qprof,nq1,nq2)
+      endif
+
+! compute altitudes of play levels.
+      zlay(1) =zsurf +  rd*tsurf*(psurf-play(1))/(rg*psurf)
+      do l = 2,llm
+        zlay(l) = zlay(l-1)+rd*tsurf*(psurf-play(1))/(rg*psurf)
+      enddo
+
+!----------------------------------------------------------------------
+! Interpolation of the profiles given on the input file to
+! model levels
+!----------------------------------------------------------------------
+      zlay(1) = zsurf +  rd*tsurf*(psurf-play(1))/(rg*psurf)
+      do l=1,llm
+        ! Above the max altutide of the input file
+
+        if (zlay(l)<height(kmax)) mxcalc=l
+
+        frac = (height(kmax)-zlay(l))/(height (kmax)-height(kmax-1))
+        ttt =tttprof(kmax)-frac*(tttprof(kmax)-tttprof(kmax-1))
+       if ((forcing_GCSSold .AND. tp_ini_GCSSold) .OR. forcing_fire)then ! pot. temp. in initial profile
+          temp(l) = ttt*(play(l)/pzero)**rkappa
+          teta(l) = ttt
+       else
+          temp(l) = ttt
+          teta(l) = ttt*(pzero/play(l))**rkappa
+       endif
+          print *,' temp,teta ',l,temp(l),teta(l)
+        q(l,1)  = qtprof(kmax)-frac*( qtprof(kmax)- qtprof(kmax-1))
+        u(l)    =  uprof(kmax)-frac*(  uprof(kmax)-  uprof(kmax-1))
+        v(l)    =  vprof(kmax)-frac*(  vprof(kmax)-  vprof(kmax-1))
+        ug(l)   = ugprof(kmax)-frac*( ugprof(kmax)- ugprof(kmax-1))
+        vg(l)   = vgprof(kmax)-frac*( vgprof(kmax)- vgprof(kmax-1))
+        IF (nq2>0) q(l,nq1:nq2)=qprof(kmax,nq1:nq2)                         &
+     &               -frac*(qprof(kmax,nq1:nq2)-qprof(kmax-1,nq1:nq2))
+        omega(l)=   wfls(kmax)-frac*(   wfls(kmax)-   wfls(kmax-1))
+
+        dq_dyn(l,1) = dqtdtls(kmax)-frac*(dqtdtls(kmax)-dqtdtls(kmax-1))
+        dt_cooling(l)=thlpcar(kmax)-frac*(thlpcar(kmax)-thlpcar(kmax-1))
+        do k=2,kmax
+          print *,'k l height(k) height(k-1) zlay(l) frac=',k,l,height(k),height(k-1),zlay(l),frac
+          frac = (height(k)-zlay(l))/(height(k)-height(k-1))
+          if(l==1) print*,'k, height, tttprof',k,height(k),tttprof(k)
+          if(zlay(l)>height(k-1).and.zlay(l)<height(k)) then
+            ttt =tttprof(k)-frac*(tttprof(k)-tttprof(k-1))
+       if ((forcing_GCSSold .AND. tp_ini_GCSSold) .OR. forcing_fire)then ! pot. temp. in initial profile
+          temp(l) = ttt*(play(l)/pzero)**rkappa
+          teta(l) = ttt
+       else
+          temp(l) = ttt
+          teta(l) = ttt*(pzero/play(l))**rkappa
+       endif
+          print *,' temp,teta ',l,temp(l),teta(l)
+            q(l,1)  = qtprof(k)-frac*( qtprof(k)- qtprof(k-1))
+            u(l)    =  uprof(k)-frac*(  uprof(k)-  uprof(k-1))
+            v(l)    =  vprof(k)-frac*(  vprof(k)-  vprof(k-1))
+            ug(l)   = ugprof(k)-frac*( ugprof(k)- ugprof(k-1))
+            vg(l)   = vgprof(k)-frac*( vgprof(k)- vgprof(k-1))
+            IF (nq2>0) q(l,nq1:nq2)=qprof(k,nq1:nq2)                        &
+     &                   -frac*(qprof(k,nq1:nq2)-qprof(k-1,nq1:nq2))
+            omega(l)=   wfls(k)-frac*(   wfls(k)-   wfls(k-1))
+            dq_dyn(l,1)=dqtdtls(k)-frac*(dqtdtls(k)-dqtdtls(k-1))
+            dt_cooling(l)=thlpcar(k)-frac*(thlpcar(k)-thlpcar(k-1))
+          elseif(zlay(l)<height(1)) then ! profils uniformes pour z<height(1)
+            ttt =tttprof(1)
+       if ((forcing_GCSSold .AND. tp_ini_GCSSold) .OR. forcing_fire)then ! pot. temp. in initial profile
+          temp(l) = ttt*(play(l)/pzero)**rkappa
+          teta(l) = ttt
+       else
+          temp(l) = ttt
+          teta(l) = ttt*(pzero/play(l))**rkappa
+       endif
+            q(l,1)  = qtprof(1)
+            u(l)    =  uprof(1)
+            v(l)    =  vprof(1)
+            ug(l)   = ugprof(1)
+            vg(l)   = vgprof(1)
+            omega(l)=   wfls(1)
+            IF (nq2>0) q(l,nq1:nq2)=qprof(1,nq1:nq2)
+            dq_dyn(l,1)  =dqtdtls(1)
+            dt_cooling(l)=thlpcar(1)
+          endif
+        enddo 
+
+        temp(l)=max(min(temp(l),350.),150.)
+        rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
+        if (l .lt. llm) then
+          zlay(l+1) = zlay(l) + (play(l)-play(l+1))/(rg*rho(l))
+        endif
+        omega2(l)=-rho(l)*omega(l)
+        omega(l)= omega(l)*(-rg*rho(l)) !en Pa/s
+        if (l>1) then
+        if(zlay(l-1)>height(kmax)) then
+           omega(l)=0.0
+           omega2(l)=0.0
+        endif   
+        endif
+        if(q(l,1)<0.) q(l,1)=0.0
+        q(l,2)  = 0.0
+      enddo
+
+      endif ! forcing_les .or. forcing_GCSSold .or. forcing_fire
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Forcing for GCSSold:
+!---------------------------------------------------------------------
+      if (forcing_GCSSold) then
+       fich_gcssold_ctl = './forcing.ctl'
+       fich_gcssold_dat = './forcing8.dat'
+       call copie(llm,play,psurf,fich_gcssold_ctl)
+       call get_uvd2(it,timestep,fich_gcssold_ctl,fich_gcssold_dat,         &
+     &               ht_gcssold,hq_gcssold,hw_gcssold,                      &
+     &               hu_gcssold,hv_gcssold,                                 &
+     &               hthturb_gcssold,hqturb_gcssold,Ts_gcssold,             &
+     &               imp_fcg_gcssold,ts_fcg_gcssold,                        &
+     &               Tp_fcg_gcssold,Turb_fcg_gcssold)
+       print *,' get_uvd2 -> hqturb_gcssold ',hqturb_gcssold
+      endif ! forcing_GCSSold
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Forcing for RICO:
+!---------------------------------------------------------------------
+      if (forcing_rico) then
+
+!       call writefield_phy('omega', omega,llm+1)
+      fich_rico = 'rico.txt'
+       call read_rico(fich_rico,nlev_rico,ps_rico,play                      &
+     &             ,ts_rico,t_rico,q_rico,u_rico,v_rico,w_rico              &
+     &             ,dth_rico,dqh_rico)
+        print*, ' on a lu et prepare RICO'
+
+       mxcalc=llm
+       print *, airefi, ' airefi '
+       do l = 1, llm
+       rho(l)  = play(l)/(rd*t_rico(l)*(1.+(rv/rd-1.)*q_rico(l)))
+       temp(l) = t_rico(l)
+       q(l,1) = q_rico(l)
+       q(l,2) = 0.0
+       u(l) = u_rico(l)
+       v(l) = v_rico(l)
+       ug(l)=u_rico(l)
+       vg(l)=v_rico(l)
+       omega(l) = -w_rico(l)*rg
+       omega2(l) = omega(l)/rg*airefi
+       enddo
+      endif
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Forcing from TOGA-COARE experiment (Ciesielski et al. 2002) :
+!---------------------------------------------------------------------
+
+      if (forcing_toga) then
+
+! read TOGA-COARE forcing (native vertical grid, nt_toga timesteps):
+      fich_toga = './d_toga/ifa_toga_coare_v21_dime.txt'
+      CALL read_togacoare(fich_toga,nlev_toga,nt_toga                       &
+     &         ,ts_toga,plev_toga,t_toga,q_toga,u_toga,v_toga,w_toga        &
+     &         ,ht_toga,vt_toga,hq_toga,vq_toga)
+
+       write(*,*) 'Forcing TOGA lu'
+
+! time interpolation for initial conditions:
+      write(*,*) 'AVT 1ere INTERPOLATION: day,day1 = ',day,day1
+      CALL interp_toga_time(daytime,day1,annee_ref                          &
+     &             ,year_ini_toga,day_ju_ini_toga,nt_toga,dt_toga           &
+     &             ,nlev_toga,ts_toga,plev_toga,t_toga,q_toga,u_toga        &
+     &             ,v_toga,w_toga,ht_toga,vt_toga,hq_toga,vq_toga           &
+     &             ,ts_prof,plev_prof,t_prof,q_prof,u_prof,v_prof,w_prof    &
+     &             ,ht_prof,vt_prof,hq_prof,vq_prof)
+
+! vertical interpolation:
+      CALL interp_toga_vertical(play,nlev_toga,plev_prof                    &
+     &         ,t_prof,q_prof,u_prof,v_prof,w_prof                          &
+     &         ,ht_prof,vt_prof,hq_prof,vq_prof                             &
+     &         ,t_mod,q_mod,u_mod,v_mod,w_mod                               &
+     &         ,ht_mod,vt_mod,hq_mod,vq_mod,mxcalc)
+       write(*,*) 'Profil initial forcing TOGA interpole'
+
+! initial and boundary conditions :
+      tsurf = ts_prof
+      write(*,*) 'SST initiale: ',tsurf
+      do l = 1, llm
+       temp(l) = t_mod(l)
+       q(l,1) = q_mod(l)
+       q(l,2) = 0.0
+       u(l) = u_mod(l)
+       v(l) = v_mod(l)
+       omega(l) = w_mod(l)
+       omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+!?       rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
+!?       omega2(l)=-rho(l)*omega(l)
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+       d_t_adv(l) = alpha*omega(l)/rcpd-(ht_mod(l)+vt_mod(l))
+       d_q_adv(l,1) = -(hq_mod(l)+vq_mod(l))
+       d_q_adv(l,2) = 0.0
+      enddo
+
+      endif ! forcing_toga
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Forcing from TWPICE experiment (Shaocheng et al. 2010) :
+!---------------------------------------------------------------------
+
+      if (forcing_twpice) then
+!read TWP-ICE forcings
+     fich_twpice='d_twpi/twp180iopsndgvarana_v2.1_C3.c1.20060117.000000.cdf'
+      call read_twpice(fich_twpice,nlev_twpi,nt_twpi                        &
+     &     ,ts_twpi,plev_twpi,t_twpi,q_twpi,u_twpi,v_twpi,w_twpi            &
+     &     ,ht_twpi,vt_twpi,hq_twpi,vq_twpi)
+
+      write(*,*) 'Forcing TWP-ICE lu'
+!Time interpolation for initial conditions using TOGA interpolation routine
+         write(*,*) 'AVT 1ere INTERPOLATION: day,day1 = ',daytime,day1   
+      CALL interp_toga_time(daytime,day1,annee_ref                          &
+     &          ,year_ini_twpi,day_ju_ini_twpi,nt_twpi,dt_twpi,nlev_twpi    &
+     &             ,ts_twpi,plev_twpi,t_twpi,q_twpi,u_twpi,v_twpi,w_twpi    &
+     &             ,ht_twpi,vt_twpi,hq_twpi,vq_twpi                         &
+     &             ,ts_proftwp,plev_proftwp,t_proftwp,q_proftwp             &
+     &             ,u_proftwp,v_proftwp,w_proftwp                           &
+     &             ,ht_proftwp,vt_proftwp,hq_proftwp,vq_proftwp)
+
+! vertical interpolation using TOGA interpolation routine:
+!      write(*,*)'avant interp vert', t_proftwp
+      CALL interp_toga_vertical(play,nlev_twpi,plev_proftwp                 &
+     &         ,t_proftwp,q_proftwp,u_proftwp,v_proftwp,w_proftwp           &
+     &         ,ht_proftwp,vt_proftwp,hq_proftwp,vq_proftwp                 &
+     &         ,t_mod,q_mod,u_mod,v_mod,w_mod                               &
+     &         ,ht_mod,vt_mod,hq_mod,vq_mod,mxcalc)
+!       write(*,*) 'Profil initial forcing TWP-ICE interpole',t_mod
+
+! initial and boundary conditions :
+!      tsurf = ts_proftwp
+      write(*,*) 'SST initiale: ',tsurf
+      do l = 1, llm
+       temp(l) = t_mod(l)
+       q(l,1) = q_mod(l)
+       q(l,2) = 0.0
+       u(l) = u_mod(l)
+       v(l) = v_mod(l)
+       omega(l) = w_mod(l)
+       omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+!on applique le forcage total au premier pas de temps
+!attention: signe different de toga
+       d_t_adv(l) = alpha*omega(l)/rcpd+(ht_mod(l)+vt_mod(l))
+       d_q_adv(l,1) = (hq_mod(l)+vq_mod(l))
+       d_q_adv(l,2) = 0.0
+      enddo     
+       
+      endif !forcing_twpice
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Forcing from AMMA experiment (Couvreux et al. 2010) :
+!---------------------------------------------------------------------
+
+      if (forcing_amma) then
+
+      call read_1D_cases
+
+      write(*,*) 'Forcing AMMA lu'
+
+!champs initiaux:
+      do k=1,nlev_amma
+         th_ammai(k)=th_amma(k)
+         q_ammai(k)=q_amma(k)
+         u_ammai(k)=u_amma(k)
+         v_ammai(k)=v_amma(k)
+         vitw_ammai(k)=vitw_amma(k,12)
+         ht_ammai(k)=ht_amma(k,12)
+         hq_ammai(k)=hq_amma(k,12)
+         vt_ammai(k)=0.
+         vq_ammai(k)=0.
+      enddo   
+      omega(:)=0.      
+      omega2(:)=0.
+      rho(:)=0.
+! vertical interpolation using TOGA interpolation routine:
+!      write(*,*)'avant interp vert', t_proftwp
+      CALL interp_toga_vertical(play,nlev_amma,plev_amma                    &
+     &         ,th_ammai,q_ammai,u_ammai,v_ammai,vitw_ammai                 &
+     &         ,ht_ammai,vt_ammai,hq_ammai,vq_ammai                         &
+     &         ,t_mod,q_mod,u_mod,v_mod,w_mod                               &
+     &         ,ht_mod,vt_mod,hq_mod,vq_mod,mxcalc)
+!       write(*,*) 'Profil initial forcing TWP-ICE interpole',t_mod
+
+! initial and boundary conditions :
+!      tsurf = ts_proftwp
+      write(*,*) 'SST initiale mxcalc: ',tsurf,mxcalc
+      do l = 1, llm
+! Ligne du dessous ?? decommenter si on lit theta au lieu de temp
+!      temp(l) = t_mod(l)*(play(l)/pzero)**rkappa 
+       temp(l) = t_mod(l) 
+       q(l,1) = q_mod(l)
+       q(l,2) = 0.0
+!      print *,'read_forc: l,temp,q=',l,temp(l),q(l,1)
+       u(l) = u_mod(l)
+       v(l) = v_mod(l)
+       rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
+       omega(l) = w_mod(l)*(-rg*rho(l))
+       omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+!on applique le forcage total au premier pas de temps
+!attention: signe different de toga
+       d_t_adv(l) = alpha*omega(l)/rcpd+ht_mod(l)
+!forcage en th
+!       d_t_adv(l) = ht_mod(l)
+       d_q_adv(l,1) = hq_mod(l)
+       d_q_adv(l,2) = 0.0
+       dt_cooling(l)=0.
+      enddo     
+       write(*,*) 'Prof initeforcing AMMA interpole temp39',temp(39)
+      
+
+!     ok_flux_surf=.false.
+      fsens=-1.*sens_amma(12)
+      flat=-1.*lat_amma(12)
+       
+      endif !forcing_amma
+
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Forcing from DICE experiment (see file DICE_protocol_vn2-3.pdf)
+!---------------------------------------------------------------------
+
+      if (forcing_dice) then
+!read DICE forcings
+      fich_dice='dice_driver.nc'
+      call read_dice(fich_dice,nlev_dice,nt_dice                    &
+     &     ,zz_dice,plev_dice,t_dice,qv_dice,u_dice,v_dice,o3_dice &
+     &     ,shf_dice,lhf_dice,lwup_dice,swup_dice,tg_dice,ustar_dice& 
+     &     ,psurf_dice,ug_dice,vg_dice,ht_dice,hq_dice              &
+     &     ,hu_dice,hv_dice,w_dice,omega_dice)
+
+      write(*,*) 'Forcing DICE lu'
+
+!champs initiaux:
+      do k=1,nlev_dice
+         t_dicei(k)=t_dice(k)
+         qv_dicei(k)=qv_dice(k)
+         u_dicei(k)=u_dice(k)
+         v_dicei(k)=v_dice(k)
+         o3_dicei(k)=o3_dice(k)
+         ht_dicei(k)=ht_dice(k,1)
+         hq_dicei(k)=hq_dice(k,1)
+         hu_dicei(k)=hu_dice(k,1)
+         hv_dicei(k)=hv_dice(k,1)
+         w_dicei(k)=w_dice(k,1)
+         omega_dicei(k)=omega_dice(k,1)
+      enddo   
+      omega(:)=0.      
+      omega2(:)=0.
+      rho(:)=0.
+! vertical interpolation using TOGA interpolation routine:
+!      write(*,*)'avant interp vert', t_proftwp
+!
+!     CALL interp_dice_time(daytime,day1,annee_ref
+!    i             ,year_ini_dice,day_ju_ini_dice,nt_dice,dt_dice
+!    i             ,nlev_dice,shf_dice,lhf_dice,lwup_dice,swup_dice
+!    i             ,tg_dice,ustar_dice,psurf_dice,ug_dice,vg_dice
+!    i             ,ht_dice,hq_dice,hu_dice,hv_dice,w_dice,omega_dice
+!    o             ,shf_prof,lhf_prof,lwup_prof,swup_prof,tg_prof
+!    o             ,ustar_prof,psurf_prof,ug_profd,vg_profd
+!    o             ,ht_profd,hq_profd,hu_profd,hv_profd,w_profd
+!    o             ,omega_profd)
+
+      CALL interp_dice_vertical(play,nlev_dice,nt_dice,plev_dice       &
+     &         ,t_dicei,qv_dicei,u_dicei,v_dicei,o3_dicei             &
+     &         ,ht_dicei,hq_dicei,hu_dicei,hv_dicei,w_dicei,omega_dicei&
+     &         ,t_mod,qv_mod,u_mod,v_mod,o3_mod                       &
+     &         ,ht_mod,hq_mod,hu_mod,hv_mod,w_mod,omega_mod,mxcalc)
+
+! Pour tester les advections horizontales de T et Q, on met w_mod et omega_mod ?? zero (MPL 20131108)
+!     w_mod(:,:)=0.
+!     omega_mod(:,:)=0.
+
+!       write(*,*) 'Profil initial forcing DICE interpole',t_mod
+! Les forcages DICE sont donnes /jour et non /seconde !
+      ht_mod(:)=ht_mod(:)/86400.
+      hq_mod(:)=hq_mod(:)/86400.
+      hu_mod(:)=hu_mod(:)/86400.
+      hv_mod(:)=hv_mod(:)/86400.
+
+! initial and boundary conditions :
+      write(*,*) 'SST initiale mxcalc: ',tsurf,mxcalc
+      do l = 1, llm
+! Ligne du dessous ?? decommenter si on lit theta au lieu de temp
+!      temp(l) = th_mod(l)*(play(l)/pzero)**rkappa 
+       temp(l) = t_mod(l) 
+       q(l,1) = qv_mod(l)
+       q(l,2) = 0.0
+!      print *,'read_forc: l,temp,q=',l,temp(l),q(l,1)
+       u(l) = u_mod(l)
+       v(l) = v_mod(l)
+       ug(l)=ug_dice(1)
+       vg(l)=vg_dice(1)
+       rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
+!      omega(l) = w_mod(l)*(-rg*rho(l))
+       omega(l) = omega_mod(l)
+       omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+!on applique le forcage total au premier pas de temps
+!attention: signe different de toga
+       d_t_adv(l) = alpha*omega(l)/rcpd+ht_mod(l)
+!forcage en th
+!       d_t_adv(l) = ht_mod(l)
+       d_q_adv(l,1) = hq_mod(l)
+       d_q_adv(l,2) = 0.0
+       dt_cooling(l)=0.
+      enddo     
+       write(*,*) 'Profil initial forcing DICE interpole temp39',temp(39)
+      
+
+!     ok_flux_surf=.false.
+      fsens=-1.*shf_dice(1)
+      flat=-1.*lhf_dice(1)
+! Le cas Dice doit etre force avec ustar mais on peut simplifier en forcant par 
+! le coefficient de trainee en surface cd**2=ustar*vent(k=1)
+! On commence ici a stocker ustar dans cdrag puis on terminera le calcul dans pbl_surface
+! MPL 05082013
+      ust=ustar_dice(1)
+      tg=tg_dice(1)
+      print *,'ust= ',ust
+      IF (tsurf .LE. 0.) THEN
+       tsurf= tg_dice(1)
+      ENDIF
+      psurf= psurf_dice(1)
+      solsw_in = (1.-albedo)/albedo*swup_dice(1)
+      sollw_in = (0.7*RSIGMA*temp(1)**4)-lwup_dice(1)
+      PRINT *,'1D_READ_FORC : solsw, sollw',solsw_in,sollw_in
+      endif !forcing_dice
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Forcing from GABLS4 experiment
+!---------------------------------------------------------------------
+
+!!!! Si la temperature de surface n'est pas impos??e:
+  
+      if (forcing_gabls4) then
+!read GABLS4 forcings
+      
+      fich_gabls4='gabls4_driver.nc'
+      
+       	
+      call read_gabls4(fich_gabls4,nlev_gabls4,nt_gabls4,nsol_gabls4,zz_gabls4,depth_sn_gabls4,ug_gabls4,vg_gabls4 &
+     & ,plev_gabls4,th_gabls4,t_gabls4,qv_gabls4,u_gabls4,v_gabls4,ht_gabls4,hq_gabls4,tg_gabls4,tsnow_gabls4,snow_dens_gabls4)
+
+      write(*,*) 'Forcing GABLS4 lu'
+
+!champs initiaux:
+      do k=1,nlev_gabls4
+         t_gabi(k)=t_gabls4(k)
+         qv_gabi(k)=qv_gabls4(k)
+         u_gabi(k)=u_gabls4(k)
+         v_gabi(k)=v_gabls4(k)
+         poub(k)=0.
+         ht_gabi(k)=ht_gabls4(k,1)
+         hq_gabi(k)=hq_gabls4(k,1)
+         ug_gabi(k)=ug_gabls4(k,1)
+         vg_gabi(k)=vg_gabls4(k,1)
+      enddo 
+  
+      omega(:)=0.      
+      omega2(:)=0.
+      rho(:)=0.
+! vertical interpolation using TOGA interpolation routine:
+!      write(*,*)'avant interp vert', t_proftwp
+!
+!     CALL interp_dice_time(daytime,day1,annee_ref
+!    i             ,year_ini_dice,day_ju_ini_dice,nt_dice,dt_dice
+!    i             ,nlev_dice,shf_dice,lhf_dice,lwup_dice,swup_dice
+!    i             ,tg_dice,ustar_dice,psurf_dice,ug_dice,vg_dice
+!    i             ,ht_dice,hq_dice,hu_dice,hv_dice,w_dice,omega_dice
+!    o             ,shf_prof,lhf_prof,lwup_prof,swup_prof,tg_prof
+!    o             ,ustar_prof,psurf_prof,ug_profd,vg_profd
+!    o             ,ht_profd,hq_profd,hu_profd,hv_profd,w_profd
+!    o             ,omega_profd)
+
+      CALL interp_dice_vertical(play,nlev_gabls4,nt_gabls4,plev_gabls4       &
+     &         ,t_gabi,qv_gabi,u_gabi,v_gabi,poub                  &
+     &         ,ht_gabi,hq_gabi,ug_gabi,vg_gabi,poub,poub          &
+     &         ,t_mod,qv_mod,u_mod,v_mod,o3_mod                    &
+     &         ,ht_mod,hq_mod,ug_mod,vg_mod,w_mod,omega_mod,mxcalc)
+
+! Les forcages GABLS4 ont l air d etre en K/S quoiqu en dise le fichier gabls4_driver.nc !? MPL 20141024
+!     ht_mod(:)=ht_mod(:)/86400.
+!     hq_mod(:)=hq_mod(:)/86400.
+
+! initial and boundary conditions :
+      write(*,*) 'SST initiale mxcalc: ',tsurf,mxcalc
+      do l = 1, llm
+! Ligne du dessous ?? decommenter si on lit theta au lieu de temp
+!      temp(l) = th_mod(l)*(play(l)/pzero)**rkappa 
+       temp(l) = t_mod(l) 
+       q(l,1) = qv_mod(l)
+       q(l,2) = 0.0
+!      print *,'read_forc: l,temp,q=',l,temp(l),q(l,1)
+       u(l) = u_mod(l)
+       v(l) = v_mod(l)
+       ug(l)=ug_mod(l)
+       vg(l)=vg_mod(l)
+       
+!
+!	tg=tsurf
+!       
+
+       print *,'***** tsurf=',tsurf
+       rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
+!      omega(l) = w_mod(l)*(-rg*rho(l))
+       omega(l) = omega_mod(l)
+       omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+       
+    
+
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+!on applique le forcage total au premier pas de temps
+!attention: signe different de toga
+!      d_t_adv(l) = alpha*omega(l)/rcpd+ht_mod(l)
+!forcage en th
+       d_t_adv(l) = ht_mod(l)
+       d_q_adv(l,1) = hq_mod(l)
+       d_q_adv(l,2) = 0.0
+       dt_cooling(l)=0.
+      enddo     
+
+!--------------- Residus forcages du cas Dice (a supprimer) MPL 20141024---------------
+! Le cas Dice doit etre force avec ustar mais on peut simplifier en forcant par 
+! le coefficient de trainee en surface cd**2=ustar*vent(k=1)
+! On commence ici a stocker ustar dans cdrag puis on terminera le calcul dans pbl_surface
+! MPL 05082013
+!     ust=ustar_dice(1)
+!     tg=tg_dice(1)
+!     print *,'ust= ',ust
+!     IF (tsurf .LE. 0.) THEN
+!      tsurf= tg_dice(1)
+!     ENDIF
+!     psurf= psurf_dice(1)
+!     solsw_in = (1.-albedo)/albedo*swup_dice(1)
+!     sollw_in = (0.7*RSIGMA*temp(1)**4)-lwup_dice(1)
+!     PRINT *,'1D_READ_FORC : solsw, sollw',solsw_in,sollw_in
+!--------------------------------------------------------------------------------------
+      endif !forcing_gabls4
+
+
+
+! Forcing from Arm_Cu case                   
+! For this case, ifa_armcu.txt contains sensible, latent heat fluxes
+! large scale advective forcing,radiative forcing 
+! and advective tendency of theta and qt to be applied 
+!---------------------------------------------------------------------
+
+      if (forcing_armcu) then
+! read armcu forcing :
+       write(*,*) 'Avant lecture Forcing Arm_Cu'
+      fich_armcu = './ifa_armcu.txt'
+      CALL read_armcu(fich_armcu,nlev_armcu,nt_armcu,                       &
+     & sens_armcu,flat_armcu,adv_theta_armcu,                               &
+     & rad_theta_armcu,adv_qt_armcu)
+       write(*,*) 'Forcing Arm_Cu lu'
+
+!----------------------------------------------------------------------
+! Read profiles from file: prof.inp.19 or prof.inp.40 
+! For this case, profiles are given for two vertical resolution
+! 19 or 40 levels
+!
+! Comment from: http://www.knmi.nl/samenw/eurocs/ARM/profiles.html
+! Note that the initial profiles contain no liquid water! 
+! (so potential temperature can be interpreted as liquid water 
+! potential temperature and water vapor as total water)
+! profiles are given at full levels
+!----------------------------------------------------------------------
+
+      call readprofile_armcu(nlev_max,kmax,height,play_mod,u_mod,           &
+     &           v_mod,theta_mod,t_mod,qv_mod,rv_mod,ap,bp)
+
+! time interpolation for initial conditions:
+      write(*,*) 'AVT 1ere INTERPOLATION: day,day1 = ',day,day1
+
+      print *,'Avant interp_armcu_time'
+      print *,'daytime=',daytime
+      print *,'day1=',day1
+      print *,'annee_ref=',annee_ref
+      print *,'year_ini_armcu=',year_ini_armcu
+      print *,'day_ju_ini_armcu=',day_ju_ini_armcu
+      print *,'nt_armcu=',nt_armcu
+      print *,'dt_armcu=',dt_armcu
+      print *,'nlev_armcu=',nlev_armcu
+      CALL interp_armcu_time(daytime,day1,annee_ref                         &
+     &            ,year_ini_armcu,day_ju_ini_armcu,nt_armcu,dt_armcu        &
+     &            ,nlev_armcu,sens_armcu,flat_armcu,adv_theta_armcu         &
+     &            ,rad_theta_armcu,adv_qt_armcu,sens_prof,flat_prof         &
+     &            ,adv_theta_prof,rad_theta_prof,adv_qt_prof)
+       write(*,*) 'Forcages interpoles dans temps'
+
+! No vertical interpolation if nlev imposed to 19 or 40
+! The vertical grid stops at 4000m # 600hPa
+      mxcalc=llm
+
+! initial and boundary conditions :
+!     tsurf = ts_prof
+! tsurf read in lmdz1d.def
+      write(*,*) 'Tsurf initiale: ',tsurf
+      do l = 1, llm
+       play(l)=play_mod(l)*100.
+       presnivs(l)=play(l)
+       zlay(l)=height(l)
+       temp(l) = t_mod(l)
+       teta(l)=theta_mod(l)
+       q(l,1) = qv_mod(l)/1000.
+! No liquid water in the initial profil
+       q(l,2) = 0.
+       u(l) = u_mod(l)
+       ug(l)= u_mod(l)
+       v(l) = v_mod(l)
+       vg(l)= v_mod(l)
+! Advective forcings are given in K or g/kg ... per HOUR
+!      IF(height(l).LT.1000) THEN
+!        d_t_adv(l) = (adv_theta_prof + rad_theta_prof)/3600.
+!        d_q_adv(l,1) = adv_qt_prof/1000./3600.
+!        d_q_adv(l,2) = 0.0
+!      ELSEIF (height(l).GE.1000.AND.height(l).LT.3000) THEN
+!        d_t_adv(l) = (adv_theta_prof + rad_theta_prof)*
+!    :               (1-(height(l)-1000.)/2000.)
+!        d_t_adv(l) = d_t_adv(l)/3600.
+!        d_q_adv(l,1) = adv_qt_prof*(1-(height(l)-1000.)/2000.)
+!        d_q_adv(l,1) = d_q_adv(l,1)/1000./3600.
+!        d_q_adv(l,2) = 0.0
+!      ELSE
+!        d_t_adv(l) = 0.0
+!        d_q_adv(l,1) = 0.0
+!        d_q_adv(l,2) = 0.0
+!      ENDIF
+      enddo
+! plev at half levels is given in proh.inp.19 or proh.inp.40 files
+      plev(1)= ap(llm+1)+bp(llm+1)*psurf
+      do l = 1, llm
+      plev(l+1) = ap(llm-l+1)+bp(llm-l+1)*psurf
+      print *,'Read_forc: l height play plev zlay temp',                    &
+     &   l,height(l),play(l),plev(l),zlay(l),temp(l)
+      enddo
+! For this case, fluxes are imposed
+       fsens=-1*sens_prof
+       flat=-1*flat_prof
+
+      endif ! forcing_armcu
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Forcing from transition case of Irina Sandu                  
+!---------------------------------------------------------------------
+
+      if (forcing_sandu) then
+       write(*,*) 'Avant lecture Forcing SANDU'
+
+! read sanduref forcing :
+      fich_sandu = './ifa_sanduref.txt'
+      CALL read_sandu(fich_sandu,nlev_sandu,nt_sandu,ts_sandu)
+
+       write(*,*) 'Forcing SANDU lu'
+
+!----------------------------------------------------------------------
+! Read profiles from file: prof.inp.001 
+!----------------------------------------------------------------------
+
+      call readprofile_sandu(nlev_max,kmax,height,plev_profs,t_profs,       &
+     &           thl_profs,q_profs,u_profs,v_profs,                         &
+     &           w_profs,omega_profs,o3mmr_profs)
+
+! time interpolation for initial conditions:
+      write(*,*) 'AVT 1ere INTERPOLATION: day,day1 = ',day,day1
+! ATTENTION, cet appel ne convient pas pour le cas SANDU !!
+! revoir 1DUTILS.h et les arguments
+
+      print *,'Avant interp_sandu_time'
+      print *,'daytime=',daytime
+      print *,'day1=',day1
+      print *,'annee_ref=',annee_ref
+      print *,'year_ini_sandu=',year_ini_sandu
+      print *,'day_ju_ini_sandu=',day_ju_ini_sandu
+      print *,'nt_sandu=',nt_sandu
+      print *,'dt_sandu=',dt_sandu
+      print *,'nlev_sandu=',nlev_sandu
+      CALL interp_sandu_time(daytime,day1,annee_ref                         &
+     &             ,year_ini_sandu,day_ju_ini_sandu,nt_sandu,dt_sandu       &
+     &             ,nlev_sandu                                              &
+     &             ,ts_sandu,ts_prof)
+
+! vertical interpolation:
+      print *,'Avant interp_vertical: nlev_sandu=',nlev_sandu
+      CALL interp_sandu_vertical(play,nlev_sandu,plev_profs                 &
+     &         ,t_profs,thl_profs,q_profs,u_profs,v_profs,w_profs           &
+     &         ,omega_profs,o3mmr_profs                                     &
+     &         ,t_mod,thl_mod,q_mod,u_mod,v_mod,w_mod                       &
+     &         ,omega_mod,o3mmr_mod,mxcalc)
+       write(*,*) 'Profil initial forcing SANDU interpole'
+
+! initial and boundary conditions :
+      tsurf = ts_prof
+      write(*,*) 'SST initiale: ',tsurf
+      do l = 1, llm
+       temp(l) = t_mod(l)
+       tetal(l)=thl_mod(l)
+       q(l,1) = q_mod(l)
+       q(l,2) = 0.0
+       u(l) = u_mod(l)
+       v(l) = v_mod(l)
+       w(l) = w_mod(l)
+       omega(l) = omega_mod(l)
+       omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+!?       rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
+!?       omega2(l)=-rho(l)*omega(l)
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+!      d_t_adv(l) = alpha*omega(l)/rcpd+vt_mod(l)
+!      d_q_adv(l,1) = vq_mod(l)
+       d_t_adv(l) = alpha*omega(l)/rcpd
+       d_q_adv(l,1) = 0.0
+       d_q_adv(l,2) = 0.0
+      enddo
+
+      endif ! forcing_sandu
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Forcing from Astex case
+!---------------------------------------------------------------------
+
+      if (forcing_astex) then
+       write(*,*) 'Avant lecture Forcing Astex'
+
+! read astex forcing :
+      fich_astex = './ifa_astex.txt'
+      CALL read_astex(fich_astex,nlev_astex,nt_astex,div_astex,ts_astex,    &
+     &  ug_astex,vg_astex,ufa_astex,vfa_astex)
+
+       write(*,*) 'Forcing Astex lu'
+
+!----------------------------------------------------------------------
+! Read profiles from file: prof.inp.001
+!----------------------------------------------------------------------
+
+      call readprofile_astex(nlev_max,kmax,height,plev_profa,t_profa,       &
+     &           thl_profa,qv_profa,ql_profa,qt_profa,u_profa,v_profa,      &
+     &           w_profa,tke_profa,o3mmr_profa)
+
+! time interpolation for initial conditions:
+      write(*,*) 'AVT 1ere INTERPOLATION: day,day1 = ',day,day1
+! ATTENTION, cet appel ne convient pas pour le cas SANDU !!
+! revoir 1DUTILS.h et les arguments
+
+      print *,'Avant interp_astex_time'
+      print *,'daytime=',daytime
+      print *,'day1=',day1
+      print *,'annee_ref=',annee_ref
+      print *,'year_ini_astex=',year_ini_astex
+      print *,'day_ju_ini_astex=',day_ju_ini_astex
+      print *,'nt_astex=',nt_astex
+      print *,'dt_astex=',dt_astex
+      print *,'nlev_astex=',nlev_astex
+      CALL interp_astex_time(daytime,day1,annee_ref                         &
+     &             ,year_ini_astex,day_ju_ini_astex,nt_astex,dt_astex       &
+     &             ,nlev_astex,div_astex,ts_astex,ug_astex,vg_astex         &
+     &             ,ufa_astex,vfa_astex,div_prof,ts_prof,ug_prof,vg_prof    &
+     &             ,ufa_prof,vfa_prof)
+
+! vertical interpolation:
+      print *,'Avant interp_vertical: nlev_astex=',nlev_astex
+      CALL interp_astex_vertical(play,nlev_astex,plev_profa                 &
+     &         ,t_profa,thl_profa,qv_profa,ql_profa,qt_profa                &
+     &         ,u_profa,v_profa,w_profa,tke_profa,o3mmr_profa               &
+     &         ,t_mod,thl_mod,qv_mod,ql_mod,qt_mod,u_mod,v_mod,w_mod        &
+     &         ,tke_mod,o3mmr_mod,mxcalc)
+       write(*,*) 'Profil initial forcing Astex interpole'
+
+! initial and boundary conditions :
+      tsurf = ts_prof
+      write(*,*) 'SST initiale: ',tsurf
+      do l = 1, llm
+       temp(l) = t_mod(l)
+       tetal(l)=thl_mod(l)
+       q(l,1) = qv_mod(l)
+       q(l,2) = ql_mod(l)
+       u(l) = u_mod(l)
+       v(l) = v_mod(l)
+       w(l) = w_mod(l)
+       omega(l) = w_mod(l)
+!      omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+!      rho(l)  = play(l)/(rd*temp(l)*(1.+(rv/rd-1.)*q(l,1)))
+!      omega2(l)=-rho(l)*omega(l)
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+!      d_t_adv(l) = alpha*omega(l)/rcpd+vt_mod(l)
+!      d_q_adv(l,1) = vq_mod(l)
+       d_t_adv(l) = alpha*omega(l)/rcpd
+       d_q_adv(l,1) = 0.0
+       d_q_adv(l,2) = 0.0
+      enddo
+
+      endif ! forcing_astex
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Forcing from standard case :
+!---------------------------------------------------------------------
+
+      if (forcing_case) then
+
+         write(*,*),'avant call read_1D_cas'
+         call read_1D_cas
+         write(*,*) 'Forcing read'
+
+!Time interpolation for initial conditions using TOGA interpolation routine
+         write(*,*) 'AVT 1ere INTERPOLATION: day,day1 = ',daytime,day1   
+      CALL interp_case_time(day,day1,annee_ref                                                              &
+!    &         ,year_ini_cas,day_ju_ini_cas,nt_cas,pdt_cas,nlev_cas                                         &
+     &         ,nt_cas,nlev_cas                                                                             &
+     &         ,ts_cas,plev_cas,t_cas,q_cas,u_cas,v_cas                                                     &
+     &         ,ug_cas,vg_cas,vitw_cas,du_cas,hu_cas,vu_cas                                                 &
+     &         ,dv_cas,hv_cas,vv_cas,dt_cas,ht_cas,vt_cas,dtrad_cas                                         &
+     &         ,dq_cas,hq_cas,vq_cas,lat_cas,sens_cas,ustar_cas                                             &
+     &         ,uw_cas,vw_cas,q1_cas,q2_cas                                                                 &
+     &         ,ts_prof_cas,plev_prof_cas,t_prof_cas,q_prof_cas,u_prof_cas,v_prof_cas                       &
+     &         ,ug_prof_cas,vg_prof_cas,vitw_prof_cas,du_prof_cas,hu_prof_cas,vu_prof_cas                   &
+     &         ,dv_prof_cas,hv_prof_cas,vv_prof_cas,dt_prof_cas,ht_prof_cas,vt_prof_cas,dtrad_prof_cas      &
+     &         ,dq_prof_cas,hq_prof_cas,vq_prof_cas,lat_prof_cas,sens_prof_cas,ustar_prof_cas               &
+     &         ,uw_prof_cas,vw_prof_cas,q1_prof_cas,q2_prof_cas)
+
+! vertical interpolation using TOGA interpolation routine:
+!      write(*,*)'avant interp vert', t_prof
+      CALL interp_case_vertical(play,nlev_cas,plev_prof_cas            &
+     &         ,t_prof_cas,q_prof_cas,u_prof_cas,v_prof_cas,ug_prof_cas,vg_prof_cas,vitw_prof_cas    &
+     &         ,du_prof_cas,hu_prof_cas,vu_prof_cas,dv_prof_cas,hv_prof_cas,vv_prof_cas           &
+     &         ,dt_prof_cas,ht_prof_cas,vt_prof_cas,dtrad_prof_cas,dq_prof_cas,hq_prof_cas,vq_prof_cas           &
+     &         ,t_mod_cas,q_mod_cas,u_mod_cas,v_mod_cas,ug_mod_cas,vg_mod_cas,w_mod_cas           &
+     &         ,du_mod_cas,hu_mod_cas,vu_mod_cas,dv_mod_cas,hv_mod_cas,vv_mod_cas               &
+     &         ,dt_mod_cas,ht_mod_cas,vt_mod_cas,dtrad_mod_cas,dq_mod_cas,hq_mod_cas,vq_mod_cas,mxcalc)
+!       write(*,*) 'Profil initial forcing case interpole',t_mod
+
+! initial and boundary conditions :
+!      tsurf = ts_prof_cas
+      ts_cur = ts_prof_cas 
+      psurf=plev_prof_cas(1)
+      write(*,*) 'SST initiale: ',tsurf
+      do l = 1, llm
+       temp(l) = t_mod_cas(l)
+       q(l,1) = q_mod_cas(l)
+       q(l,2) = 0.0
+       u(l) = u_mod_cas(l)
+       v(l) = v_mod_cas(l)
+       omega(l) = w_mod_cas(l)
+       omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+!on applique le forcage total au premier pas de temps
+!attention: signe different de toga
+       d_t_adv(l) = alpha*omega(l)/rcpd+(ht_mod_cas(l)+vt_mod_cas(l))
+       d_q_adv(l,1) = (hq_mod_cas(l)+vq_mod_cas(l))
+       d_q_adv(l,2) = 0.0
+       d_u_adv(l) = (hu_mod_cas(l)+vu_mod_cas(l))
+! correction bug d_u -> d_v (MM+MPL 20170310)
+       d_v_adv(l) = (hv_mod_cas(l)+vv_mod_cas(l))
+      enddo     
+
+! In case fluxes are imposed
+       IF (ok_flux_surf) THEN
+       fsens=sens_prof_cas
+       flat=lat_prof_cas
+       ENDIF
+       IF (ok_prescr_ust) THEN
+       ust=ustar_prof_cas
+       print *,'ust=',ust
+       ENDIF
+
+      endif !forcing_case
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Forcing from standard case :
+!---------------------------------------------------------------------
+
+      if (forcing_case2) then
+
+         write(*,*),'avant call read2_1D_cas'
+         call read2_1D_cas
+         write(*,*) 'Forcing read'
+
+!Time interpolation for initial conditions using interpolation routine
+         write(*,*) 'AVT 1ere INTERPOLATION: day,day1 = ',daytime,day1   
+        CALL interp2_case_time(daytime,day1,annee_ref                                       &
+!    &       ,year_ini_cas,day_ju_ini_cas,nt_cas,pdt_cas,nlev_cas                           &
+     &       ,nt_cas,nlev_cas                                                               &
+     &       ,ts_cas,ps_cas,plev_cas,t_cas,th_cas,thv_cas,thl_cas,qv_cas,ql_cas,qi_cas      &
+     &       ,u_cas,v_cas,ug_cas,vg_cas,vitw_cas,omega_cas,du_cas,hu_cas,vu_cas             &
+     &       ,dv_cas,hv_cas,vv_cas,dt_cas,ht_cas,vt_cas,dtrad_cas                           &
+     &       ,dq_cas,hq_cas,vq_cas,dth_cas,hth_cas,vth_cas,lat_cas,sens_cas,ustar_cas       &
+     &       ,uw_cas,vw_cas,q1_cas,q2_cas,tke_cas                                           &
+!
+     &       ,ts_prof_cas,plev_prof_cas,t_prof_cas,theta_prof_cas,thv_prof_cas  &
+     &       ,thl_prof_cas,qv_prof_cas,ql_prof_cas,qi_prof_cas                              &
+     &       ,u_prof_cas,v_prof_cas,ug_prof_cas,vg_prof_cas,vitw_prof_cas,omega_prof_cas    &
+     &       ,du_prof_cas,hu_prof_cas,vu_prof_cas                                           &
+     &       ,dv_prof_cas,hv_prof_cas,vv_prof_cas,dt_prof_cas,ht_prof_cas,vt_prof_cas       &
+     &       ,dtrad_prof_cas,dq_prof_cas,hq_prof_cas,vq_prof_cas                            &
+     &       ,dth_prof_cas,hth_prof_cas,vth_prof_cas,lat_prof_cas                           &
+     &       ,sens_prof_cas,ustar_prof_cas,uw_prof_cas,vw_prof_cas,q1_prof_cas,q2_prof_cas,tke_prof_cas)
+
+      do l = 1, nlev_cas
+      print *,'apres 1ere interp: plev_cas, plev_prof_cas=',l,plev_cas(l,1),plev_prof_cas(l)
+      enddo
+
+! vertical interpolation using interpolation routine:
+!      write(*,*)'avant interp vert', t_prof
+      CALL interp2_case_vertical(play,nlev_cas,plev_prof_cas                                              &
+     &         ,t_prof_cas,theta_prof_cas,thv_prof_cas,thl_prof_cas                                          &
+     &         ,qv_prof_cas,ql_prof_cas,qi_prof_cas,u_prof_cas,v_prof_cas                                 &
+     &         ,ug_prof_cas,vg_prof_cas,vitw_prof_cas,omega_prof_cas                                      &
+     &         ,du_prof_cas,hu_prof_cas,vu_prof_cas,dv_prof_cas,hv_prof_cas,vv_prof_cas                   &
+     &         ,dt_prof_cas,ht_prof_cas,vt_prof_cas,dtrad_prof_cas,dq_prof_cas,hq_prof_cas,vq_prof_cas    &
+     &         ,dth_prof_cas,hth_prof_cas,vth_prof_cas                                                    &
+!
+     &         ,t_mod_cas,theta_mod_cas,thv_mod_cas,thl_mod_cas,qv_mod_cas,ql_mod_cas,qi_mod_cas          &
+     &         ,u_mod_cas,v_mod_cas,ug_mod_cas,vg_mod_cas,w_mod_cas,omega_mod_cas                         &
+     &         ,du_mod_cas,hu_mod_cas,vu_mod_cas,dv_mod_cas,hv_mod_cas,vv_mod_cas                         &
+     &         ,dt_mod_cas,ht_mod_cas,vt_mod_cas,dtrad_mod_cas,dq_mod_cas,hq_mod_cas,vq_mod_cas           &
+     &         ,dth_mod_cas,hth_mod_cas,vth_mod_cas,mxcalc)
+
+!       write(*,*) 'Profil initial forcing case interpole',t_mod
+
+! initial and boundary conditions :
+!      tsurf = ts_prof_cas
+      ts_cur = ts_prof_cas 
+      psurf=plev_prof_cas(1)
+      write(*,*) 'SST initiale: ',tsurf
+      do l = 1, llm
+       temp(l) = t_mod_cas(l)
+       q(l,1) = qv_mod_cas(l)
+       q(l,2) = ql_mod_cas(l)
+       u(l) = u_mod_cas(l)
+       ug(l)= ug_mod_cas(l)
+       v(l) = v_mod_cas(l)
+       vg(l)= vg_mod_cas(l)
+! Modif w_mod_cas -> omega_mod_cas (MM+MPL 20170309)
+       omega(l) = omega_mod_cas(l)
+       omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+!on applique le forcage total au premier pas de temps
+!attention: signe different de toga
+       d_t_adv(l) = alpha*omega(l)/rcpd+(ht_mod_cas(l)+vt_mod_cas(l))
+       d_t_adv(l) = alpha*omega(l)/rcpd+(ht_mod_cas(l)+vt_mod_cas(l))
+!      d_q_adv(l,1) = (hq_mod_cas(l)+vq_mod_cas(l))
+       d_q_adv(l,1) = dq_mod_cas(l)
+       d_q_adv(l,2) = 0.0
+!      d_u_adv(l) = (hu_mod_cas(l)+vu_mod_cas(l))
+       d_u_adv(l) = du_mod_cas(l)
+!      d_v_adv(l) = (hv_mod_cas(l)+vv_mod_cas(l))
+! correction bug d_u -> d_v (MM+MPL 20170310)
+       d_v_adv(l) = dv_mod_cas(l)
+      enddo     
+
+! Faut-il multiplier par -1 ? (MPL 20160713)
+       IF (ok_flux_surf) THEN
+       fsens=-1.*sens_prof_cas
+       flat=-1.*lat_prof_cas
+       ENDIF
+!
+       IF (ok_prescr_ust) THEN
+       ust=ustar_prof_cas
+       print *,'ust=',ust
+       ENDIF
+
+      endif !forcing_case2
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!---------------------------------------------------------------------
+! Forcing from standard case :
+!---------------------------------------------------------------------
+
+      if (forcing_SCM) then
+
+         write(*,*),'avant call read_SCM'
+         call read_SCM_cas
+         write(*,*) 'Forcing read' 
+
+!Time interpolation for initial conditions using interpolation routine
+         write(*,*) 'AVT 1ere INTERPOLATION: day,day1 = ',daytime,day1   
+        CALL interp2_case_time(daytime,day1,annee_ref                                       &
+!    &       ,year_ini_cas,day_ju_ini_cas,nt_cas,pdt_cas,nlev_cas                           &
+     &       ,nt_cas,nlev_cas                                                               &
+     &       ,ts_cas,ps_cas,plev_cas,t_cas,th_cas,thv_cas,thl_cas,qv_cas,ql_cas,qi_cas      &
+     &       ,u_cas,v_cas,ug_cas,vg_cas,vitw_cas,omega_cas,du_cas,hu_cas,vu_cas             &
+     &       ,dv_cas,hv_cas,vv_cas,dt_cas,ht_cas,vt_cas,dtrad_cas                           &
+     &       ,dq_cas,hq_cas,vq_cas,dth_cas,hth_cas,vth_cas,lat_cas,sens_cas,ustar_cas       &
+     &       ,uw_cas,vw_cas,q1_cas,q2_cas,tke_cas                                           &
+!
+     &       ,ts_prof_cas,plev_prof_cas,t_prof_cas,theta_prof_cas,thv_prof_cas  &
+     &       ,thl_prof_cas,qv_prof_cas,ql_prof_cas,qi_prof_cas                              &
+     &       ,u_prof_cas,v_prof_cas,ug_prof_cas,vg_prof_cas,vitw_prof_cas,omega_prof_cas    &
+     &       ,du_prof_cas,hu_prof_cas,vu_prof_cas                                           &
+     &       ,dv_prof_cas,hv_prof_cas,vv_prof_cas,dt_prof_cas,ht_prof_cas,vt_prof_cas       &
+     &       ,dtrad_prof_cas,dq_prof_cas,hq_prof_cas,vq_prof_cas                            &
+     &       ,dth_prof_cas,hth_prof_cas,vth_prof_cas,lat_prof_cas                           &
+     &       ,sens_prof_cas,ustar_prof_cas,uw_prof_cas,vw_prof_cas,q1_prof_cas,q2_prof_cas,tke_prof_cas)
+
+      do l = 1, nlev_cas
+      print *,'apres 1ere interp: plev_cas, plev_prof_cas=',l,plev_cas(l,1),plev_prof_cas(l)
+      enddo
+
+! vertical interpolation using interpolation routine:
+!      write(*,*)'avant interp vert', t_prof
+      CALL interp2_case_vertical(play,nlev_cas,plev_prof_cas                                              &
+     &         ,t_prof_cas,theta_prof_cas,thv_prof_cas,thl_prof_cas                                          &
+     &         ,qv_prof_cas,ql_prof_cas,qi_prof_cas,u_prof_cas,v_prof_cas                                 &
+     &         ,ug_prof_cas,vg_prof_cas,vitw_prof_cas,omega_prof_cas                                      &
+     &         ,du_prof_cas,hu_prof_cas,vu_prof_cas,dv_prof_cas,hv_prof_cas,vv_prof_cas                   &
+     &         ,dt_prof_cas,ht_prof_cas,vt_prof_cas,dtrad_prof_cas,dq_prof_cas,hq_prof_cas,vq_prof_cas    &
+     &         ,dth_prof_cas,hth_prof_cas,vth_prof_cas                                                    &
+!
+     &         ,t_mod_cas,theta_mod_cas,thv_mod_cas,thl_mod_cas,qv_mod_cas,ql_mod_cas,qi_mod_cas          &
+     &         ,u_mod_cas,v_mod_cas,ug_mod_cas,vg_mod_cas,w_mod_cas,omega_mod_cas                         &
+     &         ,du_mod_cas,hu_mod_cas,vu_mod_cas,dv_mod_cas,hv_mod_cas,vv_mod_cas                         &
+     &         ,dt_mod_cas,ht_mod_cas,vt_mod_cas,dtrad_mod_cas,dq_mod_cas,hq_mod_cas,vq_mod_cas           &
+     &         ,dth_mod_cas,hth_mod_cas,vth_mod_cas,mxcalc)
+
+!       write(*,*) 'Profil initial forcing case interpole',t_mod
+
+! initial and boundary conditions :
+!      tsurf = ts_prof_cas
+      ts_cur = ts_prof_cas 
+      psurf=plev_prof_cas(1)
+      write(*,*) 'SST initiale: ',tsurf
+      do l = 1, llm
+       temp(l) = t_mod_cas(l)
+       q(l,1) = qv_mod_cas(l)
+       q(l,2) = ql_mod_cas(l)
+       u(l) = u_mod_cas(l)
+       ug(l)= ug_mod_cas(l)
+       v(l) = v_mod_cas(l)
+       vg(l)= vg_mod_cas(l)
+! Modif w_mod_cas -> omega_mod_cas (MM+MPL 20170309)
+       omega(l) = omega_mod_cas(l)
+       omega2(l)=omega(l)/rg*airefi ! flxmass_w calcule comme ds physiq
+
+       alpha = rd*temp(l)*(1.+(rv/rd-1.)*q(l,1))/play(l)
+!on applique le forcage total au premier pas de temps
+!attention: signe different de toga
+       d_t_adv(l) = alpha*omega(l)/rcpd+(ht_mod_cas(l)+vt_mod_cas(l))
+       d_t_adv(l) = alpha*omega(l)/rcpd+(ht_mod_cas(l)+vt_mod_cas(l))
+!      d_q_adv(l,1) = (hq_mod_cas(l)+vq_mod_cas(l))
+       d_q_adv(l,1) = dq_mod_cas(l)
+       d_q_adv(l,2) = 0.0
+!      d_u_adv(l) = (hu_mod_cas(l)+vu_mod_cas(l))
+       d_u_adv(l) = du_mod_cas(l)
+!      d_v_adv(l) = (hv_mod_cas(l)+vv_mod_cas(l))
+! correction bug d_u -> d_v (MM+MPL 20170310)
+       d_v_adv(l) = dv_mod_cas(l)
+      enddo     
+
+! Faut-il multiplier par -1 ? (MPL 20160713)
+       IF (ok_flux_surf) THEN
+       fsens=-1.*sens_prof_cas
+       flat=-1.*lat_prof_cas
+       ENDIF
+!
+       IF (ok_prescr_ust) THEN
+       ust=ustar_prof_cas
+       print *,'ust=',ust
+       ENDIF
+
+      endif !forcing_SCM
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/old_lmdz1d.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/old_lmdz1d.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/old_lmdz1d.F90	(revision 3605)
@@ -0,0 +1,1341 @@
+!
+! $Id: lmdz1d.F90 3540 2019-06-25 14:50:13Z fairhead $
+!
+
+      SUBROUTINE old_lmdz1d
+
+   USE ioipsl, only: ju2ymds, ymds2ju, ioconf_calendar,getin
+   USE phys_state_var_mod, ONLY : phys_state_var_init, phys_state_var_end, &
+       clwcon, detr_therm, &
+       qsol, fevap, z0m, z0h, agesno, &
+       du_gwd_rando, du_gwd_front, entr_therm, f0, fm_therm, &
+       falb_dir, falb_dif, &
+       ftsol, pbl_tke, pctsrf, radsol, rain_fall, snow_fall, ratqs, &
+       rnebcon, rugoro, sig1, w01, solaire_etat0, sollw, sollwdown, &
+       solsw, t_ancien, q_ancien, u_ancien, v_ancien, wake_cstar, &
+       wake_delta_pbl_TKE, delta_tsurf, wake_fip, wake_pe, &
+       wake_deltaq, wake_deltat, wake_s, wake_dens, &
+       zgam, zmax0, zmea, zpic, zsig, &
+       zstd, zthe, zval, ale_bl, ale_bl_trig, alp_bl, ql_ancien, qs_ancien, &
+       prlw_ancien, prsw_ancien, prw_ancien, &
+       u10m,v10m,ale_wake,ale_bl_stat
+
+  
+   USE dimphy
+   USE surface_data, only : type_ocean,ok_veget
+   USE pbl_surface_mod, only : ftsoil, pbl_surface_init, &
+                                 pbl_surface_final
+   USE fonte_neige_mod, only : fonte_neige_init, fonte_neige_final 
+
+   USE infotrac ! new
+   USE control_mod
+   USE indice_sol_mod
+   USE phyaqua_mod
+!  USE mod_1D_cases_read
+   USE mod_1D_cases_read2
+   USE mod_1D_amma_read
+   USE print_control_mod, ONLY: lunout, prt_level
+   USE iniphysiq_mod, ONLY: iniphysiq
+   USE mod_const_mpi, ONLY: comm_lmdz
+   USE physiq_mod, ONLY: physiq
+   USE comvert_mod, ONLY: presnivs, ap, bp, dpres,nivsig, nivsigs, pa, &
+                          preff, aps, bps, pseudoalt, scaleheight
+   USE temps_mod, ONLY: annee_ref, calend, day_end, day_ini, day_ref, &
+                        itau_dyn, itau_phy, start_time, year_len
+   USE phys_cal_mod, ONLY : year_len_phys_cal_mod => year_len 
+
+      implicit none
+#include "dimensions.h"
+#include "YOMCST.h"
+!!#include "control.h"
+#include "clesphys.h"
+#include "dimsoil.h"
+!#include "indicesol.h"
+
+#include "compar1d.h"
+#include "flux_arp.h"
+#include "date_cas.h"
+#include "tsoilnudge.h"
+#include "fcg_gcssold.h"
+!!!#include "fbforcing.h"
+#include "compbl.h"
+
+!=====================================================================
+! DECLARATIONS
+!=====================================================================
+
+!---------------------------------------------------------------------
+!  Externals
+!---------------------------------------------------------------------
+      external fq_sat
+      real fq_sat
+
+!---------------------------------------------------------------------
+!  Arguments d' initialisations de la physique (USER DEFINE)
+!---------------------------------------------------------------------
+
+      integer, parameter :: ngrid=1
+      real :: zcufi    = 1.
+      real :: zcvfi    = 1.
+
+!-      real :: nat_surf
+!-      logical :: ok_flux_surf
+!-      real :: fsens
+!-      real :: flat
+!-      real :: tsurf
+!-      real :: rugos
+!-      real :: qsol(1:2)
+!-      real :: qsurf
+!-      real :: psurf
+!-      real :: zsurf
+!-      real :: albedo
+!-
+!-      real :: time     = 0.
+!-      real :: time_ini
+!-      real :: xlat 
+!-      real :: xlon 
+!-      real :: wtsurf 
+!-      real :: wqsurf 
+!-      real :: restart_runoff 
+!-      real :: xagesno 
+!-      real :: qsolinp 
+!-      real :: zpicinp 
+!-
+      real :: fnday 
+      real :: day, daytime 
+      real :: day1
+      real :: heure
+      integer :: jour
+      integer :: mois
+      integer :: an
+ 
+!---------------------------------------------------------------------
+!  Declarations related to forcing and initial profiles 
+!---------------------------------------------------------------------
+
+        integer :: kmax = llm
+        integer llm700,nq1,nq2
+        INTEGER, PARAMETER :: nlev_max=1000, nqmx=1000
+        real timestep, frac
+        real height(nlev_max),tttprof(nlev_max),qtprof(nlev_max)
+        real  uprof(nlev_max),vprof(nlev_max),e12prof(nlev_max)
+        real  ugprof(nlev_max),vgprof(nlev_max),wfls(nlev_max)
+        real  dqtdxls(nlev_max),dqtdyls(nlev_max)
+        real  dqtdtls(nlev_max),thlpcar(nlev_max)
+        real  qprof(nlev_max,nqmx)
+
+!        integer :: forcing_type
+        logical :: forcing_les     = .false.
+        logical :: forcing_armcu   = .false.
+        logical :: forcing_rico    = .false.
+        logical :: forcing_radconv = .false.
+        logical :: forcing_toga    = .false.
+        logical :: forcing_twpice  = .false.
+        logical :: forcing_amma    = .false.
+        logical :: forcing_dice    = .false.
+        logical :: forcing_gabls4  = .false.
+
+        logical :: forcing_GCM2SCM = .false.
+        logical :: forcing_GCSSold = .false.
+        logical :: forcing_sandu   = .false.
+        logical :: forcing_astex   = .false.
+        logical :: forcing_fire    = .false.
+        logical :: forcing_case    = .false.
+        logical :: forcing_case2   = .false.
+        logical :: forcing_SCM   = .false.
+        integer :: type_ts_forcing ! 0 = SST constant; 1 = SST read from a file
+!                                                            (cf read_tsurf1d.F)
+
+real wwww
+!vertical advection computation
+!       real d_t_z(llm), d_q_z(llm)
+!       real d_t_dyn_z(llm), dq_dyn_z(llm)
+!       real zz(llm)
+!       real zfact
+
+!flag forcings
+        logical :: nudge_wind=.true.
+        logical :: nudge_thermo=.false.
+        logical :: cptadvw=.true.
+!=====================================================================
+! DECLARATIONS FOR EACH CASE
+!=====================================================================
+!
+#include "old_1D_decl_cases.h"
+!
+!---------------------------------------------------------------------
+!  Declarations related to nudging
+!---------------------------------------------------------------------
+     integer :: nudge_max
+     parameter (nudge_max=9)
+     integer :: inudge_RHT=1
+     integer :: inudge_UV=2
+     logical :: nudge(nudge_max)
+     real :: t_targ(llm)
+     real :: rh_targ(llm)
+     real :: u_targ(llm)
+     real :: v_targ(llm)
+!
+!---------------------------------------------------------------------
+!  Declarations related to vertical discretization:
+!---------------------------------------------------------------------
+      real :: pzero=1.e5
+      real :: play (llm),zlay (llm),sig_s(llm),plev(llm+1)
+      real :: playd(llm),zlayd(llm),ap_amma(llm+1),bp_amma(llm+1)
+
+!---------------------------------------------------------------------
+!  Declarations related to variables
+!---------------------------------------------------------------------
+
+      real :: phi(llm)
+      real :: teta(llm),tetal(llm),temp(llm),u(llm),v(llm),w(llm)
+      REAL rot(1, llm) ! relative vorticity, in s-1
+      real :: rlat_rad(1),rlon_rad(1)
+      real :: omega(llm+1),omega2(llm),rho(llm+1)
+      real :: ug(llm),vg(llm),fcoriolis
+      real :: sfdt, cfdt
+      real :: du_phys(llm),dv_phys(llm),dt_phys(llm)
+      real :: dt_dyn(llm)
+      real :: dt_cooling(llm),d_t_adv(llm),d_t_nudge(llm)
+      real :: d_u_nudge(llm),d_v_nudge(llm)
+      real :: du_adv(llm),dv_adv(llm)
+      real :: du_age(llm),dv_age(llm)
+      real :: alpha
+      real :: ttt
+
+      REAL, ALLOCATABLE, DIMENSION(:,:):: q
+      REAL, ALLOCATABLE, DIMENSION(:,:):: dq
+      REAL, ALLOCATABLE, DIMENSION(:,:):: dq_dyn
+      REAL, ALLOCATABLE, DIMENSION(:,:):: d_q_adv
+      REAL, ALLOCATABLE, DIMENSION(:,:):: d_q_nudge
+!      REAL, ALLOCATABLE, DIMENSION(:):: d_th_adv
+
+!---------------------------------------------------------------------
+!  Initialization of surface variables
+!---------------------------------------------------------------------
+      real :: run_off_lic_0(1)
+      real :: fder(1),snsrf(1,nbsrf),qsurfsrf(1,nbsrf)
+      real :: tsoil(1,nsoilmx,nbsrf)
+!     real :: agesno(1,nbsrf)
+
+!---------------------------------------------------------------------
+!  Call to phyredem
+!---------------------------------------------------------------------
+      logical :: ok_writedem =.true.
+      real :: sollw_in = 0.
+      real :: solsw_in = 0.
+      
+!---------------------------------------------------------------------
+!  Call to physiq
+!---------------------------------------------------------------------
+      logical :: firstcall=.true.
+      logical :: lastcall=.false.
+      real :: phis(1)    = 0.0
+      real :: dpsrf(1)
+
+!---------------------------------------------------------------------
+!  Initializations of boundary conditions 
+!---------------------------------------------------------------------
+      real, allocatable :: phy_nat (:)  ! 0=ocean libre,1=land,2=glacier,3=banquise
+      real, allocatable :: phy_alb (:)  ! Albedo land only (old value condsurf_jyg=0.3)
+      real, allocatable :: phy_sst (:)  ! SST (will not be used; cf read_tsurf1d.F)
+      real, allocatable :: phy_bil (:)  ! Ne sert que pour les slab_ocean
+      real, allocatable :: phy_rug (:) ! Longueur rugosite utilisee sur land only
+      real, allocatable :: phy_ice (:) ! Fraction de glace
+      real, allocatable :: phy_fter(:) ! Fraction de terre
+      real, allocatable :: phy_foce(:) ! Fraction de ocean
+      real, allocatable :: phy_fsic(:) ! Fraction de glace
+      real, allocatable :: phy_flic(:) ! Fraction de glace
+
+!---------------------------------------------------------------------
+!  Fichiers et d'autres variables
+!---------------------------------------------------------------------
+      integer :: k,l,i,it=1,mxcalc
+      integer :: nsrf
+      integer jcode
+      INTEGER read_climoz 
+!
+      integer :: it_end ! iteration number of the last call
+!Al1
+      integer ecrit_slab_oc !1=ecrit,-1=lit,0=no file
+      data ecrit_slab_oc/-1/
+!
+!     if flag_inhib_forcing = 0, tendencies of forcing are added
+!                           <> 0, tendencies of forcing are not added
+      INTEGER :: flag_inhib_forcing = 0
+
+!=====================================================================
+! INITIALIZATIONS 
+!=====================================================================
+      du_phys(:)=0.
+      dv_phys(:)=0.
+      dt_phys(:)=0.
+      dt_dyn(:)=0.
+      dt_cooling(:)=0.
+      d_t_adv(:)=0.
+      d_t_nudge(:)=0.
+      d_u_nudge(:)=0.
+      d_v_nudge(:)=0.
+      du_adv(:)=0.
+      dv_adv(:)=0.
+      du_age(:)=0.
+      dv_age(:)=0.
+      
+! Initialization of Common turb_forcing
+       dtime_frcg = 0.
+       Turb_fcg_gcssold=.false.
+       hthturb_gcssold = 0.
+       hqturb_gcssold = 0.
+
+
+
+
+!---------------------------------------------------------------------
+! OPTIONS OF THE 1D SIMULATION (lmdz1d.def => unicol.def)
+!---------------------------------------------------------------------
+!Al1
+        call conf_unicol
+!Al1 moves this gcssold var from common fcg_gcssold to 
+        Turb_fcg_gcssold = xTurb_fcg_gcssold
+! --------------------------------------------------------------------
+        close(1)
+!Al1
+        write(*,*) 'lmdz1d.def lu => unicol.def'
+
+! forcing_type defines the way the SCM is forced:
+!forcing_type = 0 ==> forcing_les = .true.
+!             initial profiles from file prof.inp.001
+!             no forcing by LS convergence ; 
+!             surface temperature imposed ;
+!             radiative cooling may be imposed (iflag_radia=0 in physiq.def)
+!forcing_type = 1 ==> forcing_radconv = .true.
+!             idem forcing_type = 0, but the imposed radiative cooling 
+!             is set to 0 (hence, if iflag_radia=0 in physiq.def, 
+!             then there is no radiative cooling at all)
+!forcing_type = 2 ==> forcing_toga = .true.
+!             initial profiles from TOGA-COARE IFA files 
+!             LS convergence and SST imposed from TOGA-COARE IFA files 
+!forcing_type = 3 ==> forcing_GCM2SCM = .true.
+!             initial profiles from the GCM output
+!             LS convergence imposed from the GCM output
+!forcing_type = 4 ==> forcing_twpice = .true.
+!             initial profiles from TWP-ICE cdf file 
+!             LS convergence, omega and SST imposed from TWP-ICE files 
+!forcing_type = 5 ==> forcing_rico = .true.
+!             initial profiles from RICO files 
+!             LS convergence imposed from RICO files 
+!forcing_type = 6 ==> forcing_amma = .true.
+!             initial profiles from AMMA nc file 
+!             LS convergence, omega and surface fluxes imposed from AMMA file  
+!forcing_type = 7 ==> forcing_dice = .true.
+!             initial profiles and large scale forcings in dice_driver.nc
+!             Different stages: soil model alone, atm. model alone
+!             then both models coupled
+!forcing_type = 8 ==> forcing_gabls4 = .true.
+!             initial profiles and large scale forcings in gabls4_driver.nc
+!forcing_type >= 100 ==> forcing_case = .true.
+!             initial profiles and large scale forcings in cas.nc
+!             LS convergence, omega and SST imposed from CINDY-DYNAMO files 
+!             101=cindynamo
+!             102=bomex
+!forcing_type >= 100 ==> forcing_case2 = .true.
+!             temporary flag while all the 1D cases are not whith the same cas.nc forcing file
+!             103=arm_cu2 ie arm_cu with new forcing format
+!             104=rico2 ie rico with new forcing format
+!forcing_type = 40 ==> forcing_GCSSold = .true.
+!             initial profile from GCSS file
+!             LS convergence imposed from GCSS file
+!forcing_type = 50 ==> forcing_fire = .true.
+!             forcing from fire.nc
+!forcing_type = 59 ==> forcing_sandu = .true.
+!             initial profiles from sanduref file: see prof.inp.001
+!             SST varying with time and divergence constante: see ifa_sanduref.txt file
+!             Radiation has to be computed interactively
+!forcing_type = 60 ==> forcing_astex = .true.
+!             initial profiles from file: see prof.inp.001 
+!             SST,divergence,ug,vg,ufa,vfa varying with time : see ifa_astex.txt file
+!             Radiation has to be computed interactively
+!forcing_type = 61 ==> forcing_armcu = .true.
+!             initial profiles from file: see prof.inp.001 
+!             sensible and latent heat flux imposed: see ifa_arm_cu_1.txt
+!             large scale advective forcing & radiative tendencies applied below 1000m: see ifa_arm_cu_2.txt
+!             use geostrophic wind ug=10m/s vg=0m/s. Duration of the case 53100s 
+!             Radiation to be switched off
+!
+      if (forcing_type <=0) THEN
+       forcing_les = .true.
+      elseif (forcing_type .eq.1) THEN
+       forcing_radconv = .true.
+      elseif (forcing_type .eq.2) THEN
+       forcing_toga    = .true.
+      elseif (forcing_type .eq.3) THEN
+       forcing_GCM2SCM = .true.
+      elseif (forcing_type .eq.4) THEN
+       forcing_twpice = .true.
+      elseif (forcing_type .eq.5) THEN
+       forcing_rico = .true.
+      elseif (forcing_type .eq.6) THEN
+       forcing_amma = .true.
+      elseif (forcing_type .eq.7) THEN
+       forcing_dice = .true.
+      elseif (forcing_type .eq.8) THEN
+       forcing_gabls4 = .true.
+      elseif (forcing_type .eq.101) THEN ! Cindynamo starts 1-10-2011 0h
+       forcing_case = .true.
+       year_ini_cas=2011
+       mth_ini_cas=10
+       day_deb=1
+       heure_ini_cas=0.
+       pdt_cas=3*3600.         ! forcing frequency
+      elseif (forcing_type .eq.102) THEN ! Bomex starts 24-6-1969 0h
+       forcing_case = .true.
+       year_ini_cas=1969
+       mth_ini_cas=6
+       day_deb=24
+       heure_ini_cas=0.
+       pdt_cas=1800.         ! forcing frequency
+      elseif (forcing_type .eq.103) THEN ! Arm_cu starts 21-6-1997 11h30
+       forcing_case2 = .true.
+       year_ini_cas=1997
+       mth_ini_cas=6
+       day_deb=21
+       heure_ini_cas=11.5
+       pdt_cas=1800.         ! forcing frequency
+      elseif (forcing_type .eq.104) THEN ! rico starts 16-12-2004 0h
+       forcing_case2 = .true.
+       year_ini_cas=2004
+       mth_ini_cas=12
+       day_deb=16
+       heure_ini_cas=0.
+       pdt_cas=1800.         ! forcing frequency
+      elseif (forcing_type .eq.105) THEN ! bomex starts 16-12-2004 0h
+       forcing_case2 = .true.
+       year_ini_cas=1969
+       mth_ini_cas=6
+       day_deb=24
+       heure_ini_cas=0.
+       pdt_cas=1800.         ! forcing frequency
+      elseif (forcing_type .eq.106) THEN ! ayotte_24SC starts 6-11-1992 0h
+       forcing_case2 = .true.
+       year_ini_cas=1992
+       mth_ini_cas=11
+       day_deb=6
+       heure_ini_cas=10.
+       pdt_cas=86400.        ! forcing frequency
+      elseif (forcing_type .eq.113) THEN ! Arm_cu starts 21-6-1997 11h30
+       forcing_SCM = .true.
+       year_ini_cas=1997
+       ! It is possible that those parameters are run twice.
+       call getin('anneeref',year_ini_cas)
+       call getin('dayref',day_deb)
+       mth_ini_cas=1 ! pour le moment on compte depuis le debut de l'annee
+       call getin('time_ini',heure_ini_cas)
+      elseif (forcing_type .eq.40) THEN
+       forcing_GCSSold = .true.
+      elseif (forcing_type .eq.50) THEN
+       forcing_fire = .true.
+      elseif (forcing_type .eq.59) THEN
+       forcing_sandu   = .true.
+      elseif (forcing_type .eq.60) THEN
+       forcing_astex   = .true.
+      elseif (forcing_type .eq.61) THEN
+       forcing_armcu = .true.
+       IF(llm.NE.19.AND.llm.NE.40) stop 'Erreur nombre de niveaux !!'
+      else
+       write (*,*) 'ERROR : unknown forcing_type ', forcing_type
+       stop 'Forcing_type should be 0,1,2,3,4,5,6 or 40,59,60,61'
+      ENDIF
+      print*,"forcing type=",forcing_type
+
+! if type_ts_forcing=0, the surface temp of 1D simulation is constant in time
+! (specified by tsurf in lmdz1d.def); if type_ts_forcing=1, the surface temperature
+! varies in time according to a forcing (e.g. forcing_toga) and is passed to read_tsurf1d.F
+! through the common sst_forcing.
+
+        type_ts_forcing = 0
+        if (forcing_toga.or.forcing_sandu.or.forcing_astex .or. forcing_dice)                 &
+     &    type_ts_forcing = 1
+!
+! Initialization of the logical switch for nudging
+     jcode = iflag_nudge
+     do i = 1,nudge_max
+       nudge(i) = mod(jcode,10) .ge. 1
+       jcode = jcode/10
+     enddo
+!---------------------------------------------------------------------
+!  Definition of the run
+!---------------------------------------------------------------------
+
+      call conf_gcm( 99, .TRUE. )
+      
+!-----------------------------------------------------------------------
+      allocate( phy_nat (year_len))  ! 0=ocean libre,1=land,2=glacier,3=banquise
+      phy_nat(:)=0.0
+      allocate( phy_alb (year_len))  ! Albedo land only (old value condsurf_jyg=0.3)
+      allocate( phy_sst (year_len))  ! SST (will not be used; cf read_tsurf1d.F)
+      allocate( phy_bil (year_len))  ! Ne sert que pour les slab_ocean
+      phy_bil(:)=1.0
+      allocate( phy_rug (year_len)) ! Longueur rugosite utilisee sur land only
+      allocate( phy_ice (year_len)) ! Fraction de glace
+      phy_ice(:)=0.0
+      allocate( phy_fter(year_len)) ! Fraction de terre
+      phy_fter(:)=0.0
+      allocate( phy_foce(year_len)) ! Fraction de ocean
+      phy_foce(:)=0.0
+      allocate( phy_fsic(year_len)) ! Fraction de glace
+      phy_fsic(:)=0.0
+      allocate( phy_flic(year_len)) ! Fraction de glace
+      phy_flic(:)=0.0
+!-----------------------------------------------------------------------
+!   Choix du calendrier
+!   -------------------
+
+!      calend = 'earth_365d'
+      if (calend == 'earth_360d') then
+        call ioconf_calendar('360d')
+        write(*,*)'CALENDRIER CHOISI: Terrestre a 360 jours/an'
+      else if (calend == 'earth_365d') then
+        call ioconf_calendar('noleap')
+        write(*,*)'CALENDRIER CHOISI: Terrestre a 365 jours/an'
+      else if (calend == 'earth_366d') then
+        call ioconf_calendar('all_leap')
+        write(*,*)'CALENDRIER CHOISI: Terrestre bissextile'
+      else if (calend == 'gregorian') then
+        stop 'gregorian calend should not be used by normal user'
+        call ioconf_calendar('gregorian') ! not to be used by normal users
+        write(*,*)'CALENDRIER CHOISI: Gregorien'
+      else
+        write (*,*) 'ERROR : unknown calendar ', calend
+        stop 'calend should be 360d,earth_365d,earth_366d,gregorian'
+      endif
+!-----------------------------------------------------------------------
+!
+!c Date :
+!      La date est supposee donnee sous la forme [annee, numero du jour dans 
+!      l annee] ; l heure est donnee dans time_ini, lu dans lmdz1d.def.
+!      On appelle ymds2ju pour convertir [annee, jour] en [jour Julien].
+!      Le numero du jour est dans "day". L heure est traitee separement.
+!      La date complete est dans "daytime" (l'unite est le jour).
+      if (nday>0) then
+         fnday=nday
+      else
+         fnday=-nday/float(day_step)
+      endif
+      print *,'fnday=',fnday
+!     start_time doit etre en FRACTION DE JOUR
+      start_time=time_ini/24.
+
+! Special case for arm_cu which lasts less than one day : 53100s !! (MPL 20111026)
+      IF(forcing_type .EQ. 61) fnday=53100./86400.
+      IF(forcing_type .EQ. 103) fnday=53100./86400.
+! Special case for amma which lasts less than one day : 64800s !! (MPL 20120216)
+      IF(forcing_type .EQ. 6) fnday=64800./86400.
+!     IF(forcing_type .EQ. 6) fnday=50400./86400.
+ IF(forcing_type .EQ. 8 ) fnday=129600./86400. 
+      annee_ref = anneeref
+      mois = 1
+      day_ref = dayref
+      heure = 0.
+      itau_dyn = 0
+      itau_phy = 0
+      call ymds2ju(annee_ref,mois,day_ref,heure,day)
+      day_ini = int(day)
+      day_end = day_ini + int(fnday)
+
+      IF (forcing_type .eq.2) THEN
+! Convert the initial date of Toga-Coare to Julian day
+      call ymds2ju                                                          &
+     & (year_ini_toga,mth_ini_toga,day_ini_toga,heure,day_ju_ini_toga)
+
+      ELSEIF (forcing_type .eq.4) THEN
+! Convert the initial date of TWPICE to Julian day
+      call ymds2ju                                                          &
+     & (year_ini_twpi,mth_ini_twpi,day_ini_twpi,heure_ini_twpi              &
+     & ,day_ju_ini_twpi)
+      ELSEIF (forcing_type .eq.6) THEN
+! Convert the initial date of AMMA to Julian day
+      call ymds2ju                                                          &
+     & (year_ini_amma,mth_ini_amma,day_ini_amma,heure_ini_amma              &
+     & ,day_ju_ini_amma)
+      ELSEIF (forcing_type .eq.7) THEN
+! Convert the initial date of DICE to Julian day
+      call ymds2ju                                                         &
+     & (year_ini_dice,mth_ini_dice,day_ini_dice,heure_ini_dice             & 
+     & ,day_ju_ini_dice)
+ ELSEIF (forcing_type .eq.8 ) THEN
+! Convert the initial date of GABLS4 to Julian day
+      call ymds2ju                                                         &
+     & (year_ini_gabls4,mth_ini_gabls4,day_ini_gabls4,heure_ini_gabls4     & 
+     & ,day_ju_ini_gabls4)
+      ELSEIF (forcing_type .gt.100) THEN
+! Convert the initial date to Julian day
+      day_ini_cas=day_deb
+      print*,'time case',year_ini_cas,mth_ini_cas,day_ini_cas
+      call ymds2ju                                                         &
+     & (year_ini_cas,mth_ini_cas,day_ini_cas,heure_ini_cas*3600            &
+     & ,day_ju_ini_cas)
+      print*,'time case 2',day_ini_cas,day_ju_ini_cas
+      ELSEIF (forcing_type .eq.59) THEN
+! Convert the initial date of Sandu case to Julian day
+      call ymds2ju                                                          &
+     &   (year_ini_sandu,mth_ini_sandu,day_ini_sandu,                       &
+     &    time_ini*3600.,day_ju_ini_sandu)
+
+      ELSEIF (forcing_type .eq.60) THEN
+! Convert the initial date of Astex case to Julian day
+      call ymds2ju                                                          &
+     &   (year_ini_astex,mth_ini_astex,day_ini_astex,                        &
+     &    time_ini*3600.,day_ju_ini_astex)
+
+      ELSEIF (forcing_type .eq.61) THEN
+! Convert the initial date of Arm_cu case to Julian day
+      call ymds2ju                                                          &
+     & (year_ini_armcu,mth_ini_armcu,day_ini_armcu,heure_ini_armcu          &
+     & ,day_ju_ini_armcu)
+      ENDIF
+
+      IF (forcing_type .gt.100) THEN
+      daytime = day + heure_ini_cas/24. ! 1st day and initial time of the simulation 
+      ELSE
+      daytime = day + time_ini/24. ! 1st day and initial time of the simulation 
+      ENDIF
+! Print out the actual date of the beginning of the simulation :
+      call ju2ymds(daytime,year_print, month_print,day_print,sec_print)
+      print *,' Time of beginning : ',                                      &
+     &        year_print, month_print, day_print, sec_print
+
+!---------------------------------------------------------------------
+! Initialization of dimensions, geometry and initial state
+!---------------------------------------------------------------------
+!      call init_phys_lmdz(1,1,llm,1,(/1/)) ! job now done via iniphysiq
+!     but we still need to initialize dimphy module (klon,klev,etc.)  here.
+      call init_dimphy1D(1,llm)
+      call suphel
+      call infotrac_init 
+
+      if (nqtot>nqmx) STOP 'Augmenter nqmx dans lmdz1d.F'
+      allocate(q(llm,nqtot)) ; q(:,:)=0.
+      allocate(dq(llm,nqtot)) 
+      allocate(dq_dyn(llm,nqtot)) 
+      allocate(d_q_adv(llm,nqtot)) 
+      allocate(d_q_nudge(llm,nqtot)) 
+!      allocate(d_th_adv(llm)) 
+
+      q(:,:) = 0.
+      dq(:,:) = 0.
+      dq_dyn(:,:) = 0.
+      d_q_adv(:,:) = 0.
+      d_q_nudge(:,:) = 0.
+
+!
+!   No ozone climatology need be read in this pre-initialization
+!          (phys_state_var_init is called again in physiq)
+      read_climoz = 0
+!
+      call phys_state_var_init(read_climoz)
+
+      if (ngrid.ne.klon) then
+         print*,'stop in inifis'
+         print*,'Probleme de dimensions :'
+         print*,'ngrid = ',ngrid
+         print*,'klon  = ',klon
+         stop
+      endif
+!!!=====================================================================
+!!! Feedback forcing values for Gateaux differentiation (al1)
+!!!=====================================================================
+!!! Surface Planck forcing bracketing call radiation
+!!      surf_Planck = 0.
+!!      surf_Conv   = 0.
+!!      write(*,*) 'Gateaux-dif Planck,Conv:',surf_Planck,surf_Conv
+!!! a mettre dans le lmdz1d.def ou autre
+!!
+!!
+      qsol = qsolinp
+      qsurf = fq_sat(tsurf,psurf/100.)
+      day1= day_ini
+      time=daytime-day
+      ts_toga(1)=tsurf ! needed by read_tsurf1d.F
+      rho(1)=psurf/(rd*tsurf*(1.+(rv/rd-1.)*qsurf)) 
+
+!
+!! mpl et jyg le 22/08/2012 : 
+!!  pour que les cas a flux de surface imposes marchent
+      IF(.NOT.ok_flux_surf.or.max(abs(wtsurf),abs(wqsurf))>0.) THEN
+       fsens=-wtsurf*rcpd*rho(1)
+       flat=-wqsurf*rlvtt*rho(1)
+       print *,'Flux: ok_flux wtsurf wqsurf',ok_flux_surf,wtsurf,wqsurf
+      ENDIF
+      print*,'Flux sol ',fsens,flat
+!!      ok_flux_surf=.false.
+!!      fsens=-wtsurf*rcpd*rho(1)
+!!      flat=-wqsurf*rlvtt*rho(1)
+!!!!
+
+! Vertical discretization and pressure levels at half and mid levels:
+
+      pa   = 5e4
+!!      preff= 1.01325e5
+      preff = psurf
+      IF (ok_old_disvert) THEN
+        call disvert0(pa,preff,ap,bp,dpres,presnivs,nivsigs,nivsig)
+        print *,'On utilise disvert0'
+        aps(1:llm)=0.5*(ap(1:llm)+ap(2:llm+1))
+        bps(1:llm)=0.5*(bp(1:llm)+bp(2:llm+1))
+        scaleheight=8.
+        pseudoalt(1:llm)=-scaleheight*log(presnivs(1:llm)/preff)
+      ELSE
+        call disvert()
+        print *,'On utilise disvert'
+!       Nouvelle version disvert permettant d imposer ap,bp (modif L.Guez) MPL 18092012
+!       Dans ce cas, on lit ap,bp dans le fichier hybrid.txt
+      ENDIF
+
+      sig_s=presnivs/preff
+      plev =ap+bp*psurf
+      play = 0.5*(plev(1:llm)+plev(2:llm+1))
+      zlay=-rd*300.*log(play/psurf)/rg ! moved after reading profiles
+
+      IF (forcing_type .eq. 59) THEN
+! pour forcing_sandu, on cherche l'indice le plus proche de 700hpa#3000m
+      write(*,*) '***********************'
+      do l = 1, llm
+       write(*,*) 'l,play(l),presnivs(l): ',l,play(l),presnivs(l)
+       if (trouve_700 .and. play(l).le.70000) then
+         llm700=l
+         print *,'llm700,play=',llm700,play(l)/100.
+         trouve_700= .false.
+       endif
+      enddo
+      write(*,*) '***********************'
+      ENDIF
+
+!
+!=====================================================================
+! EVENTUALLY, READ FORCING DATA :
+!=====================================================================
+
+#include "old_1D_read_forc_cases.h"
+
+      if (forcing_GCM2SCM) then
+        write (*,*) 'forcing_GCM2SCM not yet implemented'
+        stop 'in initialization'
+      endif ! forcing_GCM2SCM
+
+      print*,'mxcalc=',mxcalc
+!     print*,'zlay=',zlay(mxcalc)
+      print*,'play=',play(mxcalc)
+
+!Al1 pour SST forced, appell?? depuis ocean_forced_noice
+      ts_cur = tsurf ! SST used in read_tsurf1d
+!=====================================================================
+! Initialisation de la physique : 
+!=====================================================================
+
+!  Rq: conf_phys.F90 lit tous les flags de physiq.def; conf_phys appele depuis physiq.F
+!
+! day_step, iphysiq lus dans gcm.def ci-dessus
+! timestep: calcule ci-dessous from rday et day_step
+! ngrid=1
+! llm: defini dans .../modipsl/modeles/LMDZ4/libf/grid/dimension
+! rday: defini dans suphel.F (86400.)
+! day_ini: lu dans run.def (dayref)
+! rlat_rad,rlon-rad: transformes en radian de rlat,rlon lus dans lmdz1d.def (en degres)
+! airefi,zcufi,zcvfi initialises au debut de ce programme
+! rday,ra,rg,rd,rcpd declares dans YOMCST.h et calcules dans suphel.F
+      day_step = float(nsplit_phys)*day_step/float(iphysiq)
+      write (*,*) 'Time step divided by nsplit_phys (=',nsplit_phys,')'
+      timestep =rday/day_step
+      dtime_frcg = timestep
+!
+      zcufi=airefi
+      zcvfi=airefi
+!
+      rlat_rad(1)=xlat*rpi/180.
+      rlon_rad(1)=xlon*rpi/180.
+
+     ! iniphysiq will call iniaqua who needs year_len from phys_cal_mod
+     year_len_phys_cal_mod=year_len
+           
+     ! Ehouarn: iniphysiq requires arrays related to (3D) dynamics grid,
+     ! e.g. for cell boundaries, which are meaningless in 1D; so pad these 
+     ! with '0.' when necessary
+      call iniphysiq(iim,jjm,llm, &
+           1,comm_lmdz, &
+           rday,day_ini,timestep,  &
+           (/rlat_rad(1),0./),(/0./), &
+           (/0.,0./),(/rlon_rad(1),0./),  &
+           (/ (/airefi,0./),(/0.,0./) /), &
+           (/zcufi,0.,0.,0./), &
+           (/zcvfi,0./), &
+           ra,rg,rd,rcpd,1)
+      print*,'apres iniphysiq'
+
+! 2 PARAMETRES QUI DEVRAIENT ETRE LUS DANS run.def MAIS NE LE SONT PAS ICI:
+      co2_ppm= 330.0
+      solaire=1370.0
+
+! Ecriture du startphy avant le premier appel a la physique.
+! On le met juste avant pour avoir acces a tous les champs
+
+      if (ok_writedem) then
+
+!--------------------------------------------------------------------------
+! pbl_surface_init (called here) and pbl_surface_final (called by phyredem)
+! need : qsol fder snow qsurf evap rugos agesno ftsoil
+!--------------------------------------------------------------------------
+
+        type_ocean = "force"
+        run_off_lic_0(1) = restart_runoff 
+        call fonte_neige_init(run_off_lic_0)
+
+        fder=0.
+        snsrf(1,:)=snowmass ! masse de neige des sous surface
+        qsurfsrf(1,:)=qsurf ! humidite de l'air des sous surface
+        fevap=0.
+        z0m(1,:)=rugos     ! couverture de neige des sous surface
+        z0h(1,:)=rugosh    ! couverture de neige des sous surface
+        agesno  = xagesno
+        tsoil(:,:,:)=tsurf
+!------ AMMA 2e run avec modele sol et rayonnement actif (MPL 23052012)
+!       tsoil(1,1,1)=299.18
+!       tsoil(1,2,1)=300.08
+!       tsoil(1,3,1)=301.88
+!       tsoil(1,4,1)=305.48
+!       tsoil(1,5,1)=308.00
+!       tsoil(1,6,1)=308.00
+!       tsoil(1,7,1)=308.00
+!       tsoil(1,8,1)=308.00
+!       tsoil(1,9,1)=308.00
+!       tsoil(1,10,1)=308.00
+!       tsoil(1,11,1)=308.00
+!-----------------------------------------------------------------------
+        call pbl_surface_init(fder, snsrf, qsurfsrf, tsoil)
+
+!------------------ prepare limit conditions for limit.nc -----------------
+!--   Ocean force
+
+        print*,'avant phyredem'
+        pctsrf(1,:)=0.
+          if (nat_surf.eq.0.) then
+          pctsrf(1,is_oce)=1.
+          pctsrf(1,is_ter)=0.
+          pctsrf(1,is_lic)=0.
+          pctsrf(1,is_sic)=0.
+        else if (nat_surf .eq. 1) then 
+          pctsrf(1,is_oce)=0.
+          pctsrf(1,is_ter)=1.
+          pctsrf(1,is_lic)=0.
+          pctsrf(1,is_sic)=0.
+        else if (nat_surf .eq. 2) then 
+          pctsrf(1,is_oce)=0.
+          pctsrf(1,is_ter)=0.
+          pctsrf(1,is_lic)=1.
+          pctsrf(1,is_sic)=0.
+        else if (nat_surf .eq. 3) then 
+          pctsrf(1,is_oce)=0.
+          pctsrf(1,is_ter)=0.
+          pctsrf(1,is_lic)=0.
+          pctsrf(1,is_sic)=1.
+
+     end if
+
+
+        print*,'nat_surf,pctsrf(1,is_oce),pctsrf(1,is_ter)',nat_surf         &
+     &        ,pctsrf(1,is_oce),pctsrf(1,is_ter)
+
+        zmasq=pctsrf(1,is_ter)+pctsrf(1,is_lic)
+        zpic = zpicinp
+        ftsol=tsurf
+        nsw=6 ! on met le nb de bandes SW=6, pour initialiser
+              ! 6 albedo, mais on peut quand meme tourner avec
+              ! moins. Seules les 2 ou 4 premiers seront lus
+        falb_dir=albedo
+        falb_dif=albedo
+        rugoro=rugos 
+        t_ancien(1,:)=temp(:)
+        q_ancien(1,:)=q(:,1)
+        ql_ancien = 0.
+        qs_ancien = 0.
+        prlw_ancien = 0.
+        prsw_ancien = 0.
+        prw_ancien = 0.
+!jyg<
+!!        pbl_tke(:,:,:)=1.e-8
+        pbl_tke(:,:,:)=0.
+        pbl_tke(:,2,:)=1.e-2
+        PRINT *, ' pbl_tke dans lmdz1d '
+        if (prt_level .ge. 5) then 
+         DO nsrf = 1,4
+           PRINT *,'pbl_tke(1,:,',nsrf,') ',pbl_tke(1,:,nsrf)
+         ENDDO
+        end if
+
+!>jyg
+
+        rain_fall=0.
+        snow_fall=0.
+        solsw=0.
+        sollw=0.
+        sollwdown=rsigma*tsurf**4
+        radsol=0.
+        rnebcon=0.
+        ratqs=0.
+        clwcon=0.
+        zmax0 = 0.
+        zmea=0.
+        zstd=0.
+        zsig=0.
+        zgam=0.
+        zval=0. 
+        zthe=0. 
+        sig1=0.
+        w01=0.
+        wake_cstar = 0.
+        wake_deltaq = 0.
+        wake_deltat = 0.
+        wake_delta_pbl_TKE(:,:,:) = 0.
+        delta_tsurf = 0.
+        wake_fip = 0.
+        wake_pe = 0.
+        wake_s = 0.
+        wake_dens = 0.
+        ale_bl = 0.
+        ale_bl_trig = 0.
+        alp_bl = 0.
+        IF (ALLOCATED(du_gwd_rando)) du_gwd_rando = 0.
+        IF (ALLOCATED(du_gwd_front)) du_gwd_front = 0.
+        entr_therm = 0.
+        detr_therm = 0.
+        f0 = 0.
+        fm_therm = 0.
+        u_ancien(1,:)=u(:)
+        v_ancien(1,:)=v(:)
+
+u10m=0.
+v10m=0.
+ale_wake=0.
+ale_bl_stat=0.
+ 
+!------------------------------------------------------------------------
+! Make file containing restart for the physics (startphy.nc)
+!
+! NB: List of the variables to be written by phyredem (via put_field):
+! rlon,rlat,zmasq,pctsrf(:,is_ter),pctsrf(:,is_lic),pctsrf(:,is_oce)
+! pctsrf(:,is_sic),ftsol(:,nsrf),tsoil(:,isoil,nsrf),qsurf(:,nsrf)
+! qsol,falb_dir(:,nsrf),falb_dif(:,nsrf),evap(:,nsrf),snow(:,nsrf)
+! radsol,solsw,sollw, sollwdown,fder,rain_fall,snow_fall,frugs(:,nsrf)
+! agesno(:,nsrf),zmea,zstd,zsig,zgam,zthe,zpic,zval,rugoro
+! t_ancien,q_ancien,,frugs(:,is_oce),clwcon(:,1),rnebcon(:,1),ratqs(:,1)
+! run_off_lic_0,pbl_tke(:,1:klev,nsrf), zmax0,f0,sig1,w01
+! wake_deltat,wake_deltaq,wake_s,wake_dens,wake_cstar,
+! wake_fip,wake_delta_pbl_tke(:,1:klev,nsrf)
+!
+! NB2: The content of the startphy.nc file depends on some flags defined in
+! the ".def" files. However, since conf_phys is not called in lmdz1d.F90, these flags have 
+! to be set at some arbitratry convenient values.
+!------------------------------------------------------------------------
+!Al1 =============== restart option ==========================
+        if (.not.restart) then
+          iflag_pbl = 5
+          call phyredem ("startphy.nc")
+        else
+! (desallocations)
+        print*,'callin surf final'
+          call pbl_surface_final( fder, snsrf, qsurfsrf, tsoil)
+        print*,'after surf final'
+          CALL fonte_neige_final(run_off_lic_0)
+        endif
+
+        ok_writedem=.false.
+        print*,'apres phyredem'
+
+      endif ! ok_writedem
+      
+!------------------------------------------------------------------------
+! Make file containing boundary conditions (limit.nc) **Al1->restartdyn***
+! --------------------------------------------------
+! NB: List of the variables to be written in limit.nc 
+!     (by writelim.F, subroutine of 1DUTILS.h):
+!        phy_nat,phy_alb,phy_sst,phy_bil,phy_rug,phy_ice,
+!        phy_fter,phy_foce,phy_flic,phy_fsic)
+!------------------------------------------------------------------------
+      do i=1,year_len
+        phy_nat(i)  = nat_surf
+        phy_alb(i)  = albedo
+        phy_sst(i)  = tsurf ! read_tsurf1d will be used instead
+        phy_rug(i)  = rugos
+        phy_fter(i) = pctsrf(1,is_ter)
+        phy_foce(i) = pctsrf(1,is_oce)
+        phy_fsic(i) = pctsrf(1,is_sic)
+        phy_flic(i) = pctsrf(1,is_lic)
+      enddo
+
+! fabrication de limit.nc
+      call writelim (1,phy_nat,phy_alb,phy_sst,phy_bil,phy_rug,             &
+     &               phy_ice,phy_fter,phy_foce,phy_flic,phy_fsic)
+
+
+      call phys_state_var_end
+!Al1
+      if (restart) then
+        print*,'call to restart dyn 1d'
+        Call dyn1deta0("start1dyn.nc",plev,play,phi,phis,presnivs,          &
+     &              u,v,temp,q,omega2)
+
+       print*,'fnday,annee_ref,day_ref,day_ini',                            &
+     &     fnday,annee_ref,day_ref,day_ini
+!**      call ymds2ju(annee_ref,mois,day_ini,heure,day)
+       day = day_ini
+       day_end = day_ini + nday
+       daytime = day + time_ini/24. ! 1st day and initial time of the simulation 
+
+! Print out the actual date of the beginning of the simulation :
+       call ju2ymds(daytime, an, mois, jour, heure)
+       print *,' Time of beginning : y m d h',an, mois,jour,heure/3600.
+
+       day = int(daytime)
+       time=daytime-day
+  
+       print*,'****** intialised fields from restart1dyn *******'
+       print*,'plev,play,phi,phis,presnivs,u,v,temp,q,omega2'
+       print*,'temp(1),q(1,1),u(1),v(1),plev(1),phis :'
+       print*,temp(1),q(1,1),u(1),v(1),plev(1),phis
+! raz for safety
+       do l=1,llm
+         dq_dyn(l,1) = 0.
+       enddo
+      endif
+!Al1 ================  end restart =================================
+      IF (ecrit_slab_oc.eq.1) then
+         open(97,file='div_slab.dat',STATUS='UNKNOWN')
+       elseif (ecrit_slab_oc.eq.0) then
+         open(97,file='div_slab.dat',STATUS='OLD')
+       endif
+!
+!---------------------------------------------------------------------
+!    Initialize target profile for RHT nudging if needed
+!---------------------------------------------------------------------
+      if (nudge(inudge_RHT)) then
+        call nudge_RHT_init(plev,play,temp,q(:,1),t_targ,rh_targ)
+      endif
+      if (nudge(inudge_UV)) then
+        call nudge_UV_init(plev,play,u,v,u_targ,v_targ)
+      endif
+!
+!=====================================================================
+       CALL iophys_ini
+! START OF THE TEMPORAL LOOP :
+!=====================================================================
+           
+      it_end = nint(fnday*day_step)
+!test JLD     it_end = 10
+      do while(it.le.it_end)
+
+       if (prt_level.ge.1) then
+         print*,'XXXXXXXXXXXXXXXXXXX ITAP,day,time=',                       &
+     &             it,day,time,it_end,day_step
+         print*,'PAS DE TEMPS ',timestep
+       endif
+!Al1 demande de restartphy.nc
+       if (it.eq.it_end) lastcall=.True.
+
+!---------------------------------------------------------------------
+! Interpolation of forcings in time and onto model levels
+!---------------------------------------------------------------------
+
+#include "old_1D_interp_cases.h"
+
+      if (forcing_GCM2SCM) then
+        write (*,*) 'forcing_GCM2SCM not yet implemented'
+        stop 'in time loop'
+      endif ! forcing_GCM2SCM
+
+!---------------------------------------------------------------------
+!  Geopotential :
+!---------------------------------------------------------------------
+
+        phi(1)=RD*temp(1)*(plev(1)-play(1))/(.5*(plev(1)+play(1)))
+        do l = 1, llm-1
+          phi(l+1)=phi(l)+RD*(temp(l)+temp(l+1))*                           &
+     &    (play(l)-play(l+1))/(play(l)+play(l+1))
+        enddo
+
+!---------------------------------------------------------------------
+! Listing output for debug prt_level>=1
+!---------------------------------------------------------------------
+       if (prt_level>=1) then
+         print *,' avant physiq : -------- day time ',day,time
+         write(*,*) 'firstcall,lastcall,phis',                               &
+     &               firstcall,lastcall,phis
+       end if
+       if (prt_level>=5) then
+         write(*,'(a10,2a4,4a13)') 'BEFOR1 IT=','it','l',                   &
+     &        'presniv','plev','play','phi'
+         write(*,'(a10,2i4,4f13.2)') ('BEFOR1 IT= ',it,l,                   &
+     &         presnivs(l),plev(l),play(l),phi(l),l=1,llm)
+         write(*,'(a11,2a4,a11,6a8)') 'BEFOR2','it','l',                    &
+     &         'presniv','u','v','temp','q1','q2','omega2'
+         write(*,'(a11,2i4,f11.2,5f8.2,e10.2)') ('BEFOR2 IT= ',it,l,         &
+     &   presnivs(l),u(l),v(l),temp(l),q(l,1),q(l,2),omega2(l),l=1,llm)
+       endif
+
+!---------------------------------------------------------------------
+!   Call physiq :
+!---------------------------------------------------------------------
+       call physiq(ngrid,llm, &
+                    firstcall,lastcall,timestep, &
+                    plev,play,phi,phis,presnivs, &
+                    u,v, rot, temp,q,omega2, &
+                    du_phys,dv_phys,dt_phys,dq,dpsrf)
+                firstcall=.false.
+
+!---------------------------------------------------------------------
+! Listing output for debug
+!---------------------------------------------------------------------
+        if (prt_level>=5) then
+          write(*,'(a11,2a4,4a13)') 'AFTER1 IT=','it','l',                  &
+     &        'presniv','plev','play','phi'
+          write(*,'(a11,2i4,4f13.2)') ('AFTER1 it= ',it,l,                  &
+     &    presnivs(l),plev(l),play(l),phi(l),l=1,llm)
+          write(*,'(a11,2a4,a11,6a8)') 'AFTER2','it','l',                   &
+     &         'presniv','u','v','temp','q1','q2','omega2'
+          write(*,'(a11,2i4,f11.2,5f8.2,e10.2)') ('AFTER2 it= ',it,l,       &
+     &    presnivs(l),u(l),v(l),temp(l),q(l,1),q(l,2),omega2(l),l=1,llm)
+          write(*,'(a11,2a4,a11,5a8)') 'AFTER3','it','l',                   &
+     &         'presniv','du_phys','dv_phys','dt_phys','dq1','dq2'    
+           write(*,'(a11,2i4,f11.2,5f8.2)') ('AFTER3 it= ',it,l,            &
+     &      presnivs(l),86400*du_phys(l),86400*dv_phys(l),                   &
+     &       86400*dt_phys(l),86400*dq(l,1),dq(l,2),l=1,llm)
+          write(*,*) 'dpsrf',dpsrf
+        endif
+!---------------------------------------------------------------------
+!   Add physical tendencies :
+!---------------------------------------------------------------------
+
+       fcoriolis=2.*sin(rpi*xlat/180.)*romega
+       if (forcing_radconv .or. forcing_fire) then
+         fcoriolis=0.0
+         dt_cooling=0.0
+         d_t_adv=0.0
+         d_q_adv=0.0
+       endif
+!      print*, 'calcul de fcoriolis ', fcoriolis
+
+       if (forcing_toga .or. forcing_GCSSold .or. forcing_twpice            &
+     &    .or.forcing_amma .or. forcing_type.eq.101) then
+         fcoriolis=0.0 ; ug=0. ; vg=0.
+       endif
+
+       if(forcing_rico) then
+          dt_cooling=0.
+       endif
+
+!CRio:Attention modif sp??cifique cas de Caroline
+      if (forcing_type==-1) then
+         fcoriolis=0.
+!Nudging
+        
+!on calcule dt_cooling
+        do l=1,llm
+        if (play(l).ge.20000.) then
+            dt_cooling(l)=-1.5/86400.
+        elseif ((play(l).ge.10000.).and.((play(l).lt.20000.))) then
+            dt_cooling(l)=-1.5/86400.*(play(l)-10000.)/(10000.)-1./86400.*(20000.-play(l))/10000.*(temp(l)-200.)
+        else
+            dt_cooling(l)=-1.*(temp(l)-200.)/86400.
+        endif
+        enddo
+
+      endif     
+!RC
+      if (forcing_sandu) then
+         ug(1:llm)=u_mod(1:llm)
+         vg(1:llm)=v_mod(1:llm)
+      endif
+
+      IF (prt_level >= 5) print*, 'fcoriolis, xlat,mxcalc ', &
+                                   fcoriolis, xlat,mxcalc
+
+!       print *,'u-ug=',u-ug
+
+!!!!!!!!!!!!!!!!!!!!!!!!
+! Geostrophic wind
+! Le calcul ci dessous est insuffisamment precis
+!      du_age(1:mxcalc)=fcoriolis*(v(1:mxcalc)-vg(1:mxcalc))
+!      dv_age(1:mxcalc)=-fcoriolis*(u(1:mxcalc)-ug(1:mxcalc))
+!!!!!!!!!!!!!!!!!!!!!!!!
+       sfdt = sin(0.5*fcoriolis*timestep)
+       cfdt = cos(0.5*fcoriolis*timestep)
+!       print *,'fcoriolis,sfdt,cfdt,timestep',fcoriolis,sfdt,cfdt,timestep
+!
+        du_age(1:mxcalc)= -2.*sfdt/timestep*                                &
+     &          (sfdt*(u(1:mxcalc)-ug(1:mxcalc)) -                          &
+     &           cfdt*(v(1:mxcalc)-vg(1:mxcalc))  )
+!!     : fcoriolis*(v(1:mxcalc)-vg(1:mxcalc))
+!
+       dv_age(1:mxcalc)= -2.*sfdt/timestep*                                 &
+     &          (cfdt*(u(1:mxcalc)-ug(1:mxcalc)) +                           &
+     &           sfdt*(v(1:mxcalc)-vg(1:mxcalc))  )
+!!     : -fcoriolis*(u(1:mxcalc)-ug(1:mxcalc))
+!
+!!!!!!!!!!!!!!!!!!!!!!!!
+!  Nudging
+!!!!!!!!!!!!!!!!!!!!!!!!
+      d_t_nudge(:) = 0.
+      d_q_nudge(:,:) = 0.
+      d_u_nudge(:) = 0.
+      d_v_nudge(:) = 0.
+      if (nudge(inudge_RHT)) then
+        call nudge_RHT(timestep,plev,play,t_targ,rh_targ,temp,q(:,1),     &
+    &                  d_t_nudge,d_q_nudge(:,1))
+      endif
+      if (nudge(inudge_UV)) then
+        call nudge_UV(timestep,plev,play,u_targ,v_targ,u,v,     &
+    &                  d_u_nudge,d_v_nudge)
+      endif
+!
+       if (forcing_fire) THEN
+
+!let ww=if ( alt le 1100 ) then alt*-0.00001 else 0
+!let wt=if ( alt le 1100 ) then min( -3.75e-5 , -7.5e-8*alt)  else 0
+!let wq=if ( alt le 1100 ) then max( 1.5e-8 , 3e-11*alt)  else 0
+           d_t_adv=0.
+           d_q_adv=0.
+           teta=temp*(pzero/play)**rkappa
+           d_t_adv=0.
+           d_q_adv=0.
+           do l=2,llm-1
+              if (zlay(l)<=1100) then
+                  wwww=-0.00001*zlay(l)
+                  d_t_adv(l)=-wwww*(teta(l)-teta(l+1))/(zlay(l)-zlay(l+1)) /(pzero/play(l))**rkappa
+                  d_q_adv(l,1:2)=-wwww*(q(l,1:2)-q(l+1,1:2))/(zlay(l)-zlay(l+1))
+                  d_t_adv(l)=d_t_adv(l)+min(-3.75e-5 , -7.5e-8*zlay(l))
+                  d_q_adv(l,1)=d_q_adv(l,1)+max( 1.5e-8 , 3e-11*zlay(l))
+              endif
+           enddo
+
+        endif
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!         call  writefield_phy('dv_age' ,dv_age,llm)
+!         call  writefield_phy('du_age' ,du_age,llm)
+!         call  writefield_phy('du_phys' ,du_phys,llm)
+!         call  writefield_phy('u_tend' ,u,llm)
+!         call  writefield_phy('u_g' ,ug,llm)
+!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! Increment state variables
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+print*,'OLDLMDZ1D AANT'
+    IF (flag_inhib_forcing == 0) then ! if tendency of forcings should be added
+print*,'OLDLMDZ1D ARES' , forcing_sandu
+
+! pour les cas sandu et astex, on reclacule u,v,q,temp et teta dans 1D_nudge_sandu_astex.h
+! au dessus de 700hpa, on relaxe vers les profils initiaux
+      if (forcing_sandu .OR. forcing_astex) then
+#include "1D_nudge_sandu_astex.h"
+      else
+        u(1:mxcalc)=u(1:mxcalc) + timestep*(                                &
+     &              du_phys(1:mxcalc)                                       &
+     &             +du_age(1:mxcalc)+du_adv(1:mxcalc)                       &
+     &             +d_u_nudge(1:mxcalc) )            
+        v(1:mxcalc)=v(1:mxcalc) + timestep*(                                 &
+     &              dv_phys(1:mxcalc)                                       &
+     &             +dv_age(1:mxcalc)+dv_adv(1:mxcalc)                       &
+     &             +d_v_nudge(1:mxcalc) )
+        q(1:mxcalc,:)=q(1:mxcalc,:)+timestep*(                              &
+     &                dq(1:mxcalc,:)                                        &
+     &               +d_q_adv(1:mxcalc,:)                                   &
+     &               +d_q_nudge(1:mxcalc,:) )
+
+        if (prt_level.ge.3) then
+          print *,                                                          &
+     &    'physiq-> temp(1),dt_phys(1),d_t_adv(1),dt_cooling(1) ',         &
+     &              temp(1),dt_phys(1),d_t_adv(1),dt_cooling(1)
+           print* ,'dv_phys=',dv_phys
+           print* ,'dv_age=',dv_age
+           print* ,'dv_adv=',dv_adv
+           print* ,'d_v_nudge=',d_v_nudge
+           print*, v
+           print*, vg
+        endif
+
+        temp(1:mxcalc)=temp(1:mxcalc)+timestep*(                            &
+     &              dt_phys(1:mxcalc)                                       &
+     &             +d_t_adv(1:mxcalc)                                      &
+     &             +d_t_nudge(1:mxcalc)                                      &
+     &             +dt_cooling(1:mxcalc))  ! Taux de chauffage ou refroid.
+
+print*,'OLDLMDZ1D IOPH'
+      CALL iophys_ecrit('d_t_adv',klev,'d_t_adv','m/s',d_t_adv)
+      CALL iophys_ecrit('d_t_nudge',klev,'d_t_nudge','m/s',d_t_nudge)
+
+      endif  ! forcing_sandu or forcing_astex
+
+        teta=temp*(pzero/play)**rkappa
+!
+!---------------------------------------------------------------------
+!   Nudge soil temperature if requested
+!---------------------------------------------------------------------
+
+      IF (nudge_tsoil .AND. .NOT. lastcall) THEN
+       ftsoil(1,isoil_nudge,:) = ftsoil(1,isoil_nudge,:)                     &
+     &  -timestep/tau_soil_nudge*(ftsoil(1,isoil_nudge,:)-Tsoil_nudge)
+      ENDIF
+
+!---------------------------------------------------------------------
+!   Add large-scale tendencies (advection, etc) :
+!---------------------------------------------------------------------
+
+!cc nrlmd
+!cc        tmpvar=teta
+!cc        call advect_vert(llm,omega,timestep,tmpvar,plev)
+!cc
+!cc        teta(1:mxcalc)=tmpvar(1:mxcalc)
+!cc        tmpvar(:)=q(:,1)
+!cc        call advect_vert(llm,omega,timestep,tmpvar,plev)
+!cc        q(1:mxcalc,1)=tmpvar(1:mxcalc)
+!cc        tmpvar(:)=q(:,2)
+!cc        call advect_vert(llm,omega,timestep,tmpvar,plev)
+!cc        q(1:mxcalc,2)=tmpvar(1:mxcalc)
+
+   END IF ! end if tendency of tendency should be added
+
+!---------------------------------------------------------------------
+!   Air temperature :
+!---------------------------------------------------------------------        
+        if (lastcall) then
+          print*,'Pas de temps final ',it
+          call ju2ymds(daytime, an, mois, jour, heure)
+          print*,'a la date : a m j h',an, mois, jour ,heure/3600.
+        endif
+
+!  incremente day time
+!        print*,'daytime bef',daytime,1./day_step
+        daytime = daytime+1./day_step
+!Al1dbg
+        day = int(daytime+0.1/day_step)
+!        time = max(daytime-day,0.0)
+!Al1&jyg: correction de bug
+!cc        time = real(mod(it,day_step))/day_step
+        time = time_ini/24.+real(mod(it,day_step))/day_step
+!        print*,'daytime nxt time',daytime,time
+        it=it+1
+
+      enddo
+
+!Al1
+      if (ecrit_slab_oc.ne.-1) close(97)
+
+!Al1 Call to 1D equivalent of dynredem (an,mois,jour,heure ?)
+! -------------------------------------
+       call dyn1dredem("restart1dyn.nc",                                    &
+     &              plev,play,phi,phis,presnivs,                            &
+     &              u,v,temp,q,omega2)
+
+        CALL abort_gcm ('lmdz1d   ','The End  ',0)
+
+        END SUBROUTINE old_lmdz1d
+
+#include "old_1DUTILS_read_interp.h"
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/scm.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/scm.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/dyn1d/scm.F90	(revision 3605)
@@ -0,0 +1,1210 @@
+SUBROUTINE scm
+
+   USE ioipsl, only: ju2ymds, ymds2ju, ioconf_calendar,getin
+   USE phys_state_var_mod, ONLY : phys_state_var_init, phys_state_var_end, &
+       clwcon, detr_therm, &
+       qsol, fevap, z0m, z0h, agesno, &
+       du_gwd_rando, du_gwd_front, entr_therm, f0, fm_therm, &
+       falb_dir, falb_dif, &
+       ftsol, pbl_tke, pctsrf, radsol, rain_fall, snow_fall, ratqs, &
+       rnebcon, rugoro, sig1, w01, solaire_etat0, sollw, sollwdown, &
+       solsw, t_ancien, q_ancien, u_ancien, v_ancien, wake_cstar, &
+       wake_delta_pbl_TKE, delta_tsurf, wake_fip, wake_pe, &
+       wake_deltaq, wake_deltat, wake_s, wake_dens, &
+       zgam, zmax0, zmea, zpic, zsig, &
+       zstd, zthe, zval, ale_bl, ale_bl_trig, alp_bl, ql_ancien, qs_ancien, &
+       prlw_ancien, prsw_ancien, prw_ancien, &
+       u10m,v10m,ale_wake,ale_bl_stat
+
+  
+   USE dimphy
+   USE surface_data, only : type_ocean,ok_veget
+   USE pbl_surface_mod, only : ftsoil, pbl_surface_init, &
+                                 pbl_surface_final
+   USE fonte_neige_mod, only : fonte_neige_init, fonte_neige_final 
+
+   USE infotrac ! new
+   USE control_mod
+   USE indice_sol_mod
+   USE phyaqua_mod
+!  USE mod_1D_cases_read
+   USE mod_1D_cases_read_std
+   !USE mod_1D_amma_read
+   USE print_control_mod, ONLY: lunout, prt_level
+   USE iniphysiq_mod, ONLY: iniphysiq
+   USE mod_const_mpi, ONLY: comm_lmdz
+   USE physiq_mod, ONLY: physiq
+   USE comvert_mod, ONLY: presnivs, ap, bp, dpres,nivsig, nivsigs, pa, &
+                          preff, aps, bps, pseudoalt, scaleheight
+   USE temps_mod, ONLY: annee_ref, calend, day_end, day_ini, day_ref, &
+                        itau_dyn, itau_phy, start_time, year_len
+   USE phys_cal_mod, ONLY : year_len_phys_cal_mod => year_len 
+
+      implicit none
+#include "dimensions.h"
+#include "YOMCST.h"
+!!#include "control.h"
+#include "clesphys.h"
+#include "dimsoil.h"
+!#include "indicesol.h"
+
+#include "compar1d.h"
+#include "flux_arp.h"
+#include "date_cas.h"
+#include "tsoilnudge.h"
+#include "fcg_gcssold.h"
+#include "compbl.h"
+
+!=====================================================================
+! DECLARATIONS
+!=====================================================================
+
+#undef OUTPUT_PHYS_SCM
+
+!---------------------------------------------------------------------
+!  Externals
+!---------------------------------------------------------------------
+      external fq_sat
+      real fq_sat
+
+!---------------------------------------------------------------------
+!  Arguments d' initialisations de la physique (USER DEFINE)
+!---------------------------------------------------------------------
+
+      integer, parameter :: ngrid=1
+      real :: zcufi    = 1.
+      real :: zcvfi    = 1.
+
+!-      real :: nat_surf
+!-      logical :: ok_flux_surf
+!-      real :: fsens
+!-      real :: flat
+!-      real :: tsurf
+!-      real :: rugos
+!-      real :: qsol(1:2)
+!-      real :: qsurf
+!-      real :: psurf
+!-      real :: zsurf
+!-      real :: albedo
+!-
+!-      real :: time     = 0.
+!-      real :: time_ini
+!-      real :: xlat 
+!-      real :: xlon 
+!-      real :: wtsurf 
+!-      real :: wqsurf 
+!-      real :: restart_runoff 
+!-      real :: xagesno 
+!-      real :: qsolinp 
+!-      real :: zpicinp 
+!-
+      real :: fnday 
+      real :: day, daytime 
+      real :: day1
+      real :: heure
+      integer :: jour
+      integer :: mois
+      integer :: an
+ 
+!---------------------------------------------------------------------
+!  Declarations related to forcing and initial profiles 
+!---------------------------------------------------------------------
+
+        integer :: kmax = llm
+        integer llm700,nq1,nq2
+        INTEGER, PARAMETER :: nlev_max=1000, nqmx=1000
+        real timestep, frac
+        real height(nlev_max),tttprof(nlev_max),qtprof(nlev_max)
+        real  uprof(nlev_max),vprof(nlev_max),e12prof(nlev_max)
+        real  ugprof(nlev_max),vgprof(nlev_max),wfls(nlev_max)
+        real  dqtdxls(nlev_max),dqtdyls(nlev_max)
+        real  dqtdtls(nlev_max),thlpcar(nlev_max)
+        real  qprof(nlev_max,nqmx)
+
+!        integer :: forcing_type
+        logical :: forcing_les     = .false.
+        logical :: forcing_armcu   = .false.
+        logical :: forcing_rico    = .false.
+        logical :: forcing_radconv = .false.
+        logical :: forcing_toga    = .false.
+        logical :: forcing_twpice  = .false.
+        logical :: forcing_amma    = .false.
+        logical :: forcing_dice    = .false.
+        logical :: forcing_gabls4  = .false.
+
+        logical :: forcing_GCM2SCM = .false.
+        logical :: forcing_GCSSold = .false.
+        logical :: forcing_sandu   = .false.
+        logical :: forcing_astex   = .false.
+        logical :: forcing_fire    = .false.
+        logical :: forcing_case    = .false.
+        logical :: forcing_case2   = .false.
+        logical :: forcing_SCM   = .false.
+        integer :: type_ts_forcing ! 0 = SST constant; 1 = SST read from a file
+!                                                            (cf read_tsurf1d.F)
+
+!flag forcings
+        logical :: nudge_wind=.true.
+        logical :: nudge_thermo=.false.
+        logical :: cptadvw=.true.
+!=====================================================================
+! DECLARATIONS FOR EACH CASE
+!=====================================================================
+!
+#include "1D_decl_cases.h"
+!
+!---------------------------------------------------------------------
+!  Declarations related to nudging
+!---------------------------------------------------------------------
+     integer :: nudge_max
+     parameter (nudge_max=9)
+     integer :: inudge_RHT=1
+     integer :: inudge_UV=2
+     logical :: nudge(nudge_max)
+     real :: t_targ(llm)
+     real :: rh_targ(llm)
+     real :: u_targ(llm)
+     real :: v_targ(llm)
+!
+!---------------------------------------------------------------------
+!  Declarations related to vertical discretization:
+!---------------------------------------------------------------------
+      real :: pzero=1.e5
+      real :: play (llm),zlay (llm),sig_s(llm),plev(llm+1)
+      real :: playd(llm),zlayd(llm),ap_amma(llm+1),bp_amma(llm+1)
+
+!---------------------------------------------------------------------
+!  Declarations related to variables
+!---------------------------------------------------------------------
+
+      real :: phi(llm)
+      real :: teta(llm),tetal(llm),temp(llm),u(llm),v(llm),w(llm)
+      REAL rot(1, llm) ! relative vorticity, in s-1
+      real :: rlat_rad(1),rlon_rad(1)
+      real :: omega(llm),omega2(llm),rho(llm+1)
+      real :: ug(llm),vg(llm),fcoriolis
+      real :: sfdt, cfdt
+      real :: du_phys(llm),dv_phys(llm),dt_phys(llm)
+      real :: w_adv(llm),z_adv(llm)
+      real :: d_t_vert_adv(llm),d_u_vert_adv(llm),d_v_vert_adv(llm)
+      real :: dt_cooling(llm),d_t_adv(llm),d_t_nudge(llm)
+      real :: d_u_nudge(llm),d_v_nudge(llm)
+      real :: du_adv(llm),dv_adv(llm)
+      real :: du_age(llm),dv_age(llm)
+      real :: alpha
+      real :: ttt
+
+      REAL, ALLOCATABLE, DIMENSION(:,:):: q
+      REAL, ALLOCATABLE, DIMENSION(:,:):: dq
+      REAL, ALLOCATABLE, DIMENSION(:,:):: d_q_vert_adv
+      REAL, ALLOCATABLE, DIMENSION(:,:):: d_q_adv
+      REAL, ALLOCATABLE, DIMENSION(:,:):: d_q_nudge
+!      REAL, ALLOCATABLE, DIMENSION(:):: d_th_adv
+
+!---------------------------------------------------------------------
+!  Initialization of surface variables
+!---------------------------------------------------------------------
+      real :: run_off_lic_0(1)
+      real :: fder(1),snsrf(1,nbsrf),qsurfsrf(1,nbsrf)
+      real :: tsoil(1,nsoilmx,nbsrf)
+!     real :: agesno(1,nbsrf)
+
+!---------------------------------------------------------------------
+!  Call to phyredem
+!---------------------------------------------------------------------
+      logical :: ok_writedem =.true.
+      real :: sollw_in = 0.
+      real :: solsw_in = 0.
+      
+!---------------------------------------------------------------------
+!  Call to physiq
+!---------------------------------------------------------------------
+      logical :: firstcall=.true.
+      logical :: lastcall=.false.
+      real :: phis(1)    = 0.0
+      real :: dpsrf(1)
+
+!---------------------------------------------------------------------
+!  Initializations of boundary conditions 
+!---------------------------------------------------------------------
+      real, allocatable :: phy_nat (:)  ! 0=ocean libre,1=land,2=glacier,3=banquise
+      real, allocatable :: phy_alb (:)  ! Albedo land only (old value condsurf_jyg=0.3)
+      real, allocatable :: phy_sst (:)  ! SST (will not be used; cf read_tsurf1d.F)
+      real, allocatable :: phy_bil (:)  ! Ne sert que pour les slab_ocean
+      real, allocatable :: phy_rug (:) ! Longueur rugosite utilisee sur land only
+      real, allocatable :: phy_ice (:) ! Fraction de glace
+      real, allocatable :: phy_fter(:) ! Fraction de terre
+      real, allocatable :: phy_foce(:) ! Fraction de ocean
+      real, allocatable :: phy_fsic(:) ! Fraction de glace
+      real, allocatable :: phy_flic(:) ! Fraction de glace
+
+!---------------------------------------------------------------------
+!  Fichiers et d'autres variables
+!---------------------------------------------------------------------
+      integer :: k,l,i,it=1,mxcalc
+      integer :: nsrf
+      integer jcode
+      INTEGER read_climoz 
+!
+      integer :: it_end ! iteration number of the last call
+!Al1
+      integer ecrit_slab_oc !1=ecrit,-1=lit,0=no file
+      data ecrit_slab_oc/-1/
+!
+!     if flag_inhib_forcing = 0, tendencies of forcing are added
+!                           <> 0, tendencies of forcing are not added
+      INTEGER :: flag_inhib_forcing = 0
+
+
+      print*,'VOUS ENTREZ DANS LE 1D FORMAT STANDARD'
+
+!=====================================================================
+! INITIALIZATIONS 
+!=====================================================================
+      du_phys(:)=0.
+      dv_phys(:)=0.
+      dt_phys(:)=0.
+      d_t_vert_adv(:)=0.
+      d_u_vert_adv(:)=0.
+      d_v_vert_adv(:)=0.
+      dt_cooling(:)=0.
+      d_t_adv(:)=0.
+      d_t_nudge(:)=0.
+      d_u_nudge(:)=0.
+      d_v_nudge(:)=0.
+      du_adv(:)=0.
+      dv_adv(:)=0.
+      du_age(:)=0.
+      dv_age(:)=0.
+      
+! Initialization of Common turb_forcing
+       dtime_frcg = 0.
+       Turb_fcg_gcssold=.false.
+       hthturb_gcssold = 0.
+       hqturb_gcssold = 0.
+
+
+
+
+!---------------------------------------------------------------------
+! OPTIONS OF THE 1D SIMULATION (lmdz1d.def => unicol.def)
+!---------------------------------------------------------------------
+!Al1
+        call conf_unicol
+!Al1 moves this gcssold var from common fcg_gcssold to 
+        Turb_fcg_gcssold = xTurb_fcg_gcssold
+! --------------------------------------------------------------------
+        close(1)
+!Al1
+        write(*,*) 'lmdz1d.def lu => unicol.def'
+
+       forcing_SCM = .true.
+       year_ini_cas=1997
+       ! It is possible that those parameters are run twice.
+
+       ! A REVOIR : LIRE PEUT ETRE AN MOIS JOUR DIRECETEMENT
+       call getin('anneeref',year_ini_cas)
+       call getin('dayref',day_deb)
+       mth_ini_cas=1 ! pour le moment on compte depuis le debut de l'annee
+       call getin('time_ini',heure_ini_cas)
+
+        type_ts_forcing = 0
+        IF (nat_surf==0) type_ts_forcing=1 ! SST forcee sur OCEAN
+        print*,'NATURE DE LA SURFACE ',nat_surf
+!
+! Initialization of the logical switch for nudging
+     jcode = iflag_nudge
+     do i = 1,nudge_max
+       nudge(i) = mod(jcode,10) .ge. 1
+       jcode = jcode/10
+     enddo
+!---------------------------------------------------------------------
+!  Definition of the run
+!---------------------------------------------------------------------
+
+      call conf_gcm( 99, .TRUE. )
+      
+!-----------------------------------------------------------------------
+      allocate( phy_nat (year_len))  ! 0=ocean libre,1=land,2=glacier,3=banquise
+      phy_nat(:)=0.0
+      allocate( phy_alb (year_len))  ! Albedo land only (old value condsurf_jyg=0.3)
+      allocate( phy_sst (year_len))  ! SST (will not be used; cf read_tsurf1d.F)
+      allocate( phy_bil (year_len))  ! Ne sert que pour les slab_ocean
+      phy_bil(:)=1.0
+      allocate( phy_rug (year_len)) ! Longueur rugosite utilisee sur land only
+      allocate( phy_ice (year_len)) ! Fraction de glace
+      phy_ice(:)=0.0
+      allocate( phy_fter(year_len)) ! Fraction de terre
+      phy_fter(:)=0.0
+      allocate( phy_foce(year_len)) ! Fraction de ocean
+      phy_foce(:)=0.0
+      allocate( phy_fsic(year_len)) ! Fraction de glace
+      phy_fsic(:)=0.0
+      allocate( phy_flic(year_len)) ! Fraction de glace
+      phy_flic(:)=0.0
+!-----------------------------------------------------------------------
+!   Choix du calendrier
+!   -------------------
+
+!      calend = 'earth_365d'
+      if (calend == 'earth_360d') then
+        call ioconf_calendar('360d')
+        write(*,*)'CALENDRIER CHOISI: Terrestre a 360 jours/an'
+      else if (calend == 'earth_365d') then
+        call ioconf_calendar('noleap')
+        write(*,*)'CALENDRIER CHOISI: Terrestre a 365 jours/an'
+      else if (calend == 'earth_366d') then
+        call ioconf_calendar('all_leap')
+        write(*,*)'CALENDRIER CHOISI: Terrestre bissextile'
+      else if (calend == 'gregorian') then
+        stop 'gregorian calend should not be used by normal user'
+        call ioconf_calendar('gregorian') ! not to be used by normal users
+        write(*,*)'CALENDRIER CHOISI: Gregorien'
+      else
+        write (*,*) 'ERROR : unknown calendar ', calend
+        stop 'calend should be 360d,earth_365d,earth_366d,gregorian'
+      endif
+!-----------------------------------------------------------------------
+!
+!c Date :
+!      La date est supposee donnee sous la forme [annee, numero du jour dans 
+!      l annee] ; l heure est donnee dans time_ini, lu dans lmdz1d.def.
+!      On appelle ymds2ju pour convertir [annee, jour] en [jour Julien].
+!      Le numero du jour est dans "day". L heure est traitee separement.
+!      La date complete est dans "daytime" (l'unite est le jour).
+      if (nday>0) then
+         fnday=nday
+      else
+         fnday=-nday/float(day_step)
+      endif
+      print *,'fnday=',fnday
+!     start_time doit etre en FRACTION DE JOUR
+      start_time=time_ini/24.
+
+      annee_ref = anneeref
+      mois = 1
+      day_ref = dayref
+      heure = 0.
+      itau_dyn = 0
+      itau_phy = 0
+      call ymds2ju(annee_ref,mois,day_ref,heure,day)
+      day_ini = int(day)
+      day_end = day_ini + int(fnday)
+
+! Convert the initial date to Julian day
+      day_ini_cas=day_deb
+      print*,'time case',year_ini_cas,mth_ini_cas,day_ini_cas
+      call ymds2ju                                                         &
+     & (year_ini_cas,mth_ini_cas,day_ini_cas,heure_ini_cas*3600            &
+     & ,day_ju_ini_cas)
+      print*,'time case 2',day_ini_cas,day_ju_ini_cas
+      daytime = day + heure_ini_cas/24. ! 1st day and initial time of the simulation 
+
+! Print out the actual date of the beginning of the simulation :
+      call ju2ymds(daytime,year_print, month_print,day_print,sec_print)
+      print *,' Time of beginning : ',                                      &
+     &        year_print, month_print, day_print, sec_print
+
+!---------------------------------------------------------------------
+! Initialization of dimensions, geometry and initial state
+!---------------------------------------------------------------------
+!      call init_phys_lmdz(1,1,llm,1,(/1/)) ! job now done via iniphysiq
+!     but we still need to initialize dimphy module (klon,klev,etc.)  here.
+      call init_dimphy1D(1,llm)
+      call suphel
+      call infotrac_init 
+
+      if (nqtot>nqmx) STOP 'Augmenter nqmx dans lmdz1d.F'
+      allocate(q(llm,nqtot)) ; q(:,:)=0.
+      allocate(dq(llm,nqtot)) 
+      allocate(d_q_vert_adv(llm,nqtot)) 
+      allocate(d_q_adv(llm,nqtot)) 
+      allocate(d_q_nudge(llm,nqtot)) 
+!      allocate(d_th_adv(llm)) 
+
+      q(:,:) = 0.
+      dq(:,:) = 0.
+      d_q_vert_adv(:,:) = 0.
+      d_q_adv(:,:) = 0.
+      d_q_nudge(:,:) = 0.
+
+!
+!   No ozone climatology need be read in this pre-initialization
+!          (phys_state_var_init is called again in physiq)
+      read_climoz = 0
+!
+      call phys_state_var_init(read_climoz)
+
+      if (ngrid.ne.klon) then
+         print*,'stop in inifis'
+         print*,'Probleme de dimensions :'
+         print*,'ngrid = ',ngrid
+         print*,'klon  = ',klon
+         stop
+      endif
+!!!=====================================================================
+!!! Feedback forcing values for Gateaux differentiation (al1)
+!!!=====================================================================
+!!! Surface Planck forcing bracketing call radiation
+!!      surf_Planck = 0.
+!!      surf_Conv   = 0.
+!!      write(*,*) 'Gateaux-dif Planck,Conv:',surf_Planck,surf_Conv
+!!! a mettre dans le lmdz1d.def ou autre
+!!
+!!
+      qsol = qsolinp
+      qsurf = fq_sat(tsurf,psurf/100.)
+      day1= day_ini
+      time=daytime-day
+      ts_toga(1)=tsurf ! needed by read_tsurf1d.F
+      rho(1)=psurf/(rd*tsurf*(1.+(rv/rd-1.)*qsurf)) 
+
+!
+!! mpl et jyg le 22/08/2012 : 
+!!  pour que les cas a flux de surface imposes marchent
+      IF(.NOT.ok_flux_surf.or.max(abs(wtsurf),abs(wqsurf))>0.) THEN
+       fsens=-wtsurf*rcpd*rho(1)
+       flat=-wqsurf*rlvtt*rho(1)
+       print *,'Flux: ok_flux wtsurf wqsurf',ok_flux_surf,wtsurf,wqsurf
+      ENDIF
+      print*,'Flux sol ',fsens,flat
+!!      ok_flux_surf=.false.
+!!      fsens=-wtsurf*rcpd*rho(1)
+!!      flat=-wqsurf*rlvtt*rho(1)
+!!!!
+
+! Vertical discretization and pressure levels at half and mid levels:
+
+      pa   = 5e4
+!!      preff= 1.01325e5
+      preff = psurf
+      IF (ok_old_disvert) THEN
+        call disvert0(pa,preff,ap,bp,dpres,presnivs,nivsigs,nivsig)
+        print *,'On utilise disvert0'
+        aps(1:llm)=0.5*(ap(1:llm)+ap(2:llm+1))
+        bps(1:llm)=0.5*(bp(1:llm)+bp(2:llm+1))
+        scaleheight=8.
+        pseudoalt(1:llm)=-scaleheight*log(presnivs(1:llm)/preff)
+      ELSE
+        call disvert()
+        print *,'On utilise disvert'
+!       Nouvelle version disvert permettant d imposer ap,bp (modif L.Guez) MPL 18092012
+!       Dans ce cas, on lit ap,bp dans le fichier hybrid.txt
+      ENDIF
+
+      sig_s=presnivs/preff
+      plev =ap+bp*psurf
+      play = 0.5*(plev(1:llm)+plev(2:llm+1))
+      zlay=-rd*300.*log(play/psurf)/rg ! moved after reading profiles
+
+      IF (forcing_type .eq. 59) THEN
+! pour forcing_sandu, on cherche l'indice le plus proche de 700hpa#3000m
+      write(*,*) '***********************'
+      do l = 1, llm
+       write(*,*) 'l,play(l),presnivs(l): ',l,play(l),presnivs(l)
+       if (trouve_700 .and. play(l).le.70000) then
+         llm700=l
+         print *,'llm700,play=',llm700,play(l)/100.
+         trouve_700= .false.
+       endif
+      enddo
+      write(*,*) '***********************'
+      ENDIF
+
+!
+!=====================================================================
+! EVENTUALLY, READ FORCING DATA :
+!=====================================================================
+
+#include "1D_read_forc_cases.h"
+   print*,'A d_t_adv ',d_t_adv(1:20)*86400
+
+      if (forcing_GCM2SCM) then
+        write (*,*) 'forcing_GCM2SCM not yet implemented'
+        stop 'in initialization'
+      endif ! forcing_GCM2SCM
+
+      print*,'mxcalc=',mxcalc
+!     print*,'zlay=',zlay(mxcalc)
+      print*,'play=',play(mxcalc)
+
+!Al1 pour SST forced, appell?? depuis ocean_forced_noice
+      ts_cur = tsurf ! SST used in read_tsurf1d
+!=====================================================================
+! Initialisation de la physique : 
+!=====================================================================
+
+!  Rq: conf_phys.F90 lit tous les flags de physiq.def; conf_phys appele depuis physiq.F
+!
+! day_step, iphysiq lus dans gcm.def ci-dessus
+! timestep: calcule ci-dessous from rday et day_step
+! ngrid=1
+! llm: defini dans .../modipsl/modeles/LMDZ4/libf/grid/dimension
+! rday: defini dans suphel.F (86400.)
+! day_ini: lu dans run.def (dayref)
+! rlat_rad,rlon-rad: transformes en radian de rlat,rlon lus dans lmdz1d.def (en degres)
+! airefi,zcufi,zcvfi initialises au debut de ce programme
+! rday,ra,rg,rd,rcpd declares dans YOMCST.h et calcules dans suphel.F
+      day_step = float(nsplit_phys)*day_step/float(iphysiq)
+      write (*,*) 'Time step divided by nsplit_phys (=',nsplit_phys,')'
+      timestep =rday/day_step
+      dtime_frcg = timestep
+!
+      zcufi=airefi
+      zcvfi=airefi
+!
+      rlat_rad(1)=xlat*rpi/180.
+      rlon_rad(1)=xlon*rpi/180.
+
+     ! iniphysiq will call iniaqua who needs year_len from phys_cal_mod
+     year_len_phys_cal_mod=year_len
+           
+     ! Ehouarn: iniphysiq requires arrays related to (3D) dynamics grid,
+     ! e.g. for cell boundaries, which are meaningless in 1D; so pad these 
+     ! with '0.' when necessary
+      call iniphysiq(iim,jjm,llm, &
+           1,comm_lmdz, &
+           rday,day_ini,timestep,  &
+           (/rlat_rad(1),0./),(/0./), &
+           (/0.,0./),(/rlon_rad(1),0./),  &
+           (/ (/airefi,0./),(/0.,0./) /), &
+           (/zcufi,0.,0.,0./), &
+           (/zcvfi,0./), &
+           ra,rg,rd,rcpd,1)
+      print*,'apres iniphysiq'
+
+! 2 PARAMETRES QUI DEVRAIENT ETRE LUS DANS run.def MAIS NE LE SONT PAS ICI:
+      co2_ppm= 330.0
+      solaire=1370.0
+
+! Ecriture du startphy avant le premier appel a la physique.
+! On le met juste avant pour avoir acces a tous les champs
+
+      if (ok_writedem) then
+
+!--------------------------------------------------------------------------
+! pbl_surface_init (called here) and pbl_surface_final (called by phyredem)
+! need : qsol fder snow qsurf evap rugos agesno ftsoil
+!--------------------------------------------------------------------------
+
+        type_ocean = "force"
+        run_off_lic_0(1) = restart_runoff 
+        call fonte_neige_init(run_off_lic_0)
+
+        fder=0.
+        snsrf(1,:)=snowmass ! masse de neige des sous surface
+        qsurfsrf(1,:)=qsurf ! humidite de l'air des sous surface
+        fevap=0.
+        z0m(1,:)=rugos     ! couverture de neige des sous surface
+        z0h(1,:)=rugosh    ! couverture de neige des sous surface
+        agesno  = xagesno
+        tsoil(:,:,:)=tsurf
+!------ AMMA 2e run avec modele sol et rayonnement actif (MPL 23052012)
+!       tsoil(1,1,1)=299.18
+!       tsoil(1,2,1)=300.08
+!       tsoil(1,3,1)=301.88
+!       tsoil(1,4,1)=305.48
+!       tsoil(1,5,1)=308.00
+!       tsoil(1,6,1)=308.00
+!       tsoil(1,7,1)=308.00
+!       tsoil(1,8,1)=308.00
+!       tsoil(1,9,1)=308.00
+!       tsoil(1,10,1)=308.00
+!       tsoil(1,11,1)=308.00
+!-----------------------------------------------------------------------
+        call pbl_surface_init(fder, snsrf, qsurfsrf, tsoil)
+
+!------------------ prepare limit conditions for limit.nc -----------------
+!--   Ocean force
+
+        print*,'avant phyredem'
+        pctsrf(1,:)=0.
+          if (nat_surf.eq.0.) then
+          pctsrf(1,is_oce)=1.
+          pctsrf(1,is_ter)=0.
+          pctsrf(1,is_lic)=0.
+          pctsrf(1,is_sic)=0.
+        else if (nat_surf .eq. 1) then 
+          pctsrf(1,is_oce)=0.
+          pctsrf(1,is_ter)=1.
+          pctsrf(1,is_lic)=0.
+          pctsrf(1,is_sic)=0.
+        else if (nat_surf .eq. 2) then 
+          pctsrf(1,is_oce)=0.
+          pctsrf(1,is_ter)=0.
+          pctsrf(1,is_lic)=1.
+          pctsrf(1,is_sic)=0.
+        else if (nat_surf .eq. 3) then 
+          pctsrf(1,is_oce)=0.
+          pctsrf(1,is_ter)=0.
+          pctsrf(1,is_lic)=0.
+          pctsrf(1,is_sic)=1.
+
+     end if
+
+
+        print*,'nat_surf,pctsrf(1,is_oce),pctsrf(1,is_ter)',nat_surf         &
+     &        ,pctsrf(1,is_oce),pctsrf(1,is_ter)
+
+        zmasq=pctsrf(1,is_ter)+pctsrf(1,is_lic)
+        zpic = zpicinp
+        ftsol=tsurf
+        nsw=6 ! on met le nb de bandes SW=6, pour initialiser
+              ! 6 albedo, mais on peut quand meme tourner avec
+              ! moins. Seules les 2 ou 4 premiers seront lus
+        falb_dir=albedo
+        falb_dif=albedo
+        rugoro=rugos 
+        t_ancien(1,:)=temp(:)
+        q_ancien(1,:)=q(:,1)
+        ql_ancien = 0.
+        qs_ancien = 0.
+        prlw_ancien = 0.
+        prsw_ancien = 0.
+        prw_ancien = 0.
+!jyg<
+!!        pbl_tke(:,:,:)=1.e-8
+        pbl_tke(:,:,:)=0.
+        pbl_tke(:,2,:)=1.e-2
+        PRINT *, ' pbl_tke dans lmdz1d '
+        if (prt_level .ge. 5) then 
+         DO nsrf = 1,4
+           PRINT *,'pbl_tke(1,:,',nsrf,') ',pbl_tke(1,:,nsrf)
+         ENDDO
+        end if
+
+!>jyg
+
+        rain_fall=0.
+        snow_fall=0.
+        solsw=0.
+        sollw=0.
+        sollwdown=rsigma*tsurf**4
+        radsol=0.
+        rnebcon=0.
+        ratqs=0.
+        clwcon=0.
+        zmax0 = 0.
+        zmea=0.
+        zstd=0.
+        zsig=0.
+        zgam=0.
+        zval=0. 
+        zthe=0. 
+        sig1=0.
+        w01=0.
+        wake_cstar = 0.
+        wake_deltaq = 0.
+        wake_deltat = 0.
+        wake_delta_pbl_TKE(:,:,:) = 0.
+        delta_tsurf = 0.
+        wake_fip = 0.
+        wake_pe = 0.
+        wake_s = 0.
+        wake_dens = 0.
+        ale_bl = 0.
+        ale_bl_trig = 0.
+        alp_bl = 0.
+        IF (ALLOCATED(du_gwd_rando)) du_gwd_rando = 0.
+        IF (ALLOCATED(du_gwd_front)) du_gwd_front = 0.
+        entr_therm = 0.
+        detr_therm = 0.
+        f0 = 0.
+        fm_therm = 0.
+        u_ancien(1,:)=u(:)
+        v_ancien(1,:)=v(:)
+ 
+u10m=0.
+v10m=0.
+ale_wake=0.
+ale_bl_stat=0.
+
+!------------------------------------------------------------------------
+! Make file containing restart for the physics (startphy.nc)
+!
+! NB: List of the variables to be written by phyredem (via put_field):
+! rlon,rlat,zmasq,pctsrf(:,is_ter),pctsrf(:,is_lic),pctsrf(:,is_oce)
+! pctsrf(:,is_sic),ftsol(:,nsrf),tsoil(:,isoil,nsrf),qsurf(:,nsrf)
+! qsol,falb_dir(:,nsrf),falb_dif(:,nsrf),evap(:,nsrf),snow(:,nsrf)
+! radsol,solsw,sollw, sollwdown,fder,rain_fall,snow_fall,frugs(:,nsrf)
+! agesno(:,nsrf),zmea,zstd,zsig,zgam,zthe,zpic,zval,rugoro
+! t_ancien,q_ancien,,frugs(:,is_oce),clwcon(:,1),rnebcon(:,1),ratqs(:,1)
+! run_off_lic_0,pbl_tke(:,1:klev,nsrf), zmax0,f0,sig1,w01
+! wake_deltat,wake_deltaq,wake_s,wake_dens,wake_cstar,
+! wake_fip,wake_delta_pbl_tke(:,1:klev,nsrf)
+!
+! NB2: The content of the startphy.nc file depends on some flags defined in
+! the ".def" files. However, since conf_phys is not called in lmdz1d.F90, these flags have 
+! to be set at some arbitratry convenient values.
+!------------------------------------------------------------------------
+!Al1 =============== restart option ==========================
+        if (.not.restart) then
+          iflag_pbl = 5
+          call phyredem ("startphy.nc")
+        else
+! (desallocations)
+        print*,'callin surf final'
+          call pbl_surface_final( fder, snsrf, qsurfsrf, tsoil)
+        print*,'after surf final'
+          CALL fonte_neige_final(run_off_lic_0)
+        endif
+
+        ok_writedem=.false.
+        print*,'apres phyredem'
+
+      endif ! ok_writedem
+      
+!------------------------------------------------------------------------
+! Make file containing boundary conditions (limit.nc) **Al1->restartdyn***
+! --------------------------------------------------
+! NB: List of the variables to be written in limit.nc 
+!     (by writelim.F, subroutine of 1DUTILS.h):
+!        phy_nat,phy_alb,phy_sst,phy_bil,phy_rug,phy_ice,
+!        phy_fter,phy_foce,phy_flic,phy_fsic)
+!------------------------------------------------------------------------
+      do i=1,year_len
+        phy_nat(i)  = nat_surf
+        phy_alb(i)  = albedo
+        phy_sst(i)  = tsurf ! read_tsurf1d will be used instead
+        phy_rug(i)  = rugos
+        phy_fter(i) = pctsrf(1,is_ter)
+        phy_foce(i) = pctsrf(1,is_oce)
+        phy_fsic(i) = pctsrf(1,is_sic)
+        phy_flic(i) = pctsrf(1,is_lic)
+      enddo
+
+! fabrication de limit.nc
+      call writelim (1,phy_nat,phy_alb,phy_sst,phy_bil,phy_rug,             &
+     &               phy_ice,phy_fter,phy_foce,phy_flic,phy_fsic)
+
+
+      call phys_state_var_end
+!Al1
+      if (restart) then
+        print*,'call to restart dyn 1d'
+        Call dyn1deta0("start1dyn.nc",plev,play,phi,phis,presnivs,          &
+     &              u,v,temp,q,omega2)
+
+       print*,'fnday,annee_ref,day_ref,day_ini',                            &
+     &     fnday,annee_ref,day_ref,day_ini
+!**      call ymds2ju(annee_ref,mois,day_ini,heure,day)
+       day = day_ini
+       day_end = day_ini + nday
+       daytime = day + time_ini/24. ! 1st day and initial time of the simulation 
+
+! Print out the actual date of the beginning of the simulation :
+       call ju2ymds(daytime, an, mois, jour, heure)
+       print *,' Time of beginning : y m d h',an, mois,jour,heure/3600.
+
+       day = int(daytime)
+       time=daytime-day
+  
+       print*,'****** intialised fields from restart1dyn *******'
+       print*,'plev,play,phi,phis,presnivs,u,v,temp,q,omega2'
+       print*,'temp(1),q(1,1),u(1),v(1),plev(1),phis :'
+       print*,temp(1),q(1,1),u(1),v(1),plev(1),phis
+! raz for safety
+       do l=1,llm
+         d_q_vert_adv(l,1) = 0.
+       enddo
+      endif
+!Al1 ================  end restart =================================
+      IF (ecrit_slab_oc.eq.1) then
+         open(97,file='div_slab.dat',STATUS='UNKNOWN')
+       elseif (ecrit_slab_oc.eq.0) then
+         open(97,file='div_slab.dat',STATUS='OLD')
+       endif
+!
+!=====================================================================
+#ifdef OUTPUT_PHYS_SCM
+       CALL iophys_ini
+#endif
+! START OF THE TEMPORAL LOOP :
+!=====================================================================
+           
+      it_end = nint(fnday*day_step)
+!test JLD     it_end = 10
+      do while(it.le.it_end)
+
+       if (prt_level.ge.1) then
+         print*,'XXXXXXXXXXXXXXXXXXX ITAP,day,time=',                       &
+     &             it,day,time,it_end,day_step
+         print*,'PAS DE TEMPS ',timestep
+       endif
+!Al1 demande de restartphy.nc
+       if (it.eq.it_end) lastcall=.True.
+
+!---------------------------------------------------------------------
+! Interpolation of forcings in time and onto model levels
+!---------------------------------------------------------------------
+
+#include "1D_interp_cases.h"
+   ! Vertical advection
+!  call lstendH(llm,nqtot,omega,d_t_vert_adv,d_q_vert_adv,q,temp,u,v,play)
+!  print*,'B d_t_adv ',d_t_adv(1:20)*86400
+!  print*,'B d_t_vert_adv ',d_t_vert_adv(1:20)*86400
+!  print*,'B dt omega ',omega
+
+!---------------------------------------------------------------------
+!  Geopotential :
+!---------------------------------------------------------------------
+
+        phi(1)=RD*temp(1)*(plev(1)-play(1))/(.5*(plev(1)+play(1)))
+        do l = 1, llm-1
+          phi(l+1)=phi(l)+RD*(temp(l)+temp(l+1))*                           &
+     &    (play(l)-play(l+1))/(play(l)+play(l+1))
+        enddo
+
+!---------------------------------------------------------------------
+!  Vertical advection
+!---------------------------------------------------------------------
+
+   IF ( forc_w+forc_omega > 0 ) THEN
+
+      IF ( forc_w == 1 ) THEN
+         w_adv=w_mod_cas
+         z_adv=phi/RG
+      ELSE
+         w_adv=omega
+         z_adv=play
+      ENDIF
+
+      teta=temp*(pzero/play)**rkappa
+      do l=2,llm-1
+        d_u_vert_adv(l)=-w_adv(l)*(u(l+1)-u(l-1))/(z_adv(l+1)-z_adv(l-1))
+        d_v_vert_adv(l)=-w_adv(l)*(v(l+1)-v(l-1))/(z_adv(l+1)-z_adv(l-1))
+        d_t_vert_adv(l)=-(w_adv(l)*(teta(l+1)-teta(l-1))/(z_adv(l+1)-z_adv(l-1)))/(pzero/play(l))**rkappa
+        d_q_vert_adv(l,1)=-w_adv(l)*(q(l+1,1)-q(l-1,1))/(z_adv(l+1)-z_adv(l-1))
+      enddo
+      d_t_adv(:)=d_t_adv(:)+d_t_vert_adv(:)
+      d_q_adv(:,1)=d_q_adv(:,1)+d_q_vert_adv(:,1)
+
+      print*,'OMEGA ',w_adv(10),z_adv(10)
+
+   ENDIF
+
+!---------------------------------------------------------------------
+! Listing output for debug prt_level>=1
+!---------------------------------------------------------------------
+       if (prt_level>=1) then
+         print *,' avant physiq : -------- day time ',day,time
+         write(*,*) 'firstcall,lastcall,phis',                               &
+     &               firstcall,lastcall,phis
+       end if
+       if (prt_level>=5) then
+         write(*,'(a10,2a4,4a13)') 'BEFOR1 IT=','it','l',                   &
+     &        'presniv','plev','play','phi'
+         write(*,'(a10,2i4,4f13.2)') ('BEFOR1 IT= ',it,l,                   &
+     &         presnivs(l),plev(l),play(l),phi(l),l=1,llm)
+         write(*,'(a11,2a4,a11,6a8)') 'BEFOR2','it','l',                    &
+     &         'presniv','u','v','temp','q1','q2','omega2'
+         write(*,'(a11,2i4,f11.2,5f8.2,e10.2)') ('BEFOR2 IT= ',it,l,         &
+     &   presnivs(l),u(l),v(l),temp(l),q(l,1),q(l,2),omega2(l),l=1,llm)
+       endif
+
+!---------------------------------------------------------------------
+!   Call physiq :
+!---------------------------------------------------------------------
+       call physiq(ngrid,llm, &
+                    firstcall,lastcall,timestep, &
+                    plev,play,phi,phis,presnivs, &
+                    u,v, rot, temp,q,omega2, &
+                    du_phys,dv_phys,dt_phys,dq,dpsrf)
+                firstcall=.false.
+
+!---------------------------------------------------------------------
+! Listing output for debug
+!---------------------------------------------------------------------
+        if (prt_level>=5) then
+          write(*,'(a11,2a4,4a13)') 'AFTER1 IT=','it','l',                  &
+     &        'presniv','plev','play','phi'
+          write(*,'(a11,2i4,4f13.2)') ('AFTER1 it= ',it,l,                  &
+     &    presnivs(l),plev(l),play(l),phi(l),l=1,llm)
+          write(*,'(a11,2a4,a11,6a8)') 'AFTER2','it','l',                   &
+     &         'presniv','u','v','temp','q1','q2','omega2'
+          write(*,'(a11,2i4,f11.2,5f8.2,e10.2)') ('AFTER2 it= ',it,l,       &
+     &    presnivs(l),u(l),v(l),temp(l),q(l,1),q(l,2),omega2(l),l=1,llm)
+          write(*,'(a11,2a4,a11,5a8)') 'AFTER3','it','l',                   &
+     &         'presniv','du_phys','dv_phys','dt_phys','dq1','dq2'    
+           write(*,'(a11,2i4,f11.2,5f8.2)') ('AFTER3 it= ',it,l,            &
+     &      presnivs(l),86400*du_phys(l),86400*dv_phys(l),                   &
+     &       86400*dt_phys(l),86400*dq(l,1),dq(l,2),l=1,llm)
+          write(*,*) 'dpsrf',dpsrf
+        endif
+!---------------------------------------------------------------------
+!   Add physical tendencies :
+!---------------------------------------------------------------------
+
+       fcoriolis=2.*sin(rpi*xlat/180.)*romega
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! CONSERVE EN ATTENDANT QUE LE CAS EN QUESTION FONCTIONNE EN STD !!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!       if (forcing_radconv .or. forcing_fire) then
+!         fcoriolis=0.0
+!         dt_cooling=0.0
+!         d_t_adv=0.0
+!         d_q_adv=0.0
+!       endif
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! CONSERVE EN ATTENDANT QUE LE CAS EN QUESTION FONCTIONNE EN STD !!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!      if (forcing_toga .or. forcing_GCSSold .or. forcing_twpice            &
+!    &    .or.forcing_amma .or. forcing_type.eq.101) then
+!        fcoriolis=0.0 ; ug=0. ; vg=0.
+!      endif
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! CONSERVE EN ATTENDANT QUE LE CAS EN QUESTION FONCTIONNE EN STD !!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!      if(forcing_rico) then
+!         dt_cooling=0.
+!      endif
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! CONSERVE EN ATTENDANT QUE LE CAS EN QUESTION FONCTIONNE EN STD !!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!CRio:Attention modif sp??cifique cas de Caroline
+!     if (forcing_type==-1) then
+!        fcoriolis=0.
+!       
+!on calcule dt_cooling
+!       do l=1,llm
+!       if (play(l).ge.20000.) then
+!           dt_cooling(l)=-1.5/86400.
+!       elseif ((play(l).ge.10000.).and.((play(l).lt.20000.))) then
+!           dt_cooling(l)=-1.5/86400.*(play(l)-10000.)/(10000.)-1./86400.*(20000.-play(l))/10000.*(temp(l)-200.)
+!       else
+!           dt_cooling(l)=-1.*(temp(l)-200.)/86400.
+!       endif
+!       enddo
+!
+!     endif     
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! CONSERVE EN ATTENDANT QUE LE CAS EN QUESTION FONCTIONNE EN STD !!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!     if (forcing_sandu) then
+!        ug(1:llm)=u_mod(1:llm)
+!        vg(1:llm)=v_mod(1:llm)
+!     endif
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+      IF (prt_level >= 5) print*, 'fcoriolis, xlat,mxcalc ', &
+                                   fcoriolis, xlat,mxcalc
+
+!       print *,'u-ug=',u-ug
+
+!!!!!!!!!!!!!!!!!!!!!!!!
+! Geostrophic wind
+! Le calcul ci dessous est insuffisamment precis
+!      du_age(1:mxcalc)=fcoriolis*(v(1:mxcalc)-vg(1:mxcalc))
+!      dv_age(1:mxcalc)=-fcoriolis*(u(1:mxcalc)-ug(1:mxcalc))
+!!!!!!!!!!!!!!!!!!!!!!!!
+       sfdt = sin(0.5*fcoriolis*timestep)
+       cfdt = cos(0.5*fcoriolis*timestep)
+!       print *,'fcoriolis,sfdt,cfdt,timestep',fcoriolis,sfdt,cfdt,timestep
+!
+        du_age(1:mxcalc)= -2.*sfdt/timestep*                                &
+     &          (sfdt*(u(1:mxcalc)-ug(1:mxcalc)) -                          &
+     &           cfdt*(v(1:mxcalc)-vg(1:mxcalc))  )
+!!     : fcoriolis*(v(1:mxcalc)-vg(1:mxcalc))
+!
+       dv_age(1:mxcalc)= -2.*sfdt/timestep*                                 &
+     &          (cfdt*(u(1:mxcalc)-ug(1:mxcalc)) +                           &
+     &           sfdt*(v(1:mxcalc)-vg(1:mxcalc))  )
+!!     : -fcoriolis*(u(1:mxcalc)-ug(1:mxcalc))
+!
+!!!!!!!!!!!!!!!!!!!!!!!!
+!  Nudging
+!!!!!!!!!!!!!!!!!!!!!!!!
+      d_t_nudge(:) = 0.
+      d_u_nudge(:) = 0.
+      d_v_nudge(:) = 0.
+      d_q_nudge(:,:) = 0.
+      DO l=1,llm
+         IF ( play(l) < p_nudging_u .AND. nint(nudging_u) /= 0 ) &
+             & d_u_nudge(l)=(u_nudg_mod_cas(l)-u(l))/nudging_u
+         IF ( play(l) < p_nudging_v .AND. nint(nudging_v) /= 0 ) &
+             & d_v_nudge(l)=(v_nudg_mod_cas(l)-v(l))/nudging_v
+         IF ( play(l) < p_nudging_t .AND. nint(nudging_t) /= 0 ) &
+             & d_t_nudge(l)=(temp_nudg_mod_cas(l)-temp(l))/nudging_t
+         IF ( play(l) < p_nudging_qv .AND. nint(nudging_qv) /= 0 ) &
+             & d_q_nudge(l,1)=(qv_nudg_mod_cas(l)-q(l,1))/nudging_qv
+      ENDDO
+
+#ifdef OUTPUT_PHYS_SCM
+      CALL iophys_ecrit('w_adv',klev,'w_adv','K/day',w_adv)
+      CALL iophys_ecrit('z_adv',klev,'z_adv','K/day',z_adv)
+      CALL iophys_ecrit('dtadv',klev,'dtadv','K/day',86400*d_t_adv)
+      CALL iophys_ecrit('dtdyn',klev,'dtdyn','K/day',86400*d_t_vert_adv)
+      CALL iophys_ecrit('qv',klev,'qv','g/kg',1000*q(:,1))
+      CALL iophys_ecrit('qvnud',klev,'qvnud','g/kg',1000*u_nudg_mod_cas)
+      CALL iophys_ecrit('u',klev,'u','m/s',u)
+      CALL iophys_ecrit('unud',klev,'unud','m/s',u_nudg_mod_cas)
+      CALL iophys_ecrit('v',klev,'v','m/s',v)
+      CALL iophys_ecrit('vnud',klev,'vnud','m/s',v_nudg_mod_cas)
+      CALL iophys_ecrit('temp',klev,'temp','K',temp)
+      CALL iophys_ecrit('tempnud',klev,'temp_nudg_mod_cas','K',temp_nudg_mod_cas)
+      CALL iophys_ecrit('dtnud',klev,'dtnud','K/day',86400*d_t_nudge)
+      CALL iophys_ecrit('dqnud',klev,'dqnud','K/day',1000*86400*d_q_nudge(:,1))
+#endif
+
+!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! CONSERVE EN ATTENDANT QUE LE CAS EN QUESTION FONCTIONNE EN STD !!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!       if (forcing_fire) THEN
+!               print*,'Enlever cette section rapidement'
+!               stop
+!               
+!
+!!let ww=if ( alt le 1100 ) then alt*-0.00001 else 0
+!!let wt=if ( alt le 1100 ) then min( -3.75e-5 , -7.5e-8*alt)  else 0
+!!let wq=if ( alt le 1100 ) then max( 1.5e-8 , 3e-11*alt)  else 0
+!           d_t_adv=0.
+!           d_q_adv=0.
+!           teta=temp*(pzero/play)**rkappa
+!           d_t_adv=0.
+!           d_q_adv=0.
+!           do l=2,llm-1
+!              if (zlay(l)<=1100) then
+!                  wwww=-0.00001*zlay(l)
+!                  d_t_adv(l)=-wwww*(teta(l)-teta(l+1))/(zlay(l)-zlay(l+1)) /(pzero/play(l))**rkappa
+!                  d_q_adv(l,1:2)=-wwww*(q(l,1:2)-q(l+1,1:2))/(zlay(l)-zlay(l+1))
+!                  d_t_adv(l)=d_t_adv(l)+min(-3.75e-5 , -7.5e-8*zlay(l))
+!                  d_q_adv(l,1)=d_q_adv(l,1)+max( 1.5e-8 , 3e-11*zlay(l))
+!              endif
+!           enddo
+!
+!        endif
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!         call  writefield_phy('dv_age' ,dv_age,llm)
+!         call  writefield_phy('du_age' ,du_age,llm)
+!         call  writefield_phy('du_phys' ,du_phys,llm)
+!         call  writefield_phy('u_tend' ,u,llm)
+!         call  writefield_phy('u_g' ,ug,llm)
+!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! Increment state variables
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+    IF (flag_inhib_forcing == 0) then ! if tendency of forcings should be added
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! CONSERVE EN ATTENDANT QUE LE CAS EN QUESTION FONCTIONNE EN STD !!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+! pour les cas sandu et astex, on reclacule u,v,q,temp et teta dans 1D_nudge_sandu_astex.h
+! au dessus de 700hpa, on relaxe vers les profils initiaux
+!     if (forcing_sandu .OR. forcing_astex) then
+!#include "1D_nudge_sandu_astex.h"
+!      else
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+        u(1:mxcalc)=u(1:mxcalc) + timestep*(                                &
+     &              du_phys(1:mxcalc)                                       &
+     &             +du_age(1:mxcalc)+du_adv(1:mxcalc)                       &
+     &             +d_u_nudge(1:mxcalc) )            
+        v(1:mxcalc)=v(1:mxcalc) + timestep*(                                 &
+     &              dv_phys(1:mxcalc)                                       &
+     &             +dv_age(1:mxcalc)+dv_adv(1:mxcalc)                       &
+     &             +d_v_nudge(1:mxcalc) )
+        q(1:mxcalc,:)=q(1:mxcalc,:)+timestep*(                              &
+     &                dq(1:mxcalc,:)                                        &
+     &               +d_q_adv(1:mxcalc,:)                                   &
+     &               +d_q_nudge(1:mxcalc,:) )
+
+        if (prt_level.ge.3) then
+          print *,                                                          &
+     &    'physiq-> temp(1),dt_phys(1),d_t_adv(1),dt_cooling(1) ',         &
+     &              temp(1),dt_phys(1),d_t_adv(1),dt_cooling(1)
+           print* ,'dv_phys=',dv_phys
+           print* ,'dv_age=',dv_age
+           print* ,'dv_adv=',dv_adv
+           print* ,'d_v_nudge=',d_v_nudge
+           print*, v
+           print*, vg
+        endif
+
+        temp(1:mxcalc)=temp(1:mxcalc)+timestep*(                            &
+     &              dt_phys(1:mxcalc)                                       &
+     &             +d_t_adv(1:mxcalc)                                      &
+     &             +d_t_nudge(1:mxcalc)                                      &
+     &             +dt_cooling(1:mxcalc))  ! Taux de chauffage ou refroid.
+
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! CONSERVE EN ATTENDANT QUE LE CAS EN QUESTION FONCTIONNE EN STD !!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!     endif  ! forcing_sandu or forcing_astex
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+        teta=temp*(pzero/play)**rkappa
+!
+!---------------------------------------------------------------------
+!   Nudge soil temperature if requested
+!---------------------------------------------------------------------
+
+      IF (nudge_tsoil .AND. .NOT. lastcall) THEN
+       ftsoil(1,isoil_nudge,:) = ftsoil(1,isoil_nudge,:)                     &
+     &  -timestep/tau_soil_nudge*(ftsoil(1,isoil_nudge,:)-Tsoil_nudge)
+      ENDIF
+
+!---------------------------------------------------------------------
+!   Add large-scale tendencies (advection, etc) :
+!---------------------------------------------------------------------
+
+!cc nrlmd
+!cc        tmpvar=teta
+!cc        call advect_vert(llm,omega,timestep,tmpvar,plev)
+!cc
+!cc        teta(1:mxcalc)=tmpvar(1:mxcalc)
+!cc        tmpvar(:)=q(:,1)
+!cc        call advect_vert(llm,omega,timestep,tmpvar,plev)
+!cc        q(1:mxcalc,1)=tmpvar(1:mxcalc)
+!cc        tmpvar(:)=q(:,2)
+!cc        call advect_vert(llm,omega,timestep,tmpvar,plev)
+!cc        q(1:mxcalc,2)=tmpvar(1:mxcalc)
+
+   END IF ! end if tendency of tendency should be added
+
+!---------------------------------------------------------------------
+!   Air temperature :
+!---------------------------------------------------------------------        
+        if (lastcall) then
+          print*,'Pas de temps final ',it
+          call ju2ymds(daytime, an, mois, jour, heure)
+          print*,'a la date : a m j h',an, mois, jour ,heure/3600.
+        endif
+
+!  incremente day time
+!        print*,'daytime bef',daytime,1./day_step
+        daytime = daytime+1./day_step
+!Al1dbg
+        day = int(daytime+0.1/day_step)
+!        time = max(daytime-day,0.0)
+!Al1&jyg: correction de bug
+!cc        time = real(mod(it,day_step))/day_step
+        time = time_ini/24.+real(mod(it,day_step))/day_step
+!        print*,'daytime nxt time',daytime,time
+        it=it+1
+
+      enddo
+
+!Al1
+      if (ecrit_slab_oc.ne.-1) close(97)
+
+!Al1 Call to 1D equivalent of dynredem (an,mois,jour,heure ?)
+! -------------------------------------
+       call dyn1dredem("restart1dyn.nc",                                    &
+     &              plev,play,phi,phis,presnivs,                            &
+     &              u,v,temp,q,omega2)
+
+        CALL abort_gcm ('lmdz1d   ','The End  ',0)
+
+END SUBROUTINE scm
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/fisrtilp.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/fisrtilp.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/fisrtilp.F90	(revision 3605)
@@ -740,11 +740,20 @@
                call cloudth(klon,klev,k,ztv, &
                    zq,zqta,fraca, &
-                   qcloud,ctot,zpspsk,paprs,ztla,zthl, &
+                   qcloud,ctot,zpspsk,paprs,pplay,ztla,zthl, &
                    ratqs,zqs,t)
-              elseif (iflag_cloudth_vert>=3) then
+              elseif (iflag_cloudth_vert>=3 .and. iflag_cloudth_vert<=5) then
                call cloudth_v3(klon,klev,k,ztv, &
                    zq,zqta,fraca, &
-                   qcloud,ctot,ctot_vol,zpspsk,paprs,ztla,zthl, &
+                   qcloud,ctot,ctot_vol,zpspsk,paprs,pplay,ztla,zthl, &
                    ratqs,zqs,t)
+              !----------------------------------
+              !Version these Jean Jouhaud, Decembre 2018 
+              !----------------------------------              
+              elseif (iflag_cloudth_vert==6) then
+               call cloudth_v6(klon,klev,k,ztv, &
+                   zq,zqta,fraca, &
+                   qcloud,ctot,ctot_vol,zpspsk,paprs,pplay,ztla,zthl, &
+                   ratqs,zqs,t)
+
               endif
               do i=1,klon
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/flott_gwd_rando_m.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/flott_gwd_rando_m.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/flott_gwd_rando_m.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 module FLOTT_GWD_rando_m
 
@@ -20,4 +23,6 @@
       USE ioipsl_getin_p_mod, ONLY : getin_p
       USE vertical_layers_mod, ONLY : presnivs
+      CHARACTER (LEN=20) :: modname='flott_gwd_rando'
+      CHARACTER (LEN=80) :: abort_message
 
       include "YOMCST.h"
@@ -115,8 +120,4 @@
     LOGICAL, SAVE :: firstcall = .TRUE.
   !$OMP THREADPRIVATE(firstcall,gwd_reproductibilite_mpiomp)
-
-    CHARACTER (LEN=20) :: modname='flott_gwd_rando'
-    CHARACTER (LEN=80) :: abort_message
-
 
 
@@ -198,11 +199,11 @@
 
     IF(DELTAT < DTIME)THEN
-       PRINT *, 'flott_gwd_rando: deltat < dtime!'
-       STOP 1
+       abort_message='flott_gwd_rando: deltat < dtime!'
+       CALL abort_physic(modname,abort_message,1)
     ENDIF
 
     IF (KLEV < NW) THEN
-       PRINT *, 'flott_gwd_rando: you will have problem with random numbers'
-       STOP 1
+       abort_message='flott_gwd_rando: you will have problem with random numbers'
+       CALL abort_physic(modname,abort_message,1)
     ENDIF
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/geo2atm.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/geo2atm.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/geo2atm.F90	(revision 3605)
@@ -5,11 +5,21 @@
   USE dimphy
   USE mod_phys_lmdz_para
-
+  USE mod_grid_phy_lmdz, only: grid_type, unstructured, regular_lonlat
   IMPLICIT NONE
   INCLUDE 'YOMCST.h'
+  CHARACTER (len = 6)                :: clmodnam
+  CHARACTER (len = 20)               :: modname = 'geo2atm'
+  CHARACTER (len = 80)               :: abort_message
 
 ! Change wind coordinates from cartesian geocentric to local spherical
 ! NB! Fonctionne probablement uniquement en MPI seul (sans OpenMP)
 !
+! Geocentric :
+  ! axe x is eastward : crosses (0N,90E) point.
+  ! axe y  crosses (0N,180E) point.
+  ! axe z is 'up' : crosses north pole.
+!
+! NB! Aux poles, fonctionne probablement uniquement en MPI seul (sans OpenMP)
+
   INTEGER, INTENT (IN)                 :: im, jm
   REAL, DIMENSION (im,jm), INTENT(IN)  :: px, py, pz
@@ -17,9 +27,10 @@
   REAL, DIMENSION (im,jm), INTENT(OUT) :: pu, pv, pr
 
-  REAL :: rad
+  REAL :: rad,reps
 
 
   rad = rpi / 180.0E0
-  
+  reps = 1.0e-5
+
   pu(:,:) = &
        - px(:,:) * SIN(rad * plon(:,:)) &
@@ -36,17 +47,34 @@
        + pz(:,:) * SIN(rad * plat(:,:))
 
-  ! Value at North Pole
-  IF (is_north_pole_dyn) THEN
-     pu(:, 1) = -px (1,1)
-     pv(:, 1) = -py (1,1)
-     pr(:, 1) = 0.0
-  ENDIF
+  IF (grid_type==regular_lonlat) THEN
+    ! Value at North Pole
+    IF (is_north_pole_dyn) THEN
+       pu(:, 1) = -px (1,1)
+       pv(:, 1) = -py (1,1)
+       pr(:, 1) = 0.0
+    ENDIF
   
-  ! Value at South Pole     
-  IF (is_south_pole_dyn) THEN
-     pu(:,jm) = -px (1,jm)
-     pv(:,jm) = -py (1,jm)
-     pr(:,jm) = 0.0
-  ENDIF
+    ! Value at South Pole     
+    IF (is_south_pole_dyn) THEN
+       pu(:,jm) = -px (1,jm)
+       pv(:,jm) = -py (1,jm)
+       pr(:,jm) = 0.0
+    ENDIF
+
+  ELSE IF (grid_type==unstructured) THEN
+     ! Pole nord pour Dynamico
+     WHERE ( plat(:,:) >= 90.0-reps )
+        pu(:,:) =  py(:,:)
+        pv(:,:) = -px(:,:)
+        pr(:,:) = 0.0e0
+     END WHERE
+
+  ELSE
+     abort_message='Problem: unknown grid type'
+     CALL abort_physic(modname,abort_message,1)
+  END IF
+
+  
+  
   
 END SUBROUTINE geo2atm
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/grid_noro_m.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/grid_noro_m.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/grid_noro_m.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 MODULE grid_noro_m
 !
@@ -334,6 +337,4 @@
   imar=assert_eq(SIZE(x),SIZE(zphi,1),SIZE(mask,1),TRIM(modname)//" imar")-1
   jmar=assert_eq(SIZE(y),SIZE(zphi,2),SIZE(mask,2),TRIM(modname)//" jmar")
-! IF(imar/=iim)   CALL abort_gcm(TRIM(modname),'imar/=iim'  ,1)
-! IF(jmar/=jjm+1) CALL abort_gcm(TRIM(modname),'jmar/=jjm+1',1)
   iext=imdp/10
   xpi = ACOS(-1.)
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/ini_undefSTD.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/ini_undefSTD.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/ini_undefSTD.F90	(revision 3605)
@@ -55,5 +55,5 @@
 
     IF (n==1 .AND. itap-itapm1==1 .OR. n>1 .AND. mod(itap,nint( &
-        freq_outnmc(n)/dtime))==1) THEN
+        freq_outnmc(n)/phys_tstep))==1) THEN
       ! print*,'ini_undefSTD n itap',n,itap
       DO k = 1, nlevstd
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/inifis_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/inifis_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/inifis_mod.F90	(revision 3605)
@@ -6,5 +6,6 @@
   SUBROUTINE inifis(punjours, prad, pg, pr, pcpp)
   ! Initialize some physical constants and settings
-  USE print_control_mod, ONLY: init_print_control, lunout
+  USE init_print_control_mod, ONLY : init_print_control
+  USE print_control_mod, ONLY: lunout
   IMPLICIT NONE
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/iophy.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/iophy.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/iophy.F90	(revision 3605)
@@ -18,10 +18,5 @@
 #ifdef CPP_XIOS
   INTERFACE histwrite_phy
-!#ifdef CPP_XIOSnew
     MODULE PROCEDURE histwrite2d_phy,histwrite3d_phy,histwrite2d_phy_old,histwrite3d_phy_old,histwrite2d_xios,histwrite3d_xios,histwrite0d_xios
-!#else
-!    MODULE PROCEDURE histwrite2d_phy,histwrite3d_phy,histwrite2d_phy_old,histwrite3d_phy_old,histwrite2d_xios,histwrite3d_xios
-!#endif
-
   END INTERFACE
 #else
@@ -52,11 +47,11 @@
                                   mpi_size, mpi_rank, klon_mpi, &
                                 is_sequential, is_south_pole_dyn
-    USE mod_grid_phy_lmdz, ONLY: nbp_lon, nbp_lat, klon_glo
-    USE print_control_mod, ONLY: prt_level,lunout 
+  USE mod_grid_phy_lmdz, ONLY: nbp_lon, nbp_lat, klon_glo, grid_type, unstructured
+  USE print_control_mod, ONLY: prt_level,lunout 
 #ifdef CPP_IOIPSL
     USE ioipsl, ONLY: flio_dom_set
 #endif
 #ifdef CPP_XIOS
-    USE wxios, ONLY: wxios_domain_param
+  use wxios, ONLY: wxios_domain_param, wxios_domain_param_unstructured, wxios_context_init
 #endif
     IMPLICIT NONE
@@ -77,8 +72,21 @@
     INTEGER :: data_ibegin, data_iend
 
-    CALL gather(rlat,rlat_glo)
-    CALL bcast(rlat_glo)
-    CALL gather(rlon,rlon_glo)
-    CALL bcast(rlon_glo)
+#ifdef CPP_XIOS
+      CALL wxios_context_init
+#endif
+    
+
+    IF (grid_type==unstructured) THEN
+    
+#ifdef CPP_XIOS
+      CALL wxios_domain_param_unstructured("dom_glo")
+#endif
+
+    ELSE
+
+      CALL gather(rlat,rlat_glo)
+      CALL bcast(rlat_glo)
+      CALL gather(rlon,rlon_glo)
+      CALL bcast(rlon_glo)
     
 !$OMP MASTER  
@@ -133,32 +141,34 @@
 #endif
 #ifdef CPP_XIOS
-    ! Set values for the mask:
-    IF (mpi_rank == 0) THEN
-        data_ibegin = 0
-    ELSE 
-        data_ibegin = ii_begin - 1
-    ENDIF
-
-    IF (mpi_rank == mpi_size-1) THEN
-        data_iend = nbp_lon
-    ELSE
-        data_iend = ii_end + 1
-    ENDIF
-
-    IF (prt_level>=10) THEN
-      write(lunout,*) "init_iophy_new: mpirank=",mpi_rank," iibegin=",ii_begin , " ii_end=",ii_end," jjbegin=",jj_begin," jj_nb=",jj_nb," jj_end=",jj_end
-      write(lunout,*) "init_iophy_new: mpirank=",mpi_rank," nbp_lon=",nbp_lon," nbp_lat=",nbp_lat
-      write(lunout,*) "init_iophy_new: mpirank=",mpi_rank," data_ibegin=",data_ibegin," data_iend=",data_iend
-      write(lunout,*) "init_iophy_new: mpirank=",mpi_rank," data_ibegin=",data_ibegin," data_iend=",data_iend
-      write(lunout,*) "init_iophy_new: mpirank=",mpi_rank," is_south_pole=",is_south_pole_dyn
-    ENDIF
-
-    ! Initialize the XIOS domain coreesponding to this process:
-    CALL wxios_domain_param("dom_glo", is_sequential, nbp_lon, jj_nb, nbp_lon, nbp_lat, &
-                            1, nbp_lon, ii_begin, ii_end, jj_begin, jj_end,             &
-                            klon_mpi+2*(nbp_lon-1), data_ibegin, data_iend,             &
-                            io_lat, io_lon,is_south_pole_dyn,mpi_rank)
+      ! Set values for the mask:
+      IF (mpi_rank == 0) THEN
+          data_ibegin = 0
+      ELSE 
+          data_ibegin = ii_begin - 1
+      END IF
+
+      IF (mpi_rank == mpi_size-1) THEN
+          data_iend = nbp_lon
+      ELSE
+          data_iend = ii_end + 1
+      END IF
+
+      IF (prt_level>=10) THEN
+        write(lunout,*) "init_iophy_new: mpirank=",mpi_rank," iibegin=",ii_begin , " ii_end=",ii_end," jjbegin=",jj_begin," jj_nb=",jj_nb," jj_end=",jj_end
+        write(lunout,*) "init_iophy_new: mpirank=",mpi_rank," nbp_lon=",nbp_lon," nbp_lat=",nbp_lat
+        write(lunout,*) "init_iophy_new: mpirank=",mpi_rank," data_ibegin=",data_ibegin," data_iend=",data_iend
+        write(lunout,*) "init_iophy_new: mpirank=",mpi_rank," data_ibegin=",data_ibegin," data_iend=",data_iend
+        write(lunout,*) "init_iophy_new: mpirank=",mpi_rank," is_south_pole_dyn=",is_south_pole_dyn
+      ENDIF
+
+      ! Initialize the XIOS domain coreesponding to this process:
 #endif
 !$OMP END MASTER
+
+#ifdef CPP_XIOS    
+        CALL wxios_domain_param("dom_glo")
+#endif
+      
+    ENDIF
       
   END SUBROUTINE init_iophy_new
@@ -291,5 +301,5 @@
                                 is_sequential, klon_mpi_begin, klon_mpi_end, &
                                 mpi_rank
-  USE mod_grid_phy_lmdz, ONLY: klon_glo, nbp_lon, nbp_lat
+  USE mod_grid_phy_lmdz, ONLY: klon_glo, nbp_lon, nbp_lat, grid1dTo2d_glo
   USE ioipsl, ONLY: histbeg
 
@@ -366,5 +376,5 @@
      ENDDO
 
-       CALL gr_fi_ecrit(1,klon,nbp_lon,nbp_lat,rlon_glo,zx_lon)
+       CALL grid1dTo2d_glo(rlon_glo,zx_lon)
        IF ((nbp_lon*nbp_lat).GT.1) THEN
        DO i = 1, nbp_lon
@@ -373,5 +383,5 @@
        ENDDO
        ENDIF
-       CALL gr_fi_ecrit(1,klon,nbp_lon,nbp_lat,rlat_glo,zx_lat)
+       CALL grid1dTo2d_glo(rlat_glo,zx_lat)
 
     DO i=1,pim
@@ -963,8 +973,9 @@
                                  nid_files, swaerofree_diag, swaero_diag, dryaod_diag, ok_4xCO2atm
   USE print_control_mod, ONLY: prt_level,lunout
-  USE mod_grid_phy_lmdz, ONLY : nbp_lon, nbp_lat
+  USE mod_grid_phy_lmdz, ONLY : nbp_lon, nbp_lat, grid_type, unstructured, regular_lonlat
 #ifdef CPP_XIOS
   USE xios, ONLY: xios_send_field
 #endif
+  USE print_control_mod, ONLY: lunout, prt_level
 
   IMPLICIT NONE
@@ -1007,5 +1018,6 @@
       IF (.not. ok_all_xml) THEN
       IF (prt_level >= 10) THEN
-      WRITE (lunout,*)"histwrite2d_phy: .not.vars_defined ; time to define ", trim(var%name)
+      write(lunout,*)"histwrite2d_phy: .not.vars_defined ; time to define ", &
+                     trim(var%name)
       ENDIF
       DO iff=iff_beg, iff_end
@@ -1025,5 +1037,5 @@
 
     !Et sinon on.... écrit
-    IF (SIZE(field)/=klon .AND. SIZE(field)/=klev) CALL abort_physic('iophy::histwrite2d_phy','Field first DIMENSION not equal to klon/klev',1)    
+    IF (SIZE(field)/=klon .AND. SIZE(field)/=klev .AND. SIZE(field)/=klev+1) CALL abort_physic('iophy::histwrite2d_phy','Field first DIMENSION not equal to klon/klev',1)    
     IF (prt_level >= 10) THEn
       WRITE (lunout,*)"histwrite2d_phy: .not.vars_defined ; time to gather and write ", trim(var%name)
@@ -1037,5 +1049,5 @@
     ENDIF
 !$OMP MASTER
-    CALL grid1Dto2D_mpi(buffer_omp,Field2d)
+    IF (grid_type==regular_lonlat) CALL grid1Dto2D_mpi(buffer_omp,Field2d)
 
 ! La boucle sur les fichiers:
@@ -1047,11 +1059,22 @@
              write(lunout,*)'Dans iophy histwrite2D,var%name ', trim(var%name)                       
           ENDIF
-          IF (SIZE(field) == klon) then
+          
+          IF (grid_type==regular_lonlat) THEN
+            IF (SIZE(field) == klon) then
               CALL xios_send_field(var%name, Field2d)
-          ELSE
-             CALL xios_send_field(var%name, field)
-          ENDIF 
+            ELSE
+               CALL xios_send_field(var%name, field)
+            ENDIF 
+          ELSE IF (grid_type==unstructured) THEN
+            IF (SIZE(field) == klon) then
+              CALL xios_send_field(var%name, buffer_omp)
+            ELSE
+               CALL xios_send_field(var%name, field)
+            ENDIF
+
+          ENDIF
           IF (prt_level >= 10) THEN
-             WRITE (lunout,*)'Dans iophy histwrite2D,var%name apres xios_send ', trim(var%name)                       
+             write(lunout,*)'Dans iophy histwrite2D,var%name apres xios_send ',&
+                             trim(var%name)                       
           ENDIF
 #else
@@ -1065,12 +1088,22 @@
                IF (firstx) THEN
                   IF (prt_level >= 10) THEN
-                     WRITE (lunout,*)'Dans iophy histwrite2D,iff,var%name ', iff,trim(var%name)                       
-                     WRITE (lunout,*)"histwrite2d_phy:.NOT.clef_stations(iff)and iff==iff_beg, call xios_send_field"
+                     write(lunout,*)'Dans iophy histwrite2D,iff,var%name ',&
+                                    iff,trim(var%name)                       
+                     write(lunout,*)"histwrite2d_phy:.NOT.clef_stations(iff)and iff==iff_beg, call xios_send_field"
                   ENDIF
-                  IF (SIZE(field) == klon) then
-                     CALL xios_send_field(var%name, Field2d)
-                  ELSE
-                     CALL xios_send_field(var%name, field)
+                  IF (grid_type==regular_lonlat) THEN
+                    IF (SIZE(field) == klon) then
+                       CALL xios_send_field(var%name, Field2d)
+                    ELSE
+                       CALL xios_send_field(var%name, field)
+                    ENDIF
+                  ELSE IF (grid_type==unstructured) THEN
+                    IF (SIZE(field) == klon) then
+                      CALL xios_send_field(var%name, buffer_omp)
+                    ELSE
+                      CALL xios_send_field(var%name, field)
+                    ENDIF
                   ENDIF
+
                   firstx=.false.
                ENDIF
@@ -1085,7 +1118,7 @@
 !#ifdef CPP_XIOS
 !                        IF (iff == iff_beg) THEN
-!                          if (prt_level >= 10) then
+!                          IF (prt_level >= 10) THEN
 !                            write(lunout,*)"histwrite2d_phy: .NOT.clef_stations(iff) and iff==iff_beg, call xios_send_field"
-!                          endif
+!                          ENDIF
 !                          CALL xios_send_field(var%name, Field2d)
 !                        ENDIF
@@ -1109,5 +1142,5 @@
                        ENDIF ! of IF (is_sequential)
 #ifndef CPP_IOIPSL_NO_OUTPUT 
-                       IF (prt_level >= 10) THEn
+                       IF (prt_level >= 10) THEN
                          write(lunout,*)"histwrite2d_phy: clef_stations(iff) and iff==iff_beg, call wxios_write_2D"
                        ENDIF
@@ -1141,5 +1174,5 @@
                                  nfiles, vars_defined, clef_stations, &
                                  nid_files, swaerofree_diag
-  USE mod_grid_phy_lmdz, ONLY : nbp_lon, nbp_lat
+  USE mod_grid_phy_lmdz, ONLY : nbp_lon, nbp_lat, grid_type, regular_lonlat, unstructured
 #ifdef CPP_XIOS
   USE xios, ONLY: xios_send_field
@@ -1191,5 +1224,5 @@
     !Et sinon on.... écrit
 
-    IF (SIZE(field,1)/=klon .AND. SIZE(field,1)/=klev) CALL abort_physic('iophy::histwrite3d_xios','Field first DIMENSION not equal to klon/klev',1)
+    IF (SIZE(field,1)/=klon .AND. SIZE(field,1)/=klev .AND. SIZE(field,1)/=klev+1) CALL abort_physic('iophy::histwrite3d_phy','Field first DIMENSION not equal to klon/klev',1)
 
     nlev=SIZE(field,2)
@@ -1206,5 +1239,5 @@
     ENDIF
 !$OMP MASTER
-    CALL grid1Dto2D_mpi(buffer_omp,field3d)
+    IF (grid_type==regular_lonlat) CALL grid1Dto2D_mpi(buffer_omp,field3d)
 
 ! BOUCLE SUR LES FICHIERS
@@ -1213,12 +1246,22 @@
     IF (ok_all_xml) THEN
 #ifdef CPP_XIOS
-        IF (prt_level >= 10) THEN
-             write(lunout,*)'Dans iophy histwrite3D,var%name ',trim(var%name)                       
+          IF (prt_level >= 10) THEN
+             write(lunout,*)'Dans iophy histwrite3D,var%name ',&
+                             trim(var%name)                       
+          ENDIF
+          IF (grid_type==regular_lonlat) THEN
+            IF (SIZE(field,1) == klon) then
+               CALL xios_send_field(var%name, Field3d(:,:,1:nlevx))
+            ELSE
+               CALL xios_send_field(var%name, field)
+            ENDIF
+          ELSE IF (grid_type==unstructured) THEN
+            IF (SIZE(field,1) == klon) then
+               CALL xios_send_field(var%name, buffer_omp(:,1:nlevx))
+            ELSE
+               CALL xios_send_field(var%name, field)
+            ENDIF
         ENDIF
-        IF (SIZE(field,1) == klon) then
-             CALL xios_send_field(var%name, Field3d(:,:,1:nlevx))
-        ELSE
-             CALL xios_send_field(var%name, field)
-        ENDIF
+
 #else
         CALL abort_physic ('iophy','cannot have ok_all_xml = .T. without CPP_XIOS defined' ,1)
@@ -1230,16 +1273,25 @@
 #ifdef CPP_XIOS
               IF (firstx) THEN
-                IF (prt_level >= 10) THEn
-                  WRITE (lunout,*)'Dans iophy, histwrite3D iff nlev klev firstx', &
+                IF (prt_level >= 10) THEN
+                  write(lunout,*)'Dans iophy, histwrite3D iff nlev klev firstx', &
                                   iff,nlev,klev, firstx                       
-                  WRITE (lunout,*)'histwrite3d_phy: call xios_send_field for ', &
+                  write(lunout,*)'histwrite3d_phy: call xios_send_field for ', &
                                   trim(var%name), ' with iim jjm nlevx = ', &
                                   nbp_lon,jj_nb,nlevx
                 ENDIF
-                IF (SIZE(field,1) == klon) then
-                    CALL xios_send_field(var%name, Field3d(:,:,1:nlevx))
-                ELSE
+                IF (grid_type==regular_lonlat) THEN
+                  IF (SIZE(field,1) == klon) then
+                      CALL xios_send_field(var%name, Field3d(:,:,1:nlevx))
+                  ELSE
+                       CALL xios_send_field(var%name, field)
+                  ENDIF
+                ELSE IF (grid_type==unstructured) THEN
+                  IF (SIZE(field,1) == klon) then
+                     CALL xios_send_field(var%name, buffer_omp(:,1:nlevx))
+                  ELSE
                      CALL xios_send_field(var%name, field)
+                  ENDIF
                 ENDIF
+
                 firstx=.false.
               ENDIF
@@ -1305,5 +1357,5 @@
                                 is_sequential, klon_mpi_begin, klon_mpi_end, &
                                 jj_nb, klon_mpi, is_master
-  USE mod_grid_phy_lmdz, ONLY : nbp_lon, nbp_lat
+  USE mod_grid_phy_lmdz, ONLY : nbp_lon, nbp_lat, grid_type, unstructured
   USE xios, ONLY: xios_send_field
   USE print_control_mod, ONLY: prt_level,lunout
@@ -1325,9 +1377,9 @@
   IF (prt_level >= 10) WRITE(lunout,*)'Begin histrwrite2d_xios ',field_name
 
-  !Et sinon on.... écrit
-  IF (SIZE(field)/=klon .AND. SIZE(field)/=klev) CALL abort_physic('iophy::histwrite2d_xios','Field first DIMENSION not equal to klon/klev',1)
-    
-  IF (SIZE(field) == klev) then
+    !Et sinon on.... écrit
+    IF (SIZE(field)/=klon .AND. SIZE(field)/=klev .AND. SIZE(field)/=klev+1) CALL abort_physic('iophy::histwrite2d_xios','Field first DIMENSION not equal to klon/klev',1)
+    IF (SIZE(field) == klev .OR. SIZE(field) == klev+1) then
 !$OMP MASTER
+
         CALL xios_send_field(field_name,field)
 !$OMP END MASTER   
@@ -1335,4 +1387,11 @@
         CALL Gather_omp(field,buffer_omp)    
 !$OMP MASTER
+
+      IF (grid_type==unstructured) THEN
+  
+        CALL xios_send_field(field_name, buffer_omp)
+
+      ELSE
+
         CALL grid1Dto2D_mpi(buffer_omp,Field2d)
     
@@ -1342,7 +1401,4 @@
     !IF(.NOT.clef_stations(iff)) THEN
         IF (.TRUE.) THEN
-            ALLOCATE(index2d(nbp_lon*jj_nb))
-            ALLOCATE(fieldok(nbp_lon*jj_nb))
-    
     
             CALL xios_send_field(field_name, Field2d)
@@ -1365,9 +1421,9 @@
                 ENDDO
             ENDIF
-    
-        ENDIF
-                  
-        DEALLOCATE(index2d)
-        DEALLOCATE(fieldok)
+            DEALLOCATE(index2d)
+            DEALLOCATE(fieldok)
+    
+        ENDIF                  
+      ENDIF
 !$OMP END MASTER   
   ENDIF
@@ -1385,5 +1441,5 @@
                                 jj_nb, klon_mpi, is_master
   USE xios, ONLY: xios_send_field
-  USE mod_grid_phy_lmdz, ONLY : nbp_lon, nbp_lat
+  USE mod_grid_phy_lmdz, ONLY : nbp_lon, nbp_lat, grid_type, unstructured
   USE print_control_mod, ONLY: prt_level,lunout
 
@@ -1403,8 +1459,11 @@
   IF (prt_level >= 10) write(lunout,*)'Begin histrwrite3d_xios ',field_name
 
-  !Et on.... écrit
-  IF (SIZE(field,1)/=klon .AND. SIZE(field,1)/=klev) CALL abort_physic('iophy::histwrite3d_xios','Field first DIMENSION not equal to klon/klev',1)
-    
-  IF (SIZE(field,1) == klev) then
+    !Et on.... écrit
+    IF (SIZE(field,1)/=klon .AND. SIZE(field,1)/=klev .AND. SIZE(field,1)/=klev+1) then
+      write(lunout,*)' histrwrite3d_xios ', field_name, SIZE(field)
+      CALL abort_physic('iophy::histwrite3d_xios','Field first DIMENSION not equal to klon/klev',1)
+    ENDIF
+    
+    IF (SIZE(field,1) == klev .OR. SIZE(field,1) == klev+1) then
 !$OMP MASTER
         CALL xios_send_field(field_name,field)
@@ -1416,4 +1475,10 @@
         CALL Gather_omp(field,buffer_omp)
 !$OMP MASTER
+
+    IF (grid_type==unstructured) THEN
+
+      CALL xios_send_field(field_name, buffer_omp(:,1:nlev))
+
+    ELSE
         CALL grid1Dto2D_mpi(buffer_omp,field3d)
 
@@ -1423,7 +1488,6 @@
     !IF (.NOT.clef_stations(iff)) THEN
         IF(.TRUE.)THEN
-            ALLOCATE(index3d(nbp_lon*jj_nb*nlev))
-            ALLOCATE(fieldok(nbp_lon*jj_nb,nlev))
-            CALL xios_send_field(field_name, Field3d(:,:,1:nlev))
+
+           CALL xios_send_field(field_name, Field3d(:,:,1:nlev))
                             
         ELSE 
@@ -1448,7 +1512,8 @@
                 ENDDO
             ENDIF
+            DEALLOCATE(index3d)
+            DEALLOCATE(fieldok)
         ENDIF 
-        DEALLOCATE(index3d)
-        DEALLOCATE(fieldok)
+      ENDIF
 !$OMP END MASTER   
   ENDIF
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/iostart.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/iostart.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/iostart.F90	(revision 3605)
@@ -25,5 +25,5 @@
 
     PUBLIC get_field,get_var,put_field,put_var
-    PUBLIC Open_startphy,close_startphy,open_restartphy,close_restartphy
+    PUBLIC Open_startphy,close_startphy,open_restartphy,close_restartphy, enddef_restartphy
     
 CONTAINS
@@ -117,4 +117,5 @@
   USE netcdf
   USE dimphy
+  USE geometry_mod
   USE mod_grid_phy_lmdz
   USE mod_phys_lmdz_para
@@ -125,15 +126,28 @@
     LOGICAL,OPTIONAL :: found
     
-    REAL    :: field_glo(klon_glo,field_size)
+    REAL,ALLOCATABLE    :: field_glo(:,:)
+    REAL,ALLOCATABLE    :: field_glo_tmp(:,:)
+    INTEGER,ALLOCATABLE :: ind_cell_glo_glo(:)
     LOGICAL :: tmp_found
     INTEGER :: varid
-    INTEGER :: ierr
-    
-    IF (is_mpi_root .AND. is_omp_root) THEN
+    INTEGER :: ierr,i
+
+    IF (is_master) THEN 
+      ALLOCATE(ind_cell_glo_glo(klon_glo))
+      ALLOCATE(field_glo(klon_glo,field_size))
+      ALLOCATE(field_glo_tmp(klon_glo,field_size))
+    ELSE
+      ALLOCATE(ind_cell_glo_glo(0))
+      ALLOCATE(field_glo(0,0))
+    ENDIF
+    
+    CALL gather(ind_cell_glo,ind_cell_glo_glo)
+    
+    IF (is_master) THEN
   
       ierr=NF90_INQ_VARID(nid_start,Field_name,varid)
       
       IF (ierr==NF90_NOERR) THEN
-        CALL body(field_glo)
+        CALL body(field_glo_tmp)
         tmp_found=.TRUE.
       ELSE
@@ -146,4 +160,9 @@
 
     IF (tmp_found) THEN
+      IF (is_master) THEN  
+        DO i=1,klon_glo
+         field_glo(i,:)=field_glo_tmp(ind_cell_glo_glo(i),:)
+        ENDDO
+      ENDIF
       CALL scatter(field_glo,field)
     ENDIF
@@ -307,9 +326,19 @@
       ierr = NF90_DEF_DIM (nid_restart, "horizon_klevp1", klon_glo*klevp1, idim4)
 
-      ierr = NF90_ENDDEF(nid_restart)
+!      ierr = NF90_ENDDEF(nid_restart)
     ENDIF
 
   END SUBROUTINE open_restartphy
   
+  SUBROUTINE enddef_restartphy
+  USE netcdf
+  USE mod_phys_lmdz_para
+  IMPLICIT NONE
+    INTEGER          :: ierr
+
+    IF (is_master) ierr = NF90_ENDDEF(nid_restart)
+ 
+  END SUBROUTINE enddef_restartphy
+
   SUBROUTINE close_restartphy
   USE netcdf
@@ -318,47 +347,49 @@
     INTEGER          :: ierr
 
-    IF (is_mpi_root .AND. is_omp_root) THEN
-      ierr = NF90_CLOSE (nid_restart)
-    ENDIF
+    IF (is_master) ierr = NF90_CLOSE (nid_restart)
  
   END SUBROUTINE close_restartphy
 
   
-  SUBROUTINE put_field_r1(field_name,title,field)
-  IMPLICIT NONE
+  SUBROUTINE put_field_r1(pass, field_name,title,field)
+  IMPLICIT NONE
+  INTEGER, INTENT(IN)            :: pass
   CHARACTER(LEN=*),INTENT(IN)    :: field_name
   CHARACTER(LEN=*),INTENT(IN)    :: title
   REAL,INTENT(IN)                :: field(:)
-  
-    CALL put_field_rgen(field_name,title,field,1)
+    CALL put_field_rgen(pass, field_name,title,field,1)
   
   END SUBROUTINE put_field_r1
 
-  SUBROUTINE put_field_r2(field_name,title,field)
-  IMPLICIT NONE
+  SUBROUTINE put_field_r2(pass, field_name,title,field)
+  IMPLICIT NONE
+  INTEGER, INTENT(IN)            :: pass
   CHARACTER(LEN=*),INTENT(IN)    :: field_name
   CHARACTER(LEN=*),INTENT(IN)    :: title
   REAL,INTENT(IN)                :: field(:,:)
   
-    CALL put_field_rgen(field_name,title,field,size(field,2))
+    CALL put_field_rgen(pass, field_name,title,field,size(field,2))
   
   END SUBROUTINE put_field_r2
 
-  SUBROUTINE put_field_r3(field_name,title,field)
-  IMPLICIT NONE
+  SUBROUTINE put_field_r3(pass, field_name,title,field)
+  IMPLICIT NONE
+  INTEGER, INTENT(IN)            :: pass
   CHARACTER(LEN=*),INTENT(IN)    :: field_name
   CHARACTER(LEN=*),INTENT(IN)    :: title
   REAL,INTENT(IN)                :: field(:,:,:)
   
-    CALL put_field_rgen(field_name,title,field,size(field,2)*size(field,3))
+    CALL put_field_rgen(pass, field_name,title,field,size(field,2)*size(field,3))
   
   END SUBROUTINE put_field_r3
   
-  SUBROUTINE put_field_rgen(field_name,title,field,field_size)
+  SUBROUTINE put_field_rgen(pass, field_name,title,field,field_size)
   USE netcdf
   USE dimphy
+  USE geometry_mod
   USE mod_grid_phy_lmdz
   USE mod_phys_lmdz_para
   IMPLICIT NONE
+  INTEGER, INTENT(IN)            :: pass
   CHARACTER(LEN=*),INTENT(IN)    :: field_name
   CHARACTER(LEN=*),INTENT(IN)    :: title
@@ -366,13 +397,18 @@
   REAL,INTENT(IN)                :: field(klon,field_size)
   
-  REAL                           :: field_glo(klon_glo,field_size)
-  INTEGER                        :: ierr
+!  REAL                           :: field_glo(klon_glo,field_size)
+!  REAL                           :: field_glo_tmp(klon_glo,field_size)
+  REAL ,ALLOCATABLE              :: field_glo(:,:)
+  REAL ,ALLOCATABLE              :: field_glo_tmp(:,:)
+  INTEGER,ALLOCATABLE            :: ind_cell_glo_glo(:)
+!  INTEGER                        :: ind_cell_glo_glo(klon_glo)
+  INTEGER                        :: ierr,i
   INTEGER                        :: nvarid
   INTEGER                        :: idim
    
-   
-    CALL gather(field,field_glo)
-    
-    IF (is_mpi_root .AND. is_omp_root) THEN
+! first pass : definition   
+  IF (pass==1) THEN
+    
+    IF (is_master) THEN
 
       IF (field_size==1) THEN
@@ -387,5 +423,5 @@
       ENDIF
          
-      ierr = NF90_REDEF (nid_restart)
+!      ierr = NF90_REDEF (nid_restart)
 #ifdef NC_DOUBLE
       ierr = NF90_DEF_VAR (nid_restart, field_name, NF90_DOUBLE,(/ idim /),nvarid)
@@ -394,12 +430,40 @@
 #endif
       IF (LEN_TRIM(title) > 0) ierr = NF90_PUT_ATT (nid_restart,nvarid,"title", title)
-      ierr = NF90_ENDDEF(nid_restart)
-      ierr = NF90_PUT_VAR(nid_restart,nvarid,RESHAPE(field_glo,(/klon_glo*field_size/)))
-    ENDIF
-    
-   END SUBROUTINE put_field_rgen  
-  
-   SUBROUTINE put_var_r0(var_name,title,var)
+!      ierr = NF90_ENDDEF(nid_restart)
+     ENDIF
+
+! second pass : write     
+   ELSE IF (pass==2) THEN 
+    
+     IF (is_master) THEN
+       ALLOCATE(ind_cell_glo_glo(klon_glo))
+       ALLOCATE(field_glo(klon_glo,field_size))
+       ALLOCATE(field_glo_tmp(klon_glo,field_size))
+     ELSE
+       ALLOCATE(ind_cell_glo_glo(0))
+       ALLOCATE(field_glo_tmp(0,0))
+     ENDIF
+     
+     CALL gather(ind_cell_glo,ind_cell_glo_glo) 
+
+     CALL gather(field,field_glo_tmp)
+    
+     IF (is_master) THEN
+
+       DO i=1,klon_glo
+         field_glo(ind_cell_glo_glo(i),:)=field_glo_tmp(i,:)
+       ENDDO
+
+       ierr = NF90_INQ_VARID(nid_restart, field_name, nvarid)
+       ierr = NF90_PUT_VAR(nid_restart,nvarid,RESHAPE(field_glo,(/klon_glo*field_size/)))
+      ENDIF
+   ENDIF
+    
+ END SUBROUTINE put_field_rgen  
+  
+
+ SUBROUTINE put_var_r0(pass, var_name,title,var)
    IMPLICIT NONE
+     INTEGER, INTENT(IN)            :: pass
      CHARACTER(LEN=*),INTENT(IN) :: var_name
      CHARACTER(LEN=*),INTENT(IN) :: title
@@ -409,53 +473,57 @@
      varin(1)=var
      
-     CALL put_var_rgen(var_name,title,varin,size(varin))
+     CALL put_var_rgen(pass, var_name,title,varin,size(varin))
 
   END SUBROUTINE put_var_r0
 
 
-   SUBROUTINE put_var_r1(var_name,title,var)
+   SUBROUTINE put_var_r1(pass, var_name,title,var)
    IMPLICIT NONE
+     INTEGER, INTENT(IN)            :: pass
      CHARACTER(LEN=*),INTENT(IN) :: var_name
      CHARACTER(LEN=*),INTENT(IN) :: title
      REAL,INTENT(IN)             :: var(:)
      
-     CALL put_var_rgen(var_name,title,var,size(var))
+     CALL put_var_rgen(pass, var_name,title,var,size(var))
 
   END SUBROUTINE put_var_r1
  
-  SUBROUTINE put_var_r2(var_name,title,var)
+  SUBROUTINE put_var_r2(pass, var_name,title,var)
    IMPLICIT NONE
+     INTEGER, INTENT(IN)            :: pass
      CHARACTER(LEN=*),INTENT(IN) :: var_name
      CHARACTER(LEN=*),INTENT(IN) :: title
      REAL,INTENT(IN)             :: var(:,:)
      
-     CALL put_var_rgen(var_name,title,var,size(var))
+     CALL put_var_rgen(pass, var_name,title,var,size(var))
 
   END SUBROUTINE put_var_r2     
   
-  SUBROUTINE put_var_r3(var_name,title,var)
+  SUBROUTINE put_var_r3(pass, var_name,title,var)
    IMPLICIT NONE
+     INTEGER, INTENT(IN)            :: pass
      CHARACTER(LEN=*),INTENT(IN) :: var_name
      CHARACTER(LEN=*),INTENT(IN) :: title
      REAL,INTENT(IN)             :: var(:,:,:)
      
-     CALL put_var_rgen(var_name,title,var,size(var))
+     CALL put_var_rgen(pass, var_name,title,var,size(var))
 
   END SUBROUTINE put_var_r3
 
-  SUBROUTINE put_var_rgen(var_name,title,var,var_size)
+  SUBROUTINE put_var_rgen(pass, var_name,title,var,var_size)
   USE netcdf
   USE dimphy
   USE mod_phys_lmdz_para
   IMPLICIT NONE
-     CHARACTER(LEN=*),INTENT(IN) :: var_name
-     CHARACTER(LEN=*),INTENT(IN) :: title
-     INTEGER,INTENT(IN)          :: var_size
-     REAL,INTENT(IN)             :: var(var_size)
-     
-     INTEGER :: ierr
-     INTEGER :: nvarid
+    INTEGER, INTENT(IN)         :: pass
+    CHARACTER(LEN=*),INTENT(IN) :: var_name
+    CHARACTER(LEN=*),INTENT(IN) :: title
+    INTEGER,INTENT(IN)          :: var_size
+    REAL,INTENT(IN)             :: var(var_size)
+    
+    INTEGER :: ierr
+    INTEGER :: nvarid
          
-    IF (is_mpi_root .AND. is_omp_root) THEN
+    IF (is_master) THEN
 
       IF (var_size/=length) THEN
@@ -463,17 +531,23 @@
         call abort_physic("", "", 1)
       ENDIF
-      
-      ierr = NF90_REDEF (nid_restart)
+
+     ! first pass : definition   
+      IF (pass==1) THEN
+        
+!      ierr = NF90_REDEF (nid_restart)
 
 #ifdef NC_DOUBLE
-      ierr = NF90_DEF_VAR (nid_restart, var_name, NF90_DOUBLE,(/ idim1 /),nvarid)
+        ierr = NF90_DEF_VAR (nid_restart, var_name, NF90_DOUBLE,(/ idim1 /),nvarid)
 #else
-      ierr = NF90_DEF_VAR (nid_restart, var_name, NF90_FLOAT,(/ idim1 /),nvarid)
+        ierr = NF90_DEF_VAR (nid_restart, var_name, NF90_FLOAT,(/ idim1 /),nvarid)
 #endif
-      IF (LEN_TRIM(title)>0) ierr = NF90_PUT_ATT (nid_restart,nvarid,"title", title)
-      ierr = NF90_ENDDEF(nid_restart)
-     
-      ierr = NF90_PUT_VAR(nid_restart,nvarid,var)
-
+        IF (LEN_TRIM(title)>0) ierr = NF90_PUT_ATT (nid_restart,nvarid,"title", title)
+!      ierr = NF90_ENDDEF(nid_restart)
+
+    ! second pass : write     
+      ELSE IF (pass==2) THEN 
+        ierr = NF90_INQ_VARID(nid_restart, var_name, nvarid)
+        ierr = NF90_PUT_VAR(nid_restart,nvarid,var)
+      ENDIF
     ENDIF
     
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/limit_read_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/limit_read_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/limit_read_mod.F90	(revision 3605)
@@ -1,4 +1,4 @@
 !
-! $Header$
+! $Id$
 !
 MODULE limit_read_mod
@@ -31,4 +31,26 @@
 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 
+
+  SUBROUTINE init_limit_read(first_day)
+  USE mod_grid_phy_lmdz
+  USE surface_data
+  USE mod_phys_lmdz_para
+#ifdef CPP_XIOS
+  USE XIOS
+#endif
+  IMPLICIT NONE
+    INTEGER, INTENT(IN) :: first_day
+    
+    
+    IF ( type_ocean /= 'couple') THEN
+      IF (grid_type==unstructured) THEN
+#ifdef CPP_XIOS
+        IF (is_omp_master) CALL xios_set_file_attr("limit_read",enabled=.TRUE.,record_offset=first_day)
+#endif
+      ENDIF  
+    ENDIF
+
+  END SUBROUTINE init_limit_read
+  
   SUBROUTINE limit_read_frac(itime, dtime, jour, pctsrf_new, is_modified)
 !
@@ -150,5 +172,8 @@
     USE phys_cal_mod, ONLY : calend, year_len
     USE print_control_mod, ONLY: lunout, prt_level
-
+#ifdef CPP_XIOS
+    USE XIOS, ONLY: xios_recv_field
+#endif
+    
     IMPLICIT NONE
     
@@ -179,4 +204,10 @@
     REAL, DIMENSION(klon_glo)                 :: rug_glo  ! rugosity at global grid
     REAL, DIMENSION(klon_glo)                 :: alb_glo  ! albedo at global grid
+
+    REAL, DIMENSION(klon_mpi,nbsrf)           :: pct_mpi  ! fraction at global grid
+    REAL, DIMENSION(klon_mpi)                 :: sst_mpi  ! sea-surface temperature at global grid
+    REAL, DIMENSION(klon_mpi)                 :: rug_mpi  ! rugosity at global grid
+    REAL, DIMENSION(klon_mpi)                 :: alb_mpi  ! albedo at global grid
+
     CHARACTER(len=20)                         :: modname='limit_read_mod'     
     CHARACTER(LEN=99)                         :: abort_message, calendar, str
@@ -220,13 +251,21 @@
           END IF
 
-          !--- ERROR IF FILE RECORDS NUMBER IS NOT EQUAL TO EXPECTED NUMBER OF DAYS
-          ierr=NF90_INQUIRE(nid, UnlimitedDimID=ndimid)
+          !--- ERROR IF FILE RECORDS NUMBER IS NOT EQUAL TO EXPECTED NUMBER OF DAYS          
+          IF (grid_type==unstructured) THEN
+            ierr=NF90_INQ_DIMID(nid,"time_year",ndimid)
+          ELSE
+            ierr=NF90_INQUIRE(nid, UnlimitedDimID=ndimid)
+          ENDIF
           ierr=NF90_INQUIRE_DIMENSION(nid, ndimid, len=nn)
-          WRITE(abort_message,'(a,2(i3,a))')'limit.nc records number (',nn,') does no'//&
+          WRITE(abort_message,'(a,2(i0,a))')'limit.nc records number (',nn,') does no'//&
             't match year length (',year_len,')'
           IF(nn/=year_len) CALL abort_physic(modname,abort_message,1)
 
           !--- ERROR IF FILES AND LMDZ HORIZONTAL RESOLUTIONS DO NOT MATCH
-          ierr=NF90_INQ_DIMID(nid, 'points_physiques', ndimid)
+          IF (grid_type==unstructured) THEN
+            ierr=NF90_INQ_DIMID(nid, 'cell', ndimid)
+          ELSE
+            ierr=NF90_INQ_DIMID(nid, 'points_physiques', ndimid)
+          ENDIF
           ierr=NF90_INQUIRE_DIMENSION(nid, ndimid, len=nn)
           WRITE(abort_message,'(a,2(i0,a))')'limit.nc horizontal number of cells (',nn, &
@@ -249,9 +288,54 @@
 
     is_modified = .FALSE.
-    IF (MOD(itime-1, lmt_pas) == 0 .OR. jour_lu /= jour ) THEN   ! time to read
+!ym    IF (MOD(itime-1, lmt_pas) == 0 .OR. jour_lu /= jour ) THEN   ! time to read
+!  not REALLY PERIODIC
+    IF (MOD(itime-1, lmt_pas) == 0 .OR. (jour_lu /= jour .AND. grid_type /= unstructured)) THEN   ! time to read
+!    IF (MOD(itime-1, lmt_pas) == 0) THEN   ! time to read
        jour_lu = jour
        is_modified = .TRUE.
+
+      IF (grid_type==unstructured) THEN
+
+#ifdef CPP_XIOS
+        IF ( type_ocean /= 'couple') THEN
+
+           IF (is_omp_master) CALL xios_recv_field("foce_limin",pct_mpi(:,is_oce))
+           IF (is_omp_master) CALL xios_recv_field("fsic_limin",pct_mpi(:,is_sic))
+  !         IF (read_continents .OR. itime == 1) THEN
+           IF (is_omp_master) CALL xios_recv_field("fter_limin",pct_mpi(:,is_ter))
+           IF (is_omp_master) CALL xios_recv_field("flic_limin",pct_mpi(:,is_lic))
+  !         ENDIF
+         ENDIF! type_ocean /= couple
+         
+         IF ( type_ocean /= 'couple') THEN                    
+             IF (is_omp_master) CALL xios_recv_field("sst_limin",sst_mpi)
+         ENDIF
+       
+         IF (.NOT. ok_veget) THEN
+           IF (is_omp_master) CALL xios_recv_field("alb_limin",alb_mpi)
+           IF (is_omp_master) CALL xios_recv_field("rug_limin",rug_mpi)
+         ENDIF
+
+       IF ( type_ocean /= 'couple') THEN
+          CALL Scatter_omp(sst_mpi,sst)
+          CALL Scatter_omp(pct_mpi(:,is_oce),pctsrf(:,is_oce))
+          CALL Scatter_omp(pct_mpi(:,is_sic),pctsrf(:,is_sic))
+!          IF (read_continents .OR. itime == 1) THEN
+             CALL Scatter_omp(pct_mpi(:,is_ter),pctsrf(:,is_ter))
+             CALL Scatter_omp(pct_mpi(:,is_lic),pctsrf(:,is_lic))
+!          END IF
+       END IF
+
+       IF (.NOT. ok_veget) THEN
+          CALL Scatter_omp(alb_mpi, albedo)
+          CALL Scatter_omp(rug_mpi, rugos)
+       END IF
+#endif
+
+ 
+     ELSE      ! grid_type==regular
+
 !$OMP MASTER  ! Only master thread
-       IF (is_mpi_root) THEN ! Only master processus
+       IF (is_mpi_root) THEN ! Only master processus!
 
           ierr = NF90_OPEN ('limit.nc', NF90_NOWRITE, nid)
@@ -371,4 +455,6 @@
        END IF
 
+      ENDIF ! Grid type
+
     ENDIF ! time to read
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/mo_simple_plumes.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/mo_simple_plumes.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/mo_simple_plumes.F90	(revision 3605)
@@ -78,4 +78,7 @@
     !
     INTEGER :: iret, ncid, DimID, VarID, xdmy
+    CHARACTER (len = 50)     :: modname = 'mo_simple_plumes.sp_setup'
+    CHARACTER (len = 80)     :: abort_message
+
     !
     ! ---------- 
@@ -84,5 +87,8 @@
        !    
        iret = nf90_open("MACv2.0-SP_v1.nc", NF90_NOWRITE, ncid)
-       IF (iret /= NF90_NOERR) STOP 'NetCDF File not opened'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF File not opened'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        !
        ! read dimensions and make sure file conforms to expected size
@@ -90,17 +96,29 @@
        iret = nf90_inq_dimid(ncid, "plume_number"  , DimId)
        iret = nf90_inquire_dimension(ncid, DimId, len = xdmy)
-       IF (xdmy /= nplumes) STOP 'NetCDF improperly dimensioned -- plume_number'
+       IF (xdmy /= nplumes) THEN
+          abort_message='NetCDF improperly dimensioned -- plume_number'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        !
        iret = nf90_inq_dimid(ncid, "plume_feature", DimId)
        iret = nf90_inquire_dimension(ncid, DimId, len = xdmy)
-       IF (xdmy /= nfeatures) STOP 'NetCDF improperly dimensioned -- plume_feature'
+       IF (xdmy /= nfeatures) THEN
+          abort_message='NetCDF improperly dimensioned -- plume_feature'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        !
        iret = nf90_inq_dimid(ncid, "year_fr"   , DimId)
        iret = nf90_inquire_dimension(ncid, DimID, len = xdmy)
-       IF (xdmy /= ntimes) STOP 'NetCDF improperly dimensioned -- year_fr'
+       IF (xdmy /= ntimes) THEN
+          abort_message='NetCDF improperly dimensioned -- year_fr'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        !
        iret = nf90_inq_dimid(ncid, "years"   , DimId)
        iret = nf90_inquire_dimension(ncid, DimID, len = xdmy)
-       IF (xdmy /= nyears) STOP 'NetCDF improperly dimensioned -- years'
+       IF (xdmy /= nyears) THEN
+          abort_message='NetCDF improperly dimensioned -- years'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        !
        ! read variables that define the simple plume climatology
@@ -108,54 +126,105 @@
        iret = nf90_inq_varid(ncid, "plume_lat", VarId)
        iret = nf90_get_var(ncid, VarID, plume_lat(:), start=(/1/),count=(/nplumes/))
-       IF (iret /= NF90_NOERR) STOP 'NetCDF Error reading plume_lat'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF Error reading plume_lat'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        iret = nf90_inq_varid(ncid, "plume_lon", VarId)
        iret = nf90_get_var(ncid, VarID, plume_lon(:), start=(/1/),count=(/nplumes/))
-       IF (iret /= NF90_NOERR) STOP 'NetCDF Error reading plume_lon'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF Error reading plume_lon'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        iret = nf90_inq_varid(ncid, "beta_a"   , VarId)
        iret = nf90_get_var(ncid, VarID, beta_a(:)   , start=(/1/),count=(/nplumes/))
-       IF (iret /= NF90_NOERR) STOP 'NetCDF Error reading beta_a'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF Error reading beta_a'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        iret = nf90_inq_varid(ncid, "beta_b"   , VarId)
        iret = nf90_get_var(ncid, VarID, beta_b(:)   , start=(/1/),count=(/nplumes/))
-       IF (iret /= NF90_NOERR) STOP 'NetCDF Error reading beta_b'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF Error reading beta_b'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        iret = nf90_inq_varid(ncid, "aod_spmx" , VarId)
        iret = nf90_get_var(ncid, VarID, aod_spmx(:)  , start=(/1/),count=(/nplumes/))
-       IF (iret /= NF90_NOERR) STOP 'NetCDF Error reading aod_spmx'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF Error reading aod_spmx'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        iret = nf90_inq_varid(ncid, "aod_fmbg" , VarId)
        iret = nf90_get_var(ncid, VarID, aod_fmbg(:)  , start=(/1/),count=(/nplumes/))
-       IF (iret /= NF90_NOERR) STOP 'NetCDF Error reading aod_fmbg'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF Error reading aod_fmbg'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        iret = nf90_inq_varid(ncid, "ssa550"   , VarId)
        iret = nf90_get_var(ncid, VarID, ssa550(:)  , start=(/1/),count=(/nplumes/))
-       IF (iret /= NF90_NOERR) STOP 'NetCDF Error reading ssa550'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF Error reading ssa550'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        iret = nf90_inq_varid(ncid, "asy550"   , VarId)
        iret = nf90_get_var(ncid, VarID, asy550(:)  , start=(/1/),count=(/nplumes/))
-       IF (iret /= NF90_NOERR) STOP 'NetCDF Error reading asy550'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF Error reading asy550'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        iret = nf90_inq_varid(ncid, "angstrom" , VarId)
        iret = nf90_get_var(ncid, VarID, angstrom(:), start=(/1/),count=(/nplumes/))
-       IF (iret /= NF90_NOERR) STOP 'NetCDF Error reading angstrom'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF Error reading angstrom'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        !
        iret = nf90_inq_varid(ncid, "sig_lat_W"     , VarId)
        iret = nf90_get_var(ncid, VarID, sig_lat_W(:,:)    , start=(/1,1/),count=(/nfeatures,nplumes/))
-       IF (iret /= NF90_NOERR) STOP 'NetCDF Error reading sig_lat_W'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF Error reading sig_lat_W'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        iret = nf90_inq_varid(ncid, "sig_lat_E"     , VarId)
        iret = nf90_get_var(ncid, VarID, sig_lat_E(:,:)    , start=(/1,1/),count=(/nfeatures,nplumes/))
-       IF (iret /= NF90_NOERR) STOP 'NetCDF Error reading sig_lat_E'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF Error reading sig_lat_E'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        iret = nf90_inq_varid(ncid, "sig_lon_E"     , VarId)
        iret = nf90_get_var(ncid, VarID, sig_lon_E(:,:)    , start=(/1,1/),count=(/nfeatures,nplumes/))
-       IF (iret /= NF90_NOERR) STOP 'NetCDF Error reading sig_lon_E'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF Error reading sig_lon_E'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        iret = nf90_inq_varid(ncid, "sig_lon_W"     , VarId)
        iret = nf90_get_var(ncid, VarID, sig_lon_W(:,:)    , start=(/1,1/),count=(/nfeatures,nplumes/))
-       IF (iret /= NF90_NOERR) STOP 'NetCDF Error reading sig_lon_W'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF Error reading sig_lon_W'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        iret = nf90_inq_varid(ncid, "theta"         , VarId)
        iret = nf90_get_var(ncid, VarID, theta(:,:)        , start=(/1,1/),count=(/nfeatures,nplumes/))
-       IF (iret /= NF90_NOERR) STOP 'NetCDF Error reading theta'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF Error reading theta'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        iret = nf90_inq_varid(ncid, "ftr_weight"    , VarId)
        iret = nf90_get_var(ncid, VarID, ftr_weight(:,:)   , start=(/1,1/),count=(/nfeatures,nplumes/))
-       IF (iret /= NF90_NOERR) STOP 'NetCDF Error reading plume_lat'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF Error reading plume_lat'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        iret = nf90_inq_varid(ncid, "year_weight"   , VarId)
        iret = nf90_get_var(ncid, VarID, year_weight(:,:)  , start=(/1,1/),count=(/nyears,nplumes   /))
-       IF (iret /= NF90_NOERR) STOP 'NetCDF Error reading year_weight'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF Error reading year_weight'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        iret = nf90_inq_varid(ncid, "ann_cycle"     , VarId)
        iret = nf90_get_var(ncid, VarID, ann_cycle(:,:,:)  , start=(/1,1,1/),count=(/nfeatures,ntimes,nplumes/))
-       IF (iret /= NF90_NOERR) STOP 'NetCDF Error reading ann_cycle'
+       IF (iret /= NF90_NOERR) THEN
+          abort_message='NetCDF Error reading ann_cycle'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
        !
        iret = nf90_close(ncid)
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/mod_synchro_omp.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/mod_synchro_omp.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/mod_synchro_omp.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 MODULE mod_synchro_omp
 
@@ -21,4 +24,6 @@
   IMPLICIT NONE
   LOGICAL :: out
+  CHARACTER (LEN=20) :: modname='synchro_omp'
+  CHARACTER (LEN=80) :: abort_message
   
     out=.FALSE.
@@ -46,5 +51,6 @@
 
     IF (exit_omp/=0) THEN
-      STOP 'synchro_omp'
+       abort_message='synchro_omp'
+       CALL abort_physic(modname,abort_message,1)
     ENDIF
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/moy_undefSTD.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/moy_undefSTD.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/moy_undefSTD.F90	(revision 3605)
@@ -75,5 +75,5 @@
 
     IF (n==1 .AND. itap==itapm1 .OR. n>1 .AND. mod(itap,nint(freq_outnmc(n)/ & 
-        dtime))==0) THEN
+        phys_tstep))==0) THEN
 
       ! print*,'moy_undefSTD n itap itapm1',n,itap,itapm1
@@ -140,5 +140,5 @@
         END DO !i
       END DO !k
-    END IF !MOD(itap,NINT(freq_outNMC(n)/dtime)).EQ.0
+    END IF !MOD(itap,NINT(freq_outNMC(n)/phys_tstep)).EQ.0
 
   END DO !n
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/oasis.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/oasis.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/oasis.F90	(revision 3605)
@@ -104,7 +104,12 @@
 #ifdef CPP_XIOS
     USE wxios, ONLY : wxios_context_init 
+    USE xios  
 #endif
     USE print_control_mod, ONLY: lunout
-    USE mod_grid_phy_lmdz, ONLY: nbp_lon, nbp_lat
+    USE mod_grid_phy_lmdz, ONLY: nbp_lon, nbp_lat, grid_type, unstructured, regular_lonlat
+    USE geometry_mod, ONLY: ind_cell_glo                    
+    USE mod_phys_lmdz_mpi_data, ONLY: klon_mpi_para_nb
+    
+
 
 ! Local variables
@@ -113,5 +118,5 @@
     INTEGER                            :: ierror, il_commlocal
     INTEGER                            :: il_part_id
-    INTEGER, DIMENSION(3)              :: ig_paral
+    INTEGER, ALLOCATABLE               :: ig_paral(:)
     INTEGER, DIMENSION(2)              :: il_var_nodims
     INTEGER, DIMENSION(4)              :: il_var_actual_shape
@@ -136,5 +141,12 @@
 ! Define the model name
 !
-    clmodnam = 'LMDZ'       ! as in $NBMODEL in Cpl/Nam/namcouple.tmp
+    IF (grid_type==unstructured) THEN
+        clmodnam = 'icosa'                 ! as in $NBMODEL in Cpl/Nam/namcouple.tmp
+    ELSE IF (grid_type==regular_lonlat) THEN
+        clmodnam = 'LMDZ'                  ! as in $NBMODEL in Cpl/Nam/namcouple.tmp
+    ELSE
+	abort_message='Pb : type of grid unknown'
+	CALL abort_physic(modname,abort_message,1)
+    ENDIF
 
 
@@ -236,9 +248,30 @@
 ! Domain decomposition
 !************************************************************************************
-    ig_paral(1) = 1                            ! apple partition for //
-    ig_paral(2) = (jj_begin-1)*nbp_lon+ii_begin-1  ! offset
-    ig_paral(3) = (jj_end*nbp_lon+ii_end) - (jj_begin*nbp_lon+ii_begin) + 1
-
-    IF (mpi_rank==mpi_size-1) ig_paral(3)=ig_paral(3)+nbp_lon-1
+    IF (grid_type==unstructured) THEN
+
+      ALLOCATE( ig_paral(klon_mpi_para_nb(mpi_rank) + 2) ) 
+
+      ig_paral(1) = 4                                      ! points partition for //
+      ig_paral(2) = klon_mpi_para_nb(mpi_rank)             ! nb of local cells
+
+      DO jf=1, klon_mpi_para_nb(mpi_rank)
+        ig_paral(2+jf) = ind_cell_glo(jf)
+      ENDDO
+
+    ELSE IF (grid_type==regular_lonlat) THEN
+
+      ALLOCATE( ig_paral(3) )
+
+      ig_paral(1) = 1                            ! apple partition for //
+      ig_paral(2) = (jj_begin-1)*nbp_lon+ii_begin-1  ! offset
+      ig_paral(3) = (jj_end*nbp_lon+ii_end) - (jj_begin*nbp_lon+ii_begin) + 1
+
+      IF (mpi_rank==mpi_size-1) ig_paral(3)=ig_paral(3)+nbp_lon-1
+    ELSE
+      abort_message='Pb : type of grid unknown'
+      CALL abort_physic(modname,abort_message,1)
+    ENDIF
+
+
     WRITE(lunout,*) mpi_rank,'ig_paral--->',ig_paral(2),ig_paral(3)
     
@@ -253,11 +286,11 @@
     ENDIF
 
-    il_var_nodims(1) = 2
-    il_var_nodims(2) = 1
-
-    il_var_actual_shape(1) = 1
-    il_var_actual_shape(2) = nbp_lon
-    il_var_actual_shape(3) = 1
-    il_var_actual_shape(4) = nbp_lat
+    il_var_nodims(1) = 2                        ! rank of field array (1d or 2d)
+    il_var_nodims(2) = 1                        ! always 1 in current oasis version" doc oasis3mct p18
+
+    il_var_actual_shape(1) = 1                  ! min of 1st dimension (always 1)
+    il_var_actual_shape(2) = nbp_lon            ! max of 1st dimension
+    il_var_actual_shape(3) = 1                  ! min of 2nd dimension (always 1)
+    il_var_actual_shape(4) = nbp_lat            ! max of 2nd dimension
    
     il_var_type = PRISM_Real
@@ -302,4 +335,7 @@
 ! End definition
 !************************************************************************************
+#ifdef CPP_XIOS
+    CALL xios_oasis_enddef()
+#endif
     CALL prism_enddef_proto(ierror)
     IF (ierror .NE. PRISM_Ok) THEN
@@ -311,5 +347,5 @@
 
 #ifdef CPP_XIOS
-    CALL wxios_context_init()
+!    CALL wxios_context_init()
 #endif
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/orografi_strato.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/orografi_strato.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/orografi_strato.F90	(revision 3605)
@@ -1819,4 +1819,5 @@
   USE mod_phys_lmdz_para
   USE mod_grid_phy_lmdz
+  USE geometry_mod
   IMPLICIT NONE
 
@@ -1832,6 +1833,6 @@
   INTEGER jk
   REAL zpr, ztop, zsigt, zpm1r
-  REAL :: pplay_glo(klon_glo, nlev)
-  REAL :: paprs_glo(klon_glo, nlev+1)
+  INTEGER :: cell,ij,nstra_tmp,nktopg_tmp
+  REAL :: current_dist, dist_min,dist_min_glo
 
   ! *       1.    SET THE VALUES OF THE PARAMETERS
@@ -1848,20 +1849,52 @@
   ! old  ZSIGT=0.85
 
-  CALL gather(pplay, pplay_glo)
-  CALL bcast(pplay_glo)
-  CALL gather(paprs, paprs_glo)
-  CALL bcast(paprs_glo)
-
-  DO jk = 1, nlev
-    zpm1r = pplay_glo(klon_glo/2+1, jk)/paprs_glo(klon_glo/2+1, 1)
-    IF (zpm1r>=zsigt) THEN
-      nktopg = jk
-    END IF
-    zpm1r = pplay_glo(klon_glo/2+1, jk)/paprs_glo(klon_glo/2+1, 1)
-    IF (zpm1r>=ztop) THEN
-      nstra = jk
-    END IF
-  END DO
-
+
+!ym Take the point at equator close to (0,0) coordinates.
+  dist_min=360
+  dist_min_glo=360.
+  cell=-1
+  DO ij=1,klon
+    current_dist=sqrt(longitude_deg(ij)**2+latitude_deg(ij)**2)
+    current_dist=current_dist*(1+(1e-10*ind_cell_glo(ij))/klon_glo) ! For point unicity
+    IF (dist_min>current_dist) THEN
+      dist_min=current_dist
+      cell=ij    
+    ENDIF  
+  ENDDO
+  
+  !PRINT *, 'SUGWD distmin cell=', dist_min,cell
+  CALL reduce_min(dist_min,dist_min_glo)
+  CALL bcast(dist_min_glo)
+  IF (dist_min/=dist_min_glo) cell=-1
+!ym in future find the point at equator close to (0,0) coordinates.
+  PRINT *, 'SUGWD distmin dist_min_glo cell=', dist_min,dist_min_glo,cell
+
+  nktopg_tmp=nktopg
+  nstra_tmp=nstra
+  
+  IF (cell/=-1) THEN
+
+    !print*,'SUGWD shape ',shape(pplay),cell+1
+
+    DO jk = 1, nlev
+      !zpm1r = pplay(cell+1, jk)/paprs(cell+1, 1)
+      zpm1r = pplay(cell, jk)/paprs(cell, 1)
+      IF (zpm1r>=zsigt) THEN
+        nktopg_tmp = jk
+      END IF
+      IF (zpm1r>=ztop) THEN
+        nstra_tmp = jk
+      END IF
+    END DO
+  ELSE
+    nktopg_tmp=0
+    nstra_tmp=0
+  ENDIF
+  
+  CALL reduce_sum(nktopg_tmp,nktopg)
+  CALL bcast(nktopg)
+  CALL reduce_sum(nstra_tmp,nstra)
+  CALL bcast(nstra)
+  
   ! inversion car dans orodrag on compte les niveaux a l'envers
   nktopg = nlev - nktopg + 1
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/pbl_surface_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/pbl_surface_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/pbl_surface_mod.F90	(revision 3605)
@@ -60,4 +60,5 @@
     USE print_control_mod, ONLY: lunout
     USE ioipsl_getin_p_mod, ONLY : getin_p
+    IMPLICIT NONE
 
     INCLUDE "dimsoil.h"
@@ -288,5 +289,5 @@
     USE indice_sol_mod
     USE time_phylmdz_mod,   ONLY : day_ini,annee_ref,itau_phy
-    USE mod_grid_phy_lmdz,  ONLY : nbp_lon, nbp_lat
+    USE mod_grid_phy_lmdz,  ONLY : nbp_lon, nbp_lat, grid1dto2d_glo
     USE print_control_mod,  ONLY : prt_level,lunout
     USE ioipsl_getin_p_mod, ONLY : getin_p
@@ -861,10 +862,10 @@
           idayref = day_ini
           CALL ymds2ju(annee_ref, 1, idayref, 0.0, zjulian)
-          CALL gr_fi_ecrit(1,klon,nbp_lon,nbp_lat,rlon,zx_lon)
+          CALL grid1dTo2d_glo(rlon,zx_lon)
           DO i = 1, nbp_lon
              zx_lon(i,1) = rlon(i+1)
              zx_lon(i,nbp_lat) = rlon(i+1)
           ENDDO
-          CALL gr_fi_ecrit(1,klon,nbp_lon,nbp_lat,rlat,zx_lat)
+          CALL grid1dTo2d_glo(rlat,zx_lat)
           CALL histbeg("sous_index",nbp_lon,zx_lon(:,1),nbp_lat,zx_lat(1,:), &
                1,nbp_lon,1,nbp_lat, &
@@ -1951,5 +1952,5 @@
                itap, dtime, jour, knon, ni, &
 !!jyg               ypplay(:,1), zgeo1/RG, ycdragh, ycdragm, yrain_f, ysnow_f, yt(:,1), yq(:,1),&
-               ypplay(:,1), zgeo1/RG, ycdragh, ycdragm, yrain_f, ysnow_f, yt1, yq1,&
+               ypplay(:,1), zgeo1(1:knon)/RG, ycdragh, ycdragm, yrain_f, ysnow_f, yt(:,1), yq(:,1),&    ! ym missing init
                AcoefH, AcoefQ, BcoefH, BcoefQ, &
                AcoefU, AcoefV, BcoefU, BcoefV, &
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/phyaqua_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/phyaqua_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/phyaqua_mod.F90	(revision 3605)
@@ -1,2 +1,5 @@
+!
+! $Id$
+!
 MODULE phyaqua_mod
   ! Routines complementaires pour la physique planetaire.
@@ -5,5 +8,5 @@
 CONTAINS
 
-  SUBROUTINE iniaqua(nlon, iflag_phys)
+  SUBROUTINE iniaqua(nlon,year_len,iflag_phys)
 
     ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
@@ -29,5 +32,10 @@
     USE indice_sol_mod
     USE nrtype, ONLY: pi
-    USE ioipsl
+!    USE ioipsl
+    USE mod_phys_lmdz_para, ONLY: is_master
+    USE mod_phys_lmdz_transfert_para, ONLY: bcast
+    USE mod_grid_phy_lmdz
+    USE ioipsl_getin_p_mod, ONLY : getin_p
+    USE phys_cal_mod , ONLY: calend, year_len_phy => year_len 
     IMPLICIT NONE
 
@@ -36,5 +44,5 @@
     include "dimsoil.h"
 
-    INTEGER, INTENT (IN) :: nlon, iflag_phys
+    INTEGER, INTENT (IN) :: nlon, year_len, iflag_phys
     ! IM ajout latfi, lonfi
 !    REAL, INTENT (IN) :: lonfi(nlon), latfi(nlon)
@@ -57,6 +65,4 @@
     INTEGER it, unit, i, k, itap
 
-    REAL airefi, zcufi, zcvfi
-
     REAL rugos, albedo
     REAL tsurf
@@ -64,9 +70,5 @@
     REAL qsol_f
     REAL rugsrel(nlon)
-    ! real zmea(nlon),zstd(nlon),zsig(nlon)
-    ! real zgam(nlon),zthe(nlon),zpic(nlon),zval(nlon)
-    ! real rlon(nlon),rlat(nlon)
     LOGICAL alb_ocean
-    ! integer demih_pas
 
     CHARACTER *80 ans, file_forctl, file_fordat, file_start
@@ -74,23 +76,18 @@
     CHARACTER *2 cnbl
 
-    REAL phy_nat(nlon, 360)
-    REAL phy_alb(nlon, 360)
-    REAL phy_sst(nlon, 360)
-    REAL phy_bil(nlon, 360)
-    REAL phy_rug(nlon, 360)
-    REAL phy_ice(nlon, 360)
-    REAL phy_fter(nlon, 360)
-    REAL phy_foce(nlon, 360)
-    REAL phy_fsic(nlon, 360)
-    REAL phy_flic(nlon, 360)
+    REAL phy_nat(nlon, year_len)
+    REAL phy_alb(nlon, year_len)
+    REAL phy_sst(nlon, year_len)
+    REAL phy_bil(nlon, year_len)
+    REAL phy_rug(nlon, year_len)
+    REAL phy_ice(nlon, year_len)
+    REAL phy_fter(nlon, year_len)
+    REAL phy_foce(nlon, year_len)
+    REAL phy_fsic(nlon, year_len)
+    REAL phy_flic(nlon, year_len)
 
     INTEGER, SAVE :: read_climoz = 0 ! read ozone climatology
-
-    ! intermediate variables to use getin (need to be "save" to be shared by
-    ! all threads)
-    INTEGER, SAVE :: nbapp_rad_omp
-    REAL, SAVE :: co2_ppm_omp, solaire_omp
-    LOGICAL, SAVE :: alb_ocean_omp
-    REAL, SAVE :: rugos_omp
+!$OMP THREADPRIVATE(read_climoz)
+
     ! -------------------------------------------------------------------------
     ! declaration pour l'appel a phyredem
@@ -117,8 +114,10 @@
     INTEGER l, ierr, aslun
 
-!    REAL longitude, latitude
     REAL paire
 
-!    DATA latitude, longitude/48., 0./
+    ! Local
+    CHARACTER (LEN=20) :: modname='phyaqua'
+    CHARACTER (LEN=80) :: abort_message
+
 
     ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
@@ -130,4 +129,13 @@
     ! -------------------------------
 
+    !IF (calend .EQ. "earth_360d") Then
+      year_len_phy = year_len
+    !END IF
+    
+    if (year_len.ne.360) then
+      write (*,*) year_len
+      write (*,*) 'iniaqua: 360 day calendar is required !'
+      stop
+    endif
 
     type_aqua = iflag_phys/100
@@ -137,5 +145,6 @@
     IF (klon/=nlon) THEN
       WRITE (*, *) 'iniaqua: klon=', klon, ' nlon=', nlon
-      STOP 'probleme de dimensions dans iniaqua'
+      abort_message= 'probleme de dimensions dans iniaqua'
+      CALL abort_physic(modname,abort_message,1)
     END IF
     CALL phys_state_var_init(read_climoz)
@@ -148,10 +157,4 @@
     time = 0.
 
-    ! IM ajout latfi, lonfi
-!    rlatd = latfi
-!    rlond = lonfi
-!    rlat = rlatd*180./pi
-!    rlon = rlond*180./pi
-
     ! -----------------------------------------------------------------------
     ! initialisations de la physique
@@ -160,13 +163,7 @@
     day_ini = day_ref
     day_end = day_ini + ndays
-!    airefi = 1.
-!    zcufi = 1.
-!    zcvfi = 1.
-    !$OMP MASTER
-    nbapp_rad_omp = 24
-    CALL getin('nbapp_rad', nbapp_rad_omp)
-    !$OMP END MASTER
-    !$OMP BARRIER
-    nbapp_rad = nbapp_rad_omp
+
+    nbapp_rad = 24
+    CALL getin_p('nbapp_rad', nbapp_rad)
 
     ! ---------------------------------------------------------------------
@@ -175,20 +172,17 @@
     ! Initialisations des constantes
     ! Ajouter les manquants dans planete.def... (albedo etc)
-    !$OMP MASTER
-    co2_ppm_omp = 348.
-    CALL getin('co2_ppm', co2_ppm_omp)
-    solaire_omp = 1365.
-    CALL getin('solaire', solaire_omp)
+    co2_ppm = 348.
+    CALL getin_p('co2_ppm', co2_ppm)
+
+    solaire = 1365.
+    CALL getin_p('solaire', solaire)
+ 
     ! CALL getin('albedo',albedo) ! albedo is set below, depending on
     ! type_aqua
-    alb_ocean_omp = .TRUE.
-    CALL getin('alb_ocean', alb_ocean_omp)
-    !$OMP END MASTER
-    !$OMP BARRIER
-    co2_ppm = co2_ppm_omp
+    alb_ocean = .TRUE.
+    CALL getin_p('alb_ocean', alb_ocean)
+
     WRITE (*, *) 'iniaqua: co2_ppm=', co2_ppm
-    solaire = solaire_omp
     WRITE (*, *) 'iniaqua: solaire=', solaire
-    alb_ocean = alb_ocean_omp
     WRITE (*, *) 'iniaqua: alb_ocean=', alb_ocean
 
@@ -226,10 +220,6 @@
     END IF
 
-    !$OMP MASTER
-    rugos_omp = rugos
-    CALL getin('rugos', rugos_omp)
-    !$OMP END MASTER
-    !$OMP BARRIER
-    rugos = rugos_omp
+    CALL getin_p('rugos', rugos)
+
     WRITE (*, *) 'iniaqua: rugos=', rugos
     zmasq(:) = pctsrf(:, is_ter)
@@ -246,5 +236,5 @@
     ! endif !alb_ocean
 
-    DO i = 1, 360
+    DO i = 1, year_len
       ! IM Terraplanete   phy_sst(:,i) = 260.+50.*cos(rlatd(:))**2
       ! IM ajout calcul profil sst selon le cas considere (cf. FBr)
@@ -262,7 +252,12 @@
     CALL profil_sst(nlon, latitude, type_profil, phy_sst)
 
-    CALL writelim(klon, phy_nat, phy_alb, phy_sst, phy_bil, phy_rug, phy_ice, &
-      phy_fter, phy_foce, phy_flic, phy_fsic)
-
+    IF (grid_type==unstructured) THEN
+      CALL writelim_unstruct(klon, phy_nat, phy_alb, phy_sst, phy_bil, phy_rug, phy_ice, &
+                             phy_fter, phy_foce, phy_flic, phy_fsic)
+    ELSE
+      
+       CALL writelim(klon, phy_nat, phy_alb, phy_sst, phy_bil, phy_rug, phy_ice, &
+                     phy_fter, phy_foce, phy_flic, phy_fsic)
+    ENDIF
 
     ! ---------------------------------------------------------------------
@@ -339,5 +334,5 @@
     PRINT *, 'iniaqua: before phyredem'
 
-    pbl_tke(:,:,:)=1.e-8
+    pbl_tke(:,:,:) = 1.e-8 
     falb1 = albedo
     falb2 = albedo
@@ -349,5 +344,5 @@
     wake_deltaq = 0.
     wake_s = 0.
-    wake_dens = 0. 
+    wake_dens = 0.
     wake_cstar = 0.
     wake_pe = 0.
@@ -360,4 +355,29 @@
     alp_bl =0.
     treedrg(:,:,:)=0.
+
+    u10m = 0.
+    v10m = 0.
+
+    ql_ancien   = 0.
+    qs_ancien   = 0.
+    u_ancien    = 0.
+    v_ancien    = 0.
+    prw_ancien  = 0.
+    prlw_ancien = 0.
+    prsw_ancien = 0.  
+
+    ale_wake    = 0.
+    ale_bl_stat = 0.  
+
+
+!ym error : the sub surface dimension is the third not second : forgotten for iniaqua
+!    falb_dir(:,is_ter,:)=0.08; falb_dir(:,is_lic,:)=0.6
+!    falb_dir(:,is_oce,:)=0.5;  falb_dir(:,is_sic,:)=0.6
+    falb_dir(:,:,is_ter)=0.08; falb_dir(:,:,is_lic)=0.6
+    falb_dir(:,:,is_oce)=0.5;  falb_dir(:,:,is_sic)=0.6
+
+!ym falb_dif has been forgotten, initialize with defaukt value found in phyetat0 or 0 ?
+!ym probably the uninitialized value was 0 for standard (regular grid) case
+    falb_dif(:,:,:)=0
 
 
@@ -488,11 +508,14 @@
   ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 
-  SUBROUTINE writelim(klon, phy_nat, phy_alb, phy_sst, phy_bil, phy_rug, &
+  SUBROUTINE writelim_unstruct(klon, phy_nat, phy_alb, phy_sst, phy_bil, phy_rug, &
       phy_ice, phy_fter, phy_foce, phy_flic, phy_fsic)
 
-    USE mod_phys_lmdz_para, ONLY: is_mpi_root, is_omp_root
-    USE mod_grid_phy_lmdz, ONLY: klon_glo
-    USE mod_phys_lmdz_transfert_para, ONLY: gather
+    USE mod_phys_lmdz_para, ONLY: is_omp_master, klon_mpi
+    USE mod_phys_lmdz_transfert_para, ONLY: gather_omp
+#ifdef CPP_XIOS
+    USE xios
+#endif
     IMPLICIT NONE
+
     include "netcdf.inc"
 
@@ -509,5 +532,61 @@
     REAL, INTENT (IN) :: phy_fsic(klon, 360)
 
-    REAL :: phy_glo(klon_glo, 360) ! temporary variable, to store phy_***(:)
+    REAL :: phy_mpi(klon_mpi, 360) ! temporary variable, to store phy_***(:)
+      ! on the whole physics grid
+ 
+#ifdef CPP_XIOS
+    PRINT *, 'writelim: Ecriture du fichier limit'
+
+    CALL gather_omp(phy_foce, phy_mpi)
+    IF (is_omp_master) CALL xios_send_field('foce_limout',phy_mpi)
+
+    CALL gather_omp(phy_fsic, phy_mpi)
+    IF (is_omp_master) CALL xios_send_field('fsic_limout',phy_mpi)
+      
+    CALL gather_omp(phy_fter, phy_mpi)
+    IF (is_omp_master) CALL xios_send_field('fter_limout',phy_mpi)
+      
+    CALL gather_omp(phy_flic, phy_mpi)
+    IF (is_omp_master) CALL xios_send_field('flic_limout',phy_mpi)
+
+    CALL gather_omp(phy_sst, phy_mpi)
+    IF (is_omp_master) CALL xios_send_field('sst_limout',phy_mpi)
+
+    CALL gather_omp(phy_bil, phy_mpi)
+    IF (is_omp_master) CALL xios_send_field('bils_limout',phy_mpi)
+
+    CALL gather_omp(phy_alb, phy_mpi)
+    IF (is_omp_master) CALL xios_send_field('alb_limout',phy_mpi)
+
+    CALL gather_omp(phy_rug, phy_mpi)
+    IF (is_omp_master) CALL xios_send_field('rug_limout',phy_mpi)
+#endif
+  END SUBROUTINE writelim_unstruct
+
+
+
+  SUBROUTINE writelim(klon, phy_nat, phy_alb, phy_sst, phy_bil, phy_rug, &
+      phy_ice, phy_fter, phy_foce, phy_flic, phy_fsic)
+
+    USE mod_phys_lmdz_para, ONLY: is_master
+    USE mod_grid_phy_lmdz, ONLY: klon_glo
+    USE mod_phys_lmdz_transfert_para, ONLY: gather
+    USE phys_cal_mod, ONLY: year_len
+    IMPLICIT NONE
+    include "netcdf.inc"
+
+    INTEGER, INTENT (IN) :: klon
+    REAL, INTENT (IN) :: phy_nat(klon, year_len)
+    REAL, INTENT (IN) :: phy_alb(klon, year_len)
+    REAL, INTENT (IN) :: phy_sst(klon, year_len)
+    REAL, INTENT (IN) :: phy_bil(klon, year_len)
+    REAL, INTENT (IN) :: phy_rug(klon, year_len)
+    REAL, INTENT (IN) :: phy_ice(klon, year_len)
+    REAL, INTENT (IN) :: phy_fter(klon, year_len)
+    REAL, INTENT (IN) :: phy_foce(klon, year_len)
+    REAL, INTENT (IN) :: phy_flic(klon, year_len)
+    REAL, INTENT (IN) :: phy_fsic(klon, year_len)
+
+    REAL :: phy_glo(klon_glo, year_len) ! temporary variable, to store phy_***(:)
       ! on the whole physics grid
     INTEGER :: k
@@ -522,5 +601,5 @@
     INTEGER id_fter, id_foce, id_fsic, id_flic
 
-    IF (is_mpi_root .AND. is_omp_root) THEN
+    IF (is_master) THEN
 
       PRINT *, 'writelim: Ecriture du fichier limit'
@@ -615,5 +694,5 @@
 
       ! write the 'times'
-      DO k = 1, 360
+      DO k = 1, year_len
 #ifdef NC_DOUBLE
         ierr = nf_put_var1_double(nid, id_tim, k, dble(k))
@@ -627,10 +706,10 @@
       END DO
 
-    END IF ! of if (is_mpi_root.and.is_omp_root)
+    END IF ! of if (is_master)
 
     ! write the fields, after having collected them on master
 
     CALL gather(phy_nat, phy_glo)
-    IF (is_mpi_root .AND. is_omp_root) THEN
+    IF (is_master) THEN
 #ifdef NC_DOUBLE
       ierr = nf_put_var_double(nid, id_nat, phy_glo)
@@ -645,5 +724,5 @@
 
     CALL gather(phy_sst, phy_glo)
-    IF (is_mpi_root .AND. is_omp_root) THEN
+    IF (is_master) THEN
 #ifdef NC_DOUBLE
       ierr = nf_put_var_double(nid, id_sst, phy_glo)
@@ -658,5 +737,5 @@
 
     CALL gather(phy_bil, phy_glo)
-    IF (is_mpi_root .AND. is_omp_root) THEN
+    IF (is_master) THEN
 #ifdef NC_DOUBLE
       ierr = nf_put_var_double(nid, id_bils, phy_glo)
@@ -671,5 +750,5 @@
 
     CALL gather(phy_alb, phy_glo)
-    IF (is_mpi_root .AND. is_omp_root) THEN
+    IF (is_master) THEN
 #ifdef NC_DOUBLE
       ierr = nf_put_var_double(nid, id_alb, phy_glo)
@@ -684,5 +763,5 @@
 
     CALL gather(phy_rug, phy_glo)
-    IF (is_mpi_root .AND. is_omp_root) THEN
+    IF (is_master) THEN
 #ifdef NC_DOUBLE
       ierr = nf_put_var_double(nid, id_rug, phy_glo)
@@ -697,5 +776,5 @@
 
     CALL gather(phy_fter, phy_glo)
-    IF (is_mpi_root .AND. is_omp_root) THEN
+    IF (is_master) THEN
 #ifdef NC_DOUBLE
       ierr = nf_put_var_double(nid, id_fter, phy_glo)
@@ -710,5 +789,5 @@
 
     CALL gather(phy_foce, phy_glo)
-    IF (is_mpi_root .AND. is_omp_root) THEN
+    IF (is_master) THEN
 #ifdef NC_DOUBLE
       ierr = nf_put_var_double(nid, id_foce, phy_glo)
@@ -723,5 +802,5 @@
 
     CALL gather(phy_fsic, phy_glo)
-    IF (is_mpi_root .AND. is_omp_root) THEN
+    IF (is_master) THEN
 #ifdef NC_DOUBLE
       ierr = nf_put_var_double(nid, id_fsic, phy_glo)
@@ -736,5 +815,5 @@
 
     CALL gather(phy_flic, phy_glo)
-    IF (is_mpi_root .AND. is_omp_root) THEN
+    IF (is_master) THEN
 #ifdef NC_DOUBLE
       ierr = nf_put_var_double(nid, id_flic, phy_glo)
@@ -749,5 +828,5 @@
 
     ! close file:
-    IF (is_mpi_root .AND. is_omp_root) THEN
+    IF (is_master) THEN
       ierr = nf_close(nid)
     END IF
@@ -759,16 +838,22 @@
   SUBROUTINE profil_sst(nlon, rlatd, type_profil, phy_sst)
     USE dimphy
+    USE phys_cal_mod , ONLY: year_len
     IMPLICIT NONE
 
     INTEGER nlon, type_profil, i, k, j
-    REAL :: rlatd(nlon), phy_sst(nlon, 360)
+    REAL :: rlatd(nlon), phy_sst(nlon, year_len)
     INTEGER imn, imx, amn, amx, kmn, kmx
     INTEGER p, pplus, nlat_max
     PARAMETER (nlat_max=72)
     REAL x_anom_sst(nlat_max)
-
-    IF (klon/=nlon) STOP 'probleme de dimensions dans iniaqua'
+    CHARACTER (LEN=20) :: modname='profil_sst'
+    CHARACTER (LEN=80) :: abort_message
+
+    IF (klon/=nlon) THEN
+       abort_message='probleme de dimensions dans profil_sst'
+       CALL abort_physic(modname,abort_message,1)
+    ENDIF
     WRITE (*, *) ' profil_sst: type_profil=', type_profil
-    DO i = 1, 360
+    DO i = 1, year_len
       ! phy_sst(:,i) = 260.+50.*cos(rlatd(:))**2
 
@@ -963,5 +1048,5 @@
     imx = 1
     kmx = 1
-    DO k = 1, 360
+    DO k = 1, year_len
       DO i = 2, nlon
         IF (phy_sst(i,k)<amn) THEN
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/phyetat0.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/phyetat0.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/phyetat0.F90	(revision 3605)
@@ -9,5 +9,5 @@
   USE pbl_surface_mod,  ONLY : pbl_surface_init
   USE surface_data,     ONLY : type_ocean, version_ocean
-  USE phys_state_var_mod, ONLY : ancien_ok, clwcon, detr_therm, dtime, &
+  USE phys_state_var_mod, ONLY : ancien_ok, clwcon, detr_therm, phys_tstep, &
        qsol, fevap, z0m, z0h, agesno, &
        du_gwd_rando, du_gwd_front, entr_therm, f0, fm_therm, &
@@ -111,10 +111,12 @@
   IF (carbon_cycle_tr .OR. carbon_cycle_cpl) THEN
      co2_ppm = tab_cntrl(3)
-     RCO2    = co2_ppm * 1.0e-06  * 44.011/28.97 
+     RCO2    = co2_ppm * 1.0e-06 * RMCO2 / RMD
      ! ELSE : keep value from .def
-  END IF
-
-  ! co2_ppm0 : initial value of atmospheric CO2 (from create_etat0_limit.e .def)
-  co2_ppm0   = tab_cntrl(16)
+  ENDIF
+
+! co2_ppm0 : initial value of atmospheric CO2 (from create_etat0_limit.e .def)
+! co2_ppm0   = tab_cntrl(16)
+! initial value for interactive CO2 run when there is no tracer field for CO2 in restart
+  co2_ppm0=284.32
 
   solaire_etat0      = tab_cntrl(4)
@@ -122,10 +124,10 @@
   tab_cntrl(6)=nbapp_rad
 
-  if (iflag_cycle_diurne.GE.1) tab_cntrl( 7) = iflag_cycle_diurne
-  if (soil_model) tab_cntrl( 8) =1.
-  if (new_oliq) tab_cntrl( 9) =1.
-  if (ok_orodr) tab_cntrl(10) =1.
-  if (ok_orolf) tab_cntrl(11) =1.
-  if (ok_limitvrai) tab_cntrl(12) =1.
+  IF (iflag_cycle_diurne.GE.1) tab_cntrl( 7) = iflag_cycle_diurne
+  IF (soil_model) tab_cntrl( 8) =1.
+  IF (new_oliq) tab_cntrl( 9) =1.
+  IF (ok_orodr) tab_cntrl(10) =1.
+  IF (ok_orolf) tab_cntrl(11) =1.
+  IF (ok_limitvrai) tab_cntrl(12) =1.
 
   itau_phy = tab_cntrl(15)
@@ -164,14 +166,18 @@
   DO i=1,klon
     IF (ABS(lon_startphy(i)-longitude_deg(i))>=1) THEN
-      WRITE(*,*) "phyetat0: Error! Longitude discrepancy wrt startphy file:",&
-                 " i=",i," lon_startphy(i)=",lon_startphy(i),&
-                 " longitude_deg(i)=",longitude_deg(i)
-      ! This is presumably serious enough to abort run
-      CALL abort_physic("phyetat0","discrepancy in longitudes!",1)
+      IF (ABS(360-ABS(lon_startphy(i)-longitude_deg(i)))>=1) THEN
+        WRITE(*,*) "phyetat0: Error! Longitude discrepancy wrt startphy file:",&
+                   " i=",i," lon_startphy(i)=",lon_startphy(i),&
+                   " longitude_deg(i)=",longitude_deg(i)
+        ! This is presumably serious enough to abort run
+        CALL abort_physic("phyetat0","discrepancy in longitudes!",1)
+      ENDIF
     ENDIF
-    IF (ABS(lon_startphy(i)-longitude_deg(i))>=0.0001) THEN
-      WRITE(*,*) "phyetat0: Warning! Longitude discrepancy wrt startphy file:",&
-                 " i=",i," lon_startphy(i)=",lon_startphy(i),&
-                 " longitude_deg(i)=",longitude_deg(i)
+    IF (ABS(lon_startphy(i)-longitude_deg(i))>=1) THEN
+      IF (ABS(360-ABS(lon_startphy(i)-longitude_deg(i))) > 0.0001) THEN
+        WRITE(*,*) "phyetat0: Warning! Longitude discrepancy wrt startphy file:",&
+                   " i=",i," lon_startphy(i)=",lon_startphy(i),&
+                   " longitude_deg(i)=",longitude_deg(i)
+      ENDIF 
     ENDIF
   ENDDO
@@ -223,5 +229,5 @@
         zmasq(i) = fractint(i)
      ENDIF
-  END DO
+  ENDDO
   fractint (1 : klon) =  pctsrf(1 : klon, is_oce)  &
        + pctsrf(1 : klon, is_sic)
@@ -234,5 +240,5 @@
         zmasq(i) = 1. - fractint(i)
      ENDIF
-  END DO
+  ENDDO
 
 !===================================================================
@@ -359,13 +365,13 @@
   !          dummy values (as is the case when generated by ce0l,
   !          or by iniaqua)
-  if ( (maxval(q_ancien).eq.minval(q_ancien))       .or. &
-       (maxval(ql_ancien).eq.minval(ql_ancien))     .or. &
-       (maxval(qs_ancien).eq.minval(qs_ancien))     .or. &
-       (maxval(prw_ancien).eq.minval(prw_ancien))   .or. &
-       (maxval(prlw_ancien).eq.minval(prlw_ancien)) .or. &
-       (maxval(prsw_ancien).eq.minval(prsw_ancien)) .or. &
-       (maxval(t_ancien).eq.minval(t_ancien)) ) then
+  IF ( (maxval(q_ancien).EQ.minval(q_ancien))       .OR. &
+       (maxval(ql_ancien).EQ.minval(ql_ancien))     .OR. &
+       (maxval(qs_ancien).EQ.minval(qs_ancien))     .OR. &
+       (maxval(prw_ancien).EQ.minval(prw_ancien))   .OR. &
+       (maxval(prlw_ancien).EQ.minval(prlw_ancien)) .OR. &
+       (maxval(prsw_ancien).EQ.minval(prsw_ancien)) .OR. &
+       (maxval(t_ancien).EQ.minval(t_ancien)) ) THEN
     ancien_ok=.false.
-  endif
+  ENDIF
 
   found=phyetat0_get(klev,clwcon,"CLWCON","CLWCON",0.)
@@ -434,5 +440,5 @@
         found=phyetat0_get(1,trs(:,it),"trs_"//tname(iiq), &
               "Surf trac"//tname(iiq),0.)
-     END DO
+     ENDDO
      CALL traclmdz_from_restart(trs)
   ENDIF
@@ -444,6 +450,6 @@
         IF (ierr /= 0) CALL abort_physic('phyetat0', 'pb allocation co2_send', 1)
         found=phyetat0_get(1,co2_send,"co2_send","co2 send",co2_ppm)
-     END IF
-  END IF
+     ENDIF
+  ENDIF
 
 !===========================================
@@ -452,7 +458,7 @@
 
 !  ondes de gravite non orographiques
-  if (ok_gwd_rando) found = &
+  IF (ok_gwd_rando) found = &
        phyetat0_get(klev,du_gwd_rando,"du_gwd_rando","du_gwd_rando",0.)
-  IF (.not. ok_hines .and. ok_gwd_rando) found &
+  IF (.NOT. ok_hines .AND. ok_gwd_rando) found &
        = phyetat0_get(klev,du_gwd_front,"du_gwd_front","du_gwd_front",0.)
 
@@ -473,16 +479,16 @@
 
   IF ( type_ocean == 'slab' ) THEN
-      CALL ocean_slab_init(dtime, pctsrf)
+      CALL ocean_slab_init(phys_tstep, pctsrf)
       IF (nslay.EQ.1) THEN
         found=phyetat0_get(1,tslab,"tslab01","tslab",0.)
         IF (.NOT. found) THEN
             found=phyetat0_get(1,tslab,"tslab","tslab",0.)
-        END IF
+        ENDIF
       ELSE
           DO i=1,nslay
             WRITE(str2,'(i2.2)') i
             found=phyetat0_get(1,tslab(:,i),"tslab"//str2,"tslab",0.)  
-          END DO
-      END IF
+          ENDDO
+      ENDIF
       IF (.NOT. found) THEN 
           PRINT*, "phyetat0: Le champ <tslab> est absent"
@@ -490,6 +496,6 @@
           DO i=1,nslay
               tslab(:,i)=MAX(ftsol(:,is_oce),271.35)
-          END DO
-      END IF 
+          ENDDO
+      ENDIF 
 
       ! Sea ice variables
@@ -500,5 +506,5 @@
               PRINT*, "Initialisation a tsol_sic"
                   tice(:)=ftsol(:,is_sic)
-          END IF 
+          ENDIF 
           found=phyetat0_get(1,seaice,"seaice","seaice",0.)
           IF (.NOT. found) THEN
@@ -508,8 +514,8 @@
               WHERE (pctsrf(:,is_sic).GT.EPSFRA)
                   seaice=917.
-              END WHERE
-          END IF
-      END IF !sea ice INT
-  END IF ! Slab        
+              ENDWHERE
+          ENDIF
+      ENDIF !sea ice INT
+  ENDIF ! Slab        
 
   ! on ferme le fichier
@@ -522,8 +528,8 @@
   ! Initialize module ocean_cpl_mod for the case of coupled ocean
   IF ( type_ocean == 'couple' ) THEN
-     CALL ocean_cpl_init(dtime, longitude_deg, latitude_deg)
-  ENDIF
-
-  CALL init_iophy_new(latitude_deg, longitude_deg)
+     CALL ocean_cpl_init(phys_tstep, longitude_deg, latitude_deg)
+  ENDIF
+
+!  CALL init_iophy_new(latitude_deg, longitude_deg)
 
   ! Initilialize module fonte_neige_mod      
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/phyredem.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/phyredem.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/phyredem.F90	(revision 3605)
@@ -29,5 +29,5 @@
                                 treedrg, ds_ns, dt_ns
   USE geometry_mod, ONLY : longitude_deg, latitude_deg
-  USE iostart, ONLY: open_restartphy, close_restartphy, put_field, put_var
+  USE iostart, ONLY: open_restartphy, close_restartphy, enddef_restartphy, put_field, put_var
   USE traclmdz_mod, ONLY : traclmdz_to_restart
   USE infotrac_phy, ONLY: type_trac, niadv, tname, nbtr, nqo
@@ -66,5 +66,5 @@
   CHARACTER (len=2) :: str2
   CHARACTER (len=256) :: nam, lnam
-  INTEGER           :: it, iiq
+  INTEGER           :: it, iiq, pass
 
   !======================================================================
@@ -81,4 +81,5 @@
   CALL open_restartphy(fichnom)
 
+  
   DO ierr = 1, length
      tab_cntrl(ierr) = 0.0
@@ -105,243 +106,248 @@
   tab_cntrl(16) = co2_ppm0
 
-  CALL put_var("controle", "Parametres de controle", tab_cntrl)
-
-  CALL put_field("longitude", &
-       "Longitudes de la grille physique", longitude_deg)
-
-  CALL put_field("latitude", "Latitudes de la grille physique", latitude_deg)
-
-  ! PB ajout du masque terre/mer
-
-  CALL put_field("masque", "masque terre mer", zmasq)
-
-  ! BP ajout des fraction de chaque sous-surface
-
-  ! Get last fractions from slab ocean
-  IF (type_ocean == 'slab' .AND. version_ocean == "sicINT") THEN
-      WHERE (1.-zmasq(:).GT.EPSFRA)
-          pctsrf(:,is_oce)=(1.-fsic(:))*(1.-zmasq(:))
-          pctsrf(:,is_sic)=fsic(:)*(1.-zmasq(:))
-      END WHERE
-  END IF
-
-  ! 1. fraction de terre 
-
-  CALL put_field("FTER", "fraction de continent", pctsrf(:, is_ter))
-
-  ! 2. Fraction de glace de terre
-
-  CALL put_field("FLIC", "fraction glace de terre", pctsrf(:, is_lic))
-
-  ! 3. fraction ocean
-
-  CALL put_field("FOCE", "fraction ocean", pctsrf(:, is_oce))
-
-  ! 4. Fraction glace de mer
-
-  CALL put_field("FSIC", "fraction glace mer", pctsrf(:, is_sic))
-
-  IF(nbsrf>99) THEN
-    PRINT*, "Trop de sous-mailles";  CALL abort_physic("phyredem", "", 1)
-  END IF
-  IF(nsoilmx>99) THEN
-    PRINT*, "Trop de sous-surfaces"; CALL abort_physic("phyredem", "", 1)
-  END IF
-  IF(nsw>99) THEN
-    PRINT*, "Trop de bandes"; CALL abort_physic("phyredem", "", 1)
-  END IF
-
-  CALL put_field_srf1("TS","Temperature",ftsol(:,:))
+  DO pass=1,2   ! pass=1 netcdf definition ; pass=2 netcdf write
+  
+    CALL put_var(pass, "controle", "Parametres de controle", tab_cntrl)
+
+    CALL put_field(pass,"longitude", &
+         "Longitudes de la grille physique", longitude_deg)
+
+    CALL put_field(pass,"latitude", "Latitudes de la grille physique", latitude_deg)
+
+    ! PB ajout du masque terre/mer
+
+    CALL put_field(pass,"masque", "masque terre mer", zmasq)
+
+    ! BP ajout des fraction de chaque sous-surface
+
+    ! Get last fractions from slab ocean
+    IF (type_ocean == 'slab' .AND. version_ocean == "sicINT") THEN
+        WHERE (1.-zmasq(:).GT.EPSFRA)
+            pctsrf(:,is_oce)=(1.-fsic(:))*(1.-zmasq(:))
+            pctsrf(:,is_sic)=fsic(:)*(1.-zmasq(:))
+        END WHERE
+    END IF
+
+    ! 1. fraction de terre 
+
+    CALL put_field(pass,"FTER", "fraction de continent", pctsrf(:, is_ter))
+
+    ! 2. Fraction de glace de terre
+
+    CALL put_field(pass,"FLIC", "fraction glace de terre", pctsrf(:, is_lic))
+
+    ! 3. fraction ocean
+
+    CALL put_field(pass,"FOCE", "fraction ocean", pctsrf(:, is_oce))
+
+    ! 4. Fraction glace de mer
+
+    CALL put_field(pass,"FSIC", "fraction glace mer", pctsrf(:, is_sic))
+
+    IF(nbsrf>99) THEN
+      PRINT*, "Trop de sous-mailles";  CALL abort_physic("phyredem", "", 1)
+    END IF
+    IF(nsoilmx>99) THEN
+      PRINT*, "Trop de sous-surfaces"; CALL abort_physic("phyredem", "", 1)
+    END IF
+    IF(nsw>99) THEN
+      PRINT*, "Trop de bandes"; CALL abort_physic("phyredem", "", 1)
+    END IF
+
+    CALL put_field_srf1(pass,"TS","Temperature",ftsol(:,:))
 
 ! ================== Albedo =======================================
-  print*,'PHYREDEM NOUVEAU'
-  CALL put_field_srf2("A_dir_SW","Albedo direct",falb_dir(:,:,:))
-  CALL put_field_srf2("A_dif_SW","Albedo diffus",falb_dif(:,:,:))
-
-  CALL put_field_srf1("U10M", "u a 10m", u10m)
-
-  CALL put_field_srf1("V10M", "v a 10m", v10m)
+    print*,'PHYREDEM NOUVEAU'
+    CALL put_field_srf2(pass,"A_dir_SW","Albedo direct",falb_dir(:,:,:))
+    CALL put_field_srf2(pass,"A_dif_SW","Albedo diffus",falb_dif(:,:,:))
+
+    CALL put_field_srf1(pass,"U10M", "u a 10m", u10m)
+
+    CALL put_field_srf1(pass,"V10M", "v a 10m", v10m)
 
 
 ! ================== Tsoil =========================================
-  CALL put_field_srf2("Tsoil","Temperature",tsoil(:,:,:))
+    CALL put_field_srf2(pass,"Tsoil","Temperature",tsoil(:,:,:))
 !FC
 !  CALL put_field_srf2("treedrg","freinage arbres",treedrg(:,:,:))
-  CALL put_field("treedrg_ter","freinage arbres",treedrg(:,:,is_ter))
-
-
-  CALL put_field_srf1("QS"  , "Humidite",qsurf(:,:))
-
-  CALL put_field     ("QSOL", "Eau dans le sol (mm)", qsol)
-
-  CALL put_field_srf1("EVAP", "Evaporation", fevap(:,:))
-
-  CALL put_field_srf1("SNOW", "Neige", snow(:,:))
-
-  CALL put_field("RADS", "Rayonnement net a la surface", radsol)
-
-  CALL put_field("solsw", "Rayonnement solaire a la surface", solsw)
-
-  CALL put_field("sollw", "Rayonnement IF a la surface", sollw)
-
-  CALL put_field("sollwdown", "Rayonnement down IF a la surface", sollwdown)
-
-  CALL put_field("fder", "Derive de flux", fder)
-
-  CALL put_field("rain_f", "precipitation liquide", rain_fall)
-
-  CALL put_field("snow_f", "precipitation solide", snow_fall)
-
-  CALL put_field_srf1("Z0m", "rugosite", z0m(:,:))
-
-  CALL put_field_srf1("Z0h", "rugosite", z0h(:,:))
-
-  CALL put_field_srf1("AGESNO", "Age de la neige", agesno(:,:))
-
-  CALL put_field("ZMEA", "ZMEA", zmea)
-
-  CALL put_field("ZSTD", "ZSTD", zstd)
-
-  CALL put_field("ZSIG", "ZSIG", zsig)
-
-  CALL put_field("ZGAM", "ZGAM", zgam)
-
-  CALL put_field("ZTHE", "ZTHE", zthe)
-
-  CALL put_field("ZPIC", "ZPIC", zpic)
-
-  CALL put_field("ZVAL", "ZVAL", zval)
-
-  CALL put_field("RUGSREL", "RUGSREL", rugoro)
-
-  CALL put_field("TANCIEN", "TANCIEN", t_ancien)
-
-  CALL put_field("QANCIEN", "QANCIEN", q_ancien)
-
-  CALL put_field("QLANCIEN", "QLANCIEN", ql_ancien)
-
-  CALL put_field("QSANCIEN", "QSANCIEN", qs_ancien)
-
-  CALL put_field("PRWANCIEN", "PRWANCIEN", prw_ancien)
-
-  CALL put_field("PRLWANCIEN", "PRLWANCIEN", prlw_ancien)
-
-  CALL put_field("PRSWANCIEN", "PRSWANCIEN", prsw_ancien)
-
-  CALL put_field("UANCIEN", "UANCIEN", u_ancien)
-
-  CALL put_field("VANCIEN", "VANCIEN", v_ancien)
-
-  CALL put_field("CLWCON", "Eau liquide convective", clwcon)
-
-  CALL put_field("RNEBCON", "Nebulosite convective", rnebcon)
-
-  CALL put_field("RATQS", "Ratqs", ratqs)
-
-  ! run_off_lic_0
-
-  CALL put_field("RUNOFFLIC0", "Runofflic0", run_off_lic_0)
-
-  ! DEB TKE PBL !
-
-  IF (iflag_pbl>1) then
-    CALL put_field_srf3("TKE", "Energ. Cineti. Turb.", &
-         pbl_tke(:,:,:))
-    CALL put_field_srf3("DELTATKE", "Del TKE wk/env.", &
-         wake_delta_pbl_tke(:,:,:))
-  END IF
-
-  ! FIN TKE PBL !
-  !IM ajout zmax0, f0, sig1, w01
-  !IM wake_deltat, wake_deltaq, wake_s, wake_cstar, wake_pe, wake_fip
-
-  CALL put_field("ZMAX0", "ZMAX0", zmax0)
-
-  CALL put_field("F0", "F0", f0)
-
-  CALL put_field("sig1", "sig1 Emanuel", sig1)
-
-  CALL put_field("w01", "w01 Emanuel", w01)
-
-  ! wake_deltat
-  CALL put_field("WAKE_DELTAT", "WAKE_DELTAT", wake_deltat)
-
-  CALL put_field("WAKE_DELTAQ", "WAKE_DELTAQ", wake_deltaq)
-
-  CALL put_field("WAKE_S", "Wake frac. area", wake_s)
-
-  CALL put_field("WAKE_DENS", "Wake num. /unit area", wake_dens)
-
-  CALL put_field("WAKE_CSTAR", "WAKE_CSTAR", wake_cstar)
-
-  CALL put_field("WAKE_PE", "WAKE_PE", wake_pe)
-
-  CALL put_field("WAKE_FIP", "WAKE_FIP", wake_fip)
-
-  ! thermiques
-
-  CALL put_field("FM_THERM", "FM_THERM", fm_therm)
-
-  CALL put_field("ENTR_THERM", "ENTR_THERM", entr_therm)
-
-  CALL put_field("DETR_THERM", "DETR_THERM", detr_therm)
-
-  CALL put_field("ALE_BL", "ALE_BL", ale_bl)
-
-  CALL put_field("ALE_BL_TRIG", "ALE_BL_TRIG", ale_bl_trig)
-
-  CALL put_field("ALP_BL", "ALP_BL", alp_bl)
-
-  CALL put_field("ALE_WAKE", "ALE_WAKE", ale_wake)
-
-  CALL put_field("ALE_BL_STAT", "ALE_BL_STAT", ale_bl_stat)
-
-
-  ! trs from traclmdz_mod
-  IF (type_trac == 'lmdz') THEN
-     CALL traclmdz_to_restart(trs)
-     DO it=1, nbtr
+    CALL put_field(pass,"treedrg_ter","freinage arbres",treedrg(:,:,is_ter))
+
+
+    CALL put_field_srf1(pass,"QS"  , "Humidite",qsurf(:,:))
+
+    CALL put_field     (pass,"QSOL", "Eau dans le sol (mm)", qsol)
+
+    CALL put_field_srf1(pass,"EVAP", "Evaporation", fevap(:,:))
+
+    CALL put_field_srf1(pass,"SNOW", "Neige", snow(:,:))
+
+    CALL put_field(pass,"RADS", "Rayonnement net a la surface", radsol)
+
+    CALL put_field(pass,"solsw", "Rayonnement solaire a la surface", solsw)
+
+    CALL put_field(pass,"sollw", "Rayonnement IF a la surface", sollw)
+
+    CALL put_field(pass,"sollwdown", "Rayonnement down IF a la surface", sollwdown)
+
+    CALL put_field(pass,"fder", "Derive de flux", fder)
+
+    CALL put_field(pass,"rain_f", "precipitation liquide", rain_fall)
+
+    CALL put_field(pass,"snow_f", "precipitation solide", snow_fall)
+
+    CALL put_field_srf1(pass,"Z0m", "rugosite", z0m(:,:))
+
+    CALL put_field_srf1(pass,"Z0h", "rugosite", z0h(:,:))
+
+    CALL put_field_srf1(pass,"AGESNO", "Age de la neige", agesno(:,:))
+
+    CALL put_field(pass,"ZMEA", "ZMEA", zmea)
+
+    CALL put_field(pass,"ZSTD", "ZSTD", zstd)
+
+    CALL put_field(pass,"ZSIG", "ZSIG", zsig)
+
+    CALL put_field(pass,"ZGAM", "ZGAM", zgam)
+
+    CALL put_field(pass,"ZTHE", "ZTHE", zthe)
+
+    CALL put_field(pass,"ZPIC", "ZPIC", zpic)
+
+    CALL put_field(pass,"ZVAL", "ZVAL", zval)
+
+    CALL put_field(pass,"RUGSREL", "RUGSREL", rugoro)
+
+    CALL put_field(pass,"TANCIEN", "TANCIEN", t_ancien)
+
+    CALL put_field(pass,"QANCIEN", "QANCIEN", q_ancien)
+
+    CALL put_field(pass,"QLANCIEN", "QLANCIEN", ql_ancien)
+
+    CALL put_field(pass,"QSANCIEN", "QSANCIEN", qs_ancien)
+
+    CALL put_field(pass,"PRWANCIEN", "PRWANCIEN", prw_ancien)
+
+    CALL put_field(pass,"PRLWANCIEN", "PRLWANCIEN", prlw_ancien)
+
+    CALL put_field(pass,"PRSWANCIEN", "PRSWANCIEN", prsw_ancien)
+
+    CALL put_field(pass,"UANCIEN", "UANCIEN", u_ancien)
+
+    CALL put_field(pass,"VANCIEN", "VANCIEN", v_ancien)
+
+    CALL put_field(pass,"CLWCON", "Eau liquide convective", clwcon)
+
+    CALL put_field(pass,"RNEBCON", "Nebulosite convective", rnebcon)
+
+    CALL put_field(pass,"RATQS", "Ratqs", ratqs)
+
+    ! run_off_lic_0
+
+    CALL put_field(pass,"RUNOFFLIC0", "Runofflic0", run_off_lic_0)
+
+    ! DEB TKE PBL !
+
+    IF (iflag_pbl>1) then
+      CALL put_field_srf3(pass,"TKE", "Energ. Cineti. Turb.", &
+           pbl_tke(:,:,:))
+      CALL put_field_srf3(pass,"DELTATKE", "Del TKE wk/env.", &
+           wake_delta_pbl_tke(:,:,:))
+    END IF
+
+    ! FIN TKE PBL !
+    !IM ajout zmax0, f0, sig1, w01
+    !IM wake_deltat, wake_deltaq, wake_s, wake_cstar, wake_pe, wake_fip
+
+    CALL put_field(pass,"ZMAX0", "ZMAX0", zmax0)
+
+    CALL put_field(pass,"F0", "F0", f0)
+
+    CALL put_field(pass,"sig1", "sig1 Emanuel", sig1)
+
+    CALL put_field(pass,"w01", "w01 Emanuel", w01)
+
+    ! wake_deltat
+    CALL put_field(pass,"WAKE_DELTAT", "WAKE_DELTAT", wake_deltat)
+
+    CALL put_field(pass,"WAKE_DELTAQ", "WAKE_DELTAQ", wake_deltaq)
+
+    CALL put_field(pass,"WAKE_S", "Wake frac. area", wake_s)
+
+    CALL put_field(pass,"WAKE_DENS", "Wake num. /unit area", wake_dens)
+
+    CALL put_field(pass,"WAKE_CSTAR", "WAKE_CSTAR", wake_cstar)
+
+    CALL put_field(pass,"WAKE_PE", "WAKE_PE", wake_pe)
+
+    CALL put_field(pass,"WAKE_FIP", "WAKE_FIP", wake_fip)
+
+    ! thermiques
+
+    CALL put_field(pass,"FM_THERM", "FM_THERM", fm_therm)
+
+    CALL put_field(pass,"ENTR_THERM", "ENTR_THERM", entr_therm)
+
+    CALL put_field(pass,"DETR_THERM", "DETR_THERM", detr_therm)
+
+    CALL put_field(pass,"ALE_BL", "ALE_BL", ale_bl)
+
+    CALL put_field(pass,"ALE_BL_TRIG", "ALE_BL_TRIG", ale_bl_trig)
+
+    CALL put_field(pass,"ALP_BL", "ALP_BL", alp_bl)
+
+    CALL put_field(pass,"ALE_WAKE", "ALE_WAKE", ale_wake)
+
+    CALL put_field(pass,"ALE_BL_STAT", "ALE_BL_STAT", ale_bl_stat)
+
+
+    ! trs from traclmdz_mod
+    IF (type_trac == 'lmdz') THEN
+       CALL traclmdz_to_restart(trs)
+       DO it=1, nbtr
 !!        iiq=niadv(it+2)                                                           ! jyg
-        iiq=niadv(it+nqo)                                                           ! jyg
-        CALL put_field("trs_"//tname(iiq), "", trs(:, it))
-     END DO
-     IF (carbon_cycle_cpl) THEN
-        IF (.NOT. ALLOCATED(co2_send)) THEN
-           ! This is the case of create_etat0_limit, ce0l
-           ALLOCATE(co2_send(klon))
-           co2_send(:) = co2_ppm0
+          iiq=niadv(it+nqo)                                                           ! jyg
+          CALL put_field(pass,"trs_"//tname(iiq), "", trs(:, it))
+       END DO
+       IF (carbon_cycle_cpl) THEN
+          IF (.NOT. ALLOCATED(co2_send)) THEN
+             ! This is the case of create_etat0_limit, ce0l
+             ALLOCATE(co2_send(klon))
+             co2_send(:) = co2_ppm0
+          END IF
+          CALL put_field(pass,"co2_send", "co2_ppm for coupling", co2_send)
+       END IF
+    END IF
+
+    ! Restart variables for Slab ocean
+    IF (type_ocean == 'slab') THEN
+        IF (nslay.EQ.1) THEN
+          CALL put_field(pass,"tslab", "Slab ocean temperature", tslab)
+        ELSE
+          DO it=1,nslay
+            WRITE(str2,'(i2.2)') it
+            CALL put_field(pass,"tslab"//str2, "Slab ocean temperature", tslab(:,it))
+          END DO
         END IF
-        CALL put_field("co2_send", "co2_ppm for coupling", co2_send)
-     END IF
-  END IF
-
-  ! Restart variables for Slab ocean
-  IF (type_ocean == 'slab') THEN
-      IF (nslay.EQ.1) THEN
-        CALL put_field("tslab", "Slab ocean temperature", tslab)
-      ELSE
-        DO it=1,nslay
-          WRITE(str2,'(i2.2)') it
-          CALL put_field("tslab"//str2, "Slab ocean temperature", tslab(:,it))
-        END DO
-      END IF
-      IF (version_ocean == 'sicINT') THEN
-          CALL put_field("seaice", "Slab seaice (kg/m2)", seaice)
-          CALL put_field("slab_tice", "Slab sea ice temperature", tice)
-      END IF
-  END IF
-
-  if (ok_gwd_rando) call put_field("du_gwd_rando", &
-       "tendency on zonal wind due to flott gravity waves", du_gwd_rando)
-
-  IF (.not. ok_hines .and. ok_gwd_rando) call put_field("du_gwd_front", &
-       "tendency on zonal wind due to acama gravity waves", du_gwd_front)
-
-  if (activate_ocean_skin >= 1) then
-     CALL put_field("ds_ns", "delta salinity near surface", ds_ns)
-     CALL put_field("dT_ns", "delta temperature near surface", dT_ns)
-  end if
+        IF (version_ocean == 'sicINT') THEN
+            CALL put_field(pass,"seaice", "Slab seaice (kg/m2)", seaice)
+            CALL put_field(pass,"slab_tice", "Slab sea ice temperature", tice)
+        END IF
+    END IF
+
+    if (ok_gwd_rando) call put_field(pass,"du_gwd_rando", &
+         "tendency on zonal wind due to flott gravity waves", du_gwd_rando)
+
+    IF (.not. ok_hines .and. ok_gwd_rando) call put_field(pass,"du_gwd_front", &
+         "tendency on zonal wind due to acama gravity waves", du_gwd_front)
+
+    if (activate_ocean_skin >= 1) then
+       CALL put_field(pass, "ds_ns", "delta salinity near surface", ds_ns)
+       CALL put_field(pass, "dT_ns", "delta temperature near surface", dT_ns)
+    end if
+    
+    IF (pass==1) CALL enddef_restartphy
+    IF (pass==2) CALL close_restartphy
+ ENDDO
   
-  CALL close_restartphy
   !$OMP BARRIER
 
@@ -350,7 +356,8 @@
 
 
-SUBROUTINE put_field_srf1(nam,lnam,field)
+SUBROUTINE put_field_srf1(pass,nam,lnam,field)
 
   IMPLICIT NONE
+  INTEGER, INTENT(IN)            :: pass
   CHARACTER(LEN=*),  INTENT(IN) :: nam, lnam
   REAL,              INTENT(IN) :: field(:,:)
@@ -360,5 +367,5 @@
     nm=TRIM(nam)//TRIM(str)
     lm=TRIM(lnam)//" de surface No. "//TRIM(str)
-    CALL put_field(nm,lm,field(:,nsrf))
+    CALL put_field(pass,nm,lm,field(:,nsrf))
   END DO
 
@@ -366,7 +373,8 @@
 
 
-SUBROUTINE put_field_srf2(nam,lnam,field)
+SUBROUTINE put_field_srf2(pass,nam,lnam,field)
 
   IMPLICIT NONE
+  INTEGER, INTENT(IN)            :: pass
   CHARACTER(LEN=*),  INTENT(IN) :: nam, lnam
   REAL,              INTENT(IN) :: field(:,:,:)
@@ -378,5 +386,5 @@
       nm=TRIM(nam)//TRIM(str)
       lm=TRIM(lnam)//" du sol No. "//TRIM(str)
-      CALL put_field(nm,lm,field(:,isoil,nsrf))
+      CALL put_field(pass,nm,lm,field(:,isoil,nsrf))
     END DO
   END DO
@@ -385,7 +393,8 @@
 
 
-SUBROUTINE put_field_srf3(nam,lnam,field)
+SUBROUTINE put_field_srf3(pass,nam,lnam,field)
 
   IMPLICIT NONE
+  INTEGER, INTENT(IN)            :: pass
   CHARACTER(LEN=*),  INTENT(IN) :: nam, lnam
   REAL,              INTENT(IN) :: field(:,:,:)
@@ -395,5 +404,5 @@
     nm=TRIM(nam)//TRIM(str)
     lm=TRIM(lnam)//TRIM(str)
-    CALL put_field(nm,lm,field(:,1:klev+1,nsrf))
+    CALL put_field(pass,nm,lm,field(:,1:klev+1,nsrf))
   END DO
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_cal_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_cal_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_cal_mod.F90	(revision 3605)
@@ -1,3 +1,3 @@
-! $Id:$
+! $Id$
 MODULE phys_cal_mod
 ! This module contains information on the calendar at the current time step
@@ -37,5 +37,6 @@
   SUBROUTINE phys_cal_init(annee_ref,day_ref)
 
-    USE IOIPSL, ONLY:  ymds2ju
+    USE IOIPSL, ONLY:  ymds2ju, ioconf_calendar
+    USE mod_phys_lmdz_para, ONLY:  is_master,is_omp_master
     USE ioipsl_getin_p_mod, ONLY: getin_p
 
@@ -47,4 +48,17 @@
     calend = 'earth_360d' ! default
     CALL getin_p("calend",calend)
+
+    IF (is_omp_master) THEN
+      IF (calend == 'earth_360d') THEN
+        CALL ioconf_calendar('360d')
+      ELSE IF (calend == 'earth_365d') THEN
+        CALL ioconf_calendar('noleap')
+      ELSE IF (calend == 'earth_366d' .OR. calend == 'gregorian') THEN
+        CALL ioconf_calendar('gregorian')
+      ELSE
+        CALL abort_physic('phys_cal_init','Mauvais choix de calendrier',1)
+      ENDIF
+    ENDIF
+!$OMP BARRIER
      
     CALL ymds2ju(annee_ref, 1, day_ref, 0., jD_ref)
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_local_var_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_local_var_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_local_var_mod.F90	(revision 3605)
@@ -343,5 +343,5 @@
 !$OMP THREADPRIVATE(zxfluxlat_x, zxfluxlat_w)
 !jyg<
-!!! Entr\E9es suppl\E9mentaires couche-limite
+!!! Entrees supplementaires couche-limite
 !!      REAL,ALLOCATABLE,SAVE,DIMENSION(:,:) :: t_x, t_w
 !!!$OMP THREADPRIVATE(t_x, t_w)
@@ -349,5 +349,10 @@
 !!!$OMP THREADPRIVATE(q_x, q_w)
 !>jyg
-! Variables suppl\E9mentaires dans physiq.F relative au splitting de la surface
+!!! Sorties ferret
+      REAL,ALLOCATABLE,SAVE,DIMENSION(:,:) :: dtvdf_x, dtvdf_w
+!$OMP THREADPRIVATE(dtvdf_x, dtvdf_w)
+      REAL,ALLOCATABLE,SAVE,DIMENSION(:,:) :: dqvdf_x, dqvdf_w
+!$OMP THREADPRIVATE(dqvdf_x, dqvdf_w)
+! Variables supplementaires dans physiq.F relative au splitting de la surface
       REAL,ALLOCATABLE,SAVE,DIMENSION(:,:,:) :: pbl_tke_input
 !$OMP THREADPRIVATE(pbl_tke_input)
@@ -375,4 +380,10 @@
       REAL,ALLOCATABLE,SAVE,DIMENSION(:) :: t2m_min_mon, t2m_max_mon
 !$OMP THREADPRIVATE(t2m_min_mon, t2m_max_mon)
+      REAL,ALLOCATABLE,SAVE,DIMENSION(:) :: zq2m_cor, zt2m_cor
+!$OMP THREADPRIVATE(zq2m_cor, zt2m_cor)
+      REAL,ALLOCATABLE,SAVE,DIMENSION(:) :: zu10m_cor, zv10m_cor
+!$OMP THREADPRIVATE(zu10m_cor, zv10m_cor)
+      REAL,ALLOCATABLE,SAVE,DIMENSION(:) :: zrh2m_cor, zqsat2m_cor
+!$OMP THREADPRIVATE(zrh2m_cor, zqsat2m_cor)
       REAL,ALLOCATABLE,SAVE,DIMENSION(:) :: weak_inversion
 !$OMP THREADPRIVATE(weak_inversion)
@@ -405,6 +416,6 @@
       REAL,ALLOCATABLE,SAVE,DIMENSION(:,:)  :: pmflxr, pmflxs
 !$OMP THREADPRIVATE(pmflxr, pmflxs)
-      REAL,ALLOCATABLE,SAVE,DIMENSION(:,:)  :: wdtrainA, wdtrainM
-!$OMP THREADPRIVATE(wdtrainA, wdtrainM)
+      REAL,ALLOCATABLE,SAVE,DIMENSION(:,:)  :: wdtrainA, wdtrainS, wdtrainM
+!$OMP THREADPRIVATE(wdtrainA, wdtrainS, wdtrainM)
       REAL,ALLOCATABLE,SAVE,DIMENSION(:,:)  :: da, mp
 !$OMP THREADPRIVATE(da, mp)
@@ -417,4 +428,6 @@
       REAL,ALLOCATABLE,SAVE,DIMENSION(:,:)  :: ev
 !$OMP THREADPRIVATE(ev)
+      REAL,ALLOCATABLE,SAVE,DIMENSION(:,:)  :: qtaa
+!$OMP THREADPRIVATE(qtaa)
       REAL,ALLOCATABLE,SAVE,DIMENSION(:,:)  :: clw
 !$OMP THREADPRIVATE(clw)
@@ -578,4 +591,8 @@
       ALLOCATE(plul_st(klon),plul_th(klon))
       ALLOCATE(d_t_vdf(klon,klev),d_q_vdf(klon,klev),d_t_diss(klon,klev))
+
+      ALLOCATE(d_t_vdf_w(klon,klev),d_q_vdf_w(klon,klev))
+      ALLOCATE(d_t_vdf_x(klon,klev),d_q_vdf_x(klon,klev))
+
       ALLOCATE(d_u_vdf(klon,klev),d_v_vdf(klon,klev))
       ALLOCATE(d_t_oli(klon,klev),d_t_oro(klon,klev))
@@ -589,4 +606,5 @@
 ! Special RRTM
       ALLOCATE(ZLWFT0_i(klon,klev+1),ZSWFT0_i(klon,klev+1),ZFLDN0(klon,klev+1))
+      ZFLDN0= 0.
       ALLOCATE(ZFLUP0(klon,klev+1),ZFSDN0(klon,klev+1),ZFSUP0(klon,klev+1))
 !
@@ -603,4 +621,6 @@
       ALLOCATE(dv_gwd_rando(klon,klev),dv_gwd_front(klon,klev))
       ALLOCATE(east_gwstress(klon,klev),west_gwstress(klon,klev))
+      east_gwstress(:,:)=0 !ym missing init
+      west_gwstress(:,:)=0 !ym missing init
       ALLOCATE(d_t_hin(klon,klev))
       ALLOCATE(d_q_ch4(klon,klev))
@@ -627,5 +647,7 @@
       ALLOCATE(od865aer(klon))
       ALLOCATE(dryod550aer(klon))
+      dryod550aer(:) = 0.
       ALLOCATE(abs550aer(klon))
+      abs550aer(:) = 0.
       ALLOCATE(ec550aer(klon,klev))
       ALLOCATE(od550lt1aer(klon))
@@ -672,5 +694,5 @@
       ALLOCATE(toplwad0_aerop(klon), sollwad0_aerop(klon))
 
-! FH Ajout de celles n??cessaires au phys_output_write_mod
+! FH Ajout de celles necessaires au phys_output_write_mod
 
       ALLOCATE(tal1(klon), pal1(klon), pab1(klon), pab2(klon))
@@ -721,6 +743,8 @@
 !!      ALLOCATE(q_x(klon,klev), q_w(klon,klev))
 !>jyg
-      ALLOCATE(d_t_vdf_x(klon,klev), d_t_vdf_w(klon,klev))
-      ALLOCATE(d_q_vdf_x(klon,klev), d_q_vdf_w(klon,klev))
+      ALLOCATE(dtvdf_x(klon,klev), dtvdf_w(klon,klev))
+      dtvdf_x = 0 ; dtvdf_w=0 ;   !ym missing init
+      ALLOCATE(dqvdf_x(klon,klev), dqvdf_w(klon,klev))
+      dqvdf_x = 0 ; dqvdf_w=0 ;   !ym missing init
       ALLOCATE(pbl_tke_input(klon,klev+1,nbsrf))
       ALLOCATE(t_therm(klon,klev), q_therm(klon,klev),u_therm(klon,klev), v_therm(klon,klev))
@@ -736,8 +760,13 @@
       ALLOCATE(zt2m_min_mon(klon), zt2m_max_mon(klon))
       ALLOCATE(t2m_min_mon(klon), t2m_max_mon(klon))
+      ALLOCATE(zq2m_cor(klon), zt2m_cor(klon), zu10m_cor(klon), zv10m_cor(klon))
+      ALLOCATE(zrh2m_cor(klon), zqsat2m_cor(klon))
       ALLOCATE(sens(klon), flwp(klon), fiwp(klon))
       ALLOCATE(alp_bl_conv(klon), alp_bl_det(klon))
+      alp_bl_conv(:)=0 ;  alp_bl_det(:)=0
       ALLOCATE(alp_bl_fluct_m(klon), alp_bl_fluct_tke(klon))
+      alp_bl_fluct_m(:)=0 ; alp_bl_fluct_tke(:)= 0.
       ALLOCATE(alp_bl_stat(klon), n2(klon), s2(klon))
+      alp_bl_stat(:)=0
       ALLOCATE(proba_notrig(klon), random_notrig(klon))
       ALLOCATE(cv_gen(klon))
@@ -764,5 +793,5 @@
 !  Deep convective variables used in phytrac
       ALLOCATE(pmflxr(klon, klev+1), pmflxs(klon, klev+1))
-      ALLOCATE(wdtrainA(klon,klev),wdtrainM(klon,klev))
+      ALLOCATE(wdtrainA(klon,klev),wdtrainS(klon,klev),wdtrainM(klon,klev))
       ALLOCATE(dnwd(klon, klev), upwd(klon, klev) )
       ALLOCATE(ep(klon,klev))                          ! epmax_cape
@@ -774,4 +803,5 @@
       ALLOCATE(ev(klon,klev) )
       ALLOCATE(elij(klon,klev,klev) )
+      ALLOCATE(qtaa(klon,klev) )
       ALLOCATE(clw(klon,klev) )
       ALLOCATE(epmlmMm(klon,klev,klev), eplaMm(klon,klev) )
@@ -968,5 +998,5 @@
       DEALLOCATE(toplwad0_aerop, sollwad0_aerop)
 
-! FH Ajout de celles n??cessaires au phys_output_write_mod
+! FH Ajout de celles necessaires au phys_output_write_mod
       DEALLOCATE(tal1, pal1, pab1, pab2)
       DEALLOCATE(ptstar, pt0, slp)
@@ -1027,4 +1057,6 @@
       DEALLOCATE(zt2m_min_mon, zt2m_max_mon)
       DEALLOCATE(t2m_min_mon, t2m_max_mon)
+      DEALLOCATE(zq2m_cor, zt2m_cor, zu10m_cor, zv10m_cor)
+      DEALLOCATE(zrh2m_cor, zqsat2m_cor)
       DEALLOCATE(sens, flwp, fiwp)
       DEALLOCATE(alp_bl_conv,alp_bl_det)
@@ -1053,5 +1085,5 @@
 
       DEALLOCATE(pmflxr, pmflxs)
-      DEALLOCATE(wdtrainA, wdtrainM)
+      DEALLOCATE(wdtrainA, wdtrainS, wdtrainM)
       DEALLOCATE(upwd, dnwd)
       DEALLOCATE(ep)
@@ -1063,4 +1095,5 @@
       DEALLOCATE(ev )
       DEALLOCATE(elij )
+      DEALLOCATE(qtaa )
       DEALLOCATE(clw )
       DEALLOCATE(epmlmMm, eplaMm )
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_output_ctrlout_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_output_ctrlout_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_output_ctrlout_mod.F90	(revision 3605)
@@ -7,6 +7,4 @@
   USE indice_sol_mod
   USE aero_mod
-
-
 
   IMPLICIT NONE
@@ -26,14 +24,25 @@
     'io_lat', '', '', (/ ('once', i=1, 10) /))
 
-!!! Comosantes de la coordonnee sigma-hybride
+!!! Composantes de la coordonnee sigma-hybride
 !!! Ap et Bp et interfaces
   TYPE(ctrl_out), SAVE :: o_Ahyb = ctrl_out((/ 1, 1, 1, 1, 1, 1, 11, 11, 11, 11/), &
-    'Ahyb', '', '', (/ ('once', i=1, 10) /))
+    'Ahyb', 'Ahyb at level interface', '', (/ ('once', i=1, 10) /))
   TYPE(ctrl_out), SAVE :: o_Bhyb = ctrl_out((/ 1, 1, 1, 1, 1, 1, 11, 11, 11, 11/), &
-    'Bhyb', '', '', (/ ('once', i=1, 10) /))
-  TYPE(ctrl_out), SAVE :: o_Ahyb_inter = ctrl_out((/ 1, 1, 1, 1, 1, 1, 11, 11, 11, 11/), &
-    'Ahyb_inter', '', '', (/ ('once', i=1, 10) /))
-  TYPE(ctrl_out), SAVE :: o_Bhyb_inter = ctrl_out((/ 1, 1, 1, 1, 1, 1, 11, 11, 11, 11/), &
-    'Bhyb_inter', '', '', (/ ('once', i=1, 10) /))
+    'Bhyb', 'Bhyb at level interface', '', (/ ('once', i=1, 10) /))
+  TYPE(ctrl_out), SAVE :: o_Ahyb_bounds = ctrl_out((/ 1, 1, 1, 1, 1, 1, 11, 11, 11, 11/), &
+    'Ahyb_bounds', '', '', (/ ('once', i=1, 10) /))
+  TYPE(ctrl_out), SAVE :: o_Bhyb_bounds = ctrl_out((/ 1, 1, 1, 1, 1, 1, 11, 11, 11, 11/), &
+    'Bhyb_bounds', '', '', (/ ('once', i=1, 10) /))
+!!! Composantes de la coordonnee sigma-hybride  au milieu des couches
+!!! Aps et Bps et interfaces
+  TYPE(ctrl_out), SAVE :: o_Ahyb_mid = ctrl_out((/ 1, 1, 1, 1, 1, 1, 11, 11, 11, 11/), &
+    'Ahyb_mid', 'Ahyb at the middle of the level', '', (/ ('once', i=1, 10) /))
+  TYPE(ctrl_out), SAVE :: o_Bhyb_mid = ctrl_out((/ 1, 1, 1, 1, 1, 1, 11, 11, 11, 11/), &
+    'Bhyb_mid', 'Bhyb at the middle of the level', '', (/ ('once', i=1, 10) /))
+  TYPE(ctrl_out), SAVE :: o_Ahyb_mid_bounds = ctrl_out((/ 1, 1, 1, 1, 1, 1, 11, 11, 11, 11/), &
+    'Ahyb_mid_bounds', '', '', (/ ('once', i=1, 10) /))
+  TYPE(ctrl_out), SAVE :: o_Bhyb_mid_bounds = ctrl_out((/ 1, 1, 1, 1, 1, 1, 11, 11, 11, 11/), &
+    'Bhyb_mid_bounds', '', '', (/ ('once', i=1, 10) /))
+
   TYPE(ctrl_out), SAVE :: o_Alt = ctrl_out((/ 1, 1, 1, 1, 1, 1, 11, 11, 11, 11/), &
     'Alt', '', '', (/ ('', i=1, 10) /))
@@ -1018,5 +1027,4 @@
 !FC
 
-
   TYPE(ctrl_out), SAVE, DIMENSION(4) :: o_l_mixmin      = (/             &
       ctrl_out((/ 10, 10, 10, 10, 10, 10, 11, 11, 11, 11/),'l_mixmin_ter',       &
@@ -1284,4 +1292,14 @@
 !--end add ThL
 
+!---CO2 fluxes for interactive CO2 configuration
+  TYPE(ctrl_out), SAVE :: o_flx_co2_ff = ctrl_out((/ 11, 11, 11, 11, 11, 11, 11, 11, 11, 1/), &
+    'flx_co2_ff', 'CO2 flux from fossil fuel and cement', '1', (/ ('', i=1, 10) /))
+  TYPE(ctrl_out), SAVE :: o_flx_co2_bb = ctrl_out((/ 11, 11, 11, 11, 11, 11, 11, 11, 11, 1/), &
+    'flx_co2_bb', 'CO2 flux from biomass burning', '1', (/ ('', i=1, 10) /))
+  TYPE(ctrl_out), SAVE :: o_flx_co2_ocean = ctrl_out((/ 11, 11, 11, 11, 11, 11, 11, 11, 11, 1/), &
+    'flx_co2_ocean', 'CO2 flux from the ocean', '1', (/ ('', i=1, 10) /))
+  TYPE(ctrl_out), SAVE :: o_flx_co2_land = ctrl_out((/ 11, 11, 11, 11, 11, 11, 11, 11, 11, 1/), &
+    'flx_co2_land', 'CO2 flux from the land', '1', (/ ('', i=1, 10) /))
+
 #ifdef CPP_StratAer
 !--extinction coefficient
@@ -1292,5 +1310,5 @@
 !--strat aerosol optical depth
   TYPE(ctrl_out), SAVE :: o_tau_strat_550 = ctrl_out((/ 11, 11, 11, 11, 11, 11, 11, 11, 11, 1/), &
-    'od550_strat_only', 'Stratospheric Aerosol Optical depth at 550 nm ', '1', (/ ('', i=1, 10) /))
+    'OD550_strat_only', 'Stratospheric Aerosol Optical depth at 550 nm ', '1', (/ ('', i=1, 10) /))
   TYPE(ctrl_out), SAVE :: o_tau_strat_1020 = ctrl_out((/ 11, 11, 11, 11, 11, 11, 11, 11, 11, 1/), &
     'OD1020_strat_only', 'Stratospheric Aerosol Optical depth at 1020 nm ', '1', (/ ('', i=1, 10) /))
@@ -1366,4 +1384,8 @@
   TYPE(ctrl_out), SAVE :: o_temp = ctrl_out((/ 2, 3, 4, 10, 10, 10, 11, 11, 11, 11/), &
     'temp', 'Air temperature', 'K', (/ ('', i=1, 10) /))
+  TYPE(ctrl_out), SAVE :: o_heat_volc = ctrl_out((/ 4, 10, 10, 10, 10, 10, 11, 11, 11, 11/), &
+    'heat_volc', 'SW heating rate due to volcano', 'K/s', (/ ('', i=1, 10) /))
+  TYPE(ctrl_out), SAVE :: o_cool_volc = ctrl_out((/ 4, 10, 10, 10, 10, 10, 11, 11, 11, 11/), &
+    'cool_volc', 'LW cooling rate due to volcano', 'K/s', (/ ('', i=1, 10) /))
   TYPE(ctrl_out), SAVE :: o_theta = ctrl_out((/ 2, 3, 4, 10, 10, 10, 11, 11, 11, 11/), &
     'theta', 'Potential air temperature', 'K', (/ ('', i=1, 10) /))
@@ -1508,6 +1530,8 @@
   TYPE(ctrl_out), SAVE :: o_clwcon = ctrl_out((/ 4, 10, 10, 10, 10, 10, 11, 11, 11, 11/), &
     'clwcon', 'Convective Cloud Liquid water content', 'kg/kg', (/ ('', i=1, 10) /))
+  TYPE(ctrl_out), SAVE :: o_Mipsh = ctrl_out((/ 4, 10, 10, 10, 10, 10, 11, 11, 11, 11/), &
+    'Mipsh', 'mass flux shed from adiab. ascents', 'kg/m2/s', (/ ('', i=1, 10) /))
   TYPE(ctrl_out), SAVE :: o_Ma = ctrl_out((/ 4, 10, 10, 10, 10, 10, 11, 11, 11, 11/), &
-    'Ma', 'undilute adiab updraft', 'kg/m2/s', (/ ('', i=1, 10) /))
+    'Ma', 'undilute adiab updraft mass flux', 'kg/m2/s', (/ ('', i=1, 10) /))
   TYPE(ctrl_out), SAVE :: o_dnwd = ctrl_out((/ 4, 10, 10, 10, 10, 10, 11, 11, 11, 11/), &
     'dnwd', 'saturated downdraft', 'kg/m2/s', (/ ('', i=1, 10) /))
@@ -1573,8 +1597,14 @@
   TYPE(ctrl_out), SAVE :: o_wdtrainA = ctrl_out((/ 4, 5, 10,  4, 10, 10, 11, 11, 11, 11 /), &
     'wdtrainA', 'precipitation from AA', '-', (/ ('', i=1, 10) /))
+  TYPE(ctrl_out), SAVE :: o_wdtrainS = ctrl_out((/ 4, 5, 10,  4, 10, 10, 11, 11, 11, 11 /), &
+    'wdtrainS', 'precipitation from shedding of AA', '-', (/ ('', i=1, 10) /))
   TYPE(ctrl_out), SAVE :: o_wdtrainM = ctrl_out((/ 4, 5, 10,  4, 10, 10, 11, 11, 11, 11 /), &
     'wdtrainM', 'precipitation from mixture', '-', (/ ('', i=1, 10) /))
   TYPE(ctrl_out), SAVE :: o_Vprecip = ctrl_out((/ 10, 10, 10, 10, 10, 10, 11, 11, 11, 11/), &
     'Vprecip', 'precipitation vertical profile', '-', (/ ('', i=1, 10) /))
+  TYPE(ctrl_out), SAVE :: o_qtaa = ctrl_out((/ 10, 10, 10, 10, 10, 10, 11, 11, 11, 11/), &
+    'qtaa', 'specific total water in adiabatic ascents', 'kg/kg', (/ ('', i=1, 10) /))
+  TYPE(ctrl_out), SAVE :: o_clwaa = ctrl_out((/ 10, 10, 10, 10, 10, 10, 11, 11, 11, 11/), &
+    'Clwaa', 'specific condensed water in adiabatic ascents', 'kg/kg', (/ ('', i=1, 10) /))
   TYPE(ctrl_out), SAVE :: o_ftd = ctrl_out((/ 4, 5, 10, 10, 10, 10, 11, 11, 11, 11/), &
     'ftd', 'tend temp due aux descentes precip', '-', (/ ('', i=1, 10) /))
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_output_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_output_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_output_mod.F90	(revision 3605)
@@ -131,5 +131,5 @@
                                                                        90.,   90.,   90.,   90.,   90. /)
     REAL, DIMENSION(klev,2) :: Ahyb_bounds, Bhyb_bounds
-    REAL, DIMENSION(klev)   :: lev_index
+    REAL, DIMENSION(klev+1)   :: lev_index
                 
 #ifdef CPP_XIOS
@@ -156,4 +156,5 @@
       lev_index(ilev) = REAL(ilev)
     END DO
+      lev_index(klev+1) = REAL(klev+1)
 
     IF (.NOT. ALLOCATED(o_trac)) ALLOCATE(o_trac(nqtot))
@@ -361,4 +362,6 @@
     CALL wxios_add_vaxis("klev", levmax(iff) - levmin(iff) + 1, &
                           lev_index(levmin(iff):levmax(iff)))
+    CALL wxios_add_vaxis("klevp1", klev+1, &
+                          lev_index(1:klev+1))
     CALL wxios_add_vaxis("bnds", 2, (/1.,2./))
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_output_write_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_output_write_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_output_write_mod.F90	(revision 3605)
@@ -17,5 +17,5 @@
   SUBROUTINE phys_output_write(itap, pdtphys, paprs, pphis, &
        pplay, lmax_th, aerosol_couple,         &
-       ok_ade, ok_aie, ivap, iliq, isol, new_aod, ok_sync, &
+       ok_ade, ok_aie, ok_volcan, ivap, iliq, isol, new_aod, ok_sync, &
        ptconv, read_climoz, clevSTD, ptconvth, &
        d_u, d_t, qx, d_qx, zmasse, flag_aerosol, flag_aerosol_strat, ok_cdnc)
@@ -32,5 +32,6 @@
     USE phys_output_ctrlout_mod, ONLY: o_phis, o_aire, is_ter, is_lic, is_oce, &
          o_longitude, o_latitude, &
-         o_Ahyb, o_Bhyb,o_Ahyb_inter, o_Bhyb_inter, & 
+         o_Ahyb, o_Bhyb,o_Ahyb_bounds, o_Bhyb_bounds, & 
+         o_Ahyb_mid, o_Bhyb_mid,o_Ahyb_mid_bounds, o_Bhyb_mid_bounds, & 
          is_ave, is_sic, o_contfracATM, o_contfracOR, &
          o_aireTER, o_flat, o_slp, o_ptstar, o_pt0, o_tsol, &
@@ -72,5 +73,6 @@
          o_uwat, o_vwat, &
          o_ptop, o_fbase, o_plcl, o_plfc, &
-         o_wbeff, o_convoccur, o_cape_max, o_upwd, o_ep,o_epmax_diag, o_Ma, &
+         o_wbeff, o_convoccur, o_cape_max, o_upwd, o_ep,o_epmax_diag, &
+         o_Mipsh, o_Ma, &
          o_dnwd, o_dnwd0, o_ftime_deepcv, o_ftime_con, o_mc, &
          o_prw, o_prlw, o_prsw, o_s_pblh, o_s_pblt, o_s_lcl, &
@@ -87,5 +89,6 @@
          o_wake_s, o_wake_deltat, o_wake_deltaq, &
          o_wake_omg, o_dtwak, o_dqwak, o_dqwak2d, o_Vprecip, &
-         o_ftd, o_fqd, o_wdtrainA, o_wdtrainM, &
+         o_qtaa, o_Clwaa, &
+         o_ftd, o_fqd, o_wdtrainA, o_wdtrainS, o_wdtrainM, &
          o_n2, o_s2, o_proba_notrig, &
          o_random_notrig, o_ale_bl_stat, &
@@ -196,5 +199,7 @@
 ! Tropopause
          o_p_tropopause, o_z_tropopause, o_t_tropopause,  &
-         o_col_O3_strato, o_col_O3_tropo, &               ! Added ThL
+         o_col_O3_strato, o_col_O3_tropo,                 & 
+!--interactive CO2
+         o_flx_co2_ocean, o_flx_co2_land, o_flx_co2_ff, o_flx_co2_bb, &
          o_t_int, o_s_int, o_ds_ns, o_dt_ns, o_dter, o_dser, o_tkt, o_tks, &
          o_rf, o_taur
@@ -214,4 +219,7 @@
          o_vsed_aer, o_tau_strat_1020, o_ext_strat_1020, o_f_r_wet
 #endif
+    
+    USE phys_output_ctrlout_mod, ONLY: o_heat_volc, o_cool_volc !NL
+    USE phys_state_var_mod, ONLY: heat_volc, cool_volc !NL
 
     USE phys_state_var_mod, ONLY: pctsrf, rain_fall, snow_fall, &
@@ -227,5 +235,5 @@
          delta_tsurf, &
          wstar, cape, ema_pcb, ema_pct, &
-         ema_cbmf, Ma, fm_therm, ale_bl, alp_bl, ale, &
+         ema_cbmf, Mipsh, Ma, fm_therm, ale_bl, alp_bl, ale, &
          alp, cin, wake_pe, wake_dens, wake_s, wake_deltat, &
          wake_deltaq, ftd, fqd, ale_bl_trig, albsol1, &
@@ -244,4 +252,5 @@
 
     USE phys_local_var_mod, ONLY: zxfluxlat, slp, ptstar, pt0, zxtsol, zt2m, &
+         zt2m_cor,zq2m_cor,zu10m_cor,zv10m_cor, zrh2m_cor, zqsat2m_cor, &
          t2m_min_mon, t2m_max_mon, evap, &
          l_mixmin,l_mix, &
@@ -267,6 +276,6 @@
          kh         ,kh_x       ,kh_w       , &
          cv_gen, wake_h, &
-         wake_omg, d_t_wake, d_q_wake, Vprecip, &
-         wdtrainA, wdtrainM, n2, s2, proba_notrig, &
+         wake_omg, d_t_wake, d_q_wake, Vprecip, qtaa, Clw, &
+         wdtrainA, wdtrainS, wdtrainM, n2, s2, proba_notrig, &
          random_notrig, &
          alp_bl_det, alp_bl_fluct_m, alp_bl_conv, &
@@ -329,4 +338,6 @@
 #endif
 
+    USE carbon_cycle_mod, ONLY: fco2_ff, fco2_bb, fco2_land, fco2_ocean
+
     USE phys_output_var_mod, ONLY: vars_defined, snow_o, zfra_o, bils_diss, &
          bils_ec,bils_ech, bils_tke, bils_kinetic, bils_latent, bils_enthalp, &
@@ -368,5 +379,5 @@
     ! ug Pour les sorties XIOS
     USE xios
-    USE wxios, ONLY: wxios_closedef, missing_val
+    USE wxios, ONLY: wxios_closedef, missing_val, wxios_set_context
 #endif
     USE phys_cal_mod, ONLY : mth_len
@@ -390,5 +401,5 @@
     INTEGER, DIMENSION(klon) :: lmax_th
     LOGICAL :: aerosol_couple, ok_sync
-    LOGICAL :: ok_ade, ok_aie, new_aod
+    LOGICAL :: ok_ade, ok_aie, ok_volcan, new_aod
     LOGICAL, DIMENSION(klon, klev) :: ptconv, ptconvth
     REAL :: pdtphys
@@ -417,5 +428,6 @@
     REAL, PARAMETER :: dobson_u = 2.1415e-05 ! Dobson unit, in kg m-2
 !   REAL, PARAMETER :: missing_val=nf90_fill_real
-    REAL, DIMENSION(klev,2) :: Ahyb_bounds, Bhyb_bounds
+    REAL, DIMENSION(klev+1,2) :: Ahyb_bounds, Bhyb_bounds
+    REAL, DIMENSION(klev,2) :: Ahyb_mid_bounds, Bhyb_mid_bounds
     INTEGER :: ilev
 #ifndef CPP_XIOS
@@ -440,15 +452,34 @@
     CALL set_itau_iophy(itau_w)
 
-    IF (.NOT.vars_defined) THEN
-       iinitend = 2
-    ELSE
+ !   IF (.NOT.vars_defined) THEN
        iinitend = 1
-    ENDIF
-
-    DO ilev=1,klev
-      Ahyb_bounds(ilev,1) = ap(ilev)
-      Ahyb_bounds(ilev,2) = ap(ilev+1)
-      Bhyb_bounds(ilev,1) = bp(ilev)
-      Bhyb_bounds(ilev,2) = bp(ilev+1)
+ !   ELSE
+ !      iinitend = 1
+ !   ENDIF
+
+#ifdef CPP_XIOS
+    CALL wxios_set_context
+#endif
+
+    Ahyb_bounds(1,1) = 0.
+    Ahyb_bounds(1,2) = aps(1)
+    Bhyb_bounds(1,1) = 1.
+    Bhyb_bounds(1,2) = bps(1)    
+    DO ilev=2,klev
+      Ahyb_bounds(ilev,1) = aps(ilev-1)
+      Ahyb_bounds(ilev,2) = aps(ilev)
+      Bhyb_bounds(ilev,1) = bps(ilev-1)
+      Bhyb_bounds(ilev,2) = bps(ilev)
+    ENDDO
+     Ahyb_bounds(klev+1,1) = aps(klev)
+     Ahyb_bounds(klev+1,2) = 0.
+     Bhyb_bounds(klev+1,1) = bps(klev)
+     Bhyb_bounds(klev+1,2) = 0.
+
+    DO ilev=1, klev
+      Ahyb_mid_bounds(ilev,1) = ap(ilev)
+      Ahyb_mid_bounds(ilev,2) = ap(ilev+1)
+      Bhyb_mid_bounds(ilev,1) = bp(ilev)
+      Bhyb_mid_bounds(ilev,2) = bp(ilev+1)
     END DO
 
@@ -565,8 +596,12 @@
        CALL histwrite_phy("R_incl",R_incl)
        CALL histwrite_phy("solaire",solaire)
-       CALL histwrite_phy(o_Ahyb, aps)
-       CALL histwrite_phy(o_Bhyb, bps)
-       CALL histwrite_phy(o_Ahyb_inter, Ahyb_bounds)
-       CALL histwrite_phy(o_Bhyb_inter, Bhyb_bounds)
+       CALL histwrite_phy(o_Ahyb, ap)
+       CALL histwrite_phy(o_Bhyb, bp)
+       CALL histwrite_phy(o_Ahyb_bounds, Ahyb_bounds)
+       CALL histwrite_phy(o_Bhyb_bounds, Bhyb_bounds)
+       CALL histwrite_phy(o_Ahyb_mid, aps)
+       CALL histwrite_phy(o_Bhyb_mid, bps)
+       CALL histwrite_phy(o_Ahyb_mid_bounds, Ahyb_mid_bounds)
+       CALL histwrite_phy(o_Bhyb_mid_bounds, Bhyb_mid_bounds)
        CALL histwrite_phy(o_longitude, longitude_deg)
        CALL histwrite_phy(o_latitude, latitude_deg)
@@ -636,7 +671,7 @@
        CALL histwrite_phy(o_slp, slp)
        CALL histwrite_phy(o_tsol, zxtsol)
-       CALL histwrite_phy(o_t2m, zt2m)
-       CALL histwrite_phy(o_t2m_min, zt2m)
-       CALL histwrite_phy(o_t2m_max, zt2m)
+       CALL histwrite_phy(o_t2m, zt2m_cor)
+       CALL histwrite_phy(o_t2m_min, zt2m_cor)
+       CALL histwrite_phy(o_t2m_max, zt2m_cor)
        CALL histwrite_phy(o_t2m_max_mon, t2m_max_mon)
        CALL histwrite_phy(o_t2m_min_mon, t2m_min_mon)
@@ -644,5 +679,5 @@
        IF (vars_defined) THEN
           DO i=1, klon
-             zx_tmp_fi2d(i)=SQRT(zu10m(i)*zu10m(i)+zv10m(i)*zv10m(i))
+             zx_tmp_fi2d(i)=SQRT(zu10m_cor(i)*zu10m_cor(i)+zv10m_cor(i)*zv10m_cor(i))
           ENDDO
        ENDIF
@@ -651,5 +686,5 @@
        IF (vars_defined) THEN
           DO i=1, klon
-             zx_tmp_fi2d(i)=SQRT(zu10m(i)*zu10m(i)+zv10m(i)*zv10m(i))
+             zx_tmp_fi2d(i)=SQRT(zu10m_cor(i)*zu10m_cor(i)+zv10m_cor(i)*zv10m_cor(i))
           ENDDO
        ENDIF
@@ -664,8 +699,8 @@
        ENDIF
        CALL histwrite_phy(o_sicf, zx_tmp_fi2d)
-       CALL histwrite_phy(o_q2m, zq2m)
+       CALL histwrite_phy(o_q2m, zq2m_cor)
        CALL histwrite_phy(o_ustar, zustar)
-       CALL histwrite_phy(o_u10m, zu10m)
-       CALL histwrite_phy(o_v10m, zv10m)
+       CALL histwrite_phy(o_u10m, zu10m_cor)
+       CALL histwrite_phy(o_v10m, zv10m_cor)
 
        IF (vars_defined) THEN
@@ -716,6 +751,15 @@
        CALL histwrite_phy(o_fsnow, zfra_o)
        CALL histwrite_phy(o_evap, evap)
-       CALL histwrite_phy(o_tops, topsw*swradcorr)
-       CALL histwrite_phy(o_tops0, topsw0*swradcorr)
+
+       IF (vars_defined) THEN
+         zx_tmp_fi2d = topsw*swradcorr
+       ENDIF
+       CALL histwrite_phy(o_tops, zx_tmp_fi2d)
+
+       IF (vars_defined) THEN
+         zx_tmp_fi2d = topsw0*swradcorr
+       ENDIF
+       CALL histwrite_phy(o_tops0, zx_tmp_fi2d)
+
        CALL histwrite_phy(o_topl, toplw)
        CALL histwrite_phy(o_topl0, toplw0)
@@ -750,14 +794,41 @@
        ENDIF
        CALL histwrite_phy(o_nettop, zx_tmp_fi2d)
-       CALL histwrite_phy(o_SWup200, SWup200*swradcorr)
-       CALL histwrite_phy(o_SWup200clr, SWup200clr*swradcorr)
-       CALL histwrite_phy(o_SWdn200, SWdn200*swradcorr)
-       CALL histwrite_phy(o_SWdn200clr, SWdn200clr*swradcorr)
+       
+       IF (vars_defined) THEN
+          zx_tmp_fi2d = SWup200*swradcorr
+       ENDIF
+       CALL histwrite_phy(o_SWup200, zx_tmp_fi2d)
+       
+       IF (vars_defined) THEN
+          zx_tmp_fi2d = SWup200clr*swradcorr
+       ENDIF
+       CALL histwrite_phy(o_SWup200clr, zx_tmp_fi2d)
+       
+       IF (vars_defined) THEN
+          zx_tmp_fi2d = SWdn200*swradcorr
+       ENDIF
+       CALL histwrite_phy(o_SWdn200, zx_tmp_fi2d)
+       
+       
+       IF (vars_defined) THEN
+          zx_tmp_fi2d = SWdn200clr*swradcorr
+       ENDIF
+       CALL histwrite_phy(o_SWdn200clr, zx_tmp_fi2d)
+       
        CALL histwrite_phy(o_LWup200, LWup200)
        CALL histwrite_phy(o_LWup200clr, LWup200clr)
        CALL histwrite_phy(o_LWdn200, LWdn200)
        CALL histwrite_phy(o_LWdn200clr, LWdn200clr)
-       CALL histwrite_phy(o_sols, solsw*swradcorr)
-       CALL histwrite_phy(o_sols0, solsw0*swradcorr)
+       
+       IF (vars_defined) THEN
+          zx_tmp_fi2d = solsw*swradcorr
+       ENDIF
+       CALL histwrite_phy(o_sols, zx_tmp_fi2d)
+       
+       
+       IF (vars_defined) THEN
+          zx_tmp_fi2d = solsw0*swradcorr
+       ENDIF
+       CALL histwrite_phy(o_sols0, zx_tmp_fi2d)
        CALL histwrite_phy(o_soll, sollw)
        CALL histwrite_phy(o_soll0, sollw0)
@@ -909,5 +980,5 @@
           IF (iflag_pbl > 1) THEN
              CALL histwrite_phy(o_tke_srf(nsrf),  pbl_tke(:,1:klev,nsrf))
-             CALL histwrite_phy(o_l_mix(nsrf),  l_mix(:,1:klev,nsrf))
+             !CALL histwrite_phy(o_l_mix(nsrf),  l_mix(:,1:klev,nsrf))
              CALL histwrite_phy(o_l_mixmin(nsrf),  l_mixmin(:,1:klev,nsrf))
              CALL histwrite_phy(o_tke_max_srf(nsrf),  pbl_tke(:,1:klev,nsrf))
@@ -954,8 +1025,17 @@
        CALL histwrite_phy(o_cldt, cldt)
        CALL histwrite_phy(o_JrNt, JrNt)
-       CALL histwrite_phy(o_cldljn, cldl*JrNt)
-       CALL histwrite_phy(o_cldmjn, cldm*JrNt)
-       CALL histwrite_phy(o_cldhjn, cldh*JrNt)
-       CALL histwrite_phy(o_cldtjn, cldt*JrNt)
+       
+       IF (vars_defined)  zx_tmp_fi2d=cldl*JrNt      
+       CALL histwrite_phy(o_cldljn, zx_tmp_fi2d)
+       
+       IF (vars_defined)  zx_tmp_fi2d=cldm*JrNt      
+       CALL histwrite_phy(o_cldmjn, zx_tmp_fi2d)
+       
+       IF (vars_defined)  zx_tmp_fi2d=cldh*JrNt
+       CALL histwrite_phy(o_cldhjn, zx_tmp_fi2d)
+       
+       IF (vars_defined)  zx_tmp_fi2d=cldt*JrNt
+       CALL histwrite_phy(o_cldtjn, zx_tmp_fi2d)
+       
        CALL histwrite_phy(o_cldq, cldq)
        IF (vars_defined)       zx_tmp_fi2d(1:klon) = flwp(1:klon)
@@ -1108,4 +1188,5 @@
        ! Wakes
        IF (iflag_con.EQ.3) THEN
+          CALL histwrite_phy(o_Mipsh, Mipsh)
           IF (iflag_wake>=1) THEN
              CALL histwrite_phy(o_ale_wk, ale_wake)
@@ -1158,5 +1239,5 @@
              IF (vars_defined) zx_tmp_fi3d(1:klon,1:klev)=d_q_wake(1:klon,1:klev)/pdtphys
              CALL histwrite_phy(o_dqwak, zx_tmp_fi3d)
-             CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
+             IF (vars_defined) CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
              CALL histwrite_phy(o_dqwak2d, zx_tmp_fi2d)
           ENDIF ! iflag_wake>=1
@@ -1168,5 +1249,8 @@
           ! etendue a iflag_con=3 (jyg)
           CALL histwrite_phy(o_Vprecip, Vprecip)
+          CALL histwrite_phy(o_qtaa, qtaa)
+          CALL histwrite_phy(o_clwaa, clw)
           CALL histwrite_phy(o_wdtrainA, wdtrainA)
+          CALL histwrite_phy(o_wdtrainS, wdtrainS)
           CALL histwrite_phy(o_wdtrainM, wdtrainM)
        ENDIF !(iflag_con.EQ.3.or.iflag_con.EQ.30)
@@ -1208,5 +1292,5 @@
           IF (slab_gm) THEN
              CALL histwrite_phy(o_slab_gm, dt_gm(:,1:nslay))
-          END IF
+          ENDIF
           IF (slab_hdiff) THEN
             IF (nslay.EQ.1) THEN
@@ -1257,5 +1341,5 @@
 !       CALL histwrite_phy(o_rh2m_max, zx_tmp_fi2d)
 
-       CALL histwrite_phy(o_qsat2m, qsat2m)
+       CALL histwrite_phy(o_qsat2m, zqsat2m_cor)
        CALL histwrite_phy(o_tpot, tpot)
        CALL histwrite_phy(o_tpote, tpote)
@@ -1322,13 +1406,18 @@
 
 ! ThL -- In the following, we assume read_climoz == 1
-       zx_tmp_fi2d = 0.0    ! Computation for strato, added ThL
-       DO k=1, klev
-          zx_tmp_fi2d(:) = zx_tmp_fi2d(:) + wo(:,k,1) * stratomask(:,k) * 1.e3
-       END DO
+       IF (vars_defined) THEN
+         zx_tmp_fi2d = 0.0    ! Computation for strato, added ThL
+         DO k=1, klev
+            zx_tmp_fi2d(:) = zx_tmp_fi2d(:) + wo(:,k,1) * stratomask(:,k) * 1.e3
+         END DO
+       ENDIF
        CALL histwrite_phy(o_col_O3_strato, zx_tmp_fi2d) ! Added ThL
-       zx_tmp_fi2d = 0.0    ! Computation for tropo, added ThL
-       DO k=1, klev
-          zx_tmp_fi2d(:) = zx_tmp_fi2d(:) + wo(:,k,1) * (1.0-stratomask(:,k)) * 1.e3
-       END DO
+
+       IF (vars_defined) THEN
+         zx_tmp_fi2d = 0.0    ! Computation for tropo, added ThL
+         DO k=1, klev
+            zx_tmp_fi2d(:) = zx_tmp_fi2d(:) + wo(:,k,1) * (1.0-stratomask(:,k)) * 1.e3
+         END DO
+       ENDIF
        CALL histwrite_phy(o_col_O3_tropo, zx_tmp_fi2d)   ! Added ThL
 ! end add ThL
@@ -1370,9 +1459,28 @@
        ENDIF
 #endif
+       !NL
+       IF (ok_volcan .AND. ok_ade) THEN
+          DO k=1, klev
+             IF (vars_defined) zx_tmp_fi3d(:,k)=heat_volc(:,k)*swradcorr(:)
+          ENDDO
+          CALL histwrite_phy(o_heat_volc, zx_tmp_fi3d)
+          DO k=1, klev
+             IF (vars_defined) zx_tmp_fi3d(:,k)=cool_volc(:,k)
+          ENDDO
+          CALL histwrite_phy(o_cool_volc, zx_tmp_fi3d)
+       ENDIF
        IF (ok_ade) THEN
-          CALL histwrite_phy(o_topswad, topswad_aero*swradcorr)
-          CALL histwrite_phy(o_topswad0, topswad0_aero*swradcorr)
-          CALL histwrite_phy(o_solswad, solswad_aero*swradcorr)
-          CALL histwrite_phy(o_solswad0, solswad0_aero*swradcorr)
+          IF (vars_defined) zx_tmp_fi2d(:)=topswad_aero*swradcorr
+          CALL histwrite_phy(o_topswad, zx_tmp_fi2d)
+          
+          IF (vars_defined) zx_tmp_fi2d(:)=topswad0_aero*swradcorr
+          CALL histwrite_phy(o_topswad0, zx_tmp_fi2d)
+                    
+          IF (vars_defined) zx_tmp_fi2d(:)=solswad_aero*swradcorr
+          CALL histwrite_phy(o_solswad, zx_tmp_fi2d)
+                    
+          IF (vars_defined) zx_tmp_fi2d(:)=solswad0_aero*swradcorr
+          CALL histwrite_phy(o_solswad0, zx_tmp_fi2d)
+          
           CALL histwrite_phy(o_toplwad, toplwad_aero)
           CALL histwrite_phy(o_toplwad0, toplwad0_aero)
@@ -1381,34 +1489,37 @@
           !====MS forcing diagnostics
           IF (new_aod) THEN
-             zx_tmp_fi2d(:)=topsw_aero(:,1)*swradcorr(:)
+          !ym warning : topsw_aero, solsw_aero, topsw0_aero, solsw0_aero are not defined by model
+          !ym => init to 0 in radlwsw_m.F90 ztopsw_aero, zsolsw_aero, ztopsw0_aero, zsolsw0_aero
+
+             IF (vars_defined) zx_tmp_fi2d(:)=topsw_aero(:,1)*swradcorr(:)
              CALL histwrite_phy(o_swtoaas_nat,zx_tmp_fi2d)
-             zx_tmp_fi2d(:)=solsw_aero(:,1)*swradcorr(:)
+             IF (vars_defined) zx_tmp_fi2d(:)=solsw_aero(:,1)*swradcorr(:)
              CALL histwrite_phy(o_swsrfas_nat,zx_tmp_fi2d)
-             zx_tmp_fi2d(:)=topsw0_aero(:,1)*swradcorr(:)
+             IF (vars_defined) zx_tmp_fi2d(:)=topsw0_aero(:,1)*swradcorr(:)
              CALL histwrite_phy(o_swtoacs_nat,zx_tmp_fi2d)
-             zx_tmp_fi2d(:)=solsw0_aero(:,1)*swradcorr(:)
+             IF (vars_defined) zx_tmp_fi2d(:)=solsw0_aero(:,1)*swradcorr(:)
              CALL histwrite_phy(o_swsrfcs_nat,zx_tmp_fi2d)
              !ant
-             zx_tmp_fi2d(:)=topsw_aero(:,2)*swradcorr(:)
+             IF (vars_defined) zx_tmp_fi2d(:)=topsw_aero(:,2)*swradcorr(:)
              CALL histwrite_phy(o_swtoaas_ant,zx_tmp_fi2d)
-             zx_tmp_fi2d(:)=solsw_aero(:,2)*swradcorr(:)
+             IF (vars_defined) zx_tmp_fi2d(:)=solsw_aero(:,2)*swradcorr(:)
              CALL histwrite_phy(o_swsrfas_ant,zx_tmp_fi2d)
-             zx_tmp_fi2d(:)=topsw0_aero(:,2)*swradcorr(:)
+             IF (vars_defined) zx_tmp_fi2d(:)=topsw0_aero(:,2)*swradcorr(:)
              CALL histwrite_phy(o_swtoacs_ant,zx_tmp_fi2d)
-             zx_tmp_fi2d(:)=solsw0_aero(:,2)*swradcorr(:)
+             IF (vars_defined) zx_tmp_fi2d(:)=solsw0_aero(:,2)*swradcorr(:)
              CALL histwrite_phy(o_swsrfcs_ant,zx_tmp_fi2d)
              !cf
              IF (.not. aerosol_couple) THEN
-                zx_tmp_fi2d(:)=topswcf_aero(:,1)*swradcorr(:)
+                IF (vars_defined) zx_tmp_fi2d(:)=topswcf_aero(:,1)*swradcorr(:)
                 CALL histwrite_phy(o_swtoacf_nat,zx_tmp_fi2d)
-                zx_tmp_fi2d(:)=solswcf_aero(:,1)*swradcorr(:)
+                IF (vars_defined) zx_tmp_fi2d(:)=solswcf_aero(:,1)*swradcorr(:)
                 CALL histwrite_phy(o_swsrfcf_nat,zx_tmp_fi2d)
-                zx_tmp_fi2d(:)=topswcf_aero(:,2)*swradcorr(:)
+                IF (vars_defined) zx_tmp_fi2d(:)=topswcf_aero(:,2)*swradcorr(:)
                 CALL histwrite_phy(o_swtoacf_ant,zx_tmp_fi2d)
-                zx_tmp_fi2d(:)=solswcf_aero(:,2)*swradcorr(:)
+                IF (vars_defined) zx_tmp_fi2d(:)=solswcf_aero(:,2)*swradcorr(:)
                 CALL histwrite_phy(o_swsrfcf_ant,zx_tmp_fi2d)
-                zx_tmp_fi2d(:)=topswcf_aero(:,3)*swradcorr(:)
+                IF (vars_defined) zx_tmp_fi2d(:)=topswcf_aero(:,3)*swradcorr(:)
                 CALL histwrite_phy(o_swtoacf_zero,zx_tmp_fi2d)
-                zx_tmp_fi2d(:)=solswcf_aero(:,3)*swradcorr(:)
+                IF (vars_defined) zx_tmp_fi2d(:)=solswcf_aero(:,3)*swradcorr(:)
                 CALL histwrite_phy(o_swsrfcf_zero,zx_tmp_fi2d)
              ENDIF
@@ -1417,8 +1528,15 @@
        ENDIF
        IF (ok_aie) THEN
-          CALL histwrite_phy(o_topswai, topswai_aero*swradcorr)
-          CALL histwrite_phy(o_toplwai, toplwai_aero*swradcorr)
-          CALL histwrite_phy(o_solswai, solswai_aero*swradcorr)
-          CALL histwrite_phy(o_sollwai, sollwai_aero*swradcorr)
+          IF (vars_defined) zx_tmp_fi2d(:)= topswai_aero*swradcorr
+          CALL histwrite_phy(o_topswai, zx_tmp_fi2d)
+          
+          IF (vars_defined) zx_tmp_fi2d(:)=toplwai_aero*swradcorr
+          CALL histwrite_phy(o_toplwai, zx_tmp_fi2d)
+          
+          IF (vars_defined) zx_tmp_fi2d(:)=solswai_aero*swradcorr
+          CALL histwrite_phy(o_solswai, zx_tmp_fi2d)
+          
+          IF (vars_defined) zx_tmp_fi2d(:)=sollwai_aero*swradcorr
+          CALL histwrite_phy(o_sollwai, zx_tmp_fi2d)
        ENDIF
        IF (flag_aerosol.GT.0.AND.ok_cdnc) THEN
@@ -1435,5 +1553,5 @@
           CALL histwrite_phy(o_icc3dstra, icc3dstra)
           CALL histwrite_phy(o_cldicemxrat, zfice)
-          zx_tmp_fi3d(:,:)=1-zfice(:,:)
+          IF (vars_defined) zx_tmp_fi3d(:,:)=1-zfice(:,:)
           CALL histwrite_phy(o_cldwatmxrat, zx_tmp_fi3d)
           CALL histwrite_phy(o_reffclwtop, reffclwtop)
@@ -1450,5 +1568,8 @@
        CALL histwrite_phy(o_ovap, q_seri)
        CALL histwrite_phy(o_oliq, ql_seri)
-       CALL histwrite_phy(o_ocond, ql_seri+qs_seri)
+
+       IF (vars_defined) zx_tmp_fi3d = ql_seri+qs_seri
+       CALL histwrite_phy(o_ocond, zx_tmp_fi3d)
+
        CALL histwrite_phy(o_geop, zphi)
        CALL histwrite_phy(o_vitu, u_seri)
@@ -1457,5 +1578,7 @@
        CALL histwrite_phy(o_pres, pplay)
        CALL histwrite_phy(o_paprs, paprs(:,1:klev))
-       CALL histwrite_phy(o_zfull,zphi/RG)
+       
+       IF (vars_defined) zx_tmp_fi3d = zphi/RG
+       CALL histwrite_phy(o_zfull,zx_tmp_fi3d)
 
 #ifdef CPP_XIOS
@@ -1502,10 +1625,11 @@
        CALL histwrite_phy(o_rnebjn, zx_tmp_fi3d)
        CALL histwrite_phy(o_rhum, zx_rh)
-       CALL histwrite_phy(o_ozone, &
-            wo(:, :, 1) * dobson_u * 1e3 / zmasse / rmo3 * rmd)
+       
+       IF (vars_defined) zx_tmp_fi3d = wo(:, :, 1) * dobson_u * 1e3 / zmasse / rmo3 * rmd
+       CALL histwrite_phy(o_ozone, zx_tmp_fi3d)
 
        IF (read_climoz == 2) THEN
-          CALL histwrite_phy(o_ozone_light, &
-               wo(:, :, 2) * dobson_u * 1e3 / zmasse / rmo3 * rmd)
+         IF (vars_defined) zx_tmp_fi3d = wo(:, :, 2) * dobson_u * 1e3 / zmasse / rmo3 * rmd 
+         CALL histwrite_phy(o_ozone_light, zx_tmp_fi3d)
        ENDIF
 
@@ -1515,14 +1639,14 @@
 
        CALL histwrite_phy(o_dqphy,  d_qx(:,:,ivap))
-       CALL water_int(klon,klev,d_qx(:,:,ivap),zmasse,zx_tmp_fi2d)
+       IF (vars_defined) CALL water_int(klon,klev,d_qx(:,:,ivap),zmasse,zx_tmp_fi2d)
        CALL histwrite_phy(o_dqphy2d,  zx_tmp_fi2d)
 
        CALL histwrite_phy(o_dqlphy,  d_qx(:,:,iliq))
-       CALL water_int(klon,klev,d_qx(:,:,iliq),zmasse,zx_tmp_fi2d)
+       IF (vars_defined) CALL water_int(klon,klev,d_qx(:,:,iliq),zmasse,zx_tmp_fi2d)
        CALL histwrite_phy(o_dqlphy2d,  zx_tmp_fi2d)
 
        IF (nqo.EQ.3) THEN
        CALL histwrite_phy(o_dqsphy,  d_qx(:,:,isol))
-       CALL water_int(klon,klev,d_qx(:,:,isol),zmasse,zx_tmp_fi2d)
+       IF (vars_defined) CALL water_int(klon,klev,d_qx(:,:,isol),zmasse,zx_tmp_fi2d)
        CALL histwrite_phy(o_dqsphy2d,  zx_tmp_fi2d)
        ELSE 
@@ -1589,5 +1713,5 @@
        ENDIF
        CALL histwrite_phy(o_dtcon, zx_tmp_fi3d)
-       if(iflag_thermals.eq.0)then
+       IF (iflag_thermals.EQ.0) THEN
           IF (vars_defined) THEN
              zx_tmp_fi3d(1:klon,1:klev)=d_t_con(1:klon,1:klev)/pdtphys + &
@@ -1595,5 +1719,5 @@
           ENDIF
           CALL histwrite_phy(o_tntc, zx_tmp_fi3d)
-       else if(iflag_thermals.ge.1.and.iflag_wake.EQ.1)then
+       ELSE IF(iflag_thermals.GE.1.AND.iflag_wake.EQ.1) THEN
           IF (vars_defined) THEN
              zx_tmp_fi3d(1:klon,1:klev)=d_t_con(1:klon,1:klev)/pdtphys + &
@@ -1602,5 +1726,5 @@
           ENDIF
           CALL histwrite_phy(o_tntc, zx_tmp_fi3d)
-       endif
+       ENDIF
        IF (vars_defined) zx_tmp_fi3d(1:klon,1:klev)=d_u_con(1:klon,1:klev)/pdtphys
        CALL histwrite_phy(o_ducon, zx_tmp_fi3d)
@@ -1609,5 +1733,5 @@
        IF (vars_defined) zx_tmp_fi3d(1:klon,1:klev)=d_q_con(1:klon,1:klev)/pdtphys
        CALL histwrite_phy(o_dqcon, zx_tmp_fi3d)
-       CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
+       IF (vars_defined) CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
        CALL histwrite_phy(o_dqcon2d, zx_tmp_fi2d)
 
@@ -1631,5 +1755,5 @@
        IF (vars_defined) zx_tmp_fi3d(1:klon,1:klev)=d_q_lsc(1:klon,1:klev)/pdtphys
        CALL histwrite_phy(o_dqlsc, zx_tmp_fi3d)
-       CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
+       IF (vars_defined) CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
        CALL histwrite_phy(o_dqlsc2d, zx_tmp_fi2d)
        IF (vars_defined) zx_tmp_fi3d(1:klon,1:klev)=beta_prec(1:klon,1:klev)
@@ -1644,16 +1768,16 @@
           IF (vars_defined) zx_tmp_fi3d(1:klon,1:klev)=d_q_lscth(1:klon,1:klev)/pdtphys
           CALL histwrite_phy(o_dqlscth, zx_tmp_fi3d)
-          CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
+          IF (vars_defined) CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
           CALL histwrite_phy(o_dqlscth2d, zx_tmp_fi2d)
           IF (vars_defined) zx_tmp_fi3d(1:klon,1:klev)=d_q_lscst(1:klon,1:klev)/pdtphys
           CALL histwrite_phy(o_dqlscst, zx_tmp_fi3d)
-          CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
+          IF (vars_defined) CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
           CALL histwrite_phy(o_dqlscst2d, zx_tmp_fi2d)
           CALL histwrite_phy(o_plulth, plul_th)
           CALL histwrite_phy(o_plulst, plul_st)
           IF (vars_defined) THEN
-             do i=1,klon
+             DO i=1,klon
                 zx_tmp_fi2d(1:klon)=lmax_th(:)
-             enddo
+             ENDDO
           ENDIF
           CALL histwrite_phy(o_lmaxth, zx_tmp_fi2d)
@@ -1702,5 +1826,5 @@
        IF (vars_defined) zx_tmp_fi3d(1:klon,1:klev)=d_q_vdf(1:klon,1:klev)/pdtphys
        CALL histwrite_phy(o_dqvdf, zx_tmp_fi3d)
-       CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
+       IF (vars_defined) CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
        CALL histwrite_phy(o_dqvdf2d, zx_tmp_fi2d)
        IF (vars_defined) zx_tmp_fi3d(1:klon,1:klev)=d_t_eva(1:klon,1:klev)/pdtphys
@@ -1708,5 +1832,5 @@
        IF (vars_defined) zx_tmp_fi3d(1:klon,1:klev)=d_q_eva(1:klon,1:klev)/pdtphys
        CALL histwrite_phy(o_dqeva, zx_tmp_fi3d)
-       CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
+       IF (vars_defined) CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
        CALL histwrite_phy(o_dqeva2d, zx_tmp_fi2d)
        CALL histwrite_phy(o_ratqs, ratqs)
@@ -1747,5 +1871,5 @@
           ENDIF
           CALL histwrite_phy(o_dqthe, zx_tmp_fi3d)
-          CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
+          IF (vars_defined) CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
           CALL histwrite_phy(o_dqthe2d, zx_tmp_fi2d)
        ENDIF !iflag_thermals
@@ -1754,5 +1878,5 @@
        IF (vars_defined) zx_tmp_fi3d(1:klon,1:klev)=d_q_ajsb(1:klon,1:klev)/pdtphys
        CALL histwrite_phy(o_dqajs, zx_tmp_fi3d)
-       CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
+       IF (vars_defined) CALL water_int(klon,klev,zx_tmp_fi3d,zmasse,zx_tmp_fi2d)
        CALL histwrite_phy(o_dqajs2d, zx_tmp_fi2d)
        IF (vars_defined) zx_tmp_fi3d(1:klon,1:klev)=d_t_swr(1:klon,1:klev)/pdtphys
@@ -1790,6 +1914,10 @@
 
        IF (ok_hines) THEN
-          CALL histwrite_phy(o_du_gwd_hines, du_gwd_hines/pdtphys)
-          CALL histwrite_phy(o_dv_gwd_hines, dv_gwd_hines/pdtphys)
+          IF (vars_defined) zx_tmp_fi3d=du_gwd_hines/pdtphys
+          CALL histwrite_phy(o_du_gwd_hines, zx_tmp_fi3d)
+
+          IF (vars_defined) zx_tmp_fi3d= dv_gwd_hines/pdtphys          
+          CALL histwrite_phy(o_dv_gwd_hines, zx_tmp_fi3d)
+          
           IF (vars_defined) zx_tmp_fi3d(1:klon,1:klev)=d_t_hin(1:klon,1:klev)/pdtphys
           CALL histwrite_phy(o_dthin, zx_tmp_fi3d)
@@ -1799,6 +1927,10 @@
 
        IF (.not. ok_hines .and. ok_gwd_rando) THEN
-          CALL histwrite_phy(o_du_gwd_front, du_gwd_front / pdtphys)
-          CALL histwrite_phy(o_dv_gwd_front, dv_gwd_front / pdtphys)
+          IF (vars_defined)  zx_tmp_fi3d=du_gwd_front / pdtphys
+          CALL histwrite_phy(o_du_gwd_front, zx_tmp_fi3d)
+          
+          IF (vars_defined)  zx_tmp_fi3d=dv_gwd_front / pdtphys
+          CALL histwrite_phy(o_dv_gwd_front, zx_tmp_fi3d)
+          
           CALL histwrite_phy(o_ustr_gwd_front, zustr_gwd_front)
           CALL histwrite_phy(o_vstr_gwd_front, zvstr_gwd_front)
@@ -1806,6 +1938,9 @@
 
        IF (ok_gwd_rando) THEN
-          CALL histwrite_phy(o_du_gwd_rando, du_gwd_rando / pdtphys)
-          CALL histwrite_phy(o_dv_gwd_rando, dv_gwd_rando / pdtphys)
+          IF (vars_defined)  zx_tmp_fi3d=du_gwd_rando / pdtphys
+          CALL histwrite_phy(o_du_gwd_rando, zx_tmp_fi3d)
+          
+          IF (vars_defined)  zx_tmp_fi3d=dv_gwd_rando / pdtphys
+          CALL histwrite_phy(o_dv_gwd_rando, zx_tmp_fi3d)
           CALL histwrite_phy(o_ustr_gwd_rando, zustr_gwd_rando)
           CALL histwrite_phy(o_vstr_gwd_rando, zvstr_gwd_rando)
@@ -1815,30 +1950,53 @@
 
        IF (ok_qch4) THEN
-          CALL histwrite_phy(o_dqch4, d_q_ch4 / pdtphys)
-       ENDIF
-
-       DO k=1, klevp1
-         zx_tmp_fi3d1(:,k)=swup(:,k)*swradcorr(:)
-       ENDDO
+          IF (vars_defined) zx_tmp_fi3d=d_q_ch4 / pdtphys
+          CALL histwrite_phy(o_dqch4, zx_tmp_fi3d)
+       ENDIF
+       
+       IF (vars_defined) THEN
+         DO k=1, klevp1
+           zx_tmp_fi3d1(:,k)=swup(:,k)*swradcorr(:)
+         ENDDO
+       ENDIF
+       
        CALL histwrite_phy(o_rsu, zx_tmp_fi3d1)
-       DO k=1, klevp1
-         zx_tmp_fi3d1(:,k)=swdn(:,k)*swradcorr(:)
-       ENDDO
+
+
+       IF (vars_defined) THEN
+         DO k=1, klevp1
+           zx_tmp_fi3d1(:,k)=swdn(:,k)*swradcorr(:)
+         ENDDO
+       ENDIF
+       
        CALL histwrite_phy(o_rsd, zx_tmp_fi3d1)
-       DO k=1, klevp1
-         zx_tmp_fi3d1(:,k)=swup0(:,k)*swradcorr(:)
-       ENDDO
+
+       IF (vars_defined) THEN
+         DO k=1, klevp1
+           zx_tmp_fi3d1(:,k)=swup0(:,k)*swradcorr(:)
+         ENDDO
+       ENDIF
+       
        CALL histwrite_phy(o_rsucs, zx_tmp_fi3d1)
-       DO k=1, klevp1
-         zx_tmp_fi3d1(:,k)=swupc0(:,k)*swradcorr(:)
-       ENDDO
+
+       IF (vars_defined) THEN
+         DO k=1, klevp1
+           zx_tmp_fi3d1(:,k)=swupc0(:,k)*swradcorr(:)
+         ENDDO
+       ENDIF
        CALL histwrite_phy(o_rsucsaf, zx_tmp_fi3d1)
-       DO k=1, klevp1
-         zx_tmp_fi3d1(:,k)=swdn0(:,k)*swradcorr(:)
-       ENDDO
+
+       IF (vars_defined) THEN
+         DO k=1, klevp1
+           zx_tmp_fi3d1(:,k)=swdn0(:,k)*swradcorr(:)
+         ENDDO
+       ENDIF
        CALL histwrite_phy(o_rsdcs, zx_tmp_fi3d1)
-       DO k=1, klevp1
-         zx_tmp_fi3d1(:,k)=swdnc0(:,k)*swradcorr(:)
-       ENDDO
+
+
+       IF (vars_defined) THEN
+         DO k=1, klevp1
+           zx_tmp_fi3d1(:,k)=swdnc0(:,k)*swradcorr(:)
+         ENDDO
+       ENDIF
        CALL histwrite_phy(o_rsdcsaf, zx_tmp_fi3d1)
 
@@ -1894,5 +2052,6 @@
        ELSE IF (iflag_con == 2) THEN
           CALL histwrite_phy(o_mcd,  pmfd)
-          CALL histwrite_phy(o_dmc,  pmfu + pmfd)
+          IF (vars_defined) zx_tmp_fi3d = pmfu + pmfd
+          CALL histwrite_phy(o_dmc,  zx_tmp_fi3d)
        ENDIF
        CALL histwrite_phy(o_ref_liq, ref_liq)
@@ -1908,19 +2067,27 @@
           IF (vars_defined) zx_tmp_fi2d(:) = lwup0p(:,klevp1)
           CALL histwrite_phy(o_rlutcs4co2, zx_tmp_fi2d)
-          DO k=1, klevp1
-            zx_tmp_fi3d1(:,k)=swupp(:,k)*swradcorr(:)
-          ENDDO
+          IF (vars_defined) THEN
+            DO k=1, klevp1
+              zx_tmp_fi3d1(:,k)=swupp(:,k)*swradcorr(:)
+            ENDDO
+          ENDIF
           CALL histwrite_phy(o_rsu4co2, zx_tmp_fi3d1)
-          DO k=1, klevp1
-            zx_tmp_fi3d1(:,k)=swup0p(:,k)*swradcorr(:)
-          ENDDO
+          IF (vars_defined) THEN
+            DO k=1, klevp1
+              zx_tmp_fi3d1(:,k)=swup0p(:,k)*swradcorr(:)
+            ENDDO
+          ENDIF
           CALL histwrite_phy(o_rsucs4co2, zx_tmp_fi3d1)
-          DO k=1, klevp1
-            zx_tmp_fi3d1(:,k)=swdnp(:,k)*swradcorr(:)
-          ENDDO
+          IF (vars_defined) THEN
+            DO k=1, klevp1
+              zx_tmp_fi3d1(:,k)=swdnp(:,k)*swradcorr(:)
+            ENDDO
+          ENDIF
           CALL histwrite_phy(o_rsd4co2, zx_tmp_fi3d1)
-          DO k=1, klevp1
-            zx_tmp_fi3d1(:,k)=swdn0p(:,k)*swradcorr(:)
-          ENDDO
+          IF (vars_defined) THEN
+            DO k=1, klevp1
+              zx_tmp_fi3d1(:,k)=swdn0p(:,k)*swradcorr(:)
+            ENDDO
+          ENDIF
           CALL histwrite_phy(o_rsdcs4co2, zx_tmp_fi3d1)
           CALL histwrite_phy(o_rlu4co2, lwupp)
@@ -2071,7 +2238,6 @@
 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        IF (iflag_phytrac == 1 ) then
-       IF (nqtot.GE.nqo+1) THEN
-          DO iq=nqo+1, nqtot
-            IF (type_trac == 'lmdz' .OR. type_trac == 'repr' .OR. type_trac == 'coag') THEN
+         IF (type_trac == 'lmdz' .OR. type_trac == 'repr' .OR. type_trac == 'coag') THEN
+           DO iq=nqo+1, nqtot
              !--3D fields
              CALL histwrite_phy(o_trac(iq-nqo), tr_seri(:,:,iq-nqo))
@@ -2089,5 +2255,5 @@
              CALL histwrite_phy(o_dtr_sat(iq-nqo),d_tr_sat(:,:,iq-nqo))
              CALL histwrite_phy(o_dtr_uscav(iq-nqo),d_tr_uscav(:,:,iq-nqo))
-             !--2D fields
+            !--2D fields
              CALL histwrite_phy(o_dtr_dry(iq-nqo), flux_tr_dry(:,iq-nqo))
              zx_tmp_fi2d=0.
@@ -2100,9 +2266,32 @@
              CALL histwrite_phy(o_trac_cum(iq-nqo), zx_tmp_fi2d)
 #endif
-            ENDIF
-          ENDDO
-       ENDIF
-
-       IF (type_trac == 'repr') THEN
+           ENDDO !--iq
+         ENDIF   !--type_trac
+!
+         IF (type_trac == 'co2i') THEN
+           DO iq=nqo+1, nqtot
+             !--3D fields
+             CALL histwrite_phy(o_trac(iq-nqo), tr_seri(:,:,iq-nqo))
+             CALL histwrite_phy(o_dtr_vdf(iq-nqo),d_tr_cl(:,:,iq-nqo))
+             CALL histwrite_phy(o_dtr_the(iq-nqo),d_tr_th(:,:,iq-nqo))
+             CALL histwrite_phy(o_dtr_con(iq-nqo),d_tr_cv(:,:,iq-nqo))
+             !--2D fields
+             !--CO2 burden
+             zx_tmp_fi2d=0.
+             IF (vars_defined) THEN
+                DO k=1,klev
+                   zx_tmp_fi2d(:)=zx_tmp_fi2d(:)+zmasse(:,k)*tr_seri(:,k,iq-nqo)
+                ENDDO
+             ENDIF
+             CALL histwrite_phy(o_trac_cum(iq-nqo), zx_tmp_fi2d)
+           ENDDO !--iq
+           !--CO2 net fluxes
+           CALL histwrite_phy(o_flx_co2_land,  fco2_land)
+           CALL histwrite_phy(o_flx_co2_ocean, fco2_ocean)
+           CALL histwrite_phy(o_flx_co2_ff,    fco2_ff)
+           CALL histwrite_phy(o_flx_co2_bb,    fco2_bb)
+         ENDIF !--type_trac co2i
+
+         IF (type_trac == 'repr') THEN
 #ifdef REPROBUS
            DO iq=1,nbnas
@@ -2110,5 +2299,5 @@
            ENDDO
 #endif
-       ENDIF
+         ENDIF
 
        ENDIF   !(iflag_phytrac==1)
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_state_var_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_state_var_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/phys_state_var_mod.F90	(revision 3605)
@@ -18,5 +18,5 @@
       INTEGER, SAVE :: radpas  ! radiation is called every "radpas" step
       INTEGER, SAVE :: cvpas   ! convection is called every "cvpas" step
-      INTEGER, SAVE :: cvpas_0 ! reference value for cvpas
+      INTEGER, SAVE :: cvpas_0 = 1 ! reference value for cvpas
       INTEGER, SAVE :: wkpas   ! wake scheme is called every "wkpas" step
       REAL, PARAMETER :: missing_val_nf90=nf90_fill_real
@@ -25,6 +25,6 @@
 !$OMP THREADPRIVATE(cvpas_0)
 !$OMP THREADPRIVATE(wkpas)
-      REAL, SAVE :: dtime, solaire_etat0
-!$OMP THREADPRIVATE(dtime, solaire_etat0)
+      REAL, SAVE :: phys_tstep=0, solaire_etat0
+!$OMP THREADPRIVATE(phys_tstep, solaire_etat0)
 
       REAL, ALLOCATABLE, SAVE :: pctsrf(:,:)
@@ -202,5 +202,7 @@
       REAL,ALLOCATABLE,SAVE :: ema_pcb(:), ema_pct(:)
 !$OMP THREADPRIVATE(ema_pcb,ema_pct)
-      REAL,ALLOCATABLE,SAVE :: Ma(:,:)        ! undilute upward mass flux
+      REAL,ALLOCATABLE,SAVE :: Mipsh(:,:)     ! mass flux shed from  adiab. ascents
+!$OMP THREADPRIVATE(Mipsh)
+      REAL,ALLOCATABLE,SAVE :: Ma(:,:)       ! undilute upward mass flux
 !$OMP THREADPRIVATE(Ma)
       REAL,ALLOCATABLE,SAVE :: qcondc(:,:)    ! in-cld water content from convect
@@ -286,4 +288,6 @@
       REAL,ALLOCATABLE,SAVE :: total_rain(:), nday_rain(:)  
 !$OMP THREADPRIVATE(total_rain,nday_rain)
+      REAL,ALLOCATABLE,SAVE :: paire_ter(:)
+!$OMP THREADPRIVATE(paire_ter)
 ! albsol1: albedo du sol total pour SW visible
 ! albsol2: albedo du sol total pour SW proche IR
@@ -312,4 +316,6 @@
 ! toplwdown : downward CS LW flux at TOA
 ! toplwdownclr : downward CS LW flux at TOA
+! heat_volc : chauffage solaire du au volcanisme
+! cool_volc : refroidissement infrarouge du au volcanisme
       REAL,ALLOCATABLE,SAVE :: clwcon0(:,:),rnebcon0(:,:)
 !$OMP THREADPRIVATE(clwcon0,rnebcon0)
@@ -322,4 +328,8 @@
       REAL,ALLOCATABLE,SAVE :: cool0(:,:)
 !$OMP THREADPRIVATE(cool0)
+      REAL,ALLOCATABLE,SAVE :: heat_volc(:,:)   
+!$OMP THREADPRIVATE(heat_volc)
+      REAL,ALLOCATABLE,SAVE :: cool_volc(:,:)
+!$OMP THREADPRIVATE(cool_volc)
       REAL,ALLOCATABLE,SAVE :: topsw(:), toplw(:)
 !$OMP THREADPRIVATE(topsw,toplw)
@@ -417,4 +427,7 @@
       ! tendencies on wind due to gravity waves
 
+      LOGICAL,SAVE :: is_initialized=.FALSE.
+!$OMP THREADPRIVATE(is_initialized)    
+
       ! Ocean-atmosphere interface, subskin ocean and near-surface ocean:
       
@@ -452,4 +465,6 @@
 include "clesphys.h"
 
+      IF (is_initialized) RETURN
+      is_initialized=.TRUE.
       ALLOCATE(pctsrf(klon,nbsrf))
       ALLOCATE(ftsol(klon,nbsrf))
@@ -467,4 +482,5 @@
       ALLOCATE(snow_fall(klon))
       ALLOCATE(solsw(klon), sollw(klon))
+      sollw=0.0
       ALLOCATE(radsol(klon))
       ALLOCATE(swradcorr(klon))
@@ -542,4 +558,5 @@
       ALLOCATE(ema_pcb(klon), ema_pct(klon))
 !
+      ALLOCATE(Mipsh(klon,klev))
       ALLOCATE(Ma(klon,klev))
       ALLOCATE(qcondc(klon,klev))
@@ -551,4 +568,5 @@
       ALLOCATE(ale_wake(klon))
       ALLOCATE(ale_bl_stat(klon))
+      ale_bl_stat(:)=0
       ALLOCATE(Alp_bl(klon))
       ALLOCATE(lalim_conv(klon))
@@ -556,4 +574,5 @@
       ALLOCATE(wake_deltat(klon,klev), wake_deltaq(klon,klev))
       ALLOCATE(wake_s(klon), awake_dens(klon), wake_dens(klon))
+      awake_dens = 0.
       ALLOCATE(wake_Cstar(klon))
       ALLOCATE(wake_pe(klon), wake_fip(klon))
@@ -564,4 +583,5 @@
       ALLOCATE(pfrac_1nucl(klon,klev))
       ALLOCATE(total_rain(klon), nday_rain(klon))
+      ALLOCATE(paire_ter(klon))
       ALLOCATE(albsol1(klon), albsol2(klon))
 !albedo SB >>>
@@ -579,8 +599,11 @@
       ALLOCATE(heat(klon,klev), heat0(klon,klev)) 
       ALLOCATE(cool(klon,klev), cool0(klon,klev))
+      ALLOCATE(heat_volc(klon,klev), cool_volc(klon,klev)) 
       ALLOCATE(topsw(klon), toplw(klon))
       ALLOCATE(sollwdown(klon), sollwdownclr(klon))
+      sollwdown = 0.
       ALLOCATE(toplwdown(klon), toplwdownclr(klon))
       ALLOCATE(topsw0(klon),toplw0(klon),solsw0(klon),sollw0(klon))
+      sollw0 = 0.
       ALLOCATE(albpla(klon))
 !IM ajout variables CFMIP2/CMIP5
@@ -619,7 +642,12 @@
       ALLOCATE(ale_bl_trig(klon))
 !!! fin nrlmd le 10/04/2012
-      if (ok_gwd_rando) allocate(du_gwd_rando(klon, klev))
-      if (.not. ok_hines .and. ok_gwd_rando) allocate(du_gwd_front(klon, klev))
-
+      IF (ok_gwd_rando) THEN
+        allocate(du_gwd_rando(klon, klev))
+        du_gwd_rando(:,:)=0.
+      ENDIF
+      IF (.not. ok_hines .and. ok_gwd_rando) THEN
+        ALLOCATE(du_gwd_front(klon, klev))
+        du_gwd_front(:,:) = 0 !ym missing init   
+      ENDIF
       if (activate_ocean_skin >= 1) ALLOCATE(ds_ns(klon), dt_ns(klon))
 
@@ -693,5 +721,5 @@
       deallocate(ema_cbmf)
       deallocate(ema_pcb, ema_pct)
-      deallocate(Ma, qcondc)
+      deallocate(Mipsh, Ma, qcondc)
       deallocate(wd, sigd)
       deallocate(cin, ALE, ALP)
@@ -710,4 +738,5 @@
       deallocate(pfrac_1nucl)
       deallocate(total_rain, nday_rain)
+      deallocate(paire_ter)
       deallocate(albsol1, albsol2)
 !albedo SB >>>
@@ -718,4 +747,5 @@
       deallocate(heat, heat0) 
       deallocate(cool, cool0)
+      deallocate(heat_volc, cool_volc) 
       deallocate(topsw, toplw)
       deallocate(sollwdown, sollwdownclr)
@@ -757,6 +787,9 @@
       deallocate(ale_bl_trig)
 !!! fin nrlmd le 10/04/2012
+
       if (activate_ocean_skin >= 1) deALLOCATE(ds_ns, dt_ns)
 
+      is_initialized=.FALSE.
+      
 END SUBROUTINE phys_state_var_end
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/physiq_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/physiq_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/physiq_mod.F90	(revision 3605)
@@ -25,5 +25,5 @@
     USE dimphy
     USE infotrac_phy, ONLY: nqtot, nbtr, nqo, type_trac
-    USE mod_grid_phy_lmdz, ONLY: nbp_lon, nbp_lat, nbp_lev, klon_glo
+    USE mod_grid_phy_lmdz, ONLY: nbp_lon, nbp_lat, nbp_lev, klon_glo, grid1dTo2d_glo, grid_type, unstructured
     USE mod_phys_lmdz_para
     USE iophy
@@ -38,4 +38,7 @@
 #ifdef CPP_Dust
     USE phytracr_spl_mod, ONLY: phytracr_spl
+#endif
+#ifdef CPP_StratAer
+    USE strataer_mod, ONLY: strataer_init
 #endif
     USE phys_local_var_mod, ONLY: phys_local_var_init, phys_local_var_end, &
@@ -117,4 +120,6 @@
        zustar, zu10m, zv10m, rh2m, qsat2m, &
        zq2m, zt2m, weak_inversion, &
+       zq2m_cor,zt2m_cor,zu10m_cor,zv10m_cor, & ! pour corriger d'un bug
+       zrh2m_cor,zqsat2m_cor, &
        zt2m_min_mon, zt2m_max_mon,   &         ! pour calcul_divers.h
        t2m_min_mon, t2m_max_mon,  &            ! pour calcul_divers.h
@@ -170,5 +175,5 @@
        !    Deep convective variables used in phytrac
        pmflxr, pmflxs,  &
-       wdtrainA, wdtrainM,  &
+       wdtrainA, wdtrainS, wdtrainM,  &
        upwd, dnwd, &
        ep,  &
@@ -180,4 +185,5 @@
        ev, &
        elij, &
+       qtaa, &
        clw, &
        epmlmMm, eplaMm, &
@@ -243,6 +249,6 @@
 #endif
     USE indice_sol_mod
-    USE phytrac_mod, ONLY : phytrac
-    USE carbon_cycle_mod, ONLY : infocfields_init
+    USE phytrac_mod, ONLY : phytrac_init, phytrac
+    USE carbon_cycle_mod, ONLY : infocfields_init, RCO2_glo, carbon_cycle_rad
 
 #ifdef CPP_RRTM
@@ -265,4 +271,12 @@
     USE ACAMA_GWD_rando_m, only: ACAMA_GWD_rando
     USE VERTICAL_LAYERS_MOD, ONLY: aps,bps
+    USE etat0_limit_unstruct_mod
+#ifdef CPP_XIOS
+    USE xios, ONLY: xios_update_calendar, xios_context_finalize
+#endif
+    USE limit_read_mod, ONLY : init_limit_read
+    USE regr_horiz_time_climoz_m, ONLY: regr_horiz_time_climoz
+    USE readaerosol_mod, ONLY : init_aero_fromfile
+    USE readaerosolstrato_m, ONLY : init_readaerosolstrato
 
     IMPLICIT NONE
@@ -323,10 +337,11 @@
     include "dimpft.h"
     !======================================================================
+    LOGICAL, SAVE :: ok_volcan ! pour activer les diagnostics volcaniques
+    !$OMP THREADPRIVATE(ok_volcan)
     LOGICAL ok_cvl  ! pour activer le nouveau driver pour convection KE
     PARAMETER (ok_cvl=.TRUE.)
     LOGICAL ok_gust ! pour activer l'effet des gust sur flux surface
     PARAMETER (ok_gust=.FALSE.)
-    integer iflag_radia     ! active ou non le rayonnement (MPL)
-    save iflag_radia
+    INTEGER, SAVE :: iflag_radia     ! active ou non le rayonnement (MPL)
     !$OMP THREADPRIVATE(iflag_radia)
     !======================================================================
@@ -363,21 +378,21 @@
     !======================================================================
     LOGICAL ok_journe ! sortir le fichier journalier
-    save ok_journe
+    SAVE ok_journe
     !$OMP THREADPRIVATE(ok_journe)
     !
     LOGICAL ok_mensuel ! sortir le fichier mensuel
-    save ok_mensuel
+    SAVE ok_mensuel
     !$OMP THREADPRIVATE(ok_mensuel)
     !
     LOGICAL ok_instan ! sortir le fichier instantane
-    save ok_instan
+    SAVE ok_instan
     !$OMP THREADPRIVATE(ok_instan)
     !
     LOGICAL ok_LES ! sortir le fichier LES 
-    save ok_LES                            
+    SAVE ok_LES                            
     !$OMP THREADPRIVATE(ok_LES)                  
     !
     LOGICAL callstats ! sortir le fichier stats 
-    save callstats                            
+    SAVE callstats                            
     !$OMP THREADPRIVATE(callstats)                  
     !
@@ -385,9 +400,9 @@
     PARAMETER (ok_region=.FALSE.)
     !======================================================================
-    real seuil_inversion
-    save seuil_inversion
+    REAL seuil_inversion
+    SAVE seuil_inversion
     !$OMP THREADPRIVATE(seuil_inversion)
-    integer iflag_ratqs
-    save iflag_ratqs
+    INTEGER iflag_ratqs
+    SAVE iflag_ratqs
     !$OMP THREADPRIVATE(iflag_ratqs)
     real facteur
@@ -396,9 +411,9 @@
     REAL tau_overturning_th(klon)
 
-    integer lmax_th(klon)
-    integer limbas(klon)
-    real ratqscth(klon,klev)
-    real ratqsdiff(klon,klev)
-    real zqsatth(klon,klev)
+    INTEGER lmax_th(klon)
+    INTEGER limbas(klon)
+    REAL ratqscth(klon,klev)
+    REAL ratqsdiff(klon,klev)
+    REAL zqsatth(klon,klev)
 
     !======================================================================
@@ -497,16 +512,15 @@
     CHARACTER*3 region
     PARAMETER(region='3d')
-    logical ok_hf
-    !
-    save ok_hf
+    LOGICAL ok_hf
+    !
+    SAVE ok_hf
     !$OMP THREADPRIVATE(ok_hf)
 
-    INTEGER,PARAMETER :: longcles=20
-    REAL,SAVE :: clesphy0(longcles)
+    INTEGER, PARAMETER :: longcles=20
+    REAL, SAVE :: clesphy0(longcles)
     !$OMP THREADPRIVATE(clesphy0)
     !
     ! Variables propres a la physique
-    INTEGER itap
-    SAVE itap                   ! compteur pour la physique
+    INTEGER, SAVE :: itap         ! compteur pour la physique
     !$OMP THREADPRIVATE(itap)
 
@@ -514,5 +528,5 @@
     !$OMP THREADPRIVATE(abortphy)
     !
-    REAL,save ::  solarlong0
+    REAL,SAVE ::  solarlong0
     !$OMP THREADPRIVATE(solarlong0)
 
@@ -531,7 +545,5 @@
     ! Variables liees a la convection de K. Emanuel (sb):
     !
-    REAL bas, top             ! cloud base and top levels
-    SAVE bas
-    SAVE top
+    REAL, SAVE :: bas, top             ! cloud base and top levels
     !$OMP THREADPRIVATE(bas, top)
     !------------------------------------------------------------------
@@ -551,5 +563,6 @@
     ! Variables li\'ees \`a la poche froide (jyg)
 
-    REAL mip(klon,klev)  ! mass flux shed by the adiab ascent at each level
+!!    REAL mipsh(klon,klev)  ! mass flux shed by the adiab ascent at each level
+!!      Moved to phys_state_var_mod
     !
     REAL wape_prescr, fip_prescr
@@ -568,14 +581,11 @@
 !!    REAL, DIMENSION(klon,klev)     :: dql_sat
 
-    real, save :: alp_bl_prescr=0.
-    real, save :: ale_bl_prescr=0.
-
-    real, save :: wake_s_min_lsp=0.1
-
+    REAL, SAVE :: alp_bl_prescr=0.
+    REAL, SAVE :: ale_bl_prescr=0.
+    REAL, SAVE :: wake_s_min_lsp=0.1
     !$OMP THREADPRIVATE(alp_bl_prescr,ale_bl_prescr)
     !$OMP THREADPRIVATE(wake_s_min_lsp)
 
-
-    real ok_wk_lsp(klon)
+    REAL ok_wk_lsp(klon)
 
     !RC
@@ -590,4 +600,10 @@
                                                         ! gust-front in the grid cell.
     !$OMP THREADPRIVATE(iflag_alp_wk_cond)
+
+    INTEGER,  SAVE               :: iflag_bug_t2m_ipslcm61=1 !
+    !$OMP THREADPRIVATE(iflag_bug_t2m_ipslcm61)
+    INTEGER,  SAVE               :: iflag_bug_t2m_stab_ipslcm61=-1 !
+    !$OMP THREADPRIVATE(iflag_bug_t2m_stab_ipslcm61)
+
     REAL t_w(klon,klev),q_w(klon,klev) ! temperature and moisture profiles in the wake region
     REAL t_x(klon,klev),q_x(klon,klev) ! temperature and moisture profiles in the off-wake region
@@ -727,5 +743,5 @@
     REAL :: jD_eq
 
-    LOGICAL, parameter :: new_orbit = .true.
+    LOGICAL, parameter :: new_orbit = .TRUE.
 
     !
@@ -913,6 +929,6 @@
     INTEGER kcbot(klon), kctop(klon), kdtop(klon)
     !
-    real ratqsbas,ratqshaut,tau_ratqs
-    save ratqsbas,ratqshaut,tau_ratqs
+    REAL ratqsbas,ratqshaut,tau_ratqs
+    SAVE ratqsbas,ratqshaut,tau_ratqs
     !$OMP THREADPRIVATE(ratqsbas,ratqshaut,tau_ratqs)
     REAL, SAVE :: ratqsp0=50000., ratqsdp=20000.
@@ -920,19 +936,15 @@
 
     ! Parametres lies au nouveau schema de nuages (SB, PDF)
-    real fact_cldcon
-    real facttemps
-    logical ok_newmicro
-    save ok_newmicro
+    REAL, SAVE :: fact_cldcon
+    REAL, SAVE :: facttemps
+    !$OMP THREADPRIVATE(fact_cldcon,facttemps)
+    LOGICAL, SAVE :: ok_newmicro
     !$OMP THREADPRIVATE(ok_newmicro)
-    !real ref_liq_pi(klon,klev), ref_ice_pi(klon,klev)
-    save fact_cldcon,facttemps
-    !$OMP THREADPRIVATE(fact_cldcon,facttemps)
-
-    integer iflag_cld_th
-    save iflag_cld_th
+
+    INTEGER, SAVE :: iflag_cld_th
     !$OMP THREADPRIVATE(iflag_cld_th)
 !IM logical ptconv(klon,klev)  !passe dans phys_local_var_mod
     !IM cf. AM 081204 BEG
-    logical ptconvth(klon,klev)
+    LOGICAL ptconvth(klon,klev)
     !IM cf. AM 081204 END
     !
@@ -941,5 +953,4 @@
     !======================================================================
     !
-
     !
 !JLD    integer itau_w   ! pas de temps ecriture = itap + itau_phy
@@ -1007,16 +1018,15 @@
 !JLD    REAL zstophy, zout
 
-    character*20 modname
-    character*80 abort_message
-    logical, save ::  ok_sync, ok_sync_omp
+    CHARACTER*20 modname
+    CHARACTER*80 abort_message
+    LOGICAL, SAVE ::  ok_sync, ok_sync_omp
     !$OMP THREADPRIVATE(ok_sync)
-    real date0
+    REAL date0
 
     ! essai writephys
-    integer fid_day, fid_mth, fid_ins
-    parameter (fid_ins = 1, fid_day = 2, fid_mth = 3) 
-    integer prof2d_on, prof3d_on, prof2d_av, prof3d_av
-    parameter (prof2d_on = 1, prof3d_on = 2, &
-         prof2d_av = 3, prof3d_av = 4)
+    INTEGER fid_day, fid_mth, fid_ins
+    PARAMETER (fid_ins = 1, fid_day = 2, fid_mth = 3) 
+    INTEGER prof2d_on, prof3d_on, prof2d_av, prof3d_av
+    PARAMETER (prof2d_on = 1, prof3d_on = 2, prof2d_av = 3, prof3d_av = 4)
     REAL ztsol(klon)
     REAL q2m(klon,nbsrf)  ! humidite a 2m
@@ -1070,5 +1080,5 @@
     ! Declaration des constantes et des fonctions thermodynamiques
     !
-    LOGICAL,SAVE :: first=.true.
+    LOGICAL,SAVE :: first=.TRUE.
     !$OMP THREADPRIVATE(first)
 
@@ -1106,5 +1116,5 @@
     ! Declarations pour Simulateur COSP
     !============================================================
-    real :: mr_ozone(klon,klev)
+    real :: mr_ozone(klon,klev), phicosp(klon,klev)
 
     !IM stations CFMIP
@@ -1164,10 +1174,11 @@
     REAL zzz
     !albedo SB >>>
-    real,dimension(6),save :: SFRWL
+    REAL,DIMENSION(6), SAVE :: SFRWL
+!$OMP THREADPRIVATE(SFRWL)
     !albedo SB <<<
 
     !--OB variables for mass fixer (hard coded for now)
-    logical, parameter :: mass_fixer=.false.
-    real qql1(klon),qql2(klon),corrqql
+    LOGICAL, PARAMETER :: mass_fixer=.FALSE.
+    REAL qql1(klon),qql2(klon),corrqql
 
     REAL pi
@@ -1183,4 +1194,8 @@
     pdtphys=pdtphys_
     CALL update_time(pdtphys)
+    phys_tstep=NINT(pdtphys)
+#ifdef CPP_XIOS
+    IF (.NOT. debut .AND. is_omp_master) CALL xios_update_calendar(itap+1)
+#endif
 
     !======================================================================
@@ -1211,15 +1226,17 @@
 
     ! Quick check on pressure levels:
-    call assert(paprs(:, nbp_lev + 1) < paprs(:, nbp_lev), &
+    CALL assert(paprs(:, nbp_lev + 1) < paprs(:, nbp_lev), &
             "physiq_mod paprs bad order")
 
     IF (first) THEN 
+       CALL init_etat0_limit_unstruct
+       IF (.NOT. create_etat0_limit) CALL init_limit_read(days_elapsed)
        !CR:nvelles variables convection/poches froides
 
-       print*, '================================================='
-       print*, 'Allocation des variables locales et sauvegardees'
+       WRITE(lunout,*) '================================================='
+       WRITE(lunout,*) 'Allocation des variables locales et sauvegardees'
+       WRITE(lunout,*) '================================================='
        CALL phys_local_var_init
        !
-       pasphys=pdtphys
        !     appel a la lecture du run.def physique
        CALL conf_phys(ok_journe, ok_mensuel, &
@@ -1230,5 +1247,6 @@
             fact_cldcon, facttemps,ok_newmicro,iflag_radia, &
             iflag_cld_th,iflag_ratqs,ratqsbas,ratqshaut,tau_ratqs, &
-            ok_ade, ok_aie, ok_alw, ok_cdnc, aerosol_couple,  chemistry_couple, &
+            ok_ade, ok_aie, ok_alw, ok_cdnc, ok_volcan, aerosol_couple, &
+            chemistry_couple, &
             flag_aerosol, flag_aerosol_strat, flag_aer_feedback, new_aod, &
             flag_bc_internal_mixture, bl95_b0, bl95_b1, &
@@ -1239,4 +1257,11 @@
        CALL phys_state_var_init(read_climoz)
        CALL phys_output_var_init
+       IF (read_climoz>=1 .AND. create_etat0_limit .AND. grid_type==unstructured) & 
+          CALL regr_horiz_time_climoz(read_climoz,ok_daily_climoz)
+
+#ifdef CPP_StratAer
+       CALL strataer_init
+#endif
+
        print*, '================================================='
        !
@@ -1245,5 +1270,6 @@
           WRITE (lunout, *) ' iflag_ice_thermo==1 requires 3 H2O tracers ', &
                '(H2Ov, H2Ol, H2Oi) but nqo=', nqo, '. Might as well stop here.'
-          STOP
+          abort_message='see above'
+          CALL abort_physic(modname,abort_message,1)
        ENDIF
 
@@ -1258,5 +1284,5 @@
 
        itau_con=0
-       first=.false.
+       first=.FALSE.
 
     ENDIF  ! first
@@ -1287,5 +1313,11 @@
 ! secondes
        tau_gl=86400.*tau_gl
-       print*,'debut physiq_mod tau_gl=',tau_gl
+       WRITE(lunout,*) 'debut physiq_mod tau_gl=',tau_gl
+
+       iflag_bug_t2m_ipslcm61 = 1
+       CALL getin_p('iflag_bug_t2m_ipslcm61', iflag_bug_t2m_ipslcm61)
+       iflag_bug_t2m_stab_ipslcm61 = -1
+       CALL getin_p('iflag_bug_t2m_stab_ipslcm61', iflag_bug_t2m_stab_ipslcm61)
+
        CALL getin_p('iflag_alp_wk_cond', iflag_alp_wk_cond) 
        CALL getin_p('random_notrig_max',random_notrig_max)
@@ -1318,4 +1350,21 @@
        CALL getin_p('NVM',nvm_lmdz)
 
+       WRITE(lunout,*) 'iflag_alp_wk_cond=',  iflag_alp_wk_cond
+       WRITE(lunout,*) 'random_ntrig_max=',   random_notrig_max
+       WRITE(lunout,*) 'ok_adjwk=',           ok_adjwk
+       WRITE(lunout,*) 'iflag_adjwk=',        iflag_adjwk
+       WRITE(lunout,*) 'qtcon_multistep_max=',dtcon_multistep_max 
+       WRITE(lunout,*) 'qdcon_multistep_max=',dqcon_multistep_max 
+       WRITE(lunout,*) 'ratqsp0=',            ratqsp0
+       WRITE(lunout,*) 'ratqsdp=',            ratqsdp 
+       WRITE(lunout,*) 'iflag_wake_tend=',    iflag_wake_tend
+       WRITE(lunout,*) 'ok_bad_ecmwf_thermo=',ok_bad_ecmwf_thermo 
+       WRITE(lunout,*) 'ok_bug_cv_trac=',     ok_bug_cv_trac 
+       WRITE(lunout,*) 'ok_bug_split_th=',    ok_bug_split_th
+       WRITE(lunout,*) 'fl_ebil=',            fl_ebil
+       WRITE(lunout,*) 'fl_cor_ebil=',        fl_cor_ebil
+       WRITE(lunout,*) 'iflag_phytrac=',      iflag_phytrac
+       WRITE(lunout,*) 'NVM=',                nvm_lmdz
+
        !--PC: defining fields to be exchanged between LMDz, ORCHIDEE and NEMO
        WRITE(lunout,*) 'Call to infocfields from physiq'
@@ -1369,4 +1418,8 @@
        ENDIF
 
+       tau_aero(:,:,:,:) = 1.e-15
+       piz_aero(:,:,:,:) = 1.
+       cg_aero(:,:,:,:)  = 0.
+
        IF (aerosol_couple .AND. (config_inca /= "aero" &
             .AND. config_inca /= "aeNP ")) THEN
@@ -1376,6 +1429,4 @@
           CALL abort_physic (modname,abort_message,1)
        ENDIF
-
-
 
        rnebcon0(:,:) = 0.0
@@ -1417,14 +1468,12 @@
        ! pour obtenir le meme resultat.
 !jyg for fh<
-!!       dtime=pdtphys
-       dtime=NINT(pdtphys)
-       WRITE(lunout,*) 'Pas de temps dtime pdtphys ',dtime,pdtphys
-       IF (abs(dtime-pdtphys)>1.e-10) THEN
+       WRITE(lunout,*) 'Pas de temps phys_tstep pdtphys ',phys_tstep,pdtphys
+       IF (abs(phys_tstep-pdtphys)>1.e-10) THEN
           abort_message='pas de temps doit etre entier en seconde pour orchidee et XIOS'
           CALL abort_physic(modname,abort_message,1)
        ENDIF
 !>jyg
-       IF (MOD(NINT(86400./dtime),nbapp_rad).EQ.0) THEN
-          radpas = NINT( 86400./dtime)/nbapp_rad
+       IF (MOD(NINT(86400./phys_tstep),nbapp_rad).EQ.0) THEN
+          radpas = NINT( 86400./phys_tstep)/nbapp_rad
        ELSE 
           WRITE(lunout,*) 'le nombre de pas de temps physique doit etre un ', &
@@ -1436,9 +1485,9 @@
           CALL abort_physic(modname,abort_message,1)
        ENDIF
-       IF (nbapp_cv .EQ. 0) nbapp_cv=86400./dtime
-       IF (nbapp_wk .EQ. 0) nbapp_wk=86400./dtime
+       IF (nbapp_cv .EQ. 0) nbapp_cv=86400./phys_tstep
+       IF (nbapp_wk .EQ. 0) nbapp_wk=86400./phys_tstep
        print *,'physiq, nbapp_cv, nbapp_wk ',nbapp_cv,nbapp_wk
-       IF (MOD(NINT(86400./dtime),nbapp_cv).EQ.0) THEN
-          cvpas_0 = NINT( 86400./dtime)/nbapp_cv
+       IF (MOD(NINT(86400./phys_tstep),nbapp_cv).EQ.0) THEN
+          cvpas_0 = NINT( 86400./phys_tstep)/nbapp_cv
           cvpas = cvpas_0
        print *,'physiq, cvpas ',cvpas
@@ -1450,9 +1499,9 @@
           abort_message='nbre de pas de temps physique n est pas multiple ' &
                // 'de nbapp_cv'
-          call abort_physic(modname,abort_message,1)
-       ENDIF
-       IF (MOD(NINT(86400./dtime),nbapp_wk).EQ.0) THEN
-          wkpas = NINT( 86400./dtime)/nbapp_wk
-       print *,'physiq, wkpas ',wkpas
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
+       IF (MOD(NINT(86400./phys_tstep),nbapp_wk).EQ.0) THEN
+          wkpas = NINT( 86400./phys_tstep)/nbapp_wk
+!       print *,'physiq, wkpas ',wkpas
        ELSE 
           WRITE(lunout,*) 'le nombre de pas de temps physique doit etre un ', &
@@ -1462,22 +1511,208 @@
           abort_message='nbre de pas de temps physique n est pas multiple ' &
                // 'de nbapp_wk'
-          call abort_physic(modname,abort_message,1)
+          CALL abort_physic(modname,abort_message,1)
        ENDIF
        ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-
+       CALL init_iophy_new(latitude_deg,longitude_deg)
+
+          !===================================================================
+          !IM stations CFMIP
+          nCFMIP=npCFMIP
+          OPEN(98,file='npCFMIP_param.data',status='old', &
+               form='formatted',iostat=iostat)
+          IF (iostat == 0) THEN
+             READ(98,*,end=998) nCFMIP
+998          CONTINUE
+             CLOSE(98)
+             CONTINUE
+             IF(nCFMIP.GT.npCFMIP) THEN
+                print*,'nCFMIP > npCFMIP : augmenter npCFMIP et recompiler'
+                CALL abort_physic("physiq", "", 1)
+             ELSE
+                print*,'physiq npCFMIP=',npCFMIP,'nCFMIP=',nCFMIP
+             ENDIF
+
+             !
+             ALLOCATE(tabCFMIP(nCFMIP))
+             ALLOCATE(lonCFMIP(nCFMIP), latCFMIP(nCFMIP))
+             ALLOCATE(tabijGCM(nCFMIP))
+             ALLOCATE(lonGCM(nCFMIP), latGCM(nCFMIP))
+             ALLOCATE(iGCM(nCFMIP), jGCM(nCFMIP))
+             !
+             ! lecture des nCFMIP stations CFMIP, de leur numero 
+             ! et des coordonnees geographiques lonCFMIP, latCFMIP
+             !
+             CALL read_CFMIP_point_locations(nCFMIP, tabCFMIP,  &
+                  lonCFMIP, latCFMIP)
+             !
+             ! identification des
+             ! 1) coordonnees lonGCM, latGCM des points CFMIP dans la
+             ! grille de LMDZ
+             ! 2) indices points tabijGCM de la grille physique 1d sur
+             ! klon points
+             ! 3) indices iGCM, jGCM de la grille physique 2d
+             !
+             CALL LMDZ_CFMIP_point_locations(nCFMIP, lonCFMIP, latCFMIP, &
+                  tabijGCM, lonGCM, latGCM, iGCM, jGCM)
+             !
+          ELSE
+             ALLOCATE(tabijGCM(0))
+             ALLOCATE(lonGCM(0), latGCM(0))
+             ALLOCATE(iGCM(0), jGCM(0))
+          ENDIF
+
+#ifdef CPP_IOIPSL
+
+       !$OMP MASTER
+       ! FH : if ok_sync=.true. , the time axis is written at each time step
+       ! in the output files. Only at the end in the opposite case
+       ok_sync_omp=.FALSE.
+       CALL getin('ok_sync',ok_sync_omp)
+       CALL phys_output_open(longitude_deg,latitude_deg,nCFMIP,tabijGCM, &
+            iGCM,jGCM,lonGCM,latGCM, &
+            jjmp1,nlevSTD,clevSTD,rlevSTD, phys_tstep,ok_veget, &
+            type_ocean,iflag_pbl,iflag_pbl_split,ok_mensuel,ok_journe, &
+            ok_hf,ok_instan,ok_LES,ok_ade,ok_aie, &
+            read_climoz, phys_out_filestations, &
+            new_aod, aerosol_couple, &
+            flag_aerosol_strat, pdtphys, paprs, pphis,  &
+            pplay, lmax_th, ptconv, ptconvth, ivap,  &
+            d_u, d_t, qx, d_qx, zmasse, ok_sync_omp)
+       !$OMP END MASTER
+       !$OMP BARRIER
+       ok_sync=ok_sync_omp
+
+       freq_outNMC(1) = ecrit_files(7)
+       freq_outNMC(2) = ecrit_files(8)
+       freq_outNMC(3) = ecrit_files(9)
+       WRITE(lunout,*)'OK freq_outNMC(1)=',freq_outNMC(1)
+       WRITE(lunout,*)'OK freq_outNMC(2)=',freq_outNMC(2)
+       WRITE(lunout,*)'OK freq_outNMC(3)=',freq_outNMC(3)
+
+#ifndef CPP_XIOS
+       CALL ini_paramLMDZ_phy(phys_tstep,nid_ctesGCM)
+#endif
+
+#endif
+       ecrit_reg = ecrit_reg * un_jour
+       ecrit_tra = ecrit_tra * un_jour
+
+       !XXXPB Positionner date0 pour initialisation de ORCHIDEE
+       date0 = jD_ref 
+       WRITE(*,*) 'physiq date0 : ',date0
+       !
+
+!       CALL create_climoz(read_climoz)
+      IF (.NOT. create_etat0_limit) CALL init_aero_fromfile(flag_aerosol)  !! initialise aero from file for XIOS interpolation (unstructured_grid)
+      IF (.NOT. create_etat0_limit) CALL init_readaerosolstrato(flag_aerosol_strat)  !! initialise aero strato from file for XIOS interpolation (unstructured_grid)
+
+#ifdef CPP_COSP
+      IF (ok_cosp) THEN
+           DO k = 1, klev
+             DO i = 1, klon
+               phicosp(i,k) = pphi(i,k) + pphis(i)
+             ENDDO
+           ENDDO
+        CALL phys_cosp(itap,phys_tstep,freq_cosp, &
+               ok_mensuelCOSP,ok_journeCOSP,ok_hfCOSP, &
+               ecrit_mth,ecrit_day,ecrit_hf, ok_all_xml, missing_val, &
+               klon,klev,longitude_deg,latitude_deg,presnivs,overlap, &
+               JrNt,ref_liq,ref_ice, &
+               pctsrf(:,is_ter)+pctsrf(:,is_lic), &
+               zu10m,zv10m,pphis, &
+               zphi,paprs(:,1:klev),pplay,zxtsol,t_seri, &
+               qx(:,:,ivap),zx_rh,cldfra,rnebcon,flwc,fiwc, &
+               prfl(:,1:klev),psfl(:,1:klev), &
+               pmflxr(:,1:klev),pmflxs(:,1:klev), &
+               mr_ozone,cldtau, cldemi)
+      ENDIF
+#endif
+
+#ifdef CPP_COSP2
+        IF (ok_cosp) THEN
+           DO k = 1, klev
+             DO i = 1, klon
+               phicosp(i,k) = pphi(i,k) + pphis(i)
+             ENDDO
+           ENDDO
+          CALL phys_cosp2(itap,phys_tstep,freq_cosp, &
+               ok_mensuelCOSP,ok_journeCOSP,ok_hfCOSP, &
+               ecrit_mth,ecrit_day,ecrit_hf, ok_all_xml, missing_val, &
+               klon,klev,longitude_deg,latitude_deg,presnivs,overlap, &
+               JrNt,ref_liq,ref_ice, &
+               pctsrf(:,is_ter)+pctsrf(:,is_lic), &
+               zu10m,zv10m,pphis, &
+               zphi,paprs(:,1:klev),pplay,zxtsol,t_seri, &
+               qx(:,:,ivap),zx_rh,cldfra,rnebcon,flwc,fiwc, &
+               prfl(:,1:klev),psfl(:,1:klev), &
+               pmflxr(:,1:klev),pmflxs(:,1:klev), &
+               mr_ozone,cldtau, cldemi)
+       ENDIF
+#endif
+
+#ifdef CPP_COSPV2
+        IF (ok_cosp) THEN
+           DO k = 1, klev
+             DO i = 1, klon
+               phicosp(i,k) = pphi(i,k) + pphis(i)
+             ENDDO
+           ENDDO
+          CALL lmdz_cosp_interface(itap,phys_tstep,freq_cosp, &
+               ok_mensuelCOSP,ok_journeCOSP,ok_hfCOSP, &
+               ecrit_mth,ecrit_day,ecrit_hf, ok_all_xml, missing_val, &
+               klon,klev,longitude_deg,latitude_deg,presnivs,overlap, &
+               JrNt,ref_liq,ref_ice, &
+               pctsrf(:,is_ter)+pctsrf(:,is_lic), &
+               zu10m,zv10m,pphis, &
+               phicosp,paprs(:,1:klev),pplay,zxtsol,t_seri, &
+               qx(:,:,ivap),zx_rh,cldfra,rnebcon,flwc,fiwc, &
+               prfl(:,1:klev),psfl(:,1:klev), &
+               pmflxr(:,1:klev),pmflxs(:,1:klev), &
+               mr_ozone,cldtau, cldemi)
+       ENDIF
+#endif
+
+       !
+       !
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+       ! Nouvelle initialisation pour le rayonnement RRTM
+       !
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+       CALL iniradia(klon,klev,paprs(1,1:klev+1))
+       ! Initialisation des champs dans phytrac qui sont utilisés par phys_output_write
+       IF (iflag_phytrac == 1 ) THEN
+          CALL phytrac_init()
+        ENDIF
+
+       CALL phys_output_write(itap, pdtphys, paprs, pphis,                    &
+                              pplay, lmax_th, aerosol_couple,                 &
+                              ok_ade, ok_aie, ok_volcan, ivap, iliq, isol, new_aod, ok_sync,&
+                              ptconv, read_climoz, clevSTD,                   &
+                              ptconvth, d_u, d_t, qx, d_qx, zmasse,           &
+                              flag_aerosol, flag_aerosol_strat, ok_cdnc)
+
+#ifdef CPP_XIOS
+       IF (is_omp_master) CALL xios_update_calendar(1)
+#endif
+       IF(read_climoz>=1 .AND. create_etat0_limit) CALL regr_horiz_time_climoz(read_climoz,ok_daily_climoz)
+       CALL create_etat0_limit_unstruct
        CALL phyetat0 ("startphy.nc",clesphy0,tabcntr0)
+
 !jyg<
-       IF (klon_glo==1) THEN
-          IF (iflag_pbl > 1) THEN          
-              pbl_tke(:,:,is_ave) = 0.
-              DO nsrf=1,nbsrf
-                DO k = 1,klev+1
-                     pbl_tke(:,k,is_ave) = pbl_tke(:,k,is_ave) &
-                         +pctsrf(:,nsrf)*pbl_tke(:,k,nsrf)
-                ENDDO
-              ENDDO
-          ELSE   ! (iflag_pbl > 1)
-              pbl_tke(:,:,:) = 0.
-          ENDIF  ! (iflag_pbl > 1)
+       IF (iflag_pbl<=1) THEN
+          ! No TKE for Standard Physics
+          pbl_tke(:,:,:)=0.
+
+       ELSE IF (klon_glo==1) THEN
+          pbl_tke(:,:,is_ave) = 0.
+          DO nsrf=1,nbsrf
+            DO k = 1,klev+1
+                 pbl_tke(:,k,is_ave) = pbl_tke(:,k,is_ave) &
+                     +pctsrf(:,nsrf)*pbl_tke(:,k,nsrf)
+            ENDDO
+          ENDDO
+        ELSE
+          pbl_tke(:,:,is_ave) = 0. !ym missing init : maybe must be initialized in the same way that for klon_glo==1 ??
 !>jyg
        ENDIF
@@ -1496,14 +1731,11 @@
        ENDIF
 
-       CALL printflag( tabcntr0,radpas,ok_journe, &
-            ok_instan, ok_region )
-       !
-       IF (ABS(dtime-pdtphys).GT.0.001) THEN
-          WRITE(lunout,*) 'Pas physique n est pas correct',dtime, &
-               pdtphys
-          abort_message='Pas physique n est pas correct '
-          !           call abort_physic(modname,abort_message,1)
-          dtime=pdtphys
-       ENDIF
+!       IF (ABS(phys_tstep-pdtphys).GT.0.001) THEN
+!          WRITE(lunout,*) 'Pas physique n est pas correct',phys_tstep, &
+!               pdtphys
+!          abort_message='Pas physique n est pas correct '
+!          !           call abort_physic(modname,abort_message,1)
+!          phys_tstep=pdtphys
+!       ENDIF
        IF (nlon .NE. klon) THEN
           WRITE(lunout,*)'nlon et klon ne sont pas coherents', nlon,  &
@@ -1519,5 +1751,5 @@
        ENDIF
        !
-       IF (dtime*REAL(radpas).GT.21600..AND.iflag_cycle_diurne.GE.1) THEN 
+       IF (phys_tstep*REAL(radpas).GT.21600..AND.iflag_cycle_diurne.GE.1) THEN 
           WRITE(lunout,*)'Nbre d appels au rayonnement insuffisant'
           WRITE(lunout,*)"Au minimum 4 appels par jour si cycle diurne"
@@ -1581,53 +1813,8 @@
           !        enddo
 
-          !===================================================================
-          !IM stations CFMIP
-          nCFMIP=npCFMIP
-          OPEN(98,file='npCFMIP_param.data',status='old', &
-               form='formatted',iostat=iostat)
-          IF (iostat == 0) THEN
-             READ(98,*,end=998) nCFMIP
-998          CONTINUE
-             CLOSE(98)
-             CONTINUE
-             IF(nCFMIP.GT.npCFMIP) THEN
-                print*,'nCFMIP > npCFMIP : augmenter npCFMIP et recompiler'
-                CALL abort_physic("physiq", "", 1)
-             ELSE
-                print*,'physiq npCFMIP=',npCFMIP,'nCFMIP=',nCFMIP
-             ENDIF
-
-             !
-             ALLOCATE(tabCFMIP(nCFMIP))
-             ALLOCATE(lonCFMIP(nCFMIP), latCFMIP(nCFMIP))
-             ALLOCATE(tabijGCM(nCFMIP))
-             ALLOCATE(lonGCM(nCFMIP), latGCM(nCFMIP))
-             ALLOCATE(iGCM(nCFMIP), jGCM(nCFMIP))
-             !
-             ! lecture des nCFMIP stations CFMIP, de leur numero 
-             ! et des coordonnees geographiques lonCFMIP, latCFMIP
-             !
-             CALL read_CFMIP_point_locations(nCFMIP, tabCFMIP,  &
-                  lonCFMIP, latCFMIP)
-             !
-             ! identification des
-             ! 1) coordonnees lonGCM, latGCM des points CFMIP dans la
-             ! grille de LMDZ
-             ! 2) indices points tabijGCM de la grille physique 1d sur
-             ! klon points
-             ! 3) indices iGCM, jGCM de la grille physique 2d
-             !
-             CALL LMDZ_CFMIP_point_locations(nCFMIP, lonCFMIP, latCFMIP, &
-                  tabijGCM, lonGCM, latGCM, iGCM, jGCM)
-             !
-          ELSE
-             ALLOCATE(tabijGCM(0))
-             ALLOCATE(lonGCM(0), latGCM(0))
-             ALLOCATE(iGCM(0), jGCM(0))
-          ENDIF
-       ELSE
-          ALLOCATE(tabijGCM(0))
-          ALLOCATE(lonGCM(0), latGCM(0))
-          ALLOCATE(iGCM(0), jGCM(0))
+       !ELSE
+       !   ALLOCATE(tabijGCM(0))
+       !   ALLOCATE(lonGCM(0), latGCM(0))
+       !   ALLOCATE(iGCM(0), jGCM(0))
        ENDIF
 
@@ -1665,5 +1852,5 @@
        !
        !
-       lmt_pas = NINT(86400./dtime * 1.0)   ! tous les jours
+       lmt_pas = NINT(86400./phys_tstep * 1.0)   ! tous les jours
        WRITE(lunout,*)'La frequence de lecture surface est de ',  &
             lmt_pas
@@ -1681,4 +1868,13 @@
        !   Initialisation des sorties
        !=============================================================
+
+#ifdef CPP_XIOS
+       ! Get "missing_val" value from XML files (from temperature variable)
+       !$OMP MASTER
+       CALL xios_get_field_attr("temp",default_value=missing_val_omp)
+       !$OMP END MASTER
+       !$OMP BARRIER
+       missing_val=missing_val_omp
+#endif
 
 #ifdef CPP_XIOS 
@@ -1693,43 +1889,7 @@
 #endif 
 
-#ifdef CPP_IOIPSL
-
-       !$OMP MASTER
-       ! FH : if ok_sync=.true. , the time axis is written at each time step
-       ! in the output files. Only at the end in the opposite case
-       ok_sync_omp=.false.
-       CALL getin('ok_sync',ok_sync_omp)
-       CALL phys_output_open(longitude_deg,latitude_deg,nCFMIP,tabijGCM, &
-            iGCM,jGCM,lonGCM,latGCM, &
-            jjmp1,nlevSTD,clevSTD,rlevSTD, dtime,ok_veget, &
-            type_ocean,iflag_pbl,iflag_pbl_split,ok_mensuel,ok_journe, &
-            ok_hf,ok_instan,ok_LES,ok_ade,ok_aie, &
-            read_climoz, phys_out_filestations, &
-            new_aod, aerosol_couple, &
-            flag_aerosol_strat, pdtphys, paprs, pphis,  &
-            pplay, lmax_th, ptconv, ptconvth, ivap,  &
-            d_u, d_t, qx, d_qx, zmasse, ok_sync_omp)
-       !$OMP END MASTER
-       !$OMP BARRIER
-       ok_sync=ok_sync_omp
-
-       freq_outNMC(1) = ecrit_files(7)
-       freq_outNMC(2) = ecrit_files(8)
-       freq_outNMC(3) = ecrit_files(9)
-       WRITE(lunout,*)'OK freq_outNMC(1)=',freq_outNMC(1)
-       WRITE(lunout,*)'OK freq_outNMC(2)=',freq_outNMC(2)
-       WRITE(lunout,*)'OK freq_outNMC(3)=',freq_outNMC(3)
-
-#ifndef CPP_XIOS
-       CALL ini_paramLMDZ_phy(dtime,nid_ctesGCM)
-#endif
-
-#endif
-       ecrit_reg = ecrit_reg * un_jour
-       ecrit_tra = ecrit_tra * un_jour
-
-       !XXXPB Positionner date0 pour initialisation de ORCHIDEE
-       date0 = jD_ref 
-       WRITE(*,*) 'physiq date0 : ',date0
+
+       CALL printflag( tabcntr0,radpas,ok_journe, &
+            ok_instan, ok_region )
        !
        !
@@ -1792,10 +1952,4 @@
 #endif
        ENDIF
-       !
-       ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-       ! Nouvelle initialisation pour le rayonnement RRTM
-       ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-
-       CALL iniradia(klon,klev,paprs(1,1:klev+1))
 
        !$omp single
@@ -1815,14 +1969,14 @@
 
        !albedo SB >>>
-       select case(nsw)
-       case(2)
+       SELECT CASE(nsw)
+       CASE(2)
           SFRWL(1)=0.45538747
           SFRWL(2)=0.54461211
-       case(4)
+       CASE(4)
           SFRWL(1)=0.45538747
           SFRWL(2)=0.32870591
           SFRWL(3)=0.18568763
           SFRWL(4)=3.02191470E-02
-       case(6)
+       CASE(6)
           SFRWL(1)=1.28432794E-03
           SFRWL(2)=0.12304168
@@ -1831,5 +1985,5 @@
           SFRWL(5)=0.18568763
           SFRWL(6)=3.02191470E-02
-       end select
+       END SELECT
 
 
@@ -1870,4 +2024,6 @@
       sollwdown(:)= sollwdown(:) + betalwoff *(-1.*ZFLDN0(:,1) - &
                     sollwdown(:))
+
+
     ENDIF
     !
@@ -1891,5 +2047,5 @@
     ! on the surface fraction.
     !
-    CALL change_srf_frac(itap, dtime, days_elapsed+1,  &
+    CALL change_srf_frac(itap, phys_tstep, days_elapsed+1,  &
          pctsrf, fevap, z0m, z0h, agesno,              &
          falb_dir, falb_dif, ftsol, ustar, u10m, v10m, pbl_tke)
@@ -1903,5 +2059,4 @@
 #endif
     ENDIF
-
 
     ! Tendances bidons pour les processus qui n'affectent pas certaines
@@ -2005,4 +2160,13 @@
        ENDDO
     ENDIF
+!
+! Temporary solutions adressing ticket #104 and the non initialisation of tr_ancien
+! LF
+    IF (debut) THEN
+      WRITE(lunout,*)' WARNING: tr_ancien initialised to tr_seri'
+      DO iq = nqo+1, nqtot
+           tr_ancien(:,:,iq-nqo)=tr_seri(:,:,iq-nqo)
+      ENDDO
+    ENDIF
     !
     DO i = 1, klon
@@ -2021,20 +2185,20 @@
     IF (ancien_ok) THEN
     !
-       d_u_dyn(:,:)  = (u_seri(:,:)-u_ancien(:,:))/dtime
-       d_v_dyn(:,:)  = (v_seri(:,:)-v_ancien(:,:))/dtime
-       d_t_dyn(:,:)  = (t_seri(:,:)-t_ancien(:,:))/dtime
-       d_q_dyn(:,:)  = (q_seri(:,:)-q_ancien(:,:))/dtime
-       d_ql_dyn(:,:) = (ql_seri(:,:)-ql_ancien(:,:))/dtime
-       d_qs_dyn(:,:) = (qs_seri(:,:)-qs_ancien(:,:))/dtime
+       d_u_dyn(:,:)  = (u_seri(:,:)-u_ancien(:,:))/phys_tstep
+       d_v_dyn(:,:)  = (v_seri(:,:)-v_ancien(:,:))/phys_tstep
+       d_t_dyn(:,:)  = (t_seri(:,:)-t_ancien(:,:))/phys_tstep
+       d_q_dyn(:,:)  = (q_seri(:,:)-q_ancien(:,:))/phys_tstep
+       d_ql_dyn(:,:) = (ql_seri(:,:)-ql_ancien(:,:))/phys_tstep
+       d_qs_dyn(:,:) = (qs_seri(:,:)-qs_ancien(:,:))/phys_tstep
        CALL water_int(klon,klev,q_seri,zmasse,zx_tmp_fi2d)
-       d_q_dyn2d(:)=(zx_tmp_fi2d(:)-prw_ancien(:))/dtime
+       d_q_dyn2d(:)=(zx_tmp_fi2d(:)-prw_ancien(:))/phys_tstep
        CALL water_int(klon,klev,ql_seri,zmasse,zx_tmp_fi2d)
-       d_ql_dyn2d(:)=(zx_tmp_fi2d(:)-prlw_ancien(:))/dtime
+       d_ql_dyn2d(:)=(zx_tmp_fi2d(:)-prlw_ancien(:))/phys_tstep
        CALL water_int(klon,klev,qs_seri,zmasse,zx_tmp_fi2d)
-       d_qs_dyn2d(:)=(zx_tmp_fi2d(:)-prsw_ancien(:))/dtime
+       d_qs_dyn2d(:)=(zx_tmp_fi2d(:)-prsw_ancien(:))/phys_tstep
        ! !! RomP >>>   td dyn traceur
        IF (nqtot.GT.nqo) THEN     ! jyg
           DO iq = nqo+1, nqtot      ! jyg
-              d_tr_dyn(:,:,iq-nqo)=(tr_seri(:,:,iq-nqo)-tr_ancien(:,:,iq-nqo))/dtime ! jyg
+              d_tr_dyn(:,:,iq-nqo)=(tr_seri(:,:,iq-nqo)-tr_ancien(:,:,iq-nqo))/phys_tstep ! jyg
           ENDDO
        ENDIF
@@ -2138,5 +2302,5 @@
                       ro3i, 'C', press_cen_climoz, pplay, wo, paprs(:,1),    &
                       time_climoz )
-          END IF
+          ENDIF
           ! Convert from mole fraction of ozone to column density of ozone in a
           ! cell, in kDU:
@@ -2158,5 +2322,5 @@
             (du0,dv0,d_t_eva,d_q_eva,d_ql_eva,d_qi_eva,paprs,&
                'eva',abortphy,flag_inhib_tend,itap,0)
-    call prt_enerbil('eva',itap)
+    CALL prt_enerbil('eva',itap)
 
     !=========================================================================
@@ -2213,5 +2377,5 @@
           !  bit comparable a l ancienne formulation cycle_diurne=true
           !  on integre entre gmtime et gmtime+radpas
-          zdtime=dtime*REAL(radpas) ! pas de temps du rayonnement (s)
+          zdtime=phys_tstep*REAL(radpas) ! pas de temps du rayonnement (s)
           CALL zenang(zlongi,jH_cur,0.0,zdtime, &
                latitude_deg,longitude_deg,rmu0,fract)
@@ -2230,6 +2394,6 @@
           !  premier pas de temps de la physique pendant lequel
           !  itaprad=0
-          zdtime1=dtime*REAL(-MOD(itaprad,radpas)-1)      
-          zdtime2=dtime*REAL(radpas-MOD(itaprad,radpas)-1) 
+          zdtime1=phys_tstep*REAL(-MOD(itaprad,radpas)-1)      
+          zdtime2=phys_tstep*REAL(radpas-MOD(itaprad,radpas)-1) 
           CALL zenang(zlongi,jH_cur,zdtime1,zdtime2, &
                latitude_deg,longitude_deg,rmu0,fract)
@@ -2237,5 +2401,5 @@
           ! Calcul des poids
           !
-          zdtime1=-dtime !--on corrige le rayonnement pour representer le
+          zdtime1=-phys_tstep !--on corrige le rayonnement pour representer le
           zdtime2=0.0    !--pas de temps de la physique qui se termine
           CALL zenang(zlongi,jH_cur,zdtime1,zdtime2, &
@@ -2295,4 +2459,7 @@
        !
        !-------gustiness calculation-------!
+       !ym : Warning gustiness non inialized for iflag_gusts=2 & iflag_gusts=3
+       gustiness=0  !ym missing init
+       
        IF (iflag_gusts==0) THEN
           gustiness(1:klon)=0
@@ -2312,8 +2479,6 @@
        ENDIF
 
-
-
        CALL pbl_surface(  &
-            dtime,     date0,     itap,    days_elapsed+1, &
+            phys_tstep,     date0,     itap,    days_elapsed+1, &
             debut,     lafin, &
             longitude_deg, latitude_deg, rugoro,  zrmu0,      &
@@ -2382,7 +2547,20 @@
        ENDIF
 
-
-
-
+!add limitation for t,q at and wind at 10m
+        if ( iflag_bug_t2m_ipslcm61 == 0 ) THEN
+          CALL borne_var_surf( klon,klev,nbsrf,                 &
+            iflag_bug_t2m_stab_ipslcm61,                        &
+            t_seri(:,1),q_seri(:,1),u_seri(:,1),v_seri(:,1),    &
+            ftsol,zxqsurf,pctsrf,paprs,                         &
+            t2m, q2m, u10m, v10m,                               &
+            zt2m_cor, zq2m_cor, zu10m_cor, zv10m_cor,           &
+            zrh2m_cor, zqsat2m_cor)
+        ELSE
+          zt2m_cor(:)=zt2m(:)
+          zq2m_cor(:)=zq2m(:)
+          zu10m_cor(:)=zu10m(:)
+          zv10m_cor(:)=zv10m(:)
+          zqsat2m_cor=999.999
+        ENDIF
 
        !---------------------------------------------------------------------
@@ -2397,5 +2575,5 @@
                'vdf',abortphy,flag_inhib_tend,itap,0)
        ENDIF
-       call prt_enerbil('vdf',itap)
+       CALL prt_enerbil('vdf',itap)
        !--------------------------------------------------------------------
 
@@ -2482,7 +2660,7 @@
        DO i = 1, klon
           conv_q(i,k) = d_q_dyn(i,k)  &
-               + d_q_vdf(i,k)/dtime
+               + d_q_vdf(i,k)/phys_tstep
           conv_t(i,k) = d_t_dyn(i,k)  &
-               + d_t_vdf(i,k)/dtime
+               + d_t_vdf(i,k)/phys_tstep
        ENDDO
     ENDDO
@@ -2528,4 +2706,5 @@
     pmflxs(:,:) = 0.
     wdtrainA(:,:) = 0.
+    wdtrainS(:,:) = 0.
     wdtrainM(:,:) = 0.
     upwd(:,:) = 0.
@@ -2543,4 +2722,5 @@
     elij(:,:,:)=0.
     ev(:,:)=0.
+    qtaa(:,:)=0.
     clw(:,:)=0.
     sij(:,:,:)=0.
@@ -2549,9 +2729,9 @@
        abort_message ='reactiver le call conlmd dans physiq.F'
        CALL abort_physic (modname,abort_message,1)
-       !     CALL conlmd (dtime, paprs, pplay, t_seri, q_seri, conv_q,
+       !     CALL conlmd (phys_tstep, paprs, pplay, t_seri, q_seri, conv_q,
        !    .             d_t_con, d_q_con,
        !    .             rain_con, snow_con, ibas_con, itop_con)
     ELSE IF (iflag_con.EQ.2) THEN
-       CALL conflx(dtime, paprs, pplay, t_seri, q_seri, &
+       CALL conflx(phys_tstep, paprs, pplay, t_seri, q_seri, &
             conv_t, conv_q, -evap, omega, &
             d_t_con, d_q_con, rain_con, snow_con, &
@@ -2629,5 +2809,5 @@
 
 !jyg<
-       CALL alpale( debut, itap, dtime, paprs, omega, t_seri,   &
+       CALL alpale( debut, itap, phys_tstep, paprs, omega, t_seri,   &
                     alp_offset, it_wape_prescr,  wape_prescr, fip_prescr, &
                     ale_bl_prescr, alp_bl_prescr, &
@@ -2671,5 +2851,5 @@
           !c          CALL concvl (iflag_con,iflag_clos,
           CALL concvl (iflag_clos, &
-               dtime, paprs, pplay, k_upper_cv, t_x,q_x, &
+               phys_tstep, paprs, pplay, k_upper_cv, t_x,q_x, &
                t_w,q_w,wake_s, &
                u_seri,v_seri,tr_seri,nbtr_tmp, &
@@ -2679,13 +2859,13 @@
                rain_con, snow_con, ibas_con, itop_con, sigd, &
                ema_cbmf,plcl,plfc,wbeff,convoccur,upwd,dnwd,dnwd0, &
-               Ma,mip,Vprecip,cape,cin,tvp,Tconv,iflagctrl, &
+               Ma,mipsh,Vprecip,cape,cin,tvp,Tconv,iflagctrl, &
                pbase,bbase,dtvpdt1,dtvpdq1,dplcldt,dplcldr,qcondc,wd, &
                                 ! RomP >>>
                                 !!     .        pmflxr,pmflxs,da,phi,mp,
                                 !!     .        ftd,fqd,lalim_conv,wght_th)
-               pmflxr,pmflxs,da,phi,mp,phi2,d1a,dam,sij,clw,elij, &
+               pmflxr,pmflxs,da,phi,mp,phi2,d1a,dam,sij,qtaa,clw,elij, &
                ftd,fqd,lalim_conv,wght_th, &
                ev, ep,epmlmMm,eplaMm, &
-               wdtrainA,wdtrainM,wght_cvfd,qtc_cv,sigt_cv, &
+               wdtrainA, wdtrainS, wdtrainM,wght_cvfd,qtc_cv,sigt_cv, &
                tau_cld_cv,coefw_cld_cv,epmax_diag)
 
@@ -2741,6 +2921,6 @@
               DO k=1,klev
                  DO i=1,klon
-                    ftd(i,k) = ftd(i,k) + wake_s(i)*d_t_adjwk(i,k)/dtime
-                    fqd(i,k) = fqd(i,k) + wake_s(i)*d_q_adjwk(i,k)/dtime
+                    ftd(i,k) = ftd(i,k) + wake_s(i)*d_t_adjwk(i,k)/phys_tstep
+                    fqd(i,k) = fqd(i,k) + wake_s(i)*d_q_adjwk(i,k)/phys_tstep
                     d_t_con(i,k) = d_t_con(i,k) + wake_s(i)*d_t_adjwk(i,k)
                     d_q_con(i,k) = d_q_con(i,k) + wake_s(i)*d_q_adjwk(i,k)
@@ -2754,5 +2934,5 @@
 
           ! MAF conema3 ne contient pas les traceurs
-          CALL conema3 (dtime, &
+          CALL conema3 (phys_tstep, &
                paprs,pplay,t_seri,q_seri, &
                u_seri,v_seri,tr_seri,ntra, &
@@ -2865,5 +3045,5 @@
     CALL add_phys_tend(d_u_con, d_v_con, d_t_con, d_q_con, dql0, dqi0, paprs, &
          'convection',abortphy,flag_inhib_tend,itap,0)
-    call prt_enerbil('convection',itap)
+    CALL prt_enerbil('convection',itap)
 
     !-------------------------------------------------------------------------
@@ -2886,5 +3066,5 @@
                snow_con(i))*cell_area(i)/REAL(klon)
        ENDDO
-       zx_t = zx_t/za*dtime
+       zx_t = zx_t/za*phys_tstep
        WRITE(lunout,*)"Precip=", zx_t
     ENDIF
@@ -2900,5 +3080,5 @@
        ENDDO
        DO i = 1, klon
-          z_factor(i) = (z_avant(i)-(rain_con(i)+snow_con(i))*dtime) &
+          z_factor(i) = (z_avant(i)-(rain_con(i)+snow_con(i))*phys_tstep) &
                /z_apres(i)
        ENDDO
@@ -2937,6 +3117,6 @@
                 M_dwn(i,k)   = dnwd0(i,k)
                 M_up(i,k)    = upwd(i,k)
-                dt_a(i,k)    = d_t_con(i,k)/dtime - ftd(i,k) 
-                dq_a(i,k)    = d_q_con(i,k)/dtime - fqd(i,k)
+                dt_a(i,k)    = d_t_con(i,k)/phys_tstep - ftd(i,k) 
+                dq_a(i,k)    = d_q_con(i,k)/phys_tstep - fqd(i,k)
              ENDDO
           ENDDO
@@ -2946,7 +3126,7 @@
              DO k = 1,klev
                 dt_dwn(:,k)= dt_dwn(:,k)+ &
-                     ok_wk_lsp(:)*(d_t_eva(:,k)+d_t_lsc(:,k))/dtime
+                     ok_wk_lsp(:)*(d_t_eva(:,k)+d_t_lsc(:,k))/phys_tstep
                 dq_dwn(:,k)= dq_dwn(:,k)+ &
-                     ok_wk_lsp(:)*(d_q_eva(:,k)+d_q_lsc(:,k))/dtime
+                     ok_wk_lsp(:)*(d_q_eva(:,k)+d_q_lsc(:,k))/phys_tstep
              ENDDO
           ELSEIF (iflag_wake==3) THEN
@@ -2959,7 +3139,7 @@
                       ! l'eau se reevapore).
                       dt_dwn(i,k)= dt_dwn(i,k)+ &
-                           ok_wk_lsp(i)*d_t_lsc(i,k)/dtime
+                           ok_wk_lsp(i)*d_t_lsc(i,k)/phys_tstep
                       dq_dwn(i,k)= dq_dwn(i,k)+ &
-                           ok_wk_lsp(i)*d_q_lsc(i,k)/dtime
+                           ok_wk_lsp(i)*d_q_lsc(i,k)/phys_tstep
                    ENDIF
                 ENDDO
@@ -2969,5 +3149,5 @@
           !
           !calcul caracteristiques de la poche froide
-          CALL calWAKE (iflag_wake_tend, paprs, pplay, dtime, &
+          CALL calWAKE (iflag_wake_tend, paprs, pplay, phys_tstep, &
                t_seri, q_seri, omega,  &
                dt_dwn, dq_dwn, M_dwn, M_up,  &
@@ -2996,5 +3176,5 @@
        CALL add_phys_tend(du0,dv0,d_t_wake,d_q_wake,dql0,dqi0,paprs,'wake', &
             abortphy,flag_inhib_tend,itap,0)
-       call prt_enerbil('wake',itap)
+       CALL prt_enerbil('wake',itap)
        !------------------------------------------------------------------------
 
@@ -3005,5 +3185,5 @@
             (d_deltat_wk, d_deltaq_wk, d_s_wk, d_dens_a_wk, d_dens_wk, wake_k, &
              'wake', abortphy) 
-          call prt_enerbil('wake',itap)
+          CALL prt_enerbil('wake',itap)
        ENDIF   ! (iflag_wake_tend .GT. 0.)
        !
@@ -3016,5 +3196,5 @@
        IF (iflag_alp_wk_cond .GT. 0.) THEN
 
-         CALL alpale_wk(dtime, cell_area, wake_k, wake_s, wake_dens, wake_fip_0, &
+         CALL alpale_wk(phys_tstep, cell_area, wake_k, wake_s, wake_dens, wake_fip_0, &
                         wake_fip)
        ELSE
@@ -3147,5 +3327,5 @@
                    (d_deltat_the, d_deltaq_the, dsig0, ddens0, ddens0, wake_k, 'the', abortphy) 
              ENDIF
-             call prt_enerbil('the',itap)
+             CALL prt_enerbil('the',itap)
           !
           ENDIF  ! (mod(iflag_pbl_split/10,10) .GE. 1)
@@ -3153,8 +3333,8 @@
           CALL add_phys_tend(d_u_ajs,d_v_ajs,d_t_ajs,d_q_ajs,  &
                              dql0,dqi0,paprs,'thermals', abortphy,flag_inhib_tend,itap,0)
-          call prt_enerbil('thermals',itap)
+          CALL prt_enerbil('thermals',itap)
           !
 !
-          CALL alpale_th( dtime, lmax_th, t_seri, cell_area,  &
+          CALL alpale_th( phys_tstep, lmax_th, t_seri, cell_area,  &
                           cin, s2, n2,  &
                           ale_bl_trig, ale_bl_stat, ale_bl,  &
@@ -3216,5 +3396,5 @@
           CALL add_phys_tend(du0,dv0,d_t_ajsb,d_q_ajsb,dql0,dqi0,paprs, &
                'ajsb',abortphy,flag_inhib_tend,itap,0)
-          call prt_enerbil('ajsb',itap)
+          CALL prt_enerbil('ajsb',itap)
           d_t_ajs(:,:)=d_t_ajs(:,:)+d_t_ajsb(:,:)
           d_q_ajs(:,:)=d_q_ajs(:,:)+d_q_ajsb(:,:)
@@ -3246,5 +3426,5 @@
     ENDIF
     !
-    CALL fisrtilp(dtime,paprs,pplay, &
+    CALL fisrtilp(phys_tstep,paprs,pplay, &
          t_seri, q_seri,ptconv,ratqs, &
          d_t_lsc, d_q_lsc, d_ql_lsc, d_qi_lsc, rneb, cldliq, &
@@ -3267,5 +3447,5 @@
     CALL add_phys_tend(du0,dv0,d_t_lsc,d_q_lsc,d_ql_lsc,d_qi_lsc,paprs, &
          'lsc',abortphy,flag_inhib_tend,itap,0)
-    call prt_enerbil('lsc',itap)
+    CALL prt_enerbil('lsc',itap)
     rain_num(:)=0.
     DO k = 1, klev
@@ -3306,5 +3486,5 @@
                + snow_lsc(i))*cell_area(i)/REAL(klon)
        ENDDO
-       zx_t = zx_t/za*dtime
+       zx_t = zx_t/za*phys_tstep
        WRITE(lunout,*)"Precip=", zx_t
     ENDIF
@@ -3526,11 +3706,9 @@
        calday = REAL(days_elapsed + 1) + jH_cur
 
-       CALL chemtime(itap+itau_phy-1, date0, dtime, itap)
-       IF (config_inca == 'aero' .OR. config_inca == 'aeNP') THEN
-          CALL AEROSOL_METEO_CALC( &
-               calday,pdtphys,pplay,paprs,t,pmflxr,pmflxs, &
-               prfl,psfl,pctsrf,cell_area, &
-               latitude_deg,longitude_deg,u10m,v10m)
-       ENDIF
+       CALL chemtime(itap+itau_phy-1, date0, phys_tstep, itap)
+       CALL AEROSOL_METEO_CALC( &
+            calday,pdtphys,pplay,paprs,t,pmflxr,pmflxs, &
+            prfl,psfl,pctsrf,cell_area, &
+            latitude_deg,longitude_deg,u10m,v10m)
 
        zxsnow_dummy(:) = 0.0
@@ -3615,5 +3793,5 @@
 #else
                    !--climatologies or INCA aerosols
-                   CALL readaerosol_optic_rrtm( debut, aerosol_couple, ok_alw, &
+                   CALL readaerosol_optic_rrtm( debut, aerosol_couple, ok_alw, ok_volcan, &
                         new_aod, flag_aerosol, flag_bc_internal_mixture, itap, jD_cur-jD_ref, &
                         pdtphys, pplay, paprs, t_seri, rhcl, presnivs,  &
@@ -3705,5 +3883,5 @@
              CALL readaerosolstrato1_rrtm(debut)
             ELSEIF (flag_aerosol_strat.EQ.2) THEN
-             CALL readaerosolstrato2_rrtm(debut)
+             CALL readaerosolstrato2_rrtm(debut, ok_volcan)
             ELSE
              abort_message='flag_aerosol_strat must equal 1 or 2 for rrtm=1'
@@ -3717,4 +3895,6 @@
 #endif
           ENDIF
+       ELSE
+          tausum_aero(:,:,id_STRAT_phy) = 0. 
        ENDIF
 !
@@ -3895,9 +4075,13 @@
           RCFC11 = RCFC11_act
           RCFC12 = RCFC12_act
+          ! 
+          !--interactive CO2 in ppm from carbon cycle
+          IF (carbon_cycle_rad.AND..NOT.debut) THEN
+            RCO2=RCO2_glo
+          ENDIF
           !
           IF (prt_level .GE.10) THEN
              print *,' ->radlwsw, number 1 '
           ENDIF
-
           !
           CALL radlwsw &
@@ -3909,5 +4093,6 @@
                t_seri,q_seri,wo, &
                cldfrarad, cldemirad, cldtaurad, &
-               ok_ade.OR.flag_aerosol_strat.GT.0, ok_aie, flag_aerosol, &
+               ok_ade.OR.flag_aerosol_strat.GT.0, ok_aie,  ok_volcan, &
+               flag_aerosol, &
                flag_aerosol_strat, flag_aer_feedback, &
                tau_aero, piz_aero, cg_aero, &
@@ -3920,4 +4105,5 @@
                ref_liq, ref_ice, ref_liq_pi, ref_ice_pi, &
                heat,heat0,cool,cool0,albpla, &
+               heat_volc,cool_volc, &
                topsw,toplw,solsw,sollw, &
                sollwdown, &
@@ -3994,5 +4180,6 @@
                      t_seri,q_seri,wo, &
                      cldfrarad, cldemirad, cldtaurad, &
-                     ok_ade.OR.flag_aerosol_strat.GT.0, ok_aie, flag_aerosol, &
+                     ok_ade.OR.flag_aerosol_strat.GT.0, ok_aie,  ok_volcan, &
+                     flag_aerosol, &
                      flag_aerosol_strat, flag_aer_feedback, &
                      tau_aero, piz_aero, cg_aero, &
@@ -4005,4 +4192,5 @@
                      ref_liq, ref_ice, ref_liq_pi, ref_ice_pi, &
                      heatp,heat0p,coolp,cool0p,albplap, &
+                     heat_volc,cool_volc, &
                      topswp,toplwp,solswp,sollwp, &
                      sollwdownp, &
@@ -4072,14 +4260,14 @@
 
     DO k=1, klev
-       d_t_swr(:,k)=swradcorr(:)*heat(:,k)*dtime/RDAY
-       d_t_sw0(:,k)=swradcorr(:)*heat0(:,k)*dtime/RDAY
-       d_t_lwr(:,k)=-cool(:,k)*dtime/RDAY
-       d_t_lw0(:,k)=-cool0(:,k)*dtime/RDAY
+       d_t_swr(:,k)=swradcorr(:)*heat(:,k)*phys_tstep/RDAY
+       d_t_sw0(:,k)=swradcorr(:)*heat0(:,k)*phys_tstep/RDAY
+       d_t_lwr(:,k)=-cool(:,k)*phys_tstep/RDAY
+       d_t_lw0(:,k)=-cool0(:,k)*phys_tstep/RDAY
     ENDDO
 
     CALL add_phys_tend(du0,dv0,d_t_swr,dq0,dql0,dqi0,paprs,'SW',abortphy,flag_inhib_tend,itap,0)
-    call prt_enerbil('SW',itap)
+    CALL prt_enerbil('SW',itap)
     CALL add_phys_tend(du0,dv0,d_t_lwr,dq0,dql0,dqi0,paprs,'LW',abortphy,flag_inhib_tend,itap,0)
-    call prt_enerbil('LW',itap)
+    CALL prt_enerbil('LW',itap)
 
     !
@@ -4131,5 +4319,5 @@
        IF (ok_strato) THEN
 
-          CALL drag_noro_strato(0,klon,klev,dtime,paprs,pplay, &
+          CALL drag_noro_strato(0,klon,klev,phys_tstep,paprs,pplay, &
                zmea,zstd, zsig, zgam, zthe,zpic,zval, &
                igwd,idx,itest, &
@@ -4139,5 +4327,5 @@
 
        ELSE
-          CALL drag_noro(klon,klev,dtime,paprs,pplay, &
+          CALL drag_noro(klon,klev,phys_tstep,paprs,pplay, &
                zmea,zstd, zsig, zgam, zthe,zpic,zval, &
                igwd,idx,itest, &
@@ -4152,5 +4340,5 @@
        CALL add_phys_tend(d_u_oro,d_v_oro,d_t_oro,dq0,dql0,dqi0,paprs,'oro', &
             abortphy,flag_inhib_tend,itap,0)
-       call prt_enerbil('oro',itap)
+       CALL prt_enerbil('oro',itap)
        !----------------------------------------------------------------------
        !
@@ -4180,5 +4368,5 @@
        IF (ok_strato) THEN
 
-          CALL lift_noro_strato(klon,klev,dtime,paprs,pplay, &
+          CALL lift_noro_strato(klon,klev,phys_tstep,paprs,pplay, &
                latitude_deg,zmea,zstd,zpic,zgam,zthe,zpic,zval, &
                igwd,idx,itest, &
@@ -4188,5 +4376,5 @@
 
        ELSE
-          CALL lift_noro(klon,klev,dtime,paprs,pplay, &
+          CALL lift_noro(klon,klev,phys_tstep,paprs,pplay, &
                latitude_deg,zmea,zstd,zpic, &
                itest, &
@@ -4199,5 +4387,5 @@
        CALL add_phys_tend(d_u_lif, d_v_lif, d_t_lif, dq0, dql0, dqi0, paprs, &
             'lif', abortphy,flag_inhib_tend,itap,0)
-       call prt_enerbil('lif',itap)
+       CALL prt_enerbil('lif',itap)
     ENDIF ! fin de test sur ok_orolf
 
@@ -4208,5 +4396,5 @@
        du_gwd_hines=0.
        dv_gwd_hines=0.
-       CALL hines_gwd(klon, klev, dtime, paprs, pplay, latitude_deg, t_seri, &
+       CALL hines_gwd(klon, klev, phys_tstep, paprs, pplay, latitude_deg, t_seri, &
             u_seri, v_seri, zustr_gwd_hines, zvstr_gwd_hines, d_t_hin, &
             du_gwd_hines, dv_gwd_hines)
@@ -4214,7 +4402,7 @@
        zvstr_gwd_hines=0.
        DO k = 1, klev
-          zustr_gwd_hines(:)=zustr_gwd_hines(:)+ du_gwd_hines(:, k)/dtime &
+          zustr_gwd_hines(:)=zustr_gwd_hines(:)+ du_gwd_hines(:, k)/phys_tstep &
                * (paprs(:, k)-paprs(:, k+1))/rg
-          zvstr_gwd_hines(:)=zvstr_gwd_hines(:)+ dv_gwd_hines(:, k)/dtime &
+          zvstr_gwd_hines(:)=zvstr_gwd_hines(:)+ dv_gwd_hines(:, k)/phys_tstep &
                * (paprs(:, k)-paprs(:, k+1))/rg
        ENDDO
@@ -4223,9 +4411,10 @@
        CALL add_phys_tend(du_gwd_hines, dv_gwd_hines, d_t_hin, dq0, dql0, &
             dqi0, paprs, 'hin', abortphy,flag_inhib_tend,itap,0)
-       call prt_enerbil('hin',itap)
+       CALL prt_enerbil('hin',itap)
     ENDIF
 
     IF (.not. ok_hines .and. ok_gwd_rando) then
-       CALL acama_GWD_rando(DTIME, pplay, latitude_deg, t_seri, u_seri, &
+       ! ym missing init for east_gwstress & west_gwstress -> added in phys_local_var_mod
+       CALL acama_GWD_rando(PHYS_TSTEP, pplay, latitude_deg, t_seri, u_seri, &
             v_seri, rot, zustr_gwd_front, zvstr_gwd_front, du_gwd_front, &
             dv_gwd_front, east_gwstress, west_gwstress)
@@ -4233,7 +4422,7 @@
        zvstr_gwd_front=0.
        DO k = 1, klev
-          zustr_gwd_front(:)=zustr_gwd_front(:)+ du_gwd_front(:, k)/dtime &
+          zustr_gwd_front(:)=zustr_gwd_front(:)+ du_gwd_front(:, k)/phys_tstep &
                * (paprs(:, k)-paprs(:, k+1))/rg
-          zvstr_gwd_front(:)=zvstr_gwd_front(:)+ dv_gwd_front(:, k)/dtime &
+          zvstr_gwd_front(:)=zvstr_gwd_front(:)+ dv_gwd_front(:, k)/phys_tstep &
                * (paprs(:, k)-paprs(:, k+1))/rg
        ENDDO
@@ -4241,20 +4430,20 @@
        CALL add_phys_tend(du_gwd_front, dv_gwd_front, dt0, dq0, dql0, dqi0, &
             paprs, 'front_gwd_rando', abortphy,flag_inhib_tend,itap,0)
-       call prt_enerbil('front_gwd_rando',itap)
+       CALL prt_enerbil('front_gwd_rando',itap)
     ENDIF
 
     IF (ok_gwd_rando) THEN
-       CALL FLOTT_GWD_rando(DTIME, pplay, t_seri, u_seri, v_seri, &
+       CALL FLOTT_GWD_rando(PHYS_TSTEP, pplay, t_seri, u_seri, v_seri, &
             rain_fall + snow_fall, zustr_gwd_rando, zvstr_gwd_rando, &
             du_gwd_rando, dv_gwd_rando, east_gwstress, west_gwstress)
        CALL add_phys_tend(du_gwd_rando, dv_gwd_rando, dt0, dq0, dql0, dqi0, &
             paprs, 'flott_gwd_rando', abortphy,flag_inhib_tend,itap,0)
-       call prt_enerbil('flott_gwd_rando',itap)
+       CALL prt_enerbil('flott_gwd_rando',itap)
        zustr_gwd_rando=0.
        zvstr_gwd_rando=0.
        DO k = 1, klev
-          zustr_gwd_rando(:)=zustr_gwd_rando(:)+ du_gwd_rando(:, k)/dtime &
+          zustr_gwd_rando(:)=zustr_gwd_rando(:)+ du_gwd_rando(:, k)/phys_tstep &
                * (paprs(:, k)-paprs(:, k+1))/rg
-          zvstr_gwd_rando(:)=zvstr_gwd_rando(:)+ dv_gwd_rando(:, k)/dtime &
+          zvstr_gwd_rando(:)=zvstr_gwd_rando(:)+ dv_gwd_rando(:, k)/phys_tstep &
                * (paprs(:, k)-paprs(:, k+1))/rg
        ENDDO
@@ -4276,7 +4465,7 @@
     DO k = 1, klev
        DO i = 1, klon
-          zustrph(i)=zustrph(i)+(u_seri(i,k)-u(i,k))/dtime* &
+          zustrph(i)=zustrph(i)+(u_seri(i,k)-u(i,k))/phys_tstep* &
                (paprs(i,k)-paprs(i,k+1))/rg
-          zvstrph(i)=zvstrph(i)+(v_seri(i,k)-v(i,k))/dtime* &
+          zvstrph(i)=zvstrph(i)+(v_seri(i,k)-v(i,k))/phys_tstep* &
                (paprs(i,k)-paprs(i,k+1))/rg
        ENDDO
@@ -4296,11 +4485,11 @@
     !IM cf. FLott END
     !DC Calcul de la tendance due au methane
-    IF(ok_qch4) THEN
+    IF (ok_qch4) THEN
        CALL METHOX(1,klon,klon,klev,q_seri,d_q_ch4,pplay)
        ! ajout de la tendance d'humidite due au methane
-       d_q_ch4_dtime(:,:) = d_q_ch4(:,:)*dtime
+       d_q_ch4_dtime(:,:) = d_q_ch4(:,:)*phys_tstep
        CALL add_phys_tend(du0, dv0, dt0, d_q_ch4_dtime, dql0, dqi0, paprs, &
             'q_ch4', abortphy,flag_inhib_tend,itap,0)
-       d_q_ch4(:,:) = d_q_ch4_dtime(:,:)/dtime
+       d_q_ch4(:,:) = d_q_ch4_dtime(:,:)/phys_tstep
     ENDIF
     !
@@ -4313,6 +4502,4 @@
 ! Inititialization
 !------------------
-
-    
 
        addtkeoro=0   
@@ -4326,13 +4513,11 @@
        alphatkeoro=min(max(0.,alphatkeoro),1.)
 
-       smallscales_tkeoro=.false.   
+       smallscales_tkeoro=.FALSE.   
        CALL getin_p('smallscales_tkeoro',smallscales_tkeoro) 
 
 
-        dtadd(:,:)=0.
-        duadd(:,:)=0.
-        dvadd(:,:)=0.
-
-
+       dtadd(:,:)=0.
+       duadd(:,:)=0.
+       dvadd(:,:)=0.
 
 ! Choices for addtkeoro:
@@ -4349,5 +4534,4 @@
 
 
-
   IF (addtkeoro .EQ. 1 ) THEN
 
@@ -4357,7 +4541,5 @@
   ELSE IF (addtkeoro .EQ. 2) THEN
 
-
-
-       IF (smallscales_tkeoro) THEN
+     IF (smallscales_tkeoro) THEN
        igwd=0
        DO i=1,klon
@@ -4382,13 +4564,10 @@
              igwd=igwd+1
              idx(igwd)=i
-          ENDIF
-       ENDDO
-
-       END IF
-
-
-
-
-       CALL drag_noro_strato(addtkeoro,klon,klev,dtime,paprs,pplay, &
+        ENDIF
+       ENDDO
+
+     ENDIF
+
+     CALL drag_noro_strato(addtkeoro,klon,klev,phys_tstep,paprs,pplay, &
                zmea,zstd, zsig, zgam, zthe,zpic,zval, &
                igwd,idx,itest, &
@@ -4397,13 +4576,12 @@
                d_t_oro_gw, d_u_oro_gw, d_v_oro_gw)
 
-            zustrdr(:)=0.
-            zvstrdr(:)=0.
-            zulow(:)=0.
-            zvlow(:)=0.
-
-            duadd(:,:)=alphatkeoro*d_u_oro_gw(:,:)
-            dvadd(:,:)=alphatkeoro*d_v_oro_gw(:,:)
- END IF
-    
+     zustrdr(:)=0.
+     zvstrdr(:)=0.
+     zulow(:)=0.
+     zvlow(:)=0.
+
+     duadd(:,:)=alphatkeoro*d_u_oro_gw(:,:)
+     dvadd(:,:)=alphatkeoro*d_v_oro_gw(:,:)
+  ENDIF
 
 
@@ -4416,9 +4594,7 @@
 
 
-
        ENDIF
 !      -----
 !===============================================================
-
 
 
@@ -4431,5 +4607,5 @@
        ! adeclarer 
 #ifdef CPP_COSP
-       IF (itap.eq.1.or.MOD(itap,NINT(freq_cosp/dtime)).EQ.0) THEN
+       IF (itap.eq.1.or.MOD(itap,NINT(freq_cosp/phys_tstep)).EQ.0) THEN
 
           IF (prt_level .GE.10) THEN
@@ -4439,5 +4615,5 @@
           !       print*,'Dans physiq.F avant appel cosp ref_liq,ref_ice=',
           !     s        ref_liq,ref_ice
-          CALL phys_cosp(itap,dtime,freq_cosp, &
+          CALL phys_cosp(itap,phys_tstep,freq_cosp, &
                ok_mensuelCOSP,ok_journeCOSP,ok_hfCOSP, &
                ecrit_mth,ecrit_day,ecrit_hf, ok_all_xml, missing_val, &
@@ -4462,5 +4638,5 @@
 
 #ifdef CPP_COSP2
-       IF (itap.eq.1.or.MOD(itap,NINT(freq_cosp/dtime)).EQ.0) THEN
+       IF (itap.eq.1.or.MOD(itap,NINT(freq_cosp/phys_tstep)).EQ.0) THEN
 
           IF (prt_level .GE.10) THEN
@@ -4470,5 +4646,5 @@
                  print*,'Dans physiq.F avant appel '
           !     s        ref_liq,ref_ice
-          CALL phys_cosp2(itap,dtime,freq_cosp, &
+          CALL phys_cosp2(itap,phys_tstep,freq_cosp, &
                ok_mensuelCOSP,ok_journeCOSP,ok_hfCOSP, &
                ecrit_mth,ecrit_day,ecrit_hf, ok_all_xml, missing_val, &
@@ -4485,4 +4661,28 @@
 #endif
 
+#ifdef CPP_COSPV2
+       IF (itap.eq.1.or.MOD(itap,NINT(freq_cosp/phys_tstep)).EQ.0) THEN
+
+          IF (prt_level .GE.10) THEN
+             print*,'freq_cosp',freq_cosp
+          ENDIF
+          mr_ozone=wo(:, :, 1) * dobson_u * 1e3 / zmasse
+                 print*,'Dans physiq.F avant appel '
+          !     s        ref_liq,ref_ice
+          CALL lmdz_cosp_interface(itap,phys_tstep,freq_cosp, &
+               ok_mensuelCOSP,ok_journeCOSP,ok_hfCOSP, &
+               ecrit_mth,ecrit_day,ecrit_hf, ok_all_xml, missing_val, &
+               klon,klev,longitude_deg,latitude_deg,presnivs,overlap, &
+               JrNt,ref_liq,ref_ice, &
+               pctsrf(:,is_ter)+pctsrf(:,is_lic), &
+               zu10m,zv10m,pphis, &
+               zphi,paprs(:,1:klev),pplay,zxtsol,t_seri, &
+               qx(:,:,ivap),zx_rh,cldfra,rnebcon,flwc,fiwc, &
+               prfl(:,1:klev),psfl(:,1:klev), &
+               pmflxr(:,1:klev),pmflxs(:,1:klev), &
+               mr_ozone,cldtau, cldemi)
+       ENDIF
+#endif
+
     ENDIF  !ok_cosp
 
@@ -4492,5 +4692,5 @@
   IF (ok_airs) then
 
-  IF (itap.eq.1.or.MOD(itap,NINT(freq_airs/dtime)).EQ.0) THEN
+  IF (itap.eq.1.or.MOD(itap,NINT(freq_airs/phys_tstep)).EQ.0) THEN
      write(*,*) 'je vais appeler simu_airs, ok_airs, freq_airs=', ok_airs, freq_airs
      CALL simu_airs(itap,rneb, t_seri, cldemi, fiwc, ref_ice, pphi, pplay, paprs,&
@@ -4547,5 +4747,5 @@
     CALL phytrac ( &
          itap,     days_elapsed+1,    jH_cur,   debut, &
-         lafin,    dtime,     u, v,     t, &
+         lafin,    phys_tstep,     u, v,     t, &
          paprs,    pplay,     pmfu,     pmfd, &
          pen_u,    pde_u,     pen_d,    pde_d, &
@@ -4582,5 +4782,5 @@
             cdragh,coefh(1:klon,1:klev,is_ave),u1,v1,ftsol,pctsrf, &
             frac_impa, frac_nucl, &
-            pphis,cell_area,dtime,itap, &
+            pphis,cell_area,phys_tstep,itap, &
             qx(:,:,ivap),da,phi,mp,upwd,dnwd)
 
@@ -4653,5 +4853,5 @@
 
        CALL chemhook_end ( &
-            dtime, &
+            phys_tstep, &
             pplay, &
             t_seri, &
@@ -4688,12 +4888,12 @@
     DO k = 1, klev
        DO i = 1, klon
-          d_u(i,k) = ( u_seri(i,k) - u(i,k) ) / dtime
-          d_v(i,k) = ( v_seri(i,k) - v(i,k) ) / dtime
-          d_t(i,k) = ( t_seri(i,k)-t(i,k) ) / dtime
-          d_qx(i,k,ivap) = ( q_seri(i,k) - qx(i,k,ivap) ) / dtime
-          d_qx(i,k,iliq) = ( ql_seri(i,k) - qx(i,k,iliq) ) / dtime
+          d_u(i,k) = ( u_seri(i,k) - u(i,k) ) / phys_tstep
+          d_v(i,k) = ( v_seri(i,k) - v(i,k) ) / phys_tstep
+          d_t(i,k) = ( t_seri(i,k)-t(i,k) ) / phys_tstep
+          d_qx(i,k,ivap) = ( q_seri(i,k) - qx(i,k,ivap) ) / phys_tstep
+          d_qx(i,k,iliq) = ( ql_seri(i,k) - qx(i,k,iliq) ) / phys_tstep
           !CR: on ajoute le contenu en glace
           IF (nqo.eq.3) THEN
-             d_qx(i,k,isol) = ( qs_seri(i,k) - qx(i,k,isol) ) / dtime
+             d_qx(i,k,isol) = ( qs_seri(i,k) - qx(i,k,isol) ) / phys_tstep
           ENDIF
        ENDDO
@@ -4707,6 +4907,6 @@
           DO  k = 1, klev
              DO  i = 1, klon
-                ! d_qx(i,k,iq) = ( tr_seri(i,k,iq-2) - qx(i,k,iq) ) / dtime
-                d_qx(i,k,iq) = ( tr_seri(i,k,iq-nqo) - qx(i,k,iq) ) / dtime
+                ! d_qx(i,k,iq) = ( tr_seri(i,k,iq-2) - qx(i,k,iq) ) / phys_tstep
+                d_qx(i,k,iq) = ( tr_seri(i,k,iq-nqo) - qx(i,k,iq) ) / phys_tstep
              ENDDO
           ENDDO
@@ -4877,5 +5077,5 @@
     CALL phys_output_write(itap, pdtphys, paprs, pphis,  &
          pplay, lmax_th, aerosol_couple,                 &
-         ok_ade, ok_aie, ivap, iliq, isol, new_aod,      & 
+         ok_ade, ok_aie, ok_volcan, ivap, iliq, isol, new_aod,      & 
          ok_sync, ptconv, read_climoz, clevSTD,          &
          ptconvth, d_u, d_t, qx, d_qx, zmasse,           &
@@ -4890,5 +5090,5 @@
 
 ! On remet des variables a .false. apres un premier appel
-    if (debut) then
+    IF (debut) THEN
 #ifdef CPP_XIOS
       swaero_diag=.FALSE.
@@ -4898,5 +5098,5 @@
 !      write (lunout,*)'ok_4xCO2atm= ',swaero_diag, swaerofree_diag, dryaod_diag, ok_4xCO2atm
 
-      IF (is_master) then
+      IF (is_master) THEN
         !--setting up swaero_diag to TRUE in XIOS case 
         IF (xios_field_is_active("topswad").OR.xios_field_is_active("topswad0").OR. & 
@@ -4929,13 +5129,13 @@
            xios_field_is_active("rld4co2").OR.xios_field_is_active("rldcs4co2")) &
            ok_4xCO2atm=.TRUE. 
-      endif
+      ENDIF
       !$OMP BARRIER
-      call bcast(swaero_diag)
-      call bcast(swaerofree_diag)
-      call bcast(dryaod_diag)
-      call bcast(ok_4xCO2atm)
+      CALL bcast(swaero_diag)
+      CALL bcast(swaerofree_diag)
+      CALL bcast(dryaod_diag)
+      CALL bcast(ok_4xCO2atm)
 !      write (lunout,*)'ok_4xCO2atm= ',swaero_diag, swaerofree_diag, dryaod_diag, ok_4xCO2atm
 #endif
-    endif
+    ENDIF
 
     !====================================================================
@@ -4962,19 +5162,22 @@
        !         write(97) u_seri,v_seri,t_seri,q_seri
        !         close(97)
-       !$OMP MASTER
-       IF (read_climoz >= 1) THEN
-          IF (is_mpi_root) THEN
-             CALL nf95_close(ncid_climoz)
-          ENDIF
-          DEALLOCATE(press_edg_climoz) ! pointer
-          DEALLOCATE(press_cen_climoz) ! pointer
-       ENDIF
-       !$OMP END MASTER
-       print *,' physiq fin, nombre de steps ou cvpas = 1 : ', Ncvpaseq1
+      
+       IF (is_omp_master) THEN
+       
+         IF (read_climoz >= 1) THEN
+           IF (is_mpi_root) CALL nf95_close(ncid_climoz)
+            DEALLOCATE(press_edg_climoz) ! pointer
+            DEALLOCATE(press_cen_climoz) ! pointer
+         ENDIF
+       
+       ENDIF
+#ifdef CPP_XIOS
+       IF (is_omp_master) CALL xios_context_finalize
+#endif
+       WRITE(lunout,*) ' physiq fin, nombre de steps ou cvpas = 1 : ', Ncvpaseq1
     ENDIF
 
     !      first=.false.
 
-
   END SUBROUTINE physiq
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/phytrac_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/phytrac_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/phytrac_mod.F90	(revision 3605)
@@ -54,4 +54,23 @@
 CONTAINS
 
+  SUBROUTINE phytrac_init()
+    USE dimphy
+    USE infotrac_phy, ONLY: nbtr
+    IMPLICIT NONE
+
+       ALLOCATE(d_tr_cl(klon,klev,nbtr),d_tr_dry(klon,nbtr))
+       ALLOCATE(flux_tr_dry(klon,nbtr),d_tr_dec(klon,klev,nbtr),d_tr_cv(klon,klev,nbtr))
+       ALLOCATE(d_tr_insc(klon,klev,nbtr),d_tr_bcscav(klon,klev,nbtr))
+       ALLOCATE(d_tr_evapls(klon,klev,nbtr),d_tr_ls(klon,klev,nbtr))
+       ALLOCATE(qPrls(klon,nbtr),d_tr_trsp(klon,klev,nbtr))
+       ALLOCATE(d_tr_sscav(klon,klev,nbtr),d_tr_sat(klon,klev,nbtr))
+       ALLOCATE(d_tr_uscav(klon,klev,nbtr),qPr(klon,klev,nbtr),qDi(klon,klev,nbtr))
+       ALLOCATE(qPa(klon,klev,nbtr),qMel(klon,klev,nbtr))
+       ALLOCATE(qTrdi(klon,klev,nbtr),dtrcvMA(klon,klev,nbtr))
+       ALLOCATE(d_tr_th(klon,klev,nbtr))
+       ALLOCATE(d_tr_lessi_impa(klon,klev,nbtr),d_tr_lessi_nucl(klon,klev,nbtr))
+
+  END SUBROUTINE phytrac_init
+
   SUBROUTINE phytrac(                                 &
        nstep,     julien,   gmtime,   debutphy,       &
@@ -332,17 +351,4 @@
     !                    -- INITIALIZATION --
     !######################################################################
-    IF (debutphy) THEN
-       ALLOCATE(d_tr_cl(klon,klev,nbtr),d_tr_dry(klon,nbtr))
-       ALLOCATE(flux_tr_dry(klon,nbtr),d_tr_dec(klon,klev,nbtr),d_tr_cv(klon,klev,nbtr))
-       ALLOCATE(d_tr_insc(klon,klev,nbtr),d_tr_bcscav(klon,klev,nbtr))
-       ALLOCATE(d_tr_evapls(klon,klev,nbtr),d_tr_ls(klon,klev,nbtr))
-       ALLOCATE(qPrls(klon,nbtr),d_tr_trsp(klon,klev,nbtr))
-       ALLOCATE(d_tr_sscav(klon,klev,nbtr),d_tr_sat(klon,klev,nbtr))
-       ALLOCATE(d_tr_uscav(klon,klev,nbtr),qPr(klon,klev,nbtr),qDi(klon,klev,nbtr))
-       ALLOCATE(qPa(klon,klev,nbtr),qMel(klon,klev,nbtr))
-       ALLOCATE(qTrdi(klon,klev,nbtr),dtrcvMA(klon,klev,nbtr))
-       ALLOCATE(d_tr_th(klon,klev,nbtr))
-       ALLOCATE(d_tr_lessi_impa(klon,klev,nbtr),d_tr_lessi_nucl(klon,klev,nbtr))
-    ENDIF
 
     DO k=1,klev
@@ -405,9 +411,9 @@
        !Config Key  = convscav
        !Config Desc = Convective scavenging switch: 0=off, 1=on.
-       !Config Def  = .false.
+       !Config Def  = .FALSE.
        !Config Help = 
        !
 !$OMP MASTER
-       convscav_omp=.false.
+       convscav_omp=.FALSE.
        call getin('convscav', convscav_omp)
        iflag_vdf_trac_omp=1
@@ -479,4 +485,10 @@
        CASE('co2i')
           source(:,:)=0.
+          lessivage  = .FALSE.
+          aerosol(:) = .FALSE.
+          pbl_flg(:) = 1
+          iflag_the_trac= 1
+          iflag_vdf_trac= 1
+          iflag_con_trac= 1
 #ifdef CPP_StratAer
        CASE('coag')
@@ -506,23 +518,23 @@
              CASE('lmdz')
                 IF (convscav.and.aerosol(it)) THEN
-                   flag_cvltr(it)=.true.
+                   flag_cvltr(it)=.TRUE.
                    ccntrAA(it) =ccntrAA_in    !--a modifier par JYG a lire depuis fichier 
                    ccntrENV(it)=ccntrENV_in
                    coefcoli(it)=coefcoli_in
                 ELSE 
-                   flag_cvltr(it)=.false.
+                   flag_cvltr(it)=.FALSE.
                 ENDIF
 
              CASE('repr')
-                 flag_cvltr(it)=.false.
+                 flag_cvltr(it)=.FALSE.
 
              CASE('inca')
 !                IF ((it.EQ.id_Rn222) .OR. ((it.GE.id_SO2) .AND. (it.LE.id_NH3)) ) THEN 
 !                   !--gas-phase species
-!                   flag_cvltr(it)=.false.
+!                   flag_cvltr(it)=.FALSE.
 !
 !                ELSEIF ( (it.GE.id_CIDUSTM) .AND. (it.LE.id_AIN) ) THEN
 !                   !--insoluble aerosol species
-!                   flag_cvltr(it)=.true.
+!                   flag_cvltr(it)=.TRUE.
 !                   ccntrAA(it)=0.7
 !                   ccntrENV(it)=0.7
@@ -530,5 +542,5 @@
 !                ELSEIF ( (it.EQ.id_Pb210) .OR. ((it.GE.id_CSSSM) .AND. (it.LE.id_SSN))) THEN
 !                   !--soluble aerosol species
-!                   flag_cvltr(it)=.true.
+!                   flag_cvltr(it)=.TRUE.
 !                   ccntrAA(it)=0.9
 !                   ccntrENV(it)=0.9 
@@ -540,19 +552,19 @@
                 !--test OB 
                 !--for now we do not scavenge in cvltr
-                flag_cvltr(it)=.false.
+                flag_cvltr(it)=.FALSE.
 
              CASE('co2i')
                 !--co2 tracers are not scavenged
-                flag_cvltr(it)=.false.
+                flag_cvltr(it)=.FALSE.
 
 #ifdef CPP_StratAer
              CASE('coag')
                 IF (convscav.and.aerosol(it)) THEN
-                   flag_cvltr(it)=.true.
+                   flag_cvltr(it)=.TRUE.
                    ccntrAA(it) =ccntrAA_in    
                    ccntrENV(it)=ccntrENV_in
                    coefcoli(it)=coefcoli_in
                 ELSE
-                   flag_cvltr(it)=.false.
+                   flag_cvltr(it)=.FALSE.
                 ENDIF
 #endif
@@ -562,5 +574,5 @@
           !
        ELSE ! iflag_con .ne. 3 
-          flag_cvltr(:) = .false. 
+          flag_cvltr(:) = .FALSE. 
        ENDIF
        !
@@ -590,8 +602,8 @@
        IF (lessivage .AND. type_trac .EQ. 'inca') THEN
           CALL abort_physic('phytrac', 'lessivage=T config_inca=inca impossible',1)
-          STOP
+!          STOP
        ENDIF
        !
-    END IF ! of IF (debutphy)
+    ENDIF ! of IF (debutphy)
     !############################################ END INITIALIZATION #######
 
@@ -637,6 +649,7 @@
        !   -- CO2 interactif --
        !   -- source is updated with FF and BB emissions 
-       !   -- OB => PC need to add net flux from ocean and orchidee 
+       !   -- and net fluxes from ocean and orchidee 
        !   -- sign convention : positive into the atmosphere
+
        CALL tracco2i(pdtphys, debutphy, &
             xlat, xlon, pphis, pphi, &
@@ -754,5 +767,5 @@
 #endif
 
-    END IF ! convection
+    ENDIF ! convection
 
     !======================================================================
@@ -792,5 +805,5 @@
        END DO ! it
 
-    END IF ! Thermiques
+    ENDIF ! Thermiques
 
     !======================================================================
@@ -878,5 +891,5 @@
        CALL abort_physic('iflag_vdf_trac', 'cas non prevu',1)
        !
-    END IF ! couche limite
+    ENDIF ! couche limite
 
     !======================================================================
@@ -968,6 +981,6 @@
                       zdz(i,k)=(paprs(i,k)-paprs(i,k+1))/zrho(i,k)/RG
                       !
-                   END DO
-                END DO
+                   ENDDO
+                ENDDO
 
                 DO k=klev-1, 1, -1
@@ -1014,8 +1027,8 @@
                       !                                (1.-1./(frac_impa(i,k)*frac_nucl(i,k)))
                       !--------------
-                   END DO
-                END DO
-             END IF
-          END DO
+                   ENDDO
+                ENDDO
+             ENDIF
+          ENDDO
           ! *********   end modified old version
 
@@ -1053,13 +1066,13 @@
                       ! ----------------------------------------------------------------------
                       tr_seri(i,k,it)=tr_seri(i,k,it)*frac_impa(i,k)*frac_nucl(i,k)
-                   END DO
-                END DO
-             END IF
-          END DO
+                   ENDDO
+                ENDDO
+             ENDIF
+          ENDDO
 
           ! *********   end old version
        ENDIF  !  iflag_lscav . EQ. 1, 2, 3 or 4
        !
-    END IF !  lessivage
+    ENDIF !  lessivage
 
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/radlwsw_m.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/radlwsw_m.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/radlwsw_m.F90	(revision 3605)
@@ -16,5 +16,5 @@
    t,q,wo,&
    cldfra, cldemi, cldtaupd,&
-   ok_ade, ok_aie, flag_aerosol,&
+   ok_ade, ok_aie, ok_volcan, flag_aerosol,&
    flag_aerosol_strat, flag_aer_feedback, &
    tau_aero, piz_aero, cg_aero,&
@@ -25,4 +25,5 @@
    ref_liq, ref_ice, ref_liq_pi, ref_ice_pi, &
    heat,heat0,cool,cool0,albpla,&
+   heat_volc, cool_volc,&
    topsw,toplw,solsw,sollw,&
    sollwdown,&
@@ -100,4 +101,5 @@
   ! ok_ade---input-L- apply the Aerosol Direct Effect or not?
   ! ok_aie---input-L- apply the Aerosol Indirect Effect or not?
+  ! ok_volcan-input-L- activate volcanic diags (SW heat & LW cool rate, SW & LW flux)
   ! flag_aerosol-input-I- aerosol flag from 0 to 6
   ! flag_aerosol_strat-input-I- use stratospheric aerosols flag (0, 1, 2)
@@ -120,4 +122,7 @@
   ! solswai---output-R- ray. solaire net absorbe a la surface (aerosol ind)
   ! topswai---output-R- ray. solaire absorbe au sommet de l'atm. (aerosol ind)
+  !
+  ! heat_volc-----output-R- echauffement atmospherique  du au forcage volcanique (visible) (K/s)
+  ! cool_volc-----output-R- refroidissement dans l'IR du au forcage volcanique (K/s)
   !
   ! ATTENTION: swai and swad have to be interpreted in the following manner:
@@ -193,4 +198,5 @@
 
   LOGICAL, INTENT(in)  :: ok_ade, ok_aie                                 ! switches whether to use aerosol direct (indirect) effects or not
+  LOGICAL, INTENT(in)  :: ok_volcan                                      ! produce volcanic diags (SW/LW heat flux and rate)
   LOGICAL              :: lldebug
   INTEGER, INTENT(in)  :: flag_aerosol                                   ! takes value 0 (no aerosol) or 1 to 6 (aerosols)
@@ -228,4 +234,5 @@
   REAL,    INTENT(out) :: heat(KLON,KLEV), cool(KLON,KLEV)
   REAL,    INTENT(out) :: heat0(KLON,KLEV), cool0(KLON,KLEV)
+  REAL,    INTENT(out) :: heat_volc(KLON,KLEV), cool_volc(KLON,KLEV) !NL
   REAL,    INTENT(out) :: topsw(KLON), toplw(KLON)
   REAL,    INTENT(out) :: solsw(KLON), sollw(KLON), albpla(KLON)
@@ -294,4 +301,5 @@
   REAL(KIND=8) zheat(kdlon,kflev), zcool(kdlon,kflev)
   REAL(KIND=8) zheat0(kdlon,kflev), zcool0(kdlon,kflev)
+  REAL(KIND=8) zheat_volc(kdlon,kflev), zcool_volc(kdlon,kflev) !NL
   REAL(KIND=8) ztopsw(kdlon), ztoplw(kdlon)
   REAL(KIND=8) zsolsw(kdlon), zsollw(kdlon), zalbpla(kdlon)
@@ -308,4 +316,7 @@
   REAL(KIND=8) ztopswad0aero(kdlon), zsolswad0aero(kdlon)   ! Aerosol direct forcing at TOAand surface
   REAL(KIND=8) ztopswaiaero(kdlon), zsolswaiaero(kdlon)     ! dito, indirect
+!--NL
+  REAL(KIND=8) zswadaero(kdlon,kflev+1)                       ! SW Aerosol direct forcing
+  REAL(KIND=8) zlwadaero(kdlon,kflev+1)                       ! LW Aerosol direct forcing
 !-LW by CK
   REAL(KIND=8) ztoplwadaero(kdlon), zsollwadaero(kdlon)     ! LW Aerosol direct forcing at TOAand surface
@@ -398,5 +409,20 @@
   cgaero(:,:,:,:)=0.
   lldebug=.FALSE.
-  
+
+  ztopsw_aero(:,:)  = 0. !ym missing init : warning : not initialized in SW_AEROAR4
+  ztopsw0_aero(:,:) = 0. !ym missing init : warning : not initialized in SW_AEROAR4
+  zsolsw_aero(:,:)  = 0. !ym missing init : warning : not initialized in SW_AEROAR4
+  zsolsw0_aero(:,:) = 0. !ym missing init : warning : not initialized in SW_AEROAR4
+
+
+   ZTOPSWADAERO(:)  = 0. !ym missing init
+   ZSOLSWADAERO(:)  = 0. !ym missing init
+   ZTOPSWAD0AERO(:) = 0. !ym missing init
+   ZSOLSWAD0AERO(:) = 0. !ym missing init
+   ZTOPSWAIAERO(:)  = 0. !ym missing init 
+   ZSOLSWAIAERO(:)  = 0. !ym missing init  
+   ZTOPSWCF_AERO(:,:)= 0.!ym missing init  
+   ZSOLSWCF_AERO(:,:) =0. !ym missing init  
+
   !
   !-------------------------------------------
@@ -415,4 +441,6 @@
       heat(i,k)=0.
       cool(i,k)=0.
+      heat_volc(i,k)=0. !NL
+      cool_volc(i,k)=0. !NL
       heat0(i,k)=0.
       cool0(i,k)=0.
@@ -558,8 +586,9 @@
       ENDDO
       DO k = 1, kflev
-      DO i = 1, kdlon
-      zcool(i,k)=0.
-      zcool0(i,k)=0.
-      ENDDO
+         DO i = 1, kdlon
+            zcool(i,k)=0.
+            zcool_volc(i,k)=0. !NL
+            zcool0(i,k)=0.
+         ENDDO
       ENDDO
       DO i = 1, kdlon
@@ -584,27 +613,29 @@
 !----- Mise a zero des tableaux output du rayonnement SW-AR4 
       DO k = 1, kflev+1
-      DO i = 1, kdlon
-      ZFSUP(i,k)=0.
-      ZFSDN(i,k)=0.
-      ZFSUP0(i,k)=0.
-      ZFSDN0(i,k)=0.
-      ZFSUPC0(i,k)=0.
-      ZFSDNC0(i,k)=0.
-      ZFLUPC0(i,k)=0.
-      ZFLDNC0(i,k)=0.
-      ZSWFT0_i(i,k)=0.
-      ZFCUP_i(i,k)=0.
-      ZFCDWN_i(i,k)=0.
-      ZFCCUP_i(i,k)=0.
-      ZFCCDWN_i(i,k)=0.
-      ZFLCCUP_i(i,k)=0.
-      ZFLCCDWN_i(i,k)=0.
-      ENDDO
+         DO i = 1, kdlon
+            ZFSUP(i,k)=0.
+            ZFSDN(i,k)=0.
+            ZFSUP0(i,k)=0.
+            ZFSDN0(i,k)=0.
+            ZFSUPC0(i,k)=0.
+            ZFSDNC0(i,k)=0.
+            ZFLUPC0(i,k)=0.
+            ZFLDNC0(i,k)=0.
+            ZSWFT0_i(i,k)=0.
+            ZFCUP_i(i,k)=0.
+            ZFCDWN_i(i,k)=0.
+            ZFCCUP_i(i,k)=0.
+            ZFCCDWN_i(i,k)=0.
+            ZFLCCUP_i(i,k)=0.
+            ZFLCCDWN_i(i,k)=0.
+            zswadaero(i,k)=0. !--NL
+         ENDDO
       ENDDO
       DO k = 1, kflev
-      DO i = 1, kdlon
-      zheat(i,k)=0.
-      zheat0(i,k)=0.
-      ENDDO
+         DO i = 1, kdlon
+            zheat(i,k)=0.
+            zheat_volc(i,k)=0.
+            zheat0(i,k)=0.
+         ENDDO
       ENDDO
       DO i = 1, kdlon
@@ -708,6 +739,6 @@
 !
 !--OB
-!--aerosol TOT  - anthropogenic+natural
-!--aerosol NAT  - natural only
+!--aerosol TOT  - anthropogenic+natural - index 2
+!--aerosol NAT  - natural only          - index 1
 !
       DO i = 1, kdlon
@@ -729,6 +760,6 @@
 !
 !--C. Kleinschmitt
-!--aerosol TOT  - anthropogenic+natural
-!--aerosol NAT  - natural only
+!--aerosol TOT  - anthropogenic+natural - index 2
+!--aerosol NAT  - natural only          - index 1
 !
       DO i = 1, kdlon
@@ -854,8 +885,10 @@
          ZTOPSWAIAERO,ZSOLSWAIAERO, &
          ZTOPSWCF_AERO,ZSOLSWCF_AERO, &
+         ZSWADAERO, & !--NL
          ZTOPLWADAERO,ZSOLLWADAERO,&  ! rajoute par C. Kleinscmitt pour LW diagnostics
          ZTOPLWAD0AERO,ZSOLLWAD0AERO,&
          ZTOPLWAIAERO,ZSOLLWAIAERO, &
-         ok_ade, ok_aie, flag_aerosol,flag_aerosol_strat, flag_aer_feedback) ! flags aerosols
+         ZLWADAERO, & !--NL
+         ok_ade, ok_aie, ok_volcan, flag_aerosol,flag_aerosol_strat, flag_aer_feedback) ! flags aerosols
             
 !        print *,'RADLWSW: apres RECMWF'
@@ -936,4 +969,8 @@
          ZFLDNC0(i,k+1)= ZFLCCDWN_i(i,k+1)
          ZFLUPC0(i,k+1)= ZFLCCUP_i(i,k+1)
+         IF(ok_volcan) THEN
+            ZSWADAERO(i,k+1)=ZSWADAERO(i,k+1)*fract(i) !--NL
+         ENDIF
+         
 !   Nouveau calcul car visiblement ZSWFT et ZSWFC sont nuls dans RRTM cy32
 !   en sortie de radlsw.F90 - MPL 7.01.09
@@ -1016,4 +1053,8 @@
            zcool(i,k)=(ZLWFT(i,k)-ZLWFT(i,k+1))*RDAY*RG/RCPD/PDP(i,k)
            zcool0(i,k)=(ZLWFT0_i(i,k)-ZLWFT0_i(i,k+1))*RDAY*RG/RCPD/PDP(i,k)
+           IF(ok_volcan) THEN
+              zheat_volc(i,k)=(ZSWADAERO(i,k+1)-ZSWADAERO(i,k))*RG/RCPD/PDP(i,k) !NL
+              zcool_volc(i,k)=(ZLWADAERO(i,k)-ZLWADAERO(i,k+1))*RG/RCPD/PDP(i,k) !NL
+           ENDIF
 !          print *,'heat cool heat0 cool0 ',zheat(i,k),zcool(i,k),zheat0(i,k),zcool0(i,k)
 !	   ZFLUCUP_i(i,k)=ZFLUC_i(i,1,k)
@@ -1125,4 +1166,8 @@
         heat0(iof+i,k) = zheat0(i,k)/zznormcp
         cool0(iof+i,k) = zcool0(i,k)/zznormcp
+        IF(ok_volcan) THEN !NL
+           heat_volc(iof+i,k) = zheat_volc(i,k)/zznormcp
+           cool_volc(iof+i,k) = zcool_volc(i,k)/zznormcp
+        ENDIF
       ENDDO
     ENDDO
Index: DZ6/branches/Ocean_skin/libf/phylmd/readaerosol.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/readaerosol.F90	(revision 3604)
+++ 	(revision )
@@ -1,603 +1,0 @@
-! $Id$
-!
-MODULE readaerosol_mod
-
-  REAL, SAVE :: not_valid=-333.
-
-CONTAINS
-
-SUBROUTINE readaerosol(name_aero, type, filename, iyr_in, klev_src, pt_ap, pt_b, pt_out, psurf, load)
-
-!****************************************************************************************
-! This routine will read the aersosol from file. 
-!
-! Read a year data with get_aero_fromfile depending on aer_type : 
-! - actuel   : read year 1980
-! - preind   : read natural data
-! - scenario : read one or two years and do eventually linare time interpolation
-!
-! Return pointer, pt_out, to the year read or result from interpolation
-!****************************************************************************************
-  USE dimphy
-  USE print_control_mod, ONLY: lunout
-
-  IMPLICIT NONE
-
-  ! Input arguments
-  CHARACTER(len=7), INTENT(IN) :: name_aero
-  CHARACTER(len=*), INTENT(IN) :: type  ! actuel, annuel, scenario or preind
-  CHARACTER(len=8), INTENT(IN) :: filename
-  INTEGER, INTENT(IN)          :: iyr_in
-
-  ! Output
-  INTEGER, INTENT(OUT)            :: klev_src
-  REAL, POINTER, DIMENSION(:)     :: pt_ap        ! Pointer for describing the vertical levels      
-  REAL, POINTER, DIMENSION(:)     :: pt_b         ! Pointer for describing the vertical levels      
-  REAL, POINTER, DIMENSION(:,:,:) :: pt_out       ! The massvar distributions, DIMENSION(klon, klev_src, 12)
-  REAL, DIMENSION(klon,12), INTENT(OUT) :: psurf  ! Surface pression for 12 months
-  REAL, DIMENSION(klon,12), INTENT(OUT) :: load   ! Aerosol mass load in each column for 12 months
-
-  ! Local variables
-  CHARACTER(len=4)                :: cyear
-  REAL, POINTER, DIMENSION(:,:,:) :: pt_2
-  REAL, DIMENSION(klon,12)        :: psurf2, load2
-  INTEGER                         :: iyr1, iyr2, klev_src2
-  INTEGER                         :: it, k, i
-  LOGICAL, PARAMETER              :: lonlyone=.FALSE.
-
-!****************************************************************************************
-! Read data depending on aer_type
-!
-!****************************************************************************************
-
-  IF (type == 'actuel') THEN
-! Read and return data for year 1980
-!****************************************************************************************
-     cyear='1980'
-     ! get_aero_fromfile returns pt_out allocated and initialized with data for 12 month 
-     ! pt_out has dimensions (klon, klev_src, 12)
-     CALL get_aero_fromfile(name_aero, cyear, filename, klev_src, pt_ap, pt_b, pt_out, psurf, load)
-     
-
-  ELSE IF (type == 'preind') THEN
-! Read and return data from file with suffix .nat
-!****************************************************************************************     
-     cyear='.nat'
-     ! get_aero_fromfile returns pt_out allocated and initialized with data for 12 month 
-     ! pt_out has dimensions (klon, klev_src, 12)
-     CALL get_aero_fromfile(name_aero, cyear, filename, klev_src, pt_ap, pt_b, pt_out, psurf, load)
-     
-  ELSE IF (type == 'annuel') THEN
-! Read and return data from scenario annual files
-!****************************************************************************************     
-     WRITE(cyear,'(I4)') iyr_in
-     WRITE(lunout,*) 'get_aero 3 iyr_in=', iyr_in,'   ',cyear
-     ! get_aero_fromfile returns pt_out allocated and initialized with data for nbr_tsteps month 
-     ! pt_out has dimensions (klon, klev_src, 12)
-     CALL get_aero_fromfile(name_aero, cyear, filename, klev_src, pt_ap, pt_b, pt_out, psurf, load)
-     
-  ELSE IF (type == 'scenario') THEN
-! Read data depending on actual year and interpolate if necessary
-!****************************************************************************************
-     IF (iyr_in .LT. 1850) THEN
-        cyear='.nat'
-        WRITE(lunout,*) 'get_aero 1 iyr_in=', iyr_in,'   ',cyear
-        ! get_aero_fromfile returns pt_out allocated and initialized with data for 12 month 
-        ! pt_out has dimensions (klon, klev_src, 12)
-        CALL get_aero_fromfile(name_aero, cyear, filename, klev_src, pt_ap, pt_b, pt_out, psurf, load)
-        
-     ELSE IF (iyr_in .GE. 2100) THEN
-        cyear='2100'
-        WRITE(lunout,*) 'get_aero 2 iyr_in=', iyr_in,'   ',cyear
-        ! get_aero_fromfile returns pt_out allocated and initialized with data for 12 month 
-        ! pt_out has dimensions (klon, klev_src, 12)
-        CALL get_aero_fromfile(name_aero, cyear, filename, klev_src, pt_ap, pt_b, pt_out, psurf, load)
-        
-     ELSE
-        ! Read data from 2 decades and interpolate to actual year
-        ! a) from actual 10-yr-period
-        IF (iyr_in.LT.1900) THEN
-           iyr1 = 1850
-           iyr2 = 1900
-        ELSE IF (iyr_in.GE.1900.AND.iyr_in.LT.1920) THEN
-           iyr1 = 1900
-           iyr2 = 1920
-        ELSE 
-           iyr1 = INT(iyr_in/10)*10
-           iyr2 = INT(1+iyr_in/10)*10
-        ENDIF
-        
-        WRITE(cyear,'(I4)') iyr1
-        WRITE(lunout,*) 'get_aero 3 iyr_in=', iyr_in,'   ',cyear
-        ! get_aero_fromfile returns pt_out allocated and initialized with data for 12 month 
-        ! pt_out has dimensions (klon, klev_src, 12)
-        CALL get_aero_fromfile(name_aero, cyear, filename, klev_src, pt_ap, pt_b, pt_out, psurf, load)
-        
-        ! If to read two decades:
-        IF (.NOT.lonlyone) THEN 
-           
-           ! b) from the next following one
-           WRITE(cyear,'(I4)') iyr2
-           WRITE(lunout,*) 'get_aero 4 iyr_in=', iyr_in,'   ',cyear
-           
-           NULLIFY(pt_2)
-           ! get_aero_fromfile returns pt_2 allocated and initialized with data for 12 month 
-           ! pt_2 has dimensions (klon, klev_src, 12)
-           CALL get_aero_fromfile(name_aero, cyear, filename, klev_src2, pt_ap, pt_b, pt_2, psurf2, load2)
-           ! Test for same number of vertical levels
-           IF (klev_src /= klev_src2) THEN
-              WRITE(lunout,*) 'Two aerosols files with different number of vertical levels is not allowded'
-              CALL abort_physic('readaersosol','Error in number of vertical levels',1)
-           END IF
-           
-           ! Linare interpolate to the actual year:
-           DO it=1,12
-              DO k=1,klev_src
-                 DO i = 1, klon
-                    pt_out(i,k,it) = &
-                         pt_out(i,k,it) - REAL(iyr_in-iyr1)/REAL(iyr2-iyr1) * &
-                         (pt_out(i,k,it) - pt_2(i,k,it))
-                 END DO
-              END DO
-
-              DO i = 1, klon
-                 psurf(i,it) = &
-                      psurf(i,it) - REAL(iyr_in-iyr1)/REAL(iyr2-iyr1) * &
-                      (psurf(i,it) - psurf2(i,it))
-
-                 load(i,it) = &
-                      load(i,it) - REAL(iyr_in-iyr1)/REAL(iyr2-iyr1) * &
-                      (load(i,it) - load2(i,it))
-              END DO
-           END DO
-
-           ! Deallocate pt_2 no more needed
-           DEALLOCATE(pt_2)
-           
-        END IF ! lonlyone
-     END IF ! iyr_in .LT. 1850
-
-  ELSE
-     WRITE(lunout,*)'This option is not implemented : aer_type = ', type,' name_aero=',name_aero
-     CALL abort_physic('readaerosol','Error : aer_type parameter not accepted',1)
-  END IF ! type
-
-
-END SUBROUTINE readaerosol
-
-
-  SUBROUTINE get_aero_fromfile(varname, cyr, filename, klev_src, pt_ap, pt_b, pt_year, psurf_out, load_out)
-!****************************************************************************************
-! Read 12 month aerosol from file and distribute to local process on physical grid. 
-! Vertical levels, klev_src, may differ from model levels if new file format.
-!
-! For mpi_root and master thread :
-! 1) Open file 
-! 2) Find vertical dimension klev_src
-! 3) Read field month by month
-! 4) Close file  
-! 5) Transform the global field from 2D(nbp_lon,nbp_lat) to 1D(klon_glo)
-!     - Also the levels and the latitudes have to be inversed
-!
-! For all processes and threads :
-! 6) Scatter global field(klon_glo) to local process domain(klon)
-! 7) Test for negative values
-!****************************************************************************************
-
-    USE netcdf
-    USE dimphy
-    USE mod_grid_phy_lmdz, ONLY: nbp_lon, nbp_lat, klon_glo, &
-                                 grid2Dto1D_glo
-    USE mod_phys_lmdz_para
-    USE iophy, ONLY : io_lon, io_lat
-    USE print_control_mod, ONLY: lunout
-
-    IMPLICIT NONE
-      
-! Input argumets
-    CHARACTER(len=7), INTENT(IN)          :: varname
-    CHARACTER(len=4), INTENT(IN)          :: cyr
-    CHARACTER(len=8), INTENT(IN)          :: filename
-
-! Output arguments
-    INTEGER, INTENT(OUT)                  :: klev_src     ! Number of vertical levels in file
-    REAL, POINTER, DIMENSION(:)           :: pt_ap        ! Pointer for describing the vertical levels      
-    REAL, POINTER, DIMENSION(:)           :: pt_b         ! Pointer for describing the vertical levels      
-    REAL, POINTER, DIMENSION(:,:,:)       :: pt_year      ! Pointer-variabale from file, 12 month, grid : klon,klev_src
-    REAL, DIMENSION(klon,12), INTENT(OUT) :: psurf_out    ! Surface pression for 12 months
-    REAL, DIMENSION(klon,12), INTENT(OUT) :: load_out     ! Aerosol mass load in each column
-    INTEGER                               :: nbr_tsteps   ! number of month in file read
-
-! Local variables
-    CHARACTER(len=30)     :: fname
-    CHARACTER(len=30)     :: cvar
-    INTEGER               :: ncid, dimid, varid
-    INTEGER               :: imth, i, j, k, ierr
-    REAL                  :: npole, spole
-    REAL, ALLOCATABLE, DIMENSION(:,:,:)   :: varmth
-    REAL, ALLOCATABLE, DIMENSION(:,:,:,:) :: varyear       ! Global variable read from file, 12 month
-    REAL, ALLOCATABLE, DIMENSION(:,:,:)   :: varyear_glo1D !(klon_glo, klev_src, 12)
-    REAL, ALLOCATABLE, DIMENSION(:)       :: varktmp
-
-    REAL, DIMENSION(nbp_lon,nbp_lat,12)   :: psurf_glo2D   ! Surface pression for 12 months on dynamics global grid
-    REAL, DIMENSION(klon_glo,12)          :: psurf_glo1D   ! -"- on physical global grid
-    REAL, DIMENSION(nbp_lon,nbp_lat,12)   :: load_glo2D    ! Load for 12 months on dynamics global grid
-    REAL, DIMENSION(klon_glo,12)          :: load_glo1D    ! -"- on physical global grid
-    REAL, DIMENSION(nbp_lon,nbp_lat)      :: vartmp
-    REAL, DIMENSION(nbp_lon)              :: lon_src              ! longitudes in file
-    REAL, DIMENSION(nbp_lat)              :: lat_src, lat_src_inv ! latitudes in file
-    LOGICAL                               :: new_file             ! true if new file format detected
-    LOGICAL                               :: invert_lat           ! true if the field has to be inverted for latitudes
-
-
-    ! Deallocate pointers
-    IF (ASSOCIATED(pt_ap)) DEALLOCATE(pt_ap)
-    IF (ASSOCIATED(pt_b))  DEALLOCATE(pt_b)
-
-    IF (is_mpi_root .AND. is_omp_root) THEN
-
-! 1) Open file 
-!****************************************************************************************
-! Add suffix to filename
-       fname = trim(filename)//cyr//'.nc'
-  
-       WRITE(lunout,*) 'reading variable ',TRIM(varname),' in file ', TRIM(fname)
-       CALL check_err( nf90_open(TRIM(fname), NF90_NOWRITE, ncid), "pb open "//trim(fname) )
-
-! Test for equal longitudes and latitudes in file and model
-!****************************************************************************************
-       ! Read and test longitudes
-       CALL check_err( nf90_inq_varid(ncid, 'lon', varid),"pb inq lon" )
-       CALL check_err( nf90_get_var(ncid, varid, lon_src(:)),"pb get lon" )
-       
-       IF (maxval(ABS(lon_src - io_lon)) > 0.001) THEN
-          WRITE(lunout,*) 'Problem in longitudes read from file : ',TRIM(fname)
-          WRITE(lunout,*) 'longitudes in file ', TRIM(fname),' : ', lon_src
-          WRITE(lunout,*) 'longitudes in model :', io_lon
-          
-          CALL abort_physic('get_aero_fromfile', 'longitudes are not the same in file and model',1)
-       END IF
-
-       ! Read and test latitudes
-       CALL check_err( nf90_inq_varid(ncid, 'lat', varid),"pb inq lat" )
-       CALL check_err( nf90_get_var(ncid, varid, lat_src(:)),"pb get lat" )
-
-       ! Invert source latitudes
-       DO j = 1, nbp_lat
-          lat_src_inv(j) = lat_src(nbp_lat +1 -j)
-       END DO
-
-       IF (maxval(ABS(lat_src - io_lat)) < 0.001) THEN
-          ! Latitudes are the same
-          invert_lat=.FALSE.
-       ELSE IF (maxval(ABS(lat_src_inv - io_lat)) < 0.001) THEN
-          ! Inverted source latitudes correspond to model latitudes
-          WRITE(lunout,*) 'latitudes will be inverted for file : ',TRIM(fname)
-          invert_lat=.TRUE.
-       ELSE
-          WRITE(lunout,*) 'Problem in latitudes read from file : ',TRIM(fname)
-          WRITE(lunout,*) 'latitudes in file ', TRIM(fname),' : ', lat_src      
-          WRITE(lunout,*) 'latitudes in model :', io_lat
-          CALL abort_physic('get_aero_fromfile', 'latitudes do not correspond between file and model',1)
-       END IF
-
-
-! 2) Check if old or new file is avalabale.
-!    New type of file should contain the dimension 'lev'
-!    Old type of file should contain the dimension 'PRESNIVS'
-!****************************************************************************************
-       ierr = nf90_inq_dimid(ncid, 'lev', dimid) 
-       IF (ierr /= NF90_NOERR) THEN
-          ! Coordinate axe lev not found. Check for presnivs.
-          ierr = nf90_inq_dimid(ncid, 'presnivs', dimid) 
-          IF (ierr /= NF90_NOERR) THEN
-             ierr = nf90_inq_dimid(ncid, 'PRESNIVS', dimid)
-             IF (ierr /= NF90_NOERR) THEN
-                ! Dimension PRESNIVS not found either
-                CALL abort_physic('get_aero_fromfile', 'dimension lev,PRESNIVS or presnivs not in file',1)
-             ELSE 
-                ! Old file found
-                new_file=.FALSE.
-                WRITE(lunout,*) 'Vertical interpolation for ',TRIM(varname),' will not be done'
-             END IF
-          ELSE
-             ! New file found
-             new_file=.TRUE.
-             WRITE(lunout,*) 'Vertical interpolation for ',TRIM(varname),' will be done'
-          ENDIF
-       ELSE
-          ! New file found
-          new_file=.TRUE.
-          WRITE(lunout,*) 'Vertical interpolation for ',TRIM(varname),' will be done'
-       END IF
-       
-! 2) Find vertical dimension klev_src
-!****************************************************************************************
-       CALL check_err( nf90_inquire_dimension(ncid, dimid, len = klev_src),"pb inq dim for PRESNIVS or lev" )
-       
-     ! Allocate variables depending on the number of vertical levels
-       ALLOCATE(varmth(nbp_lon,nbp_lat, klev_src), varyear(nbp_lon,nbp_lat, klev_src, 12), stat=ierr)
-       IF (ierr /= 0) CALL abort_physic('get_aero_fromfile', 'pb in allocation 1',1)
-
-       ALLOCATE(pt_ap(klev_src), pt_b(klev_src), varktmp(klev_src), stat=ierr)
-       IF (ierr /= 0) CALL abort_physic('get_aero_fromfile', 'pb in allocation 2',1)
-
-! 3) Read all variables from file
-!    There is 2 options for the file structure :
-!    new_file=TRUE  : read varyear, ps, pt_ap and pt_b
-!    new_file=FALSE : read varyear month by month
-!****************************************************************************************
-
-       IF (new_file) THEN
-! ++) Check number of month in file opened
-!**************************************************************************************************
-       ierr = nf90_inq_dimid(ncid, 'TIME',dimid)
-       if (ierr /= NF90_NOERR) THEN
-          ierr = nf90_inq_dimid(ncid, 'time_counter', dimid)
-       ENDIF
-       CALL check_err( nf90_inquire_dimension(ncid, dimid, len = nbr_tsteps),"pb inq dim TIME or time_counter" )
-!       IF (nbr_tsteps /= 12 .AND. nbr_tsteps /= 14) THEN
-       IF (nbr_tsteps /= 12 ) THEN
-    CALL abort_physic('get_aero_fromfile', 'not the right number of months in aerosol file read (should be 12 for the moment)' &
-                     ,1)
-       ENDIF
-
-! ++) Read the aerosol concentration month by month and concatenate to total variable varyear
-!****************************************************************************************
-          ! Get variable id
-          !CALL check_err( nf90_inq_varid(ncid, TRIM(varname), varid),"pb inq var "//TRIM(varname) )
-          print *,'readaerosol ', TRIM(varname)
-          IF ( nf90_inq_varid(ncid, TRIM(varname), varid) /= NF90_NOERR ) THEN 
-            ! Variable is not there
-            WRITE(lunout,*) 'Attention '//TRIM(varname)//' is not in aerosol input file'
-            varyear(:,:,:,:)=0.0
-          ELSE 
-            ! Get the variable
-            CALL check_err( nf90_get_var(ncid, varid, varyear(:,:,:,:)),"pb get var "//TRIM(varname) )
-          ENDIF
-          
-! ++) Read surface pression, 12 month in one variable
-!****************************************************************************************
-          ! Get variable id
-          CALL check_err( nf90_inq_varid(ncid, "ps", varid),"pb inq var ps" )
-          ! Get the variable
-          CALL check_err( nf90_get_var(ncid, varid, psurf_glo2D),"pb get var ps" )
-          
-! ++) Read mass load, 12 month in one variable
-!****************************************************************************************
-          ! Get variable id
-          !CALL check_err( nf90_inq_varid(ncid, "load_"//TRIM(varname), varid) ,"pb inq var load_"//TRIM(varname))
-          IF ( nf90_inq_varid(ncid, "load_"//TRIM(varname), varid) /= NF90_NOERR ) THEN 
-            WRITE(lunout,*) 'Attention load_'//TRIM(varname)//' is not in aerosol input file'
-            load_glo2D(:,:,:)=0.0
-          ELSE
-            ! Get the variable
-            CALL check_err( nf90_get_var(ncid, varid, load_glo2D),"pb get var load_"//TRIM(varname) )
-          ENDIF
-          
-! ++) Read ap
-!****************************************************************************************
-          ! Get variable id
-          CALL check_err( nf90_inq_varid(ncid, "ap", varid),"pb inq var ap" )
-          ! Get the variable
-          CALL check_err( nf90_get_var(ncid, varid, pt_ap),"pb get var ap" )
-
-! ++) Read b
-!****************************************************************************************
-          ! Get variable id
-          CALL check_err( nf90_inq_varid(ncid, "b", varid),"pb inq var b" )
-          ! Get the variable
-          CALL check_err( nf90_get_var(ncid, varid, pt_b),"pb get var b" )
-
-          
-
-       ELSE  ! old file
-
-! ++) Read the aerosol concentration month by month and concatenate to total variable varyear
-!****************************************************************************************
-          DO imth=1, 12
-             IF (imth.EQ.1) THEN
-                cvar=TRIM(varname)//'JAN'
-             ELSE IF (imth.EQ.2) THEN
-                cvar=TRIM(varname)//'FEB'
-             ELSE IF (imth.EQ.3) THEN
-                cvar=TRIM(varname)//'MAR'
-             ELSE IF (imth.EQ.4) THEN
-                cvar=TRIM(varname)//'APR'
-             ELSE IF (imth.EQ.5) THEN
-                cvar=TRIM(varname)//'MAY'
-             ELSE IF (imth.EQ.6) THEN
-                cvar=TRIM(varname)//'JUN'
-             ELSE IF (imth.EQ.7) THEN
-                cvar=TRIM(varname)//'JUL'
-             ELSE IF (imth.EQ.8) THEN
-                cvar=TRIM(varname)//'AUG'
-             ELSE IF (imth.EQ.9) THEN
-                cvar=TRIM(varname)//'SEP'
-             ELSE IF (imth.EQ.10) THEN
-                cvar=TRIM(varname)//'OCT'
-             ELSE IF (imth.EQ.11) THEN
-                cvar=TRIM(varname)//'NOV'
-             ELSE IF (imth.EQ.12) THEN
-                cvar=TRIM(varname)//'DEC'
-             END IF
-             
-             ! Get variable id
-             CALL check_err( nf90_inq_varid(ncid, TRIM(cvar), varid),"pb inq var "//TRIM(cvar) )
-             
-             ! Get the variable
-             CALL check_err( nf90_get_var(ncid, varid, varmth),"pb get var "//TRIM(cvar) )
-             
-             ! Store in variable for the whole year
-             varyear(:,:,:,imth)=varmth(:,:,:)
-             
-          END DO
-          
-          ! Putting dummy 
-          psurf_glo2D(:,:,:) = not_valid
-          load_glo2D(:,:,:)  = not_valid
-          pt_ap(:) = not_valid
-          pt_b(:)  = not_valid
-
-       END IF
-
-! 4) Close file  
-!****************************************************************************************
-       CALL check_err( nf90_close(ncid),"pb in close" )
-     
-
-! 5) Transform the global field from 2D(nbp_lon,nbp_lat) to 1D(klon_glo)
-!****************************************************************************************
-! Test if vertical levels have to be inversed
-
-       IF ((pt_b(1) < pt_b(klev_src)) .OR. .NOT. new_file) THEN
-!          WRITE(lunout,*) 'Vertical axis in file ',TRIM(fname), ' needs to be inverted'
-!          WRITE(lunout,*) 'before pt_ap = ', pt_ap
-!          WRITE(lunout,*) 'before pt_b = ', pt_b
-          
-          ! Inverse vertical levels for varyear 
-          DO imth=1, 12
-             varmth(:,:,:) = varyear(:,:,:,imth) ! use varmth temporarly
-             DO k=1, klev_src
-                DO j=1, nbp_lat
-                   DO i=1, nbp_lon
-                      varyear(i,j,k,imth) = varmth(i,j,klev_src+1-k)
-                   END DO
-                END DO
-             END DO
-          END DO
-           
-          ! Inverte vertical axes for pt_ap and pt_b
-          varktmp(:) = pt_ap(:)
-          DO k=1, klev_src
-             pt_ap(k) = varktmp(klev_src+1-k)
-          END DO
-
-          varktmp(:) = pt_b(:)
-          DO k=1, klev_src
-             pt_b(k) = varktmp(klev_src+1-k)
-          END DO
-          WRITE(lunout,*) 'after pt_ap = ', pt_ap
-          WRITE(lunout,*) 'after pt_b = ', pt_b
-
-       ELSE 
-          WRITE(lunout,*) 'Vertical axis in file ',TRIM(fname), ' is ok, no vertical inversion is done'
-          WRITE(lunout,*) 'pt_ap = ', pt_ap
-          WRITE(lunout,*) 'pt_b = ', pt_b
-       END IF
-
-!     - Invert latitudes if necessary
-       DO imth=1, 12
-          IF (invert_lat) THEN
-
-             ! Invert latitudes for the variable
-             varmth(:,:,:) = varyear(:,:,:,imth) ! use varmth temporarly
-             DO k=1,klev_src
-                DO j=1,nbp_lat
-                   DO i=1,nbp_lon
-                      varyear(i,j,k,imth) = varmth(i,nbp_lat+1-j,k)
-                   END DO
-                END DO
-             END DO
-             
-             ! Invert latitudes for surface pressure
-             vartmp(:,:) = psurf_glo2D(:,:,imth)
-             DO j=1,nbp_lat
-                DO i=1,nbp_lon
-                   psurf_glo2D(i,j,imth)= vartmp(i,nbp_lat+1-j)
-                END DO
-             END DO
-             
-             ! Invert latitudes for the load
-             vartmp(:,:) = load_glo2D(:,:,imth)
-             DO j=1,nbp_lat
-                DO i=1,nbp_lon
-                   load_glo2D(i,j,imth)= vartmp(i,nbp_lat+1-j)
-                END DO
-             END DO
-          END IF ! invert_lat
-             
-          ! Do zonal mead at poles and distribut at whole first and last latitude
-          DO k=1, klev_src
-             npole=0.  ! North pole, j=1
-             spole=0.  ! South pole, j=nbp_lat        
-             DO i=1,nbp_lon
-                npole = npole + varyear(i,1,k,imth)
-                spole = spole + varyear(i,nbp_lat,k,imth)
-             END DO
-             npole = npole/REAL(nbp_lon)
-             spole = spole/REAL(nbp_lon)
-             varyear(:,1,    k,imth) = npole
-             varyear(:,nbp_lat,k,imth) = spole
-          END DO
-       END DO ! imth
-       
-       ALLOCATE(varyear_glo1D(klon_glo, klev_src, 12), stat=ierr)
-       IF (ierr /= 0) CALL abort_physic('get_aero_fromfile', 'pb in allocation 3',1)
-       
-       ! Transform from 2D to 1D field
-       CALL grid2Dto1D_glo(varyear,varyear_glo1D)
-       CALL grid2Dto1D_glo(psurf_glo2D,psurf_glo1D)
-       CALL grid2Dto1D_glo(load_glo2D,load_glo1D)
-
-    ELSE
-      ALLOCATE(varyear_glo1D(0,0,0))        
-    END IF ! is_mpi_root .AND. is_omp_root
-
-!$OMP BARRIER
-  
-! 6) Distribute to all processes
-!    Scatter global field(klon_glo) to local process domain(klon)
-!    and distribute klev_src to all processes
-!****************************************************************************************
-
-    ! Distribute klev_src
-    CALL bcast(klev_src)
-
-    ! Allocate and distribute pt_ap and pt_b
-    IF (.NOT. ASSOCIATED(pt_ap)) THEN  ! if pt_ap is allocated also pt_b is allocated
-       ALLOCATE(pt_ap(klev_src), pt_b(klev_src), stat=ierr)
-       IF (ierr /= 0) CALL abort_physic('get_aero_fromfile', 'pb in allocation 4',1)
-    END IF
-    CALL bcast(pt_ap)
-    CALL bcast(pt_b)
-
-    ! Allocate space for output pointer variable at local process
-    IF (ASSOCIATED(pt_year)) DEALLOCATE(pt_year)
-    ALLOCATE(pt_year(klon, klev_src, 12), stat=ierr)
-    IF (ierr /= 0) CALL abort_physic('get_aero_fromfile', 'pb in allocation 5',1)
-
-    ! Scatter global field to local domain at local process
-    CALL scatter(varyear_glo1D, pt_year)
-    CALL scatter(psurf_glo1D, psurf_out)
-    CALL scatter(load_glo1D,  load_out)
-
-! 7) Test for negative values
-!****************************************************************************************
-    IF (MINVAL(pt_year) < 0.) THEN
-       WRITE(lunout,*) 'Warning! Negative values read from file :', fname
-    END IF
-
-  END SUBROUTINE get_aero_fromfile
-
-
-  SUBROUTINE check_err(status,text)
-    USE netcdf
-    USE print_control_mod, ONLY: lunout
-    IMPLICIT NONE
-
-    INTEGER, INTENT (IN) :: status
-    CHARACTER(len=*), INTENT (IN), OPTIONAL :: text
-
-    IF (status /= NF90_NOERR) THEN
-       WRITE(lunout,*) 'Error in get_aero_fromfile, netcdf error code = ',status
-       IF (PRESENT(text)) THEN
-          WRITE(lunout,*) 'Error in get_aero_fromfile : ',text
-       END IF
-       CALL abort_physic('get_aero_fromfile',trim(nf90_strerror(status)),1)
-    END IF
-
-  END SUBROUTINE check_err
-
-
-END MODULE readaerosol_mod
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/readaerosol_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/readaerosol_mod.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/readaerosol_mod.F90	(revision 3605)
@@ -0,0 +1,739 @@
+! $Id: readaerosol.F90 3436 2019-01-22 16:26:21Z emillour $
+!
+MODULE readaerosol_mod
+
+  REAL, SAVE :: not_valid=-333.
+  
+  INTEGER, SAVE :: nbp_lon_src
+!$OMP THREADPRIVATE(nbp_lon_src)  
+  INTEGER, SAVE :: nbp_lat_src
+!$OMP THREADPRIVATE(nbp_lat_src)  
+  REAL, ALLOCATABLE, SAVE    :: psurf_interp(:,:)
+!$OMP THREADPRIVATE(psurf_interp)  
+
+CONTAINS
+
+SUBROUTINE readaerosol(name_aero, type, filename, iyr_in, klev_src, pt_ap, pt_b, pt_out, psurf, load)
+
+!****************************************************************************************
+! This routine will read the aersosol from file. 
+!
+! Read a year data with get_aero_fromfile depending on aer_type : 
+! - actuel   : read year 1980
+! - preind   : read natural data
+! - scenario : read one or two years and do eventually linare time interpolation
+!
+! Return pointer, pt_out, to the year read or result from interpolation
+!****************************************************************************************
+  USE dimphy
+  USE print_control_mod, ONLY: lunout
+
+  IMPLICIT NONE
+
+  ! Input arguments
+  CHARACTER(len=7), INTENT(IN) :: name_aero
+  CHARACTER(len=*), INTENT(IN) :: type  ! actuel, annuel, scenario or preind
+  CHARACTER(len=8), INTENT(IN) :: filename
+  INTEGER, INTENT(IN)          :: iyr_in
+
+  ! Output
+  INTEGER, INTENT(OUT)            :: klev_src
+  REAL, POINTER, DIMENSION(:)     :: pt_ap        ! Pointer for describing the vertical levels      
+  REAL, POINTER, DIMENSION(:)     :: pt_b         ! Pointer for describing the vertical levels      
+  REAL, POINTER, DIMENSION(:,:,:) :: pt_out       ! The massvar distributions, DIMENSION(klon, klev_src, 12)
+  REAL, DIMENSION(klon,12), INTENT(OUT) :: psurf  ! Surface pression for 12 months
+  REAL, DIMENSION(klon,12), INTENT(OUT) :: load   ! Aerosol mass load in each column for 12 months
+
+  ! Local variables
+  CHARACTER(len=4)                :: cyear
+  REAL, POINTER, DIMENSION(:,:,:) :: pt_2
+  REAL, DIMENSION(klon,12)        :: psurf2, load2
+  INTEGER                         :: iyr1, iyr2, klev_src2
+  INTEGER                         :: it, k, i
+  LOGICAL, PARAMETER              :: lonlyone=.FALSE.
+
+!****************************************************************************************
+! Read data depending on aer_type
+!
+!****************************************************************************************
+
+  IF (type == 'actuel') THEN
+! Read and return data for year 1980
+!****************************************************************************************
+     cyear='1980'
+     ! get_aero_fromfile returns pt_out allocated and initialized with data for 12 month 
+     ! pt_out has dimensions (klon, klev_src, 12)
+     CALL get_aero_fromfile(name_aero, cyear, filename, klev_src, pt_ap, pt_b, pt_out, psurf, load)
+     
+
+  ELSE IF (type == 'preind') THEN
+! Read and return data from file with suffix .nat
+!****************************************************************************************     
+     cyear='.nat'
+     ! get_aero_fromfile returns pt_out allocated and initialized with data for 12 month 
+     ! pt_out has dimensions (klon, klev_src, 12)
+     CALL get_aero_fromfile(name_aero, cyear, filename, klev_src, pt_ap, pt_b, pt_out, psurf, load)
+     
+  ELSE IF (type == 'annuel') THEN
+! Read and return data from scenario annual files
+!****************************************************************************************     
+     WRITE(cyear,'(I4)') iyr_in
+     WRITE(lunout,*) 'get_aero 3 iyr_in=', iyr_in,'   ',cyear
+     ! get_aero_fromfile returns pt_out allocated and initialized with data for nbr_tsteps month 
+     ! pt_out has dimensions (klon, klev_src, 12)
+     CALL get_aero_fromfile(name_aero, cyear, filename, klev_src, pt_ap, pt_b, pt_out, psurf, load)
+     
+  ELSE IF (type == 'scenario') THEN
+! Read data depending on actual year and interpolate if necessary
+!****************************************************************************************
+     IF (iyr_in .LT. 1850) THEN
+        cyear='.nat'
+        WRITE(lunout,*) 'get_aero 1 iyr_in=', iyr_in,'   ',cyear
+        ! get_aero_fromfile returns pt_out allocated and initialized with data for 12 month 
+        ! pt_out has dimensions (klon, klev_src, 12)
+        CALL get_aero_fromfile(name_aero, cyear, filename, klev_src, pt_ap, pt_b, pt_out, psurf, load)
+        
+     ELSE IF (iyr_in .GE. 2100) THEN
+        cyear='2100'
+        WRITE(lunout,*) 'get_aero 2 iyr_in=', iyr_in,'   ',cyear
+        ! get_aero_fromfile returns pt_out allocated and initialized with data for 12 month 
+        ! pt_out has dimensions (klon, klev_src, 12)
+        CALL get_aero_fromfile(name_aero, cyear, filename, klev_src, pt_ap, pt_b, pt_out, psurf, load)
+        
+     ELSE
+        ! Read data from 2 decades and interpolate to actual year
+        ! a) from actual 10-yr-period
+        IF (iyr_in.LT.1900) THEN
+           iyr1 = 1850
+           iyr2 = 1900
+        ELSE IF (iyr_in.GE.1900.AND.iyr_in.LT.1920) THEN
+           iyr1 = 1900
+           iyr2 = 1920
+        ELSE 
+           iyr1 = INT(iyr_in/10)*10
+           iyr2 = INT(1+iyr_in/10)*10
+        ENDIF
+        
+        WRITE(cyear,'(I4)') iyr1
+        WRITE(lunout,*) 'get_aero 3 iyr_in=', iyr_in,'   ',cyear
+        ! get_aero_fromfile returns pt_out allocated and initialized with data for 12 month 
+        ! pt_out has dimensions (klon, klev_src, 12)
+        CALL get_aero_fromfile(name_aero, cyear, filename, klev_src, pt_ap, pt_b, pt_out, psurf, load)
+        
+        ! If to read two decades:
+        IF (.NOT.lonlyone) THEN 
+           
+           ! b) from the next following one
+           WRITE(cyear,'(I4)') iyr2
+           WRITE(lunout,*) 'get_aero 4 iyr_in=', iyr_in,'   ',cyear
+           
+           NULLIFY(pt_2)
+           ! get_aero_fromfile returns pt_2 allocated and initialized with data for 12 month 
+           ! pt_2 has dimensions (klon, klev_src, 12)
+           CALL get_aero_fromfile(name_aero, cyear, filename, klev_src2, pt_ap, pt_b, pt_2, psurf2, load2)
+           ! Test for same number of vertical levels
+           IF (klev_src /= klev_src2) THEN
+              WRITE(lunout,*) 'Two aerosols files with different number of vertical levels is not allowded'
+              CALL abort_physic('readaersosol','Error in number of vertical levels',1)
+           END IF
+           
+           ! Linare interpolate to the actual year:
+           DO it=1,12
+              DO k=1,klev_src
+                 DO i = 1, klon
+                    pt_out(i,k,it) = &
+                         pt_out(i,k,it) - REAL(iyr_in-iyr1)/REAL(iyr2-iyr1) * &
+                         (pt_out(i,k,it) - pt_2(i,k,it))
+                 END DO
+              END DO
+
+              DO i = 1, klon
+                 psurf(i,it) = &
+                      psurf(i,it) - REAL(iyr_in-iyr1)/REAL(iyr2-iyr1) * &
+                      (psurf(i,it) - psurf2(i,it))
+
+                 load(i,it) = &
+                      load(i,it) - REAL(iyr_in-iyr1)/REAL(iyr2-iyr1) * &
+                      (load(i,it) - load2(i,it))
+              END DO
+           END DO
+
+           ! Deallocate pt_2 no more needed
+           DEALLOCATE(pt_2)
+           
+        END IF ! lonlyone
+     END IF ! iyr_in .LT. 1850
+
+  ELSE
+     WRITE(lunout,*)'This option is not implemented : aer_type = ', type,' name_aero=',name_aero
+     CALL abort_physic('readaerosol','Error : aer_type parameter not accepted',1)
+  END IF ! type
+
+
+END SUBROUTINE readaerosol
+
+
+  SUBROUTINE init_aero_fromfile(flag_aerosol)
+  USE netcdf
+  USE mod_phys_lmdz_para
+  USE mod_grid_phy_lmdz, ONLY: grid_type, unstructured
+#ifdef CPP_XIOS
+  USE xios
+#endif
+  IMPLICIT NONE
+  INTEGER, INTENT(IN) :: flag_aerosol
+#ifdef CPP_XIOS
+  REAL,ALLOCATABLE :: lat_src(:)
+  REAL,ALLOCATABLE :: lon_src(:)
+  CHARACTER(LEN=*),PARAMETER :: file_aerosol='aerosols.nat.nc'
+  CHARACTER(LEN=*),PARAMETER :: file_so4='so4.nat.nc'
+  INTEGER :: klev_src
+  INTEGER :: ierr ,ncid, dimID, varid
+  REAL :: null_array(0)
+
+  IF (flag_aerosol>0 .AND. grid_type==unstructured) THEN
+  
+    IF (is_omp_root) THEN
+  
+      IF (is_mpi_root) THEN
+    
+        IF (nf90_open(TRIM(file_aerosol), NF90_NOWRITE, ncid) /= NF90_NOERR) THEN
+          CALL check_err( nf90_open(TRIM(file_so4), NF90_NOWRITE, ncid), "pb open "//trim(file_so4) )
+        ENDIF
+
+        ! Read and test longitudes
+        CALL check_err( nf90_inq_dimid(ncid, "lon", dimID),"pb inq dim lon") 
+        CALL check_err( nf90_inquire_dimension(ncid, dimID, len = nbp_lon_src),"pb inq dim lon")
+        CALL check_err( nf90_inq_varid(ncid, 'lon', varid),"pb inq lon" )
+        ALLOCATE(lon_src(nbp_lon_src))
+        CALL check_err( nf90_get_var(ncid, varid, lon_src(:)),"pb get lon" )
+
+        ! Read and test latitudes
+        CALL check_err( nf90_inq_dimid(ncid, "lat", dimID),"pb inq dim lat") 
+        CALL check_err( nf90_inquire_dimension(ncid, dimID, len = nbp_lat_src),"pb inq dim lat")
+        CALL check_err( nf90_inq_varid(ncid, 'lat', varid),"pb inq lat" )
+        ALLOCATE(lat_src(nbp_lat_src))
+        CALL check_err( nf90_get_var(ncid, varid, lat_src(:)),"pb get lat" )
+        IF (nf90_inq_dimid(ncid, 'lev', dimid) /= NF90_NOERR) THEN
+          IF (nf90_inq_dimid(ncid, 'presnivs', dimid)/= NF90_NOERR) THEN
+             CALL check_err(nf90_inq_dimid(ncid, 'PRESNIVS', dimid),'dimension lev,PRESNIVS or presnivs not in file')
+          ENDIF
+        ENDIF
+        CALL check_err( nf90_inquire_dimension(ncid, dimid, len = klev_src),"pb inq dim for PRESNIVS or lev" )
+        CALL check_err( nf90_close(ncid),"pb in close" )   
+      ENDIF
+
+      CALL bcast_mpi(nbp_lat_src)
+      CALL bcast_mpi(nbp_lon_src)
+      CALL bcast_mpi(klev_src)
+
+      IF (is_mpi_root ) THEN
+        CALL xios_set_domain_attr("domain_aerosol",nj_glo=nbp_lat_src, nj=nbp_lat_src, jbegin=0, latvalue_1d=lat_src)
+        CALL xios_set_domain_attr("domain_aerosol",ni_glo=nbp_lon_src, ni=nbp_lon_src, ibegin=0, lonvalue_1d=lon_src)
+      ELSE
+        CALL xios_set_domain_attr("domain_aerosol",nj_glo=nbp_lat_src, nj=0, jbegin=0, latvalue_1d=null_array )
+        CALL xios_set_domain_attr("domain_aerosol",ni_glo=nbp_lon_src, ni=0, ibegin=0, lonvalue_1d=null_array)
+      ENDIF
+      CALL xios_set_axis_attr("axis_aerosol",n_glo=klev_src)
+      CALL xios_set_fieldgroup_attr("aerosols", enabled=.TRUE.)
+  
+    ENDIF
+    
+  ENDIF    
+#endif 
+  END SUBROUTINE init_aero_fromfile
+
+
+    
+
+  SUBROUTINE get_aero_fromfile(varname, cyr, filename, klev_src, pt_ap, pt_b, pt_year, psurf_out, load_out)
+!****************************************************************************************
+! Read 12 month aerosol from file and distribute to local process on physical grid. 
+! Vertical levels, klev_src, may differ from model levels if new file format.
+!
+! For mpi_root and master thread :
+! 1) Open file 
+! 2) Find vertical dimension klev_src
+! 3) Read field month by month
+! 4) Close file  
+! 5) Transform the global field from 2D(nbp_lon,nbp_lat) to 1D(klon_glo)
+!     - Also the levels and the latitudes have to be inversed
+!
+! For all processes and threads :
+! 6) Scatter global field(klon_glo) to local process domain(klon)
+! 7) Test for negative values
+!****************************************************************************************
+
+    USE netcdf
+    USE dimphy
+    USE mod_grid_phy_lmdz, ONLY: nbp_lon_=>nbp_lon, nbp_lat_=>nbp_lat, klon_glo, &
+                                 grid2Dto1D_glo, grid_type, unstructured
+    USE mod_phys_lmdz_para
+    USE iophy, ONLY : io_lon, io_lat
+    USE print_control_mod, ONLY: lunout
+#ifdef CPP_XIOS
+    USE xios
+#endif
+    IMPLICIT NONE
+      
+! Input argumets
+    CHARACTER(len=7), INTENT(IN)          :: varname
+    CHARACTER(len=4), INTENT(IN)          :: cyr
+    CHARACTER(len=8), INTENT(IN)          :: filename
+
+! Output arguments
+    INTEGER, INTENT(OUT)                  :: klev_src     ! Number of vertical levels in file
+    REAL, POINTER, DIMENSION(:)           :: pt_ap        ! Pointer for describing the vertical levels      
+    REAL, POINTER, DIMENSION(:)           :: pt_b         ! Pointer for describing the vertical levels      
+    REAL, POINTER, DIMENSION(:,:,:)       :: pt_year      ! Pointer-variabale from file, 12 month, grid : klon,klev_src
+    REAL, POINTER, DIMENSION(:,:,:)       :: pt_year_mpi  ! Pointer-variabale from file, 12 month, grid : klon,klev_src
+    REAL, DIMENSION(klon,12), INTENT(OUT) :: psurf_out    ! Surface pression for 12 months
+    REAL, DIMENSION(klon_mpi,12)          :: psurf_out_mpi    ! Surface pression for 12 months
+    REAL, DIMENSION(klon,12), INTENT(OUT) :: load_out     ! Aerosol mass load in each column
+    REAL, DIMENSION(klon_mpi,12)          :: load_out_mpi     ! Aerosol mass load in each column
+    INTEGER                               :: nbr_tsteps   ! number of month in file read
+
+! Local variables
+    CHARACTER(len=30)     :: fname
+    CHARACTER(len=30)     :: cvar
+    INTEGER               :: ncid, dimid, varid
+    INTEGER               :: imth, i, j, k, ierr
+    REAL                  :: npole, spole
+    REAL, ALLOCATABLE, DIMENSION(:,:,:)   :: varmth
+    REAL, ALLOCATABLE, DIMENSION(:,:,:,:) :: varyear       ! Global variable read from file, 12 month
+    REAL, ALLOCATABLE, DIMENSION(:,:,:)   :: varyear_glo1D !(klon_glo, klev_src, 12)
+    REAL, ALLOCATABLE, DIMENSION(:)       :: varktmp
+
+    REAL,  ALLOCATABLE                    :: psurf_glo2D(:,:,:)   ! Surface pression for 12 months on dynamics global grid
+    REAL, DIMENSION(klon_glo,12)          :: psurf_glo1D   ! -"- on physical global grid
+    REAL,  ALLOCATABLE                    :: load_glo2D(:,:,:)    ! Load for 12 months on dynamics global grid
+    REAL, DIMENSION(klon_glo,12)          :: load_glo1D    ! -"- on physical global grid
+    REAL, ALLOCATABLE, DIMENSION(:,:)     :: vartmp
+    REAL, ALLOCATABLE,DIMENSION(:)        :: lon_src              ! longitudes in file
+    REAL, ALLOCATABLE,DIMENSION(:)        :: lat_src, lat_src_inv ! latitudes in file
+    LOGICAL                               :: new_file             ! true if new file format detected
+    LOGICAL                               :: invert_lat           ! true if the field has to be inverted for latitudes
+    INTEGER                               :: nbp_lon, nbp_lat
+    LOGICAL,SAVE                          :: first=.TRUE.
+!$OMP THREADPRIVATE(first)
+    
+    IF (grid_type==unstructured) THEN
+      nbp_lon=nbp_lon_src
+      nbp_lat=nbp_lat_src
+    ELSE
+      nbp_lon=nbp_lon_
+      nbp_lat=nbp_lat_
+    ENDIF
+    
+    IF (is_mpi_root) THEN
+    
+      ALLOCATE(psurf_glo2D(nbp_lon,nbp_lat,12))
+      ALLOCATE(load_glo2D(nbp_lon,nbp_lat,12))
+      ALLOCATE(vartmp(nbp_lon,nbp_lat))
+      ALLOCATE(lon_src(nbp_lon))
+      ALLOCATE(lat_src(nbp_lat))
+      ALLOCATE(lat_src_inv(nbp_lat))
+    ELSE
+      ALLOCATE(varyear(0,0,0,0))
+      ALLOCATE(psurf_glo2D(0,0,0))
+      ALLOCATE(load_glo2D(0,0,0))
+    ENDIF
+            
+    ! Deallocate pointers
+    IF (ASSOCIATED(pt_ap)) DEALLOCATE(pt_ap)
+    IF (ASSOCIATED(pt_b))  DEALLOCATE(pt_b)
+
+    IF (is_mpi_root .AND. is_omp_root) THEN
+
+! 1) Open file 
+!****************************************************************************************
+! Add suffix to filename
+       fname = trim(filename)//cyr//'.nc'
+  
+       WRITE(lunout,*) 'reading variable ',TRIM(varname),' in file ', TRIM(fname)
+       CALL check_err( nf90_open(TRIM(fname), NF90_NOWRITE, ncid), "pb open "//trim(fname) )
+
+
+       IF (grid_type/=unstructured) THEN
+
+! Test for equal longitudes and latitudes in file and model
+!****************************************************************************************
+       ! Read and test longitudes
+         CALL check_err( nf90_inq_varid(ncid, 'lon', varid),"pb inq lon" )
+         CALL check_err( nf90_get_var(ncid, varid, lon_src(:)),"pb get lon" )
+       
+         IF (maxval(ABS(lon_src - io_lon)) > 0.001) THEN
+            WRITE(lunout,*) 'Problem in longitudes read from file : ',TRIM(fname)
+            WRITE(lunout,*) 'longitudes in file ', TRIM(fname),' : ', lon_src
+            WRITE(lunout,*) 'longitudes in model :', io_lon
+          
+            CALL abort_physic('get_aero_fromfile', 'longitudes are not the same in file and model',1)
+         END IF
+
+         ! Read and test latitudes
+         CALL check_err( nf90_inq_varid(ncid, 'lat', varid),"pb inq lat" )
+         CALL check_err( nf90_get_var(ncid, varid, lat_src(:)),"pb get lat" )
+
+         ! Invert source latitudes
+         DO j = 1, nbp_lat
+            lat_src_inv(j) = lat_src(nbp_lat +1 -j)
+         END DO
+
+         IF (maxval(ABS(lat_src - io_lat)) < 0.001) THEN
+            ! Latitudes are the same
+            invert_lat=.FALSE.
+         ELSE IF (maxval(ABS(lat_src_inv - io_lat)) < 0.001) THEN
+            ! Inverted source latitudes correspond to model latitudes
+            WRITE(lunout,*) 'latitudes will be inverted for file : ',TRIM(fname)
+            invert_lat=.TRUE.
+         ELSE
+            WRITE(lunout,*) 'Problem in latitudes read from file : ',TRIM(fname)
+            WRITE(lunout,*) 'latitudes in file ', TRIM(fname),' : ', lat_src      
+            WRITE(lunout,*) 'latitudes in model :', io_lat
+            CALL abort_physic('get_aero_fromfile', 'latitudes do not correspond between file and model',1)
+         END IF
+       ENDIF
+
+! 2) Check if old or new file is avalabale.
+!    New type of file should contain the dimension 'lev'
+!    Old type of file should contain the dimension 'PRESNIVS'
+!****************************************************************************************
+       ierr = nf90_inq_dimid(ncid, 'lev', dimid) 
+       IF (ierr /= NF90_NOERR) THEN
+          ! Coordinate axe lev not found. Check for presnivs.
+          ierr = nf90_inq_dimid(ncid, 'presnivs', dimid) 
+          IF (ierr /= NF90_NOERR) THEN
+             ierr = nf90_inq_dimid(ncid, 'PRESNIVS', dimid)
+             IF (ierr /= NF90_NOERR) THEN
+                ! Dimension PRESNIVS not found either
+                CALL abort_physic('get_aero_fromfile', 'dimension lev,PRESNIVS or presnivs not in file',1)
+             ELSE 
+                ! Old file found
+                new_file=.FALSE.
+                WRITE(lunout,*) 'Vertical interpolation for ',TRIM(varname),' will not be done'
+             END IF
+          ELSE
+             ! New file found
+             new_file=.TRUE.
+             WRITE(lunout,*) 'Vertical interpolation for ',TRIM(varname),' will be done'
+          ENDIF
+       ELSE
+          ! New file found
+          new_file=.TRUE.
+          WRITE(lunout,*) 'Vertical interpolation for ',TRIM(varname),' will be done'
+       END IF
+       
+! 2) Find vertical dimension klev_src
+!****************************************************************************************
+       CALL check_err( nf90_inquire_dimension(ncid, dimid, len = klev_src),"pb inq dim for PRESNIVS or lev" )
+       
+     ! Allocate variables depending on the number of vertical levels
+       ALLOCATE(varmth(nbp_lon,nbp_lat, klev_src), varyear(nbp_lon,nbp_lat, klev_src, 12), stat=ierr)
+       IF (ierr /= 0) CALL abort_physic('get_aero_fromfile', 'pb in allocation 1',1)
+
+       ALLOCATE(pt_ap(klev_src), pt_b(klev_src), varktmp(klev_src), stat=ierr)
+       IF (ierr /= 0) CALL abort_physic('get_aero_fromfile', 'pb in allocation 2',1)
+
+! 3) Read all variables from file
+!    There is 2 options for the file structure :
+!    new_file=TRUE  : read varyear, ps, pt_ap and pt_b
+!    new_file=FALSE : read varyear month by month
+!****************************************************************************************
+
+       IF (new_file) THEN
+! ++) Check number of month in file opened
+!**************************************************************************************************
+       ierr = nf90_inq_dimid(ncid, 'TIME',dimid)
+       if (ierr /= NF90_NOERR) THEN
+          ierr = nf90_inq_dimid(ncid, 'time_counter', dimid)
+       ENDIF
+       CALL check_err( nf90_inquire_dimension(ncid, dimid, len = nbr_tsteps),"pb inq dim TIME or time_counter" )
+!       IF (nbr_tsteps /= 12 .AND. nbr_tsteps /= 14) THEN
+       IF (nbr_tsteps /= 12 ) THEN
+    CALL abort_physic('get_aero_fromfile', 'not the right number of months in aerosol file read (should be 12 for the moment)' &
+                     ,1)
+       ENDIF
+
+! ++) Read the aerosol concentration month by month and concatenate to total variable varyear
+!****************************************************************************************
+          ! Get variable id
+          !CALL check_err( nf90_inq_varid(ncid, TRIM(varname), varid),"pb inq var "//TRIM(varname) )
+          print *,'readaerosol ', TRIM(varname)
+          IF ( nf90_inq_varid(ncid, TRIM(varname), varid) /= NF90_NOERR ) THEN 
+            ! Variable is not there
+            WRITE(lunout,*) 'Attention '//TRIM(varname)//' is not in aerosol input file'
+            varyear(:,:,:,:)=0.0
+          ELSE 
+            ! Get the variable
+            CALL check_err( nf90_get_var(ncid, varid, varyear(:,:,:,:)),"pb get var "//TRIM(varname) )
+          ENDIF
+          
+! ++) Read surface pression, 12 month in one variable
+!****************************************************************************************
+          ! Get variable id
+          CALL check_err( nf90_inq_varid(ncid, "ps", varid),"pb inq var ps" )
+          ! Get the variable
+          CALL check_err( nf90_get_var(ncid, varid, psurf_glo2D),"pb get var ps" )
+          
+! ++) Read mass load, 12 month in one variable
+!****************************************************************************************
+          ! Get variable id
+          !CALL check_err( nf90_inq_varid(ncid, "load_"//TRIM(varname), varid) ,"pb inq var load_"//TRIM(varname))
+          IF ( nf90_inq_varid(ncid, "load_"//TRIM(varname), varid) /= NF90_NOERR ) THEN 
+            WRITE(lunout,*) 'Attention load_'//TRIM(varname)//' is not in aerosol input file'
+            load_glo2D(:,:,:)=0.0
+          ELSE
+            ! Get the variable
+            CALL check_err( nf90_get_var(ncid, varid, load_glo2D),"pb get var load_"//TRIM(varname) )
+          ENDIF
+          
+! ++) Read ap
+!****************************************************************************************
+          ! Get variable id
+          CALL check_err( nf90_inq_varid(ncid, "ap", varid),"pb inq var ap" )
+          ! Get the variable
+          CALL check_err( nf90_get_var(ncid, varid, pt_ap),"pb get var ap" )
+
+! ++) Read b
+!****************************************************************************************
+          ! Get variable id
+          CALL check_err( nf90_inq_varid(ncid, "b", varid),"pb inq var b" )
+          ! Get the variable
+          CALL check_err( nf90_get_var(ncid, varid, pt_b),"pb get var b" )
+
+          
+
+       ELSE  ! old file
+
+! ++) Read the aerosol concentration month by month and concatenate to total variable varyear
+!****************************************************************************************
+          DO imth=1, 12
+             IF (imth.EQ.1) THEN
+                cvar=TRIM(varname)//'JAN'
+             ELSE IF (imth.EQ.2) THEN
+                cvar=TRIM(varname)//'FEB'
+             ELSE IF (imth.EQ.3) THEN
+                cvar=TRIM(varname)//'MAR'
+             ELSE IF (imth.EQ.4) THEN
+                cvar=TRIM(varname)//'APR'
+             ELSE IF (imth.EQ.5) THEN
+                cvar=TRIM(varname)//'MAY'
+             ELSE IF (imth.EQ.6) THEN
+                cvar=TRIM(varname)//'JUN'
+             ELSE IF (imth.EQ.7) THEN
+                cvar=TRIM(varname)//'JUL'
+             ELSE IF (imth.EQ.8) THEN
+                cvar=TRIM(varname)//'AUG'
+             ELSE IF (imth.EQ.9) THEN
+                cvar=TRIM(varname)//'SEP'
+             ELSE IF (imth.EQ.10) THEN
+                cvar=TRIM(varname)//'OCT'
+             ELSE IF (imth.EQ.11) THEN
+                cvar=TRIM(varname)//'NOV'
+             ELSE IF (imth.EQ.12) THEN
+                cvar=TRIM(varname)//'DEC'
+             END IF
+             
+             ! Get variable id
+             CALL check_err( nf90_inq_varid(ncid, TRIM(cvar), varid),"pb inq var "//TRIM(cvar) )
+             
+             ! Get the variable
+             CALL check_err( nf90_get_var(ncid, varid, varmth),"pb get var "//TRIM(cvar) )
+             
+             ! Store in variable for the whole year
+             varyear(:,:,:,imth)=varmth(:,:,:)
+             
+          END DO
+          
+          ! Putting dummy 
+          psurf_glo2D(:,:,:) = not_valid
+          load_glo2D(:,:,:)  = not_valid
+          pt_ap(:) = not_valid
+          pt_b(:)  = not_valid
+
+       END IF
+
+! 4) Close file  
+!****************************************************************************************
+       CALL check_err( nf90_close(ncid),"pb in close" )
+     
+
+! 5) Transform the global field from 2D(nbp_lon,nbp_lat) to 1D(klon_glo)
+!****************************************************************************************
+! Test if vertical levels have to be inversed
+
+       IF ((pt_b(1) < pt_b(klev_src)) .OR. .NOT. new_file) THEN
+!          WRITE(lunout,*) 'Vertical axis in file ',TRIM(fname), ' needs to be inverted'
+!          WRITE(lunout,*) 'before pt_ap = ', pt_ap
+!          WRITE(lunout,*) 'before pt_b = ', pt_b
+          
+          ! Inverse vertical levels for varyear 
+          DO imth=1, 12
+             varmth(:,:,:) = varyear(:,:,:,imth) ! use varmth temporarly
+             DO k=1, klev_src
+                DO j=1, nbp_lat
+                   DO i=1, nbp_lon
+                      varyear(i,j,k,imth) = varmth(i,j,klev_src+1-k)
+                   END DO
+                END DO
+             END DO
+          END DO
+           
+          ! Inverte vertical axes for pt_ap and pt_b
+          varktmp(:) = pt_ap(:)
+          DO k=1, klev_src
+             pt_ap(k) = varktmp(klev_src+1-k)
+          END DO
+
+          varktmp(:) = pt_b(:)
+          DO k=1, klev_src
+             pt_b(k) = varktmp(klev_src+1-k)
+          END DO
+          WRITE(lunout,*) 'after pt_ap = ', pt_ap
+          WRITE(lunout,*) 'after pt_b = ', pt_b
+
+       ELSE 
+          WRITE(lunout,*) 'Vertical axis in file ',TRIM(fname), ' is ok, no vertical inversion is done'
+          WRITE(lunout,*) 'pt_ap = ', pt_ap
+          WRITE(lunout,*) 'pt_b = ', pt_b
+       END IF
+
+
+       IF (grid_type/=unstructured) THEN
+  !     - Invert latitudes if necessary
+         DO imth=1, 12
+            IF (invert_lat) THEN
+
+               ! Invert latitudes for the variable
+               varmth(:,:,:) = varyear(:,:,:,imth) ! use varmth temporarly
+               DO k=1,klev_src
+                  DO j=1,nbp_lat
+                     DO i=1,nbp_lon
+                        varyear(i,j,k,imth) = varmth(i,nbp_lat+1-j,k)
+                     END DO
+                  END DO
+               END DO
+             
+               ! Invert latitudes for surface pressure
+               vartmp(:,:) = psurf_glo2D(:,:,imth)
+               DO j=1,nbp_lat
+                  DO i=1,nbp_lon
+                     psurf_glo2D(i,j,imth)= vartmp(i,nbp_lat+1-j)
+                  END DO
+               END DO
+             
+               ! Invert latitudes for the load
+               vartmp(:,:) = load_glo2D(:,:,imth)
+               DO j=1,nbp_lat
+                  DO i=1,nbp_lon
+                     load_glo2D(i,j,imth)= vartmp(i,nbp_lat+1-j)
+                  END DO
+               END DO
+            END IF ! invert_lat
+             
+            ! Do zonal mead at poles and distribut at whole first and last latitude
+            DO k=1, klev_src
+               npole=0.  ! North pole, j=1
+               spole=0.  ! South pole, j=nbp_lat        
+               DO i=1,nbp_lon
+                  npole = npole + varyear(i,1,k,imth)
+                  spole = spole + varyear(i,nbp_lat,k,imth)
+               END DO
+               npole = npole/REAL(nbp_lon)
+               spole = spole/REAL(nbp_lon)
+               varyear(:,1,    k,imth) = npole
+               varyear(:,nbp_lat,k,imth) = spole
+            END DO
+         END DO ! imth
+       
+         ALLOCATE(varyear_glo1D(klon_glo, klev_src, 12), stat=ierr)
+         IF (ierr /= 0) CALL abort_physic('get_aero_fromfile', 'pb in allocation 3',1)
+       
+         ! Transform from 2D to 1D field
+         CALL grid2Dto1D_glo(varyear,varyear_glo1D)
+         CALL grid2Dto1D_glo(psurf_glo2D,psurf_glo1D)
+         CALL grid2Dto1D_glo(load_glo2D,load_glo1D)
+      
+      ENDIF
+      
+    ELSE
+        ALLOCATE(varyear_glo1D(0,0,0))        
+    END IF ! is_mpi_root .AND. is_omp_root
+
+!$OMP BARRIER
+  
+! 6) Distribute to all processes
+!    Scatter global field(klon_glo) to local process domain(klon)
+!    and distribute klev_src to all processes
+!****************************************************************************************
+
+    ! Distribute klev_src
+    CALL bcast(klev_src)
+
+    ! Allocate and distribute pt_ap and pt_b
+    IF (.NOT. ASSOCIATED(pt_ap)) THEN  ! if pt_ap is allocated also pt_b is allocated
+       ALLOCATE(pt_ap(klev_src), pt_b(klev_src), stat=ierr)
+       IF (ierr /= 0) CALL abort_physic('get_aero_fromfile', 'pb in allocation 4',1)
+    END IF
+    CALL bcast(pt_ap)
+    CALL bcast(pt_b)
+
+    ! Allocate space for output pointer variable at local process
+    IF (ASSOCIATED(pt_year)) DEALLOCATE(pt_year)
+    ALLOCATE(pt_year(klon, klev_src, 12), stat=ierr)
+    ALLOCATE(pt_year_mpi(klon_mpi, klev_src, 12), stat=ierr)
+    IF (ierr /= 0) CALL abort_physic('get_aero_fromfile', 'pb in allocation 5',1)
+
+    IF (grid_type==unstructured) THEN
+#ifdef CPP_XIOS
+      IF (is_omp_master) THEN
+        CALL xios_send_field(TRIM(varname)//"_in",varyear)
+        CALL xios_recv_field(TRIM(varname)//"_out",pt_year_mpi)
+        CALL xios_send_field("load_"//TRIM(varname)//"_in",load_glo2D)
+        CALL xios_recv_field("load_"//TRIM(varname)//"_out",load_out_mpi)
+        IF (first) THEN
+          ALLOCATE(psurf_interp(klon_mpi,12))
+          CALL xios_send_field("psurf_aerosol_in",psurf_glo2D)
+          CALL xios_recv_field("psurf_aerosol_out",psurf_interp)
+        ENDIF
+      ENDIF
+      CALL scatter_omp(pt_year_mpi,pt_year)
+      CALL scatter_omp(load_out_mpi,load_out)
+      CALL scatter_omp(psurf_interp,psurf_out)
+      first=.FALSE.
+#endif
+    ELSE
+      ! Scatter global field to local domain at local process
+      CALL scatter(varyear_glo1D, pt_year)
+      CALL scatter(psurf_glo1D, psurf_out)
+      CALL scatter(load_glo1D,  load_out)
+    ENDIF
+! 7) Test for negative values
+!****************************************************************************************
+    IF (MINVAL(pt_year) < 0.) THEN
+       WRITE(lunout,*) 'Warning! Negative values read from file :', fname
+    END IF
+
+  END SUBROUTINE get_aero_fromfile
+
+
+  SUBROUTINE check_err(status,text)
+    USE netcdf
+    USE print_control_mod, ONLY: lunout
+    IMPLICIT NONE
+
+    INTEGER, INTENT (IN) :: status
+    CHARACTER(len=*), INTENT (IN), OPTIONAL :: text
+
+    IF (status /= NF90_NOERR) THEN
+       WRITE(lunout,*) 'Error in get_aero_fromfile, netcdf error code = ',status
+       IF (PRESENT(text)) THEN
+          WRITE(lunout,*) 'Error in get_aero_fromfile : ',text
+       END IF
+       CALL abort_physic('get_aero_fromfile',trim(nf90_strerror(status)),1)
+    END IF
+
+  END SUBROUTINE check_err
+
+
+END MODULE readaerosol_mod
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/readaerosolstrato.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/readaerosolstrato.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/readaerosolstrato.F90	(revision 3605)
@@ -7,5 +7,5 @@
     USE phys_cal_mod, ONLY : mth_cur
     USE mod_grid_phy_lmdz, ONLY: nbp_lon, nbp_lat, klon_glo, &
-                                 grid2dto1d_glo
+                                 grid2dto1d_glo, grid_type, unstructured
     USE mod_phys_lmdz_mpi_data, ONLY :  is_mpi_root
     USE mod_phys_lmdz_omp_data, ONLY :  is_omp_root
@@ -15,5 +15,8 @@
     USE aero_mod
     USE dimphy
-
+    USE print_control_mod, ONLY: prt_level,lunout
+#ifdef CPP_XIOS
+    USE xios
+#endif
     implicit none
 
@@ -43,4 +46,5 @@
     real, allocatable:: tauaerstrat_mois(:, :, :)
     real, allocatable:: tauaerstrat_mois_glo(:, :)
+    real, allocatable:: tau_aer_strat_mpi(:, :)
 
 ! For NetCDF:
@@ -58,4 +62,7 @@
     data alpha_strat_wave/3.36780953,3.34667683,3.20444202,3.0293026,2.82108808/
 
+    CHARACTER (len = 20)                      :: modname = 'readaerosolstrato'
+    CHARACTER (len = 80)                      :: abort_message
+
 !--------------------------------------------------------
 
@@ -69,6 +76,6 @@
 
     IF (nbands.NE.2) THEN 
-        print *,'nbands doit etre egal a 2 dans readaerosolstrat'
-        STOP
+        abort_message='nbands doit etre egal a 2 dans readaerosolstrat'
+        CALL abort_physic(modname,abort_message,1)
     ENDIF
 
@@ -79,6 +86,6 @@
     n_lev = size(lev)
     IF (n_lev.NE.klev) THEN 
-       print *,'Le nombre de niveaux n est pas egal a klev'
-       STOP
+       abort_message='Le nombre de niveaux n est pas egal a klev'
+       CALL abort_physic(modname,abort_message,1)
     ENDIF
 
@@ -86,26 +93,30 @@
     CALL nf95_gw_var(ncid_in, varid, latitude)
     n_lat = size(latitude)
-    print *, 'LAT aerosol strato=', n_lat, latitude
-    IF (n_lat.NE.nbp_lat) THEN 
-       print *,'Le nombre de lat n est pas egal a nbp_lat'
-       STOP
-    ENDIF
-
+    WRITE(lunout,*) 'LAT aerosol strato=', n_lat, latitude
+    IF (grid_type/=unstructured) THEN
+      IF (n_lat.NE.nbp_lat) THEN 
+         abort_message='Le nombre de lat n est pas egal a nbp_lat'
+         CALL abort_physic(modname,abort_message,1)
+      ENDIF
+    ENDIF
+    
     CALL nf95_inq_varid(ncid_in, "LON", varid)
     CALL nf95_gw_var(ncid_in, varid, longitude)
     n_lon = size(longitude)
-    print *, 'LON aerosol strato=', n_lon, longitude
-    IF (n_lon.NE.nbp_lon) THEN 
-       print *,'Le nombre de lon n est pas egal a nbp_lon'
-       STOP
-    ENDIF
-
+    IF (grid_type/=unstructured) THEN
+      WRITE(lunout,*) 'LON aerosol strato=', n_lon, longitude
+      IF (n_lon.NE.nbp_lon) THEN 
+         abort_message='Le nombre de lon n est pas egal a nbp_lon'
+         CALL abort_physic(modname,abort_message,1)
+      ENDIF
+    ENDIF
+    
     CALL nf95_inq_varid(ncid_in, "TIME", varid)
     CALL nf95_gw_var(ncid_in, varid, time)
     n_month = size(time)
-    print *, 'TIME aerosol strato=', n_month, time
+    WRITE(lunout,*) 'TIME aerosol strato=', n_month, time
     IF (n_month.NE.12) THEN 
-       print *,'Le nombre de month n est pas egal a 12'
-       STOP
+       abort_message='Le nombre de month n est pas egal a 12'
+       CALL abort_physic(modname,abort_message,1)
     ENDIF
 
@@ -117,5 +128,5 @@
     CALL nf95_inq_varid(ncid_in, "TAUSTRAT", varid)
     ncerr = nf90_get_var(ncid_in, varid, tauaerstrat)
-    print *,'code erreur readaerosolstrato=', ncerr, varid
+    WRITE(lunout,*) 'code erreur readaerosolstrato=', ncerr, varid
 
     CALL nf95_close(ncid_in)
@@ -123,5 +134,5 @@
 !---select the correct month
     IF (mth_cur.LT.1.OR.mth_cur.GT.12) THEN
-      print *,'probleme avec le mois dans readaerosolstrat =', mth_cur
+     WRITE(lunout,*) 'probleme avec le mois dans readaerosolstrat =', mth_cur
     ENDIF
     tauaerstrat_mois(:,:,:) = tauaerstrat(:,:,:,mth_cur)
@@ -130,10 +141,25 @@
     CALL grid2dTo1d_glo(tauaerstrat_mois,tauaerstrat_mois_glo)
 
+    ELSE
+      ALLOCATE(tauaerstrat_mois(0,0,0))
     ENDIF !--is_mpi_root and is_omp_root
 
 !$OMP BARRIER
 
+    IF (grid_type==unstructured) THEN
+#ifdef CPP_XIOS
+      IF (is_omp_master) THEN
+        CALL xios_send_field("taustrat_in",tauaerstrat_mois)
+        ALLOCATE(tau_aer_strat_mpi(klon_mpi, klev))
+        CALL xios_recv_field("taustrat_out",tau_aer_strat_mpi)
+      ELSE
+        ALLOCATE(tau_aer_strat_mpi(0,0))
+      ENDIF
+      CALL scatter_omp(tau_aer_strat_mpi,tau_aer_strat)
+#endif
+    ELSE  
 !--scatter on all proc
-    CALL scatter(tauaerstrat_mois_glo,tau_aer_strat)
+      CALL scatter(tauaerstrat_mois_glo,tau_aer_strat)
+    ENDIF
 
 !--keep memory of previous month
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/readaerosolstrato_m.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/readaerosolstrato_m.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/readaerosolstrato_m.F90	(revision 3605)
@@ -0,0 +1,138 @@
+MODULE readaerosolstrato_m
+
+
+CONTAINS
+
+  SUBROUTINE init_readaerosolstrato(flag_aerosol_strat)
+  USE mod_grid_phy_lmdz, ONLY: grid_type, unstructured
+  IMPLICIT NONE
+  INTEGER,INTENT(IN) :: flag_aerosol_strat
+    
+    IF (grid_type==unstructured)  THEN 
+   
+      IF (flag_aerosol_strat == 1) THEN
+        CALL init_readaerosolstrato1
+      ELSE IF (flag_aerosol_strat == 2) THEN
+        CALL init_readaerosolstrato2
+      ENDIF
+  
+    ENDIF
+  
+  END SUBROUTINE init_readaerosolstrato
+  
+
+
+  SUBROUTINE init_readaerosolstrato1
+#ifdef CPP_XIOS
+  USE netcdf
+  USE netcdf95, ONLY: nf95_close, nf95_gw_var, nf95_inq_dimid, & 
+                      nf95_inq_varid, nf95_open
+  USE mod_phys_lmdz_para
+  USE xios
+!  USE YOERAD, ONLY : NLW
+  IMPLICIT NONE
+  REAL, POINTER:: latitude(:)
+  REAL, POINTER:: longitude(:)
+  INTEGER :: nlat, nlon
+  REAL    :: null_array(0)
+  INTEGER :: ncid_in, varid
+  
+    IF (is_omp_master) THEN  
+      IF (is_mpi_root) THEN
+        CALL nf95_open("taustrat.nc", nf90_nowrite, ncid_in)
+        CALL nf95_inq_varid(ncid_in, "LAT", varid)
+        CALL nf95_gw_var(ncid_in, varid, latitude)
+        CALL nf95_inq_varid(ncid_in, "LON", varid)
+        CALL nf95_gw_var(ncid_in, varid, longitude)
+        CALL nf95_close(ncid_in)
+        nlat=size(latitude)
+        nlon=size(longitude)
+      ENDIF
+      CALL bcast_mpi(nlat)
+      CALL bcast_mpi(nlon)
+
+      IF (is_mpi_root) THEN
+        CALL xios_set_domain_attr("domain_taustrat",nj_glo=nlat, nj=nlat, jbegin=0, latvalue_1d=latitude)
+        CALL xios_set_domain_attr("domain_taustrat",ni_glo=nlon, ni=nlon, ibegin=0, lonvalue_1d = longitude)
+       ELSE
+        CALL xios_set_domain_attr("domain_taustrat",nj_glo=nlat, nj=0, jbegin=0, latvalue_1d=null_array )
+        CALL xios_set_domain_attr("domain_taustrat",ni_glo=nlon, ni=0, ibegin=0, lonvalue_1d=null_array)
+      ENDIF    
+  
+      CALL xios_set_fieldgroup_attr("aerosol_strato1",enabled=.TRUE.)
+    ENDIF
+    
+#endif
+  END SUBROUTINE init_readaerosolstrato1
+  
+  SUBROUTINE init_readaerosolstrato2
+#ifdef CPP_XIOS
+  USE netcdf
+  USE netcdf95, ONLY: nf95_close, nf95_gw_var, nf95_inq_dimid, & 
+                      nf95_inq_varid, nf95_open
+  USE mod_phys_lmdz_para
+  USE xios
+!  USE YOERAD, ONLY : NLW
+  IMPLICIT NONE
+  REAL, POINTER:: latitude(:)
+  REAL, POINTER:: wav(:)
+  INTEGER :: nlat,n_wav
+  REAL    :: null_array(0)
+  INTEGER :: ncid_in, varid
+
+    IF (is_omp_master) THEN    
+      IF (is_mpi_root) THEN
+        CALL nf95_open("tauswstrat.2D.nc", nf90_nowrite, ncid_in)
+        CALL nf95_inq_varid(ncid_in, "LAT", varid)
+        CALL nf95_gw_var(ncid_in, varid, latitude)
+        CALL nf95_inq_varid(ncid_in, "WAV", varid)
+        CALL nf95_gw_var(ncid_in, varid, wav)
+        CALL nf95_close(ncid_in)
+        nlat=size(latitude)
+        n_wav = size(wav)
+      ENDIF
+      CALL bcast_mpi(nlat)
+      CALL bcast_mpi(n_wav)
+
+      IF (is_mpi_root) THEN
+        CALL xios_set_domain_attr("domain_tauswstrat",nj_glo=nlat, nj=nlat, jbegin=0, latvalue_1d=latitude)
+        CALL xios_set_domain_attr("domain_tauswstrat",ni_glo=8, ni=8, ibegin=0, lonvalue_1d = (/ 0.,45.,90.,135.,180.,225.,270., 315. /))
+        DEALLOCATE(latitude)
+      ELSE
+        CALL xios_set_domain_attr("domain_tauswstrat",nj_glo=nlat, nj=0, jbegin=0, latvalue_1d=null_array )
+        CALL xios_set_domain_attr("domain_tauswstrat",ni_glo=8, ni=0, ibegin=0, lonvalue_1d=null_array)
+      ENDIF    
+      CALL  xios_set_axis_attr("nsw", n_glo=n_wav)
+    
+      IF (is_mpi_root) THEN
+        CALL nf95_open("taulwstrat.2D.nc", nf90_nowrite, ncid_in)
+        CALL nf95_inq_varid(ncid_in, "LAT", varid)
+        CALL nf95_gw_var(ncid_in, varid, latitude)
+        CALL nf95_inq_varid(ncid_in, "WAV", varid)
+        CALL nf95_gw_var(ncid_in, varid, wav)
+        CALL nf95_close(ncid_in)
+        nlat=size(latitude)
+        n_wav = size(wav)
+      ENDIF
+      CALL bcast_mpi(nlat)
+      CALL bcast_mpi(n_wav)
+
+      IF (is_mpi_root) THEN
+        CALL xios_set_domain_attr("domain_taulwstrat",nj_glo=nlat, nj=nlat, jbegin=0, latvalue_1d=latitude)
+        CALL xios_set_domain_attr("domain_taulwstrat",ni_glo=8, ni=8, ibegin=0, lonvalue_1d = (/ 0.,45.,90.,135.,180.,225.,270., 315. /))
+        DEALLOCATE(latitude)
+      ELSE
+        CALL xios_set_domain_attr("domain_taulwstrat",nj_glo=nlat, nj=0, jbegin=0, latvalue_1d=null_array )
+        CALL xios_set_domain_attr("domain_taulwstrat",ni_glo=8, ni=0, ibegin=0, lonvalue_1d=null_array)
+      ENDIF    
+    
+      CALL  xios_set_axis_attr("nlw", n_glo=n_wav)
+      CALL xios_set_fieldgroup_attr("aerosol_strato2",enabled=.TRUE.)
+
+    ENDIF
+#endif    
+  END SUBROUTINE init_readaerosolstrato2
+  
+
+END MODULE readaerosolstrato_m
+
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/readchlorophyll.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/readchlorophyll.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/readchlorophyll.F90	(revision 3605)
@@ -15,4 +15,5 @@
     USE mod_phys_lmdz_para, ONLY: scatter 
     USE phys_state_var_mod, ONLY: chl_con
+    USE print_control_mod, ONLY: prt_level,lunout
 
     IMPLICIT NONE
@@ -45,4 +46,6 @@
 
 !--------------------------------------------------------
+    CHARACTER (len = 20)  :: modname = 'readchlorophyll'
+    CHARACTER (len = 80)  :: abort_message
 
 !--only read file if beginning of run or start of new month
@@ -56,8 +59,7 @@
     CALL nf95_gw_var(ncid_in, varid, longitude)
     n_lon = size(longitude)
-!    print *, 'LON chlorophyll=', n_lon, longitude
     IF (n_lon.NE.nbp_lon) THEN
-       print *,'Le nombre de lon n est pas egal a nbp_lon'
-       STOP
+       abort_message='Le nombre de lon n est pas egal a nbp_lon'
+       CALL abort_physic(modname,abort_message,1)
     ENDIF
 
@@ -65,8 +67,7 @@
     CALL nf95_gw_var(ncid_in, varid, latitude)
     n_lat = size(latitude)
-!    print *, 'LAT chlorophyll=', n_lat, latitude
     IF (n_lat.NE.nbp_lat) THEN 
-       print *,'Le nombre de lat n est pas egal a jnbp_lat'
-       STOP
+       abort_message='Le nombre de lat n est pas egal a jnbp_lat'
+       CALL abort_physic(modname,abort_message,1)
     ENDIF
 
@@ -74,8 +75,7 @@
     CALL nf95_gw_var(ncid_in, varid, time)
     n_month = size(time)
-!    print *, 'TIME aerosol strato=', n_month, time
     IF (n_month.NE.12) THEN 
-       print *,'Le nombre de month n est pas egal a 12'
-       STOP
+       abort_message='Le nombre de month n est pas egal a 12'
+       CALL abort_physic(modname,abort_message,1)
     ENDIF
 
@@ -87,5 +87,5 @@
     CALL nf95_inq_varid(ncid_in, "CHL", varid)
     ncerr = nf90_get_var(ncid_in, varid, chlorocon)
-    print *,'code erreur readchlorophyll=', ncerr, varid
+    WRITE(lunout,*)'code erreur readchlorophyll=', ncerr, varid
 
     CALL nf95_close(ncid_in)
@@ -93,5 +93,5 @@
 !---select the correct month
     IF (mth_cur.LT.1.OR.mth_cur.GT.12) THEN
-      print *,'probleme avec le mois dans readchlorophyll =', mth_cur
+      WRITE(lunout,*)'probleme avec le mois dans readchlorophyll =', mth_cur
     ENDIF
     chlorocon_mois(:,:) = chlorocon(:,:,mth_cur)
@@ -100,5 +100,5 @@
     CALL grid2dTo1d_glo(chlorocon_mois,chlorocon_mois_glo)
 
-    print *,"chrolophyll current month",mth_cur
+    WRITE(lunout,*)"chrolophyll current month",mth_cur
     DO i=1,klon_glo
 !      if(isnan(chlorocon_mois_glo(i)))then ! isnan() is not in the Fortran standard...
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/regr_horiz_time_climoz_m.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/regr_horiz_time_climoz_m.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/regr_horiz_time_climoz_m.F90	(revision 3605)
@@ -2,5 +2,5 @@
 
   USE interpolation,     ONLY: locate
-  USE mod_grid_phy_lmdz, ONLY: nlon_ou => nbp_lon, nlat_ou => nbp_lat
+  USE mod_grid_phy_lmdz, ONLY: nbp_lon, nbp_lat, grid_type, unstructured
   USE nrtype,            ONLY: pi
   USE netcdf,   ONLY: NF90_CLOBBER, NF90_FLOAT,     NF90_GET_VAR, NF90_OPEN,   &
@@ -11,4 +11,5 @@
           NF95_CLOSE, NF95_ENDDEF,  NF95_PUT_ATT,   NF95_PUT_VAR, NF95_COPY_ATT
   USE print_control_mod, ONLY: lunout
+  USE dimphy
   IMPLICIT NONE
   PRIVATE
@@ -16,4 +17,10 @@
   REAL, PARAMETER :: deg2rad=pi/180.
   CHARACTER(LEN=13), PARAMETER :: vars_in(2)=['tro3         ','tro3_daylight']
+
+  INTEGER :: nlat_ou, nlon_ou
+  REAL, ALLOCATABLE :: latitude_glo(:)
+!$OMP THREADPRIVATE(latitude_glo)
+  INTEGER, ALLOCATABLE :: ind_cell_glo_glo(:)
+!$OMP THREADPRIVATE(ind_cell_glo_glo)
 
 CONTAINS
@@ -52,5 +59,6 @@
   USE assert_m,           ONLY: assert
   USE cal_tools_m,        ONLY: year_len, mid_month
-  USE control_mod,        ONLY: anneeref
+!!  USE control_mod,        ONLY: anneeref
+  USE time_phylmdz_mod,   ONLY: annee_ref
   USE ioipsl,             ONLY: ioget_year_len, ioget_calendar
   USE regr_conserv_m,     ONLY: regr_conserv
@@ -58,4 +66,11 @@
   USE regular_lonlat_mod, ONLY: boundslon_reg, boundslat_reg, south, west, east
   USE slopes_m,           ONLY: slopes
+#ifdef CPP_XIOS
+  USE xios
+#endif
+  USE mod_phys_lmdz_para, ONLY: is_mpi_root, is_master, is_omp_master, gather, gather_mpi, bcast_mpi, klon_mpi
+  USE geometry_mod, ONLY : latitude_deg, ind_cell_glo
+  USE mod_grid_phy_lmdz, ONLY: klon_glo
+
 !-------------------------------------------------------------------------------
 ! Arguments:
@@ -83,5 +98,7 @@
   CHARACTER(LEN=20) :: cal_in              ! Calendar
   REAL, ALLOCATABLE :: o3_in3(:,:,:,:,:)   ! Ozone climatologies
+  REAL, ALLOCATABLE :: o3_in3bis(:,:,:,:,:)   ! Ozone climatologies
   REAL, ALLOCATABLE :: o3_in2  (:,:,:,:)   ! Ozone climatologies
+  REAL, ALLOCATABLE :: o3_in2bis(:,:,:,:,:)   ! Ozone climatologies
   ! last index: 1 for the day-night average, 2 for the daylight field.
   REAL :: NaN
@@ -91,6 +108,9 @@
   REAL, ALLOCATABLE :: o3_regr_lonlat(:,:,:,:,:) ! (nlon_ou,nlat_ou,:,0:13   ,:)
   REAL, ALLOCATABLE :: o3_out3       (:,:,:,:,:) ! (nlon_ou,nlat_ou,:,ntim_ou,:)
+  REAL, ALLOCATABLE :: o3_out3_glo   (:,:,:,:) !   (nbp_lat,:,ntim_ou,:)
   REAL, ALLOCATABLE :: o3_regr_lat     (:,:,:,:) !         (nlat_in,:,0:13   ,:)
   REAL, ALLOCATABLE :: o3_out2         (:,:,:,:) !         (nlat_ou,:,ntim_ou,:)
+  REAL, ALLOCATABLE :: o3_out2_glo     (:,:,:,:) !         (nbp_lat,:,ntim_ou,:)
+  REAL, ALLOCATABLE :: o3_out          (:,:,:,:) !         (nbp_lat,:,ntim_ou,:)
 ! Dimension number  | Interval                | Contains  | For variables:
 !   1 (longitude)   | [rlonu(i-1), rlonu(i)]  | rlonv(i)  | all
@@ -116,282 +136,469 @@
   INTEGER, ALLOCATABLE :: sta(:), cnt(:)
   CHARACTER(LEN=80) :: sub, dim_nam, msg
-!-------------------------------------------------------------------------------
-  sub="regr_horiz_time_climoz"
-  WRITE(lunout,*)"Call sequence information: "//TRIM(sub)
-  CALL assert(read_climoz == 1 .OR. read_climoz == 2, "regr_lat_time_climoz")
-
-  CALL  NF95_OPEN("climoz.nc"  , NF90_NOWRITE, fID_in)
-  lprev=NF90_OPEN("climoz_m.nc", NF90_NOWRITE, fID_in_m)==NF90_NOERR
-  lnext=NF90_OPEN("climoz_p.nc", NF90_NOWRITE, fID_in_p)==NF90_NOERR
-
-  !--- Get coordinates from the input file. Converts lon/lat in radians.
-  !    Few inversions because "regr_conserv" and gcm need ascending vectors.
-  CALL NF95_INQ_VARID(fID_in, vars_in(1), varid)
-  CALL NF95_INQUIRE_VARIABLE(fID_in, varid, dimids=dIDs, ndims=ndims)
-  l3D=ndims==4; l2D=ndims==3
-  IF(l3D) WRITE(lunout,*)"Input files contain full 3D ozone fields."
-  IF(l2D) WRITE(lunout,*)"Input files contain zonal 2D ozone fields."
-  DO i=1,ndims
-    CALL NF95_INQUIRE_DIMENSION(fID_in, dIDs(i), name=dim_nam, nclen=dln)
-    CALL NF95_INQ_VARID(fID_in, dim_nam, varid)
-    ii=i; IF(l2D) ii=i+1                              !--- ndims==3:NO LONGITUDE 
-    SELECT CASE(ii)
-      CASE(1)                                         !--- LONGITUDE
-        CALL NF95_GW_VAR(fID_in, varid, lon_in)
-        ldec_lon=lon_in(1)>lon_in(dln); IF(ldec_lon) lon_in=lon_in(dln:1:-1)
-        nlon_in=dln; lon_in=lon_in*deg2rad
-      CASE(2)                                         !--- LATITUDE
-        CALL NF95_GW_VAR(fID_in, varid, lat_in)
-        ldec_lat=lat_in(1)>lat_in(dln); IF(ldec_lat) lat_in=lat_in(dln:1:-1)
-        nlat_in=dln; lat_in=lat_in*deg2rad
-      CASE(3)                                         !--- PRESSURE LEVELS
-        CALL NF95_GW_VAR(fID_in, varid, lev_in)
-        ldec_lev=lev_in(1)>lev_in(dln); IF(ldec_lev) lev_in=lev_in(dln:1:-1)
-        nlev_in=dln
-        CALL NF95_GET_ATT(fID_in, varid, "units", press_unit)
-        k=LEN_TRIM(press_unit)
-        DO WHILE(ICHAR(press_unit(k:k))==0)
-          press_unit(k:k)=' '; k=LEN_TRIM(press_unit) !--- REMOVE NULL END CHAR
-        END DO
-        IF(press_unit ==  "Pa") THEN
-          lev_in = lev_in/100.                        !--- CONVERT TO hPa
-        ELSE IF(press_unit /= "hPa") THEN
-          CALL abort_physic(sub, "the only recognized units are Pa and hPa.",1)
+  REAL :: null_array(0)
+  LOGICAL,SAVE :: first=.TRUE.
+!$OMP THREADPRIVATE(first)  
+  REAL, ALLOCATABLE :: test_o3_in(:,:)
+  REAL, ALLOCATABLE :: test_o3_out(:)
+
+
+  IF (grid_type==unstructured) THEN 
+    IF (first) THEN
+      IF (is_master) THEN
+        ALLOCATE(latitude_glo(klon_glo))
+        ALLOCATE(ind_cell_glo_glo(klon_glo))
+      ELSE
+        ALLOCATE(latitude_glo(0))
+        ALLOCATE(ind_cell_glo_glo(0))
+      ENDIF
+      CALL gather(latitude_deg,  latitude_glo)
+      CALL gather(ind_cell_glo,  ind_cell_glo_glo)
+    ENDIF 
+  ENDIF
+    
+  IF (is_omp_master) THEN
+    nlat_ou=nbp_lat
+    nlon_ou=nbp_lon
+    
+   !-------------------------------------------------------------------------------
+    IF (is_mpi_root) THEN
+      sub="regr_horiz_time_climoz"
+      WRITE(lunout,*)"Call sequence information: "//TRIM(sub)
+      CALL assert(read_climoz == 1 .OR. read_climoz == 2, "regr_lat_time_climoz")
+
+      CALL  NF95_OPEN("climoz.nc"  , NF90_NOWRITE, fID_in)
+      lprev=NF90_OPEN("climoz_m.nc", NF90_NOWRITE, fID_in_m)==NF90_NOERR
+      lnext=NF90_OPEN("climoz_p.nc", NF90_NOWRITE, fID_in_p)==NF90_NOERR
+
+      !--- Get coordinates from the input file. Converts lon/lat in radians.
+      !    Few inversions because "regr_conserv" and gcm need ascending vectors.
+      CALL NF95_INQ_VARID(fID_in, vars_in(1), varid)
+      CALL NF95_INQUIRE_VARIABLE(fID_in, varid, dimids=dIDs, ndims=ndims)
+      l3D=ndims==4; l2D=ndims==3
+      IF(l3D) WRITE(lunout,*)"Input files contain full 3D ozone fields."
+      IF(l2D) WRITE(lunout,*)"Input files contain zonal 2D ozone fields."
+      DO i=1,ndims
+        CALL NF95_INQUIRE_DIMENSION(fID_in, dIDs(i), name=dim_nam, nclen=dln)
+        CALL NF95_INQ_VARID(fID_in, dim_nam, varid)
+        ii=i; IF(l2D) ii=i+1                              !--- ndims==3:NO LONGITUDE 
+        SELECT CASE(ii)
+          CASE(1)                                         !--- LONGITUDE
+            CALL NF95_GW_VAR(fID_in, varid, lon_in)
+            ldec_lon=lon_in(1)>lon_in(dln); IF(ldec_lon) lon_in=lon_in(dln:1:-1)
+            nlon_in=dln; lon_in=lon_in*deg2rad
+          CASE(2)                                         !--- LATITUDE
+            CALL NF95_GW_VAR(fID_in, varid, lat_in)
+            ldec_lat=lat_in(1)>lat_in(dln); IF(ldec_lat) lat_in=lat_in(dln:1:-1)
+            nlat_in=dln; lat_in=lat_in*deg2rad
+          CASE(3)                                         !--- PRESSURE LEVELS
+            CALL NF95_GW_VAR(fID_in, varid, lev_in)
+            ldec_lev=lev_in(1)>lev_in(dln); IF(ldec_lev) lev_in=lev_in(dln:1:-1)
+            nlev_in=dln
+            CALL NF95_GET_ATT(fID_in, varid, "units", press_unit)
+            k=LEN_TRIM(press_unit)
+            DO WHILE(ICHAR(press_unit(k:k))==0)
+              press_unit(k:k)=' '; k=LEN_TRIM(press_unit) !--- REMOVE NULL END CHAR
+            END DO
+            IF(press_unit ==  "Pa") THEN
+              lev_in = lev_in/100.                        !--- CONVERT TO hPa
+            ELSE IF(press_unit /= "hPa") THEN
+              CALL abort_physic(sub, "the only recognized units are Pa and hPa.",1)
+            END IF
+          CASE(4)                                         !--- TIME
+            CALL NF95_INQUIRE_DIMENSION(fID_in, dIDs(i), nclen=nmth_in)
+            cal_in='gregorian'
+            IF(NF90_GET_ATT(fID_in, varid, 'calendar', cal_in)/=NF90_NOERR)        &  
+            WRITE(lunout,*)'WARNING: missing "calendar" attribute for "'//       &
+            TRIM(dim_nam)//'" in "climoz.nc". Choosing default: "gregorian".'
+            k=LEN_TRIM(cal_in)
+            DO WHILE(ICHAR(cal_in(k:k))==0)
+              cal_in(k:k)=' '; k=LEN_TRIM(cal_in)         !--- REMOVE NULL END CHAR
+            END DO
+        END SELECT
+      END DO
+
+      !--- Prepare quantities for time interpolation
+      tmidmonth=mid_month(annee_ref, cal_in)
+      IF(interpt) THEN
+        ntim_ou=ioget_year_len(annee_ref)
+        ALLOCATE(tmidday(ntim_ou))
+        tmidday=[(REAL(k)-0.5,k=1,ntim_ou)]
+        CALL ioget_calendar(cal_ou)
+      ELSE
+        ntim_ou=14
+        cal_ou=cal_in
+      END IF
+    ENDIF
+
+    IF (grid_type==unstructured) THEN
+      CALL bcast_mpi(nlon_in)
+      CALL bcast_mpi(nlat_in)
+      CALL bcast_mpi(nlev_in)
+      CALL bcast_mpi(l3d)
+      CALL bcast_mpi(tmidmonth)
+      CALL bcast_mpi(tmidday)
+      CALL bcast_mpi(ntim_ou)
+
+#ifdef CPP_XIOS    
+      IF (is_mpi_root) THEN
+        CALL xios_set_domain_attr("domain_climoz",nj_glo=nlat_in, nj=nlat_in, jbegin=0, latvalue_1d=lat_in/deg2rad)
+        IF (l3D) THEN
+          CALL xios_set_domain_attr("domain_climoz",ni_glo=nlon_in, ni=nlon_in, ibegin=0, lonvalue_1d=lon_in/deg2rad)
+        ELSE
+          CALL xios_set_domain_attr("domain_climoz",ni_glo=8, ni=8, ibegin=0, lonvalue_1d = (/ 0.,45.,90.,135.,180.,225.,270., 315. /))
+        ENDIF
+      ELSE
+        CALL xios_set_domain_attr("domain_climoz",nj_glo=nlat_in, nj=0, jbegin=0, latvalue_1d=null_array )
+        IF (l3D) THEN
+          CALL xios_set_domain_attr("domain_climoz",ni_glo=nlon_in, ni=0, ibegin=0, lonvalue_1d=null_array)
+        ELSE
+          CALL xios_set_domain_attr("domain_climoz",ni_glo=8, ni=0, ibegin=0, lonvalue_1d=null_array)
+        ENDIF
+      ENDIF
+      CALL  xios_set_axis_attr("axis_climoz", n_glo=nlev_in)
+      CALL  xios_set_axis_attr("time_axis_climoz", n_glo=ntim_ou)
+      CALL  xios_set_axis_attr("time_axis_climoz", n_glo=ntim_ou)
+      CALL  xios_set_axis_attr("tr_climoz", n_glo=read_climoz)
+      CALL  xios_set_field_attr("tro3_out", enabled=.TRUE.)
+      CALL  xios_set_field_attr("tro3_out", enabled=.TRUE.)
+#endif
+      
+      IF (first) THEN
+        first=.FALSE.
+        RETURN
+      ENDIF
+    ENDIF
+    
+    
+    IF (is_mpi_root) THEN     
+      !--- Longitudes management:
+      !    * Need to shift data if the origin of input file longitudes /= -pi
+      !    * Need to add some margin in longitude to ensure input interval contains
+      !      all the output intervals => at least one longitudes slice has to be
+      !      duplicated, possibly more for undersampling.
+      IF(l3D) THEN
+        IF (grid_type==unstructured) THEN
+          dx2=0
+        ELSE
+          !--- Compute input edges longitudes vector (no end point yet)
+          ALLOCATE(v1(nlon_in+1))
+          v1(1)=(lon_in(nlon_in)+lon_in(1))/2.-pi
+          FORALL(i=2:nlon_in) v1(i)=(lon_in(i-1)+lon_in(i))/2.
+          v1(nlon_in+1)=v1(1)+2.*pi
+          DEALLOCATE(lon_in)
+
+          !--- Shift input longitudes vector until it contains first output point boundslon_reg(1,west)
+          v1=v1+2*pi*REAL(FLOOR((boundslon_reg(1,west)-v1(1))/(2.*pi)))
+
+          !--- Ensure first input longitudes interval contains first output point boundslon_reg(1,west)
+          dx1=locate(v1,boundslon_reg(1,west))-1
+          v1=CSHIFT(v1,SHIFT=dx1,DIM=1) 
+          v1(nlon_in-dx1+2:)=v1(nlon_in-dx1+2:)+2.*pi
+    
+          !--- Extend input longitudes vector until last interval contains boundslon_reg(nlat_ou,east)
+          dx2=0; DO WHILE(v1(1+dx2)+2.*pi<=boundslon_reg(nlon_ou,east)); dx2=dx2+1; END DO
+
+          !--- Final edges longitudes vector (with margin and end point)
+          ALLOCATE(lon_in_edge(nlon_in+dx2+1)); lon_in_edge=[v1,v1(2:1+dx2)+2.*pi]
+          DEALLOCATE(v1)
+        ENDIF
+      END IF
+
+      !--- Compute sinus of intervals edges latitudes:
+      ALLOCATE(sinlat_in_edge(nlat_in+1))
+      sinlat_in_edge(1) = -1. ; sinlat_in_edge(nlat_in+1) = 1.
+      FORALL(j=2:nlat_in) sinlat_in_edge(j)=SIN((lat_in(j-1)+lat_in(j))/2.)
+      DEALLOCATE(lat_in)
+
+
+
+      !--- Check for contiguous years:
+      ib=0; ie=13
+      IF(nmth_in == 14) THEN; lprev=.FALSE.; lnext=.FALSE.
+        WRITE(lunout,*)'Using 14 months ozone climatology "climoz.nc"...'
+      ELSE  
+        IF(     lprev) WRITE(lunout,*)'Using "climoz_m.nc" last record (previous year).'
+        IF(.NOT.lprev) WRITE(lunout,*)"No previous year file ; assuming periodicity."
+        IF(     lnext) WRITE(lunout,*)'Using "climoz_p.nc" first record (next year).'
+        IF(.NOT.lnext) WRITE(lunout,*)"No next year file ; assuming periodicity."
+        IF(.NOT.lprev) ib=1
+        IF(.NOT.lnext) ie=12
+      END IF
+      ALLOCATE(sta(ndims),cnt(ndims)); sta(:)=1  
+      IF(l3D) cnt=[nlon_in,nlat_in,nlev_in,1]
+      IF(l2D) cnt=[        nlat_in,nlev_in,1]  
+      IF(l3D) ALLOCATE(o3_in3(nlon_in+dx2,nlat_in,nlev_in,ib:ie,read_climoz))
+      IF(l2D) ALLOCATE(o3_in2(            nlat_in,nlev_in,ib:ie,read_climoz))
+
+      !--- Read full current file and one record each available contiguous file
+      DO iv=1,read_climoz
+        msg=TRIM(sub)//" NF90_GET_VAR "//TRIM(vars_in(iv))
+        CALL NF95_INQ_VARID(fID_in, vars_in(1), vID_in(iv))
+        IF(l3D) ncerr=NF90_GET_VAR(fID_in, vID_in(iv), o3_in3(1:nlon_in,:,:,1:12,iv))
+        IF(l2D) ncerr=NF90_GET_VAR(fID_in, vID_in(iv), o3_in2(          :,:,1:12,iv))
+        CALL handle_err(TRIM(msg), ncerr, fID_in)
+        IF(lprev) THEN; sta(ndims)=12  
+          CALL NF95_INQ_VARID(fID_in_m, vars_in(1), vID_in(iv))
+          IF(l3D) ncerr=NF90_GET_VAR(fID_in_m,vID_in(iv),o3_in3(1:nlon_in,:,:, 0,iv),sta,cnt)
+          IF(l2d) ncerr=NF90_GET_VAR(fID_in_m,vID_in(iv),o3_in2(          :,:, 0,iv),sta,cnt)
+          CALL handle_err(TRIM(msg)//" previous", ncerr, fID_in_m)
         END IF
-      CASE(4)                                         !--- TIME
-        CALL NF95_INQUIRE_DIMENSION(fID_in, dIDs(i), nclen=nmth_in)
-        cal_in='gregorian'
-        IF(NF90_GET_ATT(fID_in, varid, 'calendar', cal_in)/=NF90_NOERR)        &
-          WRITE(lunout,*)'WARNING: missing "calendar" attribute for "'//       &
-          TRIM(dim_nam)//'" in "climoz.nc". Choosing default: "gregorian".'
-        k=LEN_TRIM(cal_in)
-        DO WHILE(ICHAR(cal_in(k:k))==0)
-          cal_in(k:k)=' '; k=LEN_TRIM(cal_in)         !--- REMOVE NULL END CHAR
-        END DO
-    END SELECT
-  END DO
-
-  !--- Longitudes management:
-  !    * Need to shift data if the origin of input file longitudes /= -pi
-  !    * Need to add some margin in longitude to ensure input interval contains
-  !      all the output intervals => at least one longitudes slice has to be
-  !      duplicated, possibly more for undersampling.
-  IF(l3D) THEN
-    !--- Compute input edges longitudes vector (no end point yet)
-    ALLOCATE(v1(nlon_in+1))
-    v1(1)=(lon_in(nlon_in)+lon_in(1))/2.-pi
-    FORALL(i=2:nlon_in) v1(i)=(lon_in(i-1)+lon_in(i))/2.
-    v1(nlon_in+1)=v1(1)+2.*pi
-    DEALLOCATE(lon_in)
-
-    !--- Shift input longitudes vector until it contains first output point boundslon_reg(1,west)
-    v1=v1+2*pi*REAL(FLOOR((boundslon_reg(1,west)-v1(1))/(2.*pi)))
-
-    !--- Ensure first input longitudes interval contains first output point boundslon_reg(1,west)
-    dx1=locate(v1,boundslon_reg(1,west))-1
-    v1=CSHIFT(v1,SHIFT=dx1,DIM=1); v1(nlon_in-dx1+2:)=v1(nlon_in-dx1+2:)+2.*pi
-
-    !--- Extend input longitudes vector until last interval contains boundslon_reg(nlon_ou,east)
-    dx2=0; DO WHILE(v1(1+dx2)+2.*pi<=boundslon_reg(nlon_ou,east)); dx2=dx2+1; END DO
-
-    !--- Final edges longitudes vector (with margin and end point)
-    ALLOCATE(lon_in_edge(nlon_in+dx2+1)); lon_in_edge=[v1,v1(2:1+dx2)+2.*pi]
-    DEALLOCATE(v1)
-  END IF
-
-  !--- Compute sinus of intervals edges latitudes:
-  ALLOCATE(sinlat_in_edge(nlat_in+1))
-  sinlat_in_edge(1) = -1. ; sinlat_in_edge(nlat_in+1) = 1.
-  FORALL(j=2:nlat_in) sinlat_in_edge(j)=SIN((lat_in(j-1)+lat_in(j))/2.)
-  DEALLOCATE(lat_in)
-
-  !--- Prepare quantities for time interpolation
-  tmidmonth=mid_month(anneeref, cal_in)
-  IF(interpt) THEN
-    ntim_ou=ioget_year_len(anneeref)
-    ALLOCATE(tmidday(ntim_ou))
-    tmidday=[(REAL(k)-0.5,k=1,ntim_ou)]
-    CALL ioget_calendar(cal_ou)
-  ELSE
-    ntim_ou=14
-    cal_ou=cal_in
-  END IF
-
-  !--- Create the output file and get the variable IDs:
-  CALL prepare_out(fID_in,nlev_in,ntim_ou, fID_ou,levID_ou,timID_ou,vID_ou, &
-                   ndims, cal_ou)
-
-  !--- Write remaining coordinate variables:
-  CALL NF95_PUT_VAR(fID_ou, levID_ou, lev_in); DEALLOCATE(lev_in)
-  IF(     interpt) CALL NF95_PUT_VAR(fID_ou, timID_ou, tmidday)
-  IF(.NOT.interpt) CALL NF95_PUT_VAR(fID_ou, timID_ou, tmidmonth)
-
-  !--- Check for contiguous years:
-  ib=0; ie=13
-  IF(nmth_in == 14) THEN; lprev=.FALSE.; lnext=.FALSE.
-    WRITE(lunout,*)'Using 14 months ozone climatology "climoz.nc"...'
-  ELSE
-    IF(     lprev) WRITE(lunout,*)'Using "climoz_m.nc" last record (previous year).'
-    IF(.NOT.lprev) WRITE(lunout,*)"No previous year file ; assuming periodicity."
-    IF(     lnext) WRITE(lunout,*)'Using "climoz_p.nc" first record (next year).'
-    IF(.NOT.lnext) WRITE(lunout,*)"No next year file ; assuming periodicity."
-    IF(.NOT.lprev) ib=1
-    IF(.NOT.lnext) ie=12
-  END IF
-  ALLOCATE(sta(ndims),cnt(ndims)); sta(:)=1
-  IF(l3D) cnt=[nlon_in,nlat_in,nlev_in,1]
-  IF(l2D) cnt=[        nlat_in,nlev_in,1]
-  IF(l3D) ALLOCATE(o3_in3(nlon_in+dx2,nlat_in,nlev_in,ib:ie,read_climoz))
-  IF(l2D) ALLOCATE(o3_in2(            nlat_in,nlev_in,ib:ie,read_climoz))
-
-  !--- Read full current file and one record each available contiguous file
-  DO iv=1,read_climoz
-    msg=TRIM(sub)//" NF90_GET_VAR "//TRIM(vars_in(iv))
-    CALL NF95_INQ_VARID(fID_in, vars_in(1), vID_in(iv))
-    IF(l3D) ncerr=NF90_GET_VAR(fID_in, vID_in(iv), o3_in3(1:nlon_in,:,:,1:12,iv))
-    IF(l2D) ncerr=NF90_GET_VAR(fID_in, vID_in(iv), o3_in2(          :,:,1:12,iv))
-    CALL handle_err(TRIM(msg), ncerr, fID_in)
-    IF(lprev) THEN; sta(ndims)=12
-      CALL NF95_INQ_VARID(fID_in_m, vars_in(1), vID_in(iv))
-      IF(l3D) ncerr=NF90_GET_VAR(fID_in_m,vID_in(iv),o3_in3(1:nlon_in,:,:, 0,iv),sta,cnt)
-      IF(l2d) ncerr=NF90_GET_VAR(fID_in_m,vID_in(iv),o3_in2(          :,:, 0,iv),sta,cnt)
-      CALL handle_err(TRIM(msg)//" previous", ncerr, fID_in_m)
+        IF(lnext) THEN; sta(ndims)=1  
+          CALL NF95_INQ_VARID(fID_in_p, vars_in(1), vID_in(iv))
+          IF(l3D) ncerr=NF90_GET_VAR(fID_in_p,vID_in(iv),o3_in3(1:nlon_in,:,:,13,iv),sta,cnt)
+          IF(l2D) ncerr=NF90_GET_VAR(fID_in_p,vID_in(iv),o3_in2(          :,:,13,iv),sta,cnt)
+          CALL handle_err(TRIM(msg)//" next", ncerr, fID_in_p)
+        END IF
+      END DO
+      IF(lprev.OR.lnext) DEALLOCATE(sta,cnt)
+      IF(lprev) CALL NF95_CLOSE(fID_in_m)
+      IF(lnext) CALL NF95_CLOSE(fID_in_p)
+
+      !--- Revert decreasing coordinates vector
+      IF(l3D) THEN
+        IF(ldec_lon) o3_in3(1:nlon_in,:,:,:,:) = o3_in3(nlon_in:1:-1,:,:,:,:)
+        IF(ldec_lat) o3_in3 = o3_in3(:,nlat_in:1:-1,:,:,:)
+        IF(ldec_lev) o3_in3 = o3_in3(:,:,nlev_in:1:-1,:,:)
+        
+        IF (grid_type /= unstructured) THEN
+          !--- Shift values for longitude and duplicate some longitudes slices
+          o3_in3(1:nlon_in,:,:,:,:)=CSHIFT(o3_in3(1:nlon_in,:,:,:,:),SHIFT=dx1,DIM=1)
+          o3_in3(nlon_in+1:nlon_in+dx2,:,:,:,:)=o3_in3(1:dx2,:,:,:,:)
+        ENDIF
+      ELSE
+        IF(ldec_lat) o3_in2 = o3_in2(  nlat_in:1:-1,:,:,:)
+        IF(ldec_lev) o3_in2 = o3_in2(  :,nlev_in:1:-1,:,:)
+      END IF
+
+     !--- Deal with missing values 
+      DO m=1, read_climoz
+        WRITE(msg,'(a,i0)')"regr_lat_time_climoz: field Nr.",m
+        IF(NF90_GET_ATT(fID_in,vID_in(m),"missing_value",NaN)/= NF90_NOERR) THEN
+          IF(NF90_GET_ATT(fID_in, vID_in(m),"_FillValue",NaN)/= NF90_NOERR) THEN
+            WRITE(lunout,*)TRIM(msg)//": no missing value attribute found."; CYCLE
+          END IF
+        END IF
+        WRITE(lunout,*)TRIM(msg)//": missing value attribute found."
+        WRITE(lunout,*)"Trying to fill in NaNs ; a full field would be better."
+
+        !--- Check top layer contains no NaNs & search NaNs from top to ground
+        msg=TRIM(sub)//": NaNs in top layer !"
+        IF(l3D) THEN
+          IF(ANY(o3_in3(:,:,1,:,m)==NaN)) CALL abort_physic(sub,msg,1)
+          DO k = 2,nlev_in
+            WHERE(o3_in3(:,:,k,:,m)==NaN) o3_in3(:,:,k,:,m)=o3_in3(:,:,k-1,:,m)
+          END DO
+        ELSE
+          IF(ANY(o3_in2(  :,1,:,m)==NaN)) THEN
+            WRITE(lunout,*)msg
+            !--- Fill in latitudes where all values are missing
+            DO l=1,nmth_in
+              !--- Next to south pole
+              j=1;       DO WHILE(o3_in2(j,1,l,m)==NaN); j=j+1; END DO
+              IF(j>1) &
+                o3_in2(:j-1,:,l,m)=SPREAD(o3_in2(j,:,l,m),DIM=1,ncopies=j-1)
+              !--- Next to north pole
+              j=nlat_in; DO WHILE(o3_in2(j,1,l,m)==NaN); j=j+1; END DO
+              IF(j<nlat_in) &
+                o3_in2(j+1:,:,l,m)=SPREAD(o3_in2(j,:,l,m),DIM=1,ncopies=nlat_in-j)
+            END DO
+          END IF
+
+          !--- Fill in high latitudes missing values
+          !--- Highest level been filled-in, so has always valid values.
+          DO k = 2,nlev_in
+            WHERE(o3_in2(:,k,:,m)==NaN) o3_in2(:,k,:,m)=o3_in2(:,k-1,:,m)
+          END DO
+        END IF
+      END DO
+
+    ENDIF
+    
+    !=============================================================================
+    IF(l3D) THEN                                                   !=== 3D FIELDS
+    !=============================================================================
+     IF (grid_type==unstructured) THEN
+#ifdef CPP_XIOS
+       nlat_ou=klon_mpi
+       
+       IF (is_mpi_root) THEN 
+         ALLOCATE(o3_in3bis(nlon_in,nlat_in,nlev_in,0:13,read_climoz)) 
+         o3_in3bis(:,:,:,ib:ie,:)=o3_in3(1:nlon_in,:,:,ib:ie,:)
+       ELSE
+         ALLOCATE(o3_in3bis(0,0,0,0,read_climoz))
+       ENDIF
+       ALLOCATE(o3_regr_lonlat(1, nlat_ou, nlev_in, 0:13, read_climoz))
+       
+       CALL xios_send_field("tro3_in",o3_in3bis(:,:,:,:,:))
+       CALL xios_recv_field("tro3_out",o3_regr_lonlat(1,:,:,:,:))
+#endif
+     ELSE
+          
+       !--- Regrid in longitude
+        ALLOCATE(o3_regr_lon(nlon_ou, nlat_in, nlev_in, ie-ib+1, read_climoz))
+        CALL regr_conserv(1, o3_in3, xs = lon_in_edge,                             &
+                            xt = [boundslon_reg(1,west),boundslon_reg(:,east)],    &
+                            vt = o3_regr_lon, slope = slopes(1,o3_in3, lon_in_edge))
+        DEALLOCATE(o3_in3)
+
+        !--- Regrid in latitude: averaging with respect to SIN(lat) is
+        !                        equivalent to weighting by COS(lat)
+        !--- (inverted indices in "o3_regr_lonlat" because "rlatu" is decreasing)
+        ALLOCATE(o3_regr_lonlat(nlon_ou, nlat_ou, nlev_in, 0:13, read_climoz))
+        CALL regr_conserv(2, o3_regr_lon, xs = sinlat_in_edge,                     &
+                        xt = [- 1., SIN(boundslat_reg(nlat_ou-1:1:-1,south)), 1.], &
+                        vt = o3_regr_lonlat(:,nlat_ou:1:- 1,:,ib:ie,:),            &
+                   slope = slopes(2,o3_regr_lon, sinlat_in_edge))
+        DEALLOCATE(o3_regr_lon)
+
+     ENDIF
+
+     !--- Duplicate previous/next record(s) if they are not available
+     IF(.NOT.lprev) o3_regr_lonlat(:,:,:, 0,:) = o3_regr_lonlat(:,:,:,12,:)
+     IF(.NOT.lnext) o3_regr_lonlat(:,:,:,13,:) = o3_regr_lonlat(:,:,:, 1,:)
+      
+     !--- Regrid in time by linear interpolation:
+     ALLOCATE(o3_out3(nlon_ou, nlat_ou, nlev_in, ntim_ou, read_climoz))
+     IF(     interpt) CALL regr_lint(4,o3_regr_lonlat,tmidmonth,tmidday,o3_out3)
+     IF(.NOT.interpt) o3_out3=o3_regr_lonlat
+     DEALLOCATE(o3_regr_lonlat)
+
+     nlat_ou=nbp_lat
+     IF (grid_type==unstructured) THEN
+#ifdef CPP_XIOS
+       CALL xios_send_field('o3_out',o3_out3)
+       ndims=3 
+       ALLOCATE(o3_out3_glo(nlat_ou, nlev_in, ntim_ou, read_climoz))
+       CALL gather_mpi(o3_out3(1,:,:,:,:), o3_out3_glo)
+#endif
+     ENDIF
+
+    !--- Create the output file and get the variable IDs:
+    CALL prepare_out(fID_in,nlev_in,ntim_ou, fID_ou,levID_ou,timID_ou,vID_ou, &
+                     ndims, cal_ou)
+
+    IF (is_mpi_root) THEN
+      !--- Write remaining coordinate variables:
+      CALL NF95_PUT_VAR(fID_ou, levID_ou, lev_in); DEALLOCATE(lev_in)
+      IF(     interpt) CALL NF95_PUT_VAR(fID_ou, timID_ou, tmidday)
+      IF(.NOT.interpt) CALL NF95_PUT_VAR(fID_ou, timID_ou, tmidmonth)
+
+      !--- Write to file (the order of "rlatu" is inverted in the output file):
+        IF (grid_type==unstructured) THEN
+
+          ALLOCATE(o3_out(nlat_ou, nlev_in, ntim_ou, read_climoz))
+          DO i=1,klon_glo
+            o3_out(ind_cell_glo_glo(i),:,:,:)=o3_out3_glo(i,:,:,:)
+          ENDDO
+
+          DO m = 1, read_climoz
+            CALL NF95_PUT_VAR(fID_ou, vID_ou(m), o3_out(nlat_ou:1:-1,:,:,m))
+          END DO
+          
+        ELSE
+          DO m = 1, read_climoz
+            CALL NF95_PUT_VAR(fID_ou, vID_ou(m), o3_out3(:,nlat_ou:1:-1,:,:,m))
+          END DO
+      ENDIF
+      CALL NF95_CLOSE(fID_ou)
+
+
+    ENDIF
+
+
+    !=============================================================================
+    ELSE                                                         !=== ZONAL FIELDS
+    !=============================================================================
+   
+     IF (grid_type==unstructured) THEN
+#ifdef CPP_XIOS
+       nlat_ou=klon_mpi
+
+       IF (is_mpi_root) THEN 
+         ALLOCATE(o3_in2bis(8,nlat_in,nlev_in,0:13,read_climoz)) 
+         o3_in2bis(:,:,:,ib:ie,:)=SPREAD(o3_in2,1,8)
+       ELSE
+         ALLOCATE(o3_in2bis(0,0,0,0,read_climoz))
+       ENDIF
+       ALLOCATE(o3_regr_lat(nlat_ou, nlev_in, 0:13, read_climoz))
+       CALL xios_send_field("tro3_in",o3_in2bis(:,:,:,:,:))
+       CALL xios_recv_field("tro3_out",o3_regr_lat(:,:,:,:))
+       IF(.NOT.lprev) o3_regr_lat(:,:, 0, :) = o3_regr_lat(:,:,12,:)
+       IF(.NOT.lnext) o3_regr_lat(:,:,13, :) = o3_regr_lat(:,:, 1,:)
+#endif       
+     
+     ELSE 
+        !--- Regrid in latitude: averaging with respect to SIN(lat) is
+        !                        equivalent to weighting by COS(lat)
+        !--- (inverted indices in "o3_regr_lat" because "rlatu" is decreasing)
+        ALLOCATE(o3_regr_lat(nlat_ou, nlev_in, 0:13, read_climoz))
+        CALL regr_conserv(1, o3_in2, xs = sinlat_in_edge,                          &
+                        xt = [- 1., SIN(boundslat_reg(nlat_ou-1:1:-1,south)), 1.], &
+                        vt = o3_regr_lat(nlat_ou:1:- 1,:,ib:ie,:),                 &
+                     slope = slopes(1,o3_in2, sinlat_in_edge))
+        DEALLOCATE(o3_in2)
+
+        !--- Duplicate previous/next record(s) if they are not available
+        IF(.NOT.lprev) o3_regr_lat(:,:, 0,:) = o3_regr_lat(:,:,12,:)
+        IF(.NOT.lnext) o3_regr_lat(:,:,13,:) = o3_regr_lat(:,:, 1,:)
+
+     ENDIF
+     
+      !--- Regrid in time by linear interpolation:
+      ALLOCATE(o3_out2(nlat_ou, nlev_in, ntim_ou, read_climoz))
+      IF(     interpt) CALL regr_lint(3,o3_regr_lat, tmidmonth, tmidday, o3_out2)
+      IF(.NOT.interpt) o3_out2=o3_regr_lat
+      DEALLOCATE(o3_regr_lat)
+
+      nlat_ou=nbp_lat
+    
+      IF (grid_type==unstructured) THEN
+        ndims=3 
+        ALLOCATE(o3_out2_glo(nlat_ou, nlev_in, ntim_ou, read_climoz))
+        CALL gather_mpi(o3_out2, o3_out2_glo)
+      ENDIF
+      
+      !--- Create the output file and get the variable IDs:
+      CALL prepare_out(fID_in,nlev_in,ntim_ou, fID_ou,levID_ou,timID_ou,vID_ou, &
+                         ndims, cal_ou)
+
+      IF (is_mpi_root) THEN
+      
+        !--- Write remaining coordinate variables:
+        CALL NF95_PUT_VAR(fID_ou, levID_ou, lev_in); DEALLOCATE(lev_in)
+        IF(     interpt) CALL NF95_PUT_VAR(fID_ou, timID_ou, tmidday)
+        IF(.NOT.interpt) CALL NF95_PUT_VAR(fID_ou, timID_ou, tmidmonth)
+
+        IF (grid_type==unstructured) THEN
+
+          ALLOCATE(o3_out3_glo(nlat_ou, nlev_in, ntim_ou, read_climoz))
+          DO i=1,klon_glo
+            o3_out(ind_cell_glo_glo(i),:,:,:)=o3_out2_glo(i,:,:,:)
+          ENDDO
+
+
+          DO m = 1, read_climoz
+            CALL NF95_PUT_VAR(fID_ou, vID_ou(m), o3_out(nlat_ou:1:-1,:,:,m))
+          END DO
+        ELSE
+          !--- Write to file (the order of "rlatu" is inverted in the output file):
+          DO m = 1, read_climoz
+            CALL NF95_PUT_VAR(fID_ou, vID_ou(m), o3_out2(nlat_ou:1:-1,:,:,m))
+          END DO
+        ENDIF
+        
+        CALL NF95_CLOSE(fID_ou)
+      
+      ENDIF
+
+    !=============================================================================
     END IF
-    IF(lnext) THEN; sta(ndims)=1
-      CALL NF95_INQ_VARID(fID_in_p, vars_in(1), vID_in(iv))
-      IF(l3D) ncerr=NF90_GET_VAR(fID_in_p,vID_in(iv),o3_in3(1:nlon_in,:,:,13,iv),sta,cnt)
-      IF(l2D) ncerr=NF90_GET_VAR(fID_in_p,vID_in(iv),o3_in2(          :,:,13,iv),sta,cnt)
-      CALL handle_err(TRIM(msg)//" next", ncerr, fID_in_p)
-    END IF
-  END DO
-  IF(lprev.OR.lnext) DEALLOCATE(sta,cnt)
-  IF(lprev) CALL NF95_CLOSE(fID_in_m)
-  IF(lnext) CALL NF95_CLOSE(fID_in_p)
-
-  !--- Revert decreasing coordinates vector
-  IF(l3D) THEN
-    IF(ldec_lon) o3_in3(1:nlon_in,:,:,:,:) = o3_in3(nlon_in:1:-1,:,:,:,:)
-    IF(ldec_lat) o3_in3 = o3_in3(:,nlat_in:1:-1,:,:,:)
-    IF(ldec_lev) o3_in3 = o3_in3(:,:,nlev_in:1:-1,:,:)
-    !--- Shift values for longitude and duplicate some longitudes slices
-    o3_in3(1:nlon_in,:,:,:,:)=CSHIFT(o3_in3(1:nlon_in,:,:,:,:),SHIFT=dx1,DIM=1)
-    o3_in3(nlon_in+1:nlon_in+dx2,:,:,:,:)=o3_in3(1:dx2,:,:,:,:)
-  ELSE
-    IF(ldec_lat) o3_in2 = o3_in2(  nlat_in:1:-1,:,:,:)
-    IF(ldec_lev) o3_in2 = o3_in2(  :,nlev_in:1:-1,:,:)
-  END IF
-
- !--- Deal with missing values
-  DO m=1, read_climoz
-    WRITE(msg,'(a,i0)')"regr_lat_time_climoz: field Nr.",m
-    IF(NF90_GET_ATT(fID_in,vID_in(m),"missing_value",NaN)/= NF90_NOERR) THEN
-      IF(NF90_GET_ATT(fID_in, vID_in(m),"_FillValue",NaN)/= NF90_NOERR) THEN
-        WRITE(lunout,*)TRIM(msg)//": no missing value attribute found."; CYCLE
-      END IF
-    END IF
-    WRITE(lunout,*)TRIM(msg)//": missing value attribute found."
-    WRITE(lunout,*)"Trying to fill in NaNs ; a full field would be better."
-
-    !--- Check top layer contains no NaNs & search NaNs from top to ground
-    msg=TRIM(sub)//": NaNs in top layer !"
-    IF(l3D) THEN
-      IF(ANY(o3_in3(:,:,1,:,m)==NaN)) CALL abort_physic(sub,msg,1)
-      DO k = 2,nlev_in
-        WHERE(o3_in3(:,:,k,:,m)==NaN) o3_in3(:,:,k,:,m)=o3_in3(:,:,k-1,:,m)
-      END DO
-    ELSE
-      IF(ANY(o3_in2(  :,1,:,m)==NaN)) THEN
-        WRITE(lunout,*)msg
-        !--- Fill in latitudes where all values are missing
-        DO l=1,nmth_in
-          !--- Next to south pole
-          j=1;       DO WHILE(o3_in2(j,1,l,m)==NaN); j=j+1; END DO
-          IF(j>1) &
-            o3_in2(:j-1,:,l,m)=SPREAD(o3_in2(j,:,l,m),DIM=1,ncopies=j-1)
-          !--- Next to north pole
-          j=nlat_in; DO WHILE(o3_in2(j,1,l,m)==NaN); j=j+1; END DO
-          IF(j<nlat_in) &
-            o3_in2(j+1:,:,l,m)=SPREAD(o3_in2(j,:,l,m),DIM=1,ncopies=nlat_in-j)
-        END DO
-      END IF
-
-      !--- Fill in high latitudes missing values
-      !--- Highest level been filled-in, so has always valid values.
-      DO k = 2,nlev_in
-        WHERE(o3_in2(:,k,:,m)==NaN) o3_in2(:,k,:,m)=o3_in2(:,k-1,:,m)
-      END DO
-    END IF
-  END DO
-  CALL NF95_CLOSE(fID_in)
-
-  !=============================================================================
-  IF(l3D) THEN                                                   !=== 3D FIELDS
-  !=============================================================================
-    !--- Regrid in longitude
-    ALLOCATE(o3_regr_lon(nlon_ou, nlat_in, nlev_in, ie-ib+1, read_climoz))
-    CALL regr_conserv(1, o3_in3, xs = lon_in_edge,                             &
-                        xt = [boundslon_reg(1,west),boundslon_reg(:,east)],    &
-                        vt = o3_regr_lon, slope = slopes(1,o3_in3, lon_in_edge))
-    DEALLOCATE(o3_in3)
-
-    !--- Regrid in latitude: averaging with respect to SIN(lat) is
-    !                        equivalent to weighting by COS(lat)
-    !--- (inverted indices in "o3_regr_lonlat" because "rlatu" is decreasing)
-    ALLOCATE(o3_regr_lonlat(nlon_ou, nlat_ou, nlev_in, 0:13, read_climoz))
-    CALL regr_conserv(2, o3_regr_lon, xs = sinlat_in_edge,                     &
-                    xt = [- 1., SIN(boundslat_reg(nlat_ou-1:1:-1,south)), 1.], &
-                    vt = o3_regr_lonlat(:,nlat_ou:1:- 1,:,ib:ie,:),            &
-                 slope = slopes(2,o3_regr_lon, sinlat_in_edge))
-    DEALLOCATE(o3_regr_lon)
-
-    !--- Duplicate previous/next record(s) if they are not available
-    IF(.NOT.lprev) o3_regr_lonlat(:,:,:, 0,:) = o3_regr_lonlat(:,:,:,12,:)
-    IF(.NOT.lnext) o3_regr_lonlat(:,:,:,13,:) = o3_regr_lonlat(:,:,:, 1,:)
-
-    !--- Regrid in time by linear interpolation:
-    ALLOCATE(o3_out3(nlon_ou, nlat_ou, nlev_in, ntim_ou, read_climoz))
-    IF(     interpt) CALL regr_lint(4,o3_regr_lonlat,tmidmonth,tmidday,o3_out3)
-    IF(.NOT.interpt) o3_out3=o3_regr_lonlat
-    DEALLOCATE(o3_regr_lonlat)
-
-    !--- Write to file (the order of "rlatu" is inverted in the output file):
-    DO m = 1, read_climoz
-      CALL NF95_PUT_VAR(fID_ou, vID_ou(m), o3_out3(:,nlat_ou:1:-1,:,:,m))
-    END DO
-
-  !=============================================================================
-  ELSE                                                         !=== ZONAL FIELDS
-  !=============================================================================
-    !--- Regrid in latitude: averaging with respect to SIN(lat) is
-    !                        equivalent to weighting by COS(lat)
-    !--- (inverted indices in "o3_regr_lat" because "rlatu" is decreasing)
-    ALLOCATE(o3_regr_lat(nlat_ou, nlev_in, 0:13, read_climoz))
-    CALL regr_conserv(1, o3_in2, xs = sinlat_in_edge,                          &
-                    xt = [- 1., SIN(boundslat_reg(nlat_ou-1:1:-1,south)), 1.], &
-                    vt = o3_regr_lat(nlat_ou:1:- 1,:,ib:ie,:),                 &
-                 slope = slopes(1,o3_in2, sinlat_in_edge))
-    DEALLOCATE(o3_in2)
-
-    !--- Duplicate previous/next record(s) if they are not available
-    IF(.NOT.lprev) o3_regr_lat(:,:, 0,:) = o3_regr_lat(:,:,12,:)
-    IF(.NOT.lnext) o3_regr_lat(:,:,13,:) = o3_regr_lat(:,:, 1,:)
-
-    !--- Regrid in time by linear interpolation:
-    ALLOCATE(o3_out2(nlat_ou, nlev_in, ntim_ou, read_climoz))
-    IF(     interpt) CALL regr_lint(3,o3_regr_lat, tmidmonth, tmidday, o3_out2)
-    IF(.NOT.interpt) o3_out2=o3_regr_lat
-    DEALLOCATE(o3_regr_lat)
-
-    !--- Write to file (the order of "rlatu" is inverted in the output file):
-    DO m = 1, read_climoz
-      CALL NF95_PUT_VAR(fID_ou, vID_ou(m), o3_out2(nlat_ou:1:-1,:,:,m))
-    END DO
-
-  !=============================================================================
-  END IF
-  !=============================================================================
-
-  CALL NF95_CLOSE(fID_ou)
-
+    !=============================================================================
+
+    IF (is_mpi_root) CALL NF95_CLOSE(fID_in)
+
+  ENDIF ! is_omp_master
+
+  first=.FALSE.
 END SUBROUTINE regr_horiz_time_climoz
 !
@@ -408,4 +615,8 @@
 !-------------------------------------------------------------------------------
   USE regular_lonlat_mod, ONLY: lon_reg, lat_reg
+  USE regular_lonlat_mod, ONLY: lon_reg, lat_reg
+  USE mod_phys_lmdz_para, ONLY: is_mpi_root
+  USE mod_grid_phy_lmdz, ONLY: klon_glo
+!
 !-------------------------------------------------------------------------------
 ! Arguments:
@@ -419,68 +630,83 @@
   INTEGER :: dlonID, dlatID, dlevID, dtimID, dIDs(4)
   INTEGER :: vlonID, vlatID, ncerr,  is
+  REAL,ALLOCATABLE    :: latitude_glo_(:)
   CHARACTER(LEN=80) :: sub
-!-------------------------------------------------------------------------------
-  sub="prepare_out"
-  WRITE(lunout,*)"CALL sequence information: "//TRIM(sub)
-  CALL NF95_CREATE("climoz_LMDZ.nc", NF90_clobber, fID_ou)
+  INTEGER :: i
+
+
+!-------------------------------------------------------------------------------
+  
+  IF (is_mpi_root) THEN  
+    sub="prepare_out"
+    WRITE(lunout,*)"CALL sequence information: "//TRIM(sub)
+    CALL NF95_CREATE("climoz_LMDZ.nc", NF90_clobber, fID_ou)
 
   !--- Dimensions:
-  IF(ndims==4) &
-  CALL NF95_DEF_DIM(fID_ou, "rlonv", nlon_ou, dlonID)
-  CALL NF95_DEF_DIM(fID_ou, "rlatu", nlat_ou, dlatID)
-  CALL NF95_DEF_DIM(fID_ou, "plev",  nlev_in, dlevID)
-  CALL NF95_DEF_DIM(fID_ou, "time",  ntim_ou, dtimID)
-
-  !--- Define coordinate variables:
-  IF(ndims==4) &
-  CALL NF95_DEF_VAR(fID_ou, "rlonv", NF90_FLOAT, dlonID, vlonID)
-  CALL NF95_DEF_VAR(fID_ou, "rlatu", NF90_FLOAT, dlatID, vlatID)
-  CALL NF95_DEF_VAR(fID_ou, "plev",  NF90_FLOAT, dlevID, vlevID)
-  CALL NF95_DEF_VAR(fID_ou, "time",  NF90_FLOAT, dtimID, vtimID)
-  IF(ndims==4) &
-  CALL NF95_PUT_ATT(fID_ou, vlonID, "units", "degrees_east")
-  CALL NF95_PUT_ATT(fID_ou, vlatID, "units", "degrees_north")
-  CALL NF95_PUT_ATT(fID_ou, vlevID, "units", "millibar")
-  CALL NF95_PUT_ATT(fID_ou, vtimID, "units", "days since 2000-1-1")
-  IF(ndims==4) &
-  CALL NF95_PUT_ATT(fID_ou, vlonID, "standard_name", "longitude")
-  CALL NF95_PUT_ATT(fID_ou, vlatID, "standard_name", "latitude")
-  CALL NF95_PUT_ATT(fID_ou, vlevID, "standard_name", "air_pressure")
-  CALL NF95_PUT_ATT(fID_ou, vtimID, "standard_name", "time")
-  CALL NF95_PUT_ATT(fID_ou, vlevID, "long_name",     "air pressure")
-  CALL NF95_PUT_ATT(fID_ou, vtimID, "calendar",      cal_ou)
+    IF(ndims==4) &
+    CALL NF95_DEF_DIM(fID_ou, "rlonv", nlon_ou, dlonID)
+    CALL NF95_DEF_DIM(fID_ou, "rlatu", nlat_ou, dlatID)
+    CALL NF95_DEF_DIM(fID_ou, "plev",  nlev_in, dlevID)
+    CALL NF95_DEF_DIM(fID_ou, "time",  ntim_ou, dtimID)
+
+    !--- Define coordinate variables:
+    IF(ndims==4) &
+    CALL NF95_DEF_VAR(fID_ou, "rlonv", NF90_FLOAT, dlonID, vlonID)
+    CALL NF95_DEF_VAR(fID_ou, "rlatu", NF90_FLOAT, dlatID, vlatID)
+    CALL NF95_DEF_VAR(fID_ou, "plev",  NF90_FLOAT, dlevID, vlevID)
+    CALL NF95_DEF_VAR(fID_ou, "time",  NF90_FLOAT, dtimID, vtimID)
+    IF(ndims==4) &
+    CALL NF95_PUT_ATT(fID_ou, vlonID, "units", "degrees_east")
+    CALL NF95_PUT_ATT(fID_ou, vlatID, "units", "degrees_north")
+    CALL NF95_PUT_ATT(fID_ou, vlevID, "units", "millibar")
+    CALL NF95_PUT_ATT(fID_ou, vtimID, "units", "days since 2000-1-1")
+    IF(ndims==4) &
+    CALL NF95_PUT_ATT(fID_ou, vlonID, "standard_name", "longitude")
+    CALL NF95_PUT_ATT(fID_ou, vlatID, "standard_name", "latitude")
+    CALL NF95_PUT_ATT(fID_ou, vlevID, "standard_name", "air_pressure")
+    CALL NF95_PUT_ATT(fID_ou, vtimID, "standard_name", "time")
+    CALL NF95_PUT_ATT(fID_ou, vlevID, "long_name",     "air pressure")
+    CALL NF95_PUT_ATT(fID_ou, vtimID, "calendar",      cal_ou)
 
   !--- Define the main variables:
-  IF(ndims==3) dIDs(1:3) = [ dlatID, dlevID, dtimID]
-  IF(ndims==4) dIDs=[dlonID, dlatID, dlevID, dtimID]
-  CALL NF95_DEF_VAR(fID_ou, vars_in(1), NF90_FLOAT, dIDs(1:ndims), vID_ou(1))
-  CALL NF95_PUT_ATT(fID_ou, vID_ou(1), "long_name", "ozone mole fraction")
-  CALL NF95_PUT_ATT(fID_ou, vID_ou(1), "standard_name", "mole_fraction_of_ozone&
+    IF(ndims==3) dIDs(1:3) = [ dlatID, dlevID, dtimID]
+    IF(ndims==4) dIDs=[dlonID, dlatID, dlevID, dtimID]
+    CALL NF95_DEF_VAR(fID_ou, vars_in(1), NF90_FLOAT, dIDs(1:ndims), vID_ou(1))
+    CALL NF95_PUT_ATT(fID_ou, vID_ou(1), "long_name", "ozone mole fraction")
+    CALL NF95_PUT_ATT(fID_ou, vID_ou(1), "standard_name", "mole_fraction_of_ozone&
       &_in_air")
-  IF(SIZE(vID_ou) == 2) THEN
-    CALL NF95_DEF_VAR(fID_ou, vars_in(2), NF90_FLOAT, dIDs(1:ndims), vID_ou(2))
-    CALL NF95_PUT_ATT(fID_ou, vID_ou(2), "long_name","ozone mole fraction in da&
-      &ylight")
-  END IF
+    IF(SIZE(vID_ou) == 2) THEN
+      CALL NF95_DEF_VAR(fID_ou, vars_in(2), NF90_FLOAT, dIDs(1:ndims), vID_ou(2))
+      CALL NF95_PUT_ATT(fID_ou, vID_ou(2), "long_name","ozone mole fraction in da&
+        &ylight")
+    END IF
 
   !--- Global attributes:
   ! The following commands, copying attributes, may fail. That is OK.
   ! It should just mean that the attribute is not defined in the input file.
-  CALL NF95_COPY_ATT(fID_in,NF90_GLOBAL,"Conventions",fID_ou,NF90_GLOBAL, ncerr)
-  CALL handle_err_copy_att("Conventions")
-  CALL NF95_COPY_ATT(fID_in,NF90_GLOBAL,"title",      fID_ou,NF90_GLOBAL, ncerr)
-  CALL handle_err_copy_att("title")
-  CALL NF95_COPY_ATT(fID_in,NF90_GLOBAL,"institution",fID_ou,NF90_GLOBAL, ncerr)
-  CALL handle_err_copy_att("institution")
-  CALL NF95_COPY_ATT(fID_in,NF90_GLOBAL,"source",     fID_ou,NF90_GLOBAL, ncerr)
-  CALL handle_err_copy_att("source")
-  CALL NF95_PUT_ATT (fID_ou,NF90_GLOBAL,"comment", "Regridded for LMDZ")
-  CALL NF95_ENDDEF(fID_ou)
-
-  !--- Write one of the coordinate variables:
-  IF(ndims==4) CALL NF95_PUT_VAR(fID_ou, vlonID, lon_reg/deg2rad)
-  CALL NF95_PUT_VAR(fID_ou, vlatID, lat_reg(nlat_ou:1:-1)/deg2rad)
-  !    (convert from rad to degrees and sort in ascending order)
-
+    CALL NF95_COPY_ATT(fID_in,NF90_GLOBAL,"Conventions",fID_ou,NF90_GLOBAL, ncerr)
+    CALL handle_err_copy_att("Conventions")
+    CALL NF95_COPY_ATT(fID_in,NF90_GLOBAL,"title",      fID_ou,NF90_GLOBAL, ncerr)
+    CALL handle_err_copy_att("title")
+    CALL NF95_COPY_ATT(fID_in,NF90_GLOBAL,"institution",fID_ou,NF90_GLOBAL, ncerr)
+    CALL handle_err_copy_att("institution")
+    CALL NF95_COPY_ATT(fID_in,NF90_GLOBAL,"source",     fID_ou,NF90_GLOBAL, ncerr)
+    CALL handle_err_copy_att("source")
+    CALL NF95_PUT_ATT (fID_ou,NF90_GLOBAL,"comment", "Regridded for LMDZ")
+    CALL NF95_ENDDEF(fID_ou)
+
+    IF (grid_type==unstructured) THEN
+      ALLOCATE(latitude_glo_(klon_glo))
+      DO i=1,klon_glo
+        latitude_glo_(ind_cell_glo_glo(i))=latitude_glo(i)
+      ENDDO
+      CALL NF95_PUT_VAR(fID_ou, vlatID, latitude_glo_)
+    ELSE
+      !--- Write one of the coordinate variables:
+      IF(ndims==4) CALL NF95_PUT_VAR(fID_ou, vlonID, lon_reg/deg2rad)
+      CALL NF95_PUT_VAR(fID_ou, vlatID, lat_reg(nlat_ou:1:-1)/deg2rad)
+    !    (convert from rad to degrees and sort in ascending order)
+    ENDIF
+  ENDIF
+  
 CONTAINS
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/regr_pr_time_av_m.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/regr_pr_time_av_m.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/regr_pr_time_av_m.F90	(revision 3605)
@@ -118,13 +118,14 @@
   USE assert_m,       ONLY: assert
   USE assert_eq_m,    ONLY: assert_eq
-  USE comvert_mod,    ONLY: scaleheight
+!!  USE comvert_mod,    ONLY: scaleheight
   USE interpolation,  ONLY: locate
   USE regr_conserv_m, ONLY: regr_conserv
   USE regr_lint_m,    ONLY: regr_lint
   USE slopes_m,       ONLY: slopes
-  USE mod_phys_lmdz_mpi_data,       ONLY: is_mpi_root
-  USE mod_grid_phy_lmdz, ONLY: nlon=>nbp_lon, nlat=>nbp_lat, nlev_ou=>nbp_lev
-  USE mod_phys_lmdz_transfert_para, ONLY: scatter2d, scatter
+  USE mod_phys_lmdz_para,           ONLY: is_mpi_root,is_master
+  USE mod_grid_phy_lmdz,            ONLY: nlon=>nbp_lon, nlat=>nbp_lat, nlev_ou=>nbp_lev, klon_glo, grid_type, unstructured
+  USE mod_phys_lmdz_transfert_para, ONLY: scatter2d, scatter, gather
   USE phys_cal_mod,                 ONLY: calend, year_len, days_elapsed, jH_cur
+  USE geometry_mod,                 ONLY: ind_cell_glo
 !-------------------------------------------------------------------------------
 ! Arguments:
@@ -175,4 +176,5 @@
     v2i(klon,SIZE(Pre_in)-1,SIZE(nam)), &     !--- v2 in Ploc=='I' case
     v2c(klon,SIZE(Pre_in)  ,SIZE(nam))        !--- v2 in Ploc=='C' case
+  INTEGER,ALLOCATABLE :: ind_cell_glo_glo(:)
   LOGICAL :: ll
 !--- For debug
@@ -247,6 +249,9 @@
       IF(lO3Tfile) ot1=al*otm+(1.-al)*otp
     END IF
+  ELSE
+    IF (lfirst) ALLOCATE(v1(0,0,0,0))
   END IF
   !$OMP END MASTER
+  !$OMP BARRIER
   IF(lfirst) THEN
     lfirst=.FALSE.;       CALL bcast(lfirst)
@@ -255,14 +260,37 @@
     CALL bcast(lO3Tfile); CALL bcast(linterp)
   END IF
+  
+  IF (is_master) THEN 
+    ALLOCATE(ind_cell_glo_glo(klon_glo))
+  ELSE
+    ALLOCATE(ind_cell_glo_glo(0))
+  ENDIF
+  CALL gather(ind_cell_glo,ind_cell_glo_glo)
+  IF (is_master .AND. grid_type==unstructured) v1(:,:,:,:)=v1(:,ind_cell_glo_glo(:),:,:)
+  
   CALL scatter2d(v1,v2)
-  IF(lPrSfile) CALL scatter2d(pg1,Pgnd_in)
-  IF(lPrTfile) CALL scatter2d(pt1,Ptrp_in)
-  IF(lO3Tfile) CALL scatter2d(ot1,Otrp_in)
+
+  !--- No "ps" in input file => assumed to be equal to current LMDZ ground press
+  IF(lPrSfile) THEN
+    IF (is_master .AND. grid_type==unstructured) pg1(:,:)=pg1(:,ind_cell_glo_glo(:))
+    CALL scatter2d(pg1,Pgnd_in)
+  ELSE
+    Pgnd_in=Pre_ou(:,1)
+  END IF
+
+  IF(lPrTfile) THEN
+    IF (is_master .AND. grid_type==unstructured) pt1(:,:)=pt1(:,ind_cell_glo_glo(:))
+    CALL scatter2d(pt1,Ptrp_in)
+  ENDIF
+
+  IF(lO3Tfile) THEN
+    IF (is_master .AND. grid_type==unstructured) ot1(:,:)=ot1(:,ind_cell_glo_glo(:))
+    CALL scatter2d(ot1,Otrp_in)
+  ENDIF
   !--- No ground pressure in input file => choose it to be the one of LMDZ
   IF(lAdjTro.AND..NOT.lPrSfile) Pgnd_in(:)=Pgrnd_ou(:)
-  
-!-------------------------------------------------------------------------------
-  IF(.NOT.lAdjTro) THEN       !--- REGRID IN PRESSURE ; NO TROPOPAUSE ADJUSTMENT
-!-------------------------------------------------------------------------------
+
+  !--- REGRID IN PRESSURE ; 3rd index inverted because "paprs" is decreasing
+  IF(.NOT.lAdjTro) THEN
     DO i=1,klon
       Pres_ou=Pre_ou(i,SIZE(Pre_ou,2):1:-1)   !--- pplay & paprs are decreasing
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/aeropt_6bands_rrtm.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/aeropt_6bands_rrtm.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/aeropt_6bands_rrtm.F90	(revision 3605)
@@ -6,5 +6,5 @@
      tau_allaer, piz_allaer, &
      cg_allaer, m_allaer_pi, &
-     flag_aerosol, flag_bc_internal_mixture, zrho )
+     flag_aerosol, flag_bc_internal_mixture, zrho, ok_volcan )
 
   USE dimphy
@@ -32,4 +32,5 @@
   LOGICAL,                        INTENT(IN)  :: flag_bc_internal_mixture
   REAL, DIMENSION(klon,klev),     INTENT(IN)  :: zrho
+  LOGICAL,                        INTENT(IN)  :: ok_volcan ! volcanic diags
   !
   ! Output arguments:
@@ -794,40 +795,58 @@
          cg_allaer(i,k,2,inu)=MIN(MAX(cg_allaer(i,k,2,inu),0.0),1.0)
 
-!--natural aerosol
-!--ASBCM aerosols take _pi value because of internal mixture option
-         tau_allaer(i,k,1,inu)=tau_ae_pi(i,k,id_ASSO4M_phy,inu)+tau_ae_pi(i,k,id_CSSO4M_phy,inu)+ &
-                               tau_ae_pi(i,k,id_ASBCM_phy,inu)+tau_ae_pi(i,k,id_AIBCM_phy,inu)+   &
-                               tau_ae_pi(i,k,id_ASPOMM_phy,inu)+tau_ae_pi(i,k,id_AIPOMM_phy,inu)+ &
-                               tau_ae_pi(i,k,id_ASSSM_phy,inu)+tau_ae_pi(i,k,id_CSSSM_phy,inu)+   &
-                               tau_ae_pi(i,k,id_SSSSM_phy,inu)+ tau_ae_pi(i,k,id_CIDUSTM_phy,inu)
-         tau_allaer(i,k,1,inu)=MAX(tau_allaer(i,k,1,inu),tau_min)
-
-         piz_allaer(i,k,1,inu)=(tau_ae_pi(i,k,id_ASSO4M_phy,inu)*piz_ae(i,k,id_ASSO4M_phy,inu)+   &
-                                tau_ae_pi(i,k,id_CSSO4M_phy,inu)*piz_ae(i,k,id_CSSO4M_phy,inu)+   &
-                                tau_ae_pi(i,k,id_ASBCM_phy,inu)*piz_ae_pi(i,k,id_ASBCM_phy,inu)+  &
-                                tau_ae_pi(i,k,id_AIBCM_phy,inu)*piz_ae(i,k,id_AIBCM_phy,inu)+     &
-                                tau_ae_pi(i,k,id_ASPOMM_phy,inu)*piz_ae(i,k,id_ASPOMM_phy,inu)+   &
-                                tau_ae_pi(i,k,id_AIPOMM_phy,inu)*piz_ae(i,k,id_AIPOMM_phy,inu)+   &
-                                tau_ae_pi(i,k,id_ASSSM_phy,inu)*piz_ae(i,k,id_ASSSM_phy,inu)+     &
-                                tau_ae_pi(i,k,id_CSSSM_phy,inu)*piz_ae(i,k,id_CSSSM_phy,inu)+     &
-                                tau_ae_pi(i,k,id_SSSSM_phy,inu)*piz_ae(i,k,id_SSSSM_phy,inu)+     &
-                                tau_ae_pi(i,k,id_CIDUSTM_phy,inu)*piz_ae(i,k,id_CIDUSTM_phy,inu)) &
-                                /tau_allaer(i,k,1,inu)
-         piz_allaer(i,k,1,inu)=MIN(MAX(piz_allaer(i,k,1,inu),0.01),1.0)
-         IF (tau_allaer(i,k,1,inu).LE.tau_min) piz_allaer(i,k,1,inu)=1.0
-
-         cg_allaer(i,k,1,inu)=(tau_ae_pi(i,k,id_ASSO4M_phy,inu)*piz_ae(i,k,id_ASSO4M_phy,inu)*cg_ae(i,k,id_ASSO4M_phy,inu)+    &
-                               tau_ae_pi(i,k,id_CSSO4M_phy,inu)*piz_ae(i,k,id_CSSO4M_phy,inu)*cg_ae(i,k,id_CSSO4M_phy,inu)+    &
-                               tau_ae_pi(i,k,id_ASBCM_phy,inu)*piz_ae_pi(i,k,id_ASBCM_phy,inu)*cg_ae_pi(i,k,id_ASBCM_phy,inu)+ &
-                               tau_ae_pi(i,k,id_AIBCM_phy,inu)*piz_ae(i,k,id_AIBCM_phy,inu)*cg_ae(i,k,id_AIBCM_phy,inu)+       &
-                               tau_ae_pi(i,k,id_ASPOMM_phy,inu)*piz_ae(i,k,id_ASPOMM_phy,inu)*cg_ae(i,k,id_ASPOMM_phy,inu)+    &
-                               tau_ae_pi(i,k,id_AIPOMM_phy,inu)*piz_ae(i,k,id_AIPOMM_phy,inu)*cg_ae(i,k,id_AIPOMM_phy,inu)+    &
-                               tau_ae_pi(i,k,id_ASSSM_phy,inu)*piz_ae(i,k,id_ASSSM_phy,inu)*cg_ae(i,k,id_ASSSM_phy,inu)+       &
-                               tau_ae_pi(i,k,id_CSSSM_phy,inu)*piz_ae(i,k,id_CSSSM_phy,inu)*cg_ae(i,k,id_CSSSM_phy,inu)+       &
-                               tau_ae_pi(i,k,id_SSSSM_phy,inu)*piz_ae(i,k,id_SSSSM_phy,inu)*cg_ae(i,k,id_SSSSM_phy,inu)+       &
-                               tau_ae_pi(i,k,id_CIDUSTM_phy,inu)*piz_ae(i,k,id_CIDUSTM_phy,inu)*cg_ae(i,k,id_CIDUSTM_phy,inu))/ &
-                               (tau_allaer(i,k,1,inu)*piz_allaer(i,k,1,inu))
-         cg_allaer(i,k,1,inu)=MIN(MAX(cg_allaer(i,k,1,inu),0.0),1.0)
-
+         IF (.NOT. ok_volcan) THEN
+!
+!--this is the default case
+!--in this case, index 1 of tau_allaer contains natural aerosols only
+!--because the objective is to perform the double radiation call with and without anthropogenic aerosols 
+!
+           tau_allaer(i,k,1,inu)=tau_ae_pi(i,k,id_ASSO4M_phy,inu)+tau_ae_pi(i,k,id_CSSO4M_phy,inu)+ &
+                                 tau_ae_pi(i,k,id_ASBCM_phy,inu)+tau_ae_pi(i,k,id_AIBCM_phy,inu)+   &
+                                 tau_ae_pi(i,k,id_ASPOMM_phy,inu)+tau_ae_pi(i,k,id_AIPOMM_phy,inu)+ &
+                                 tau_ae_pi(i,k,id_ASSSM_phy,inu)+tau_ae_pi(i,k,id_CSSSM_phy,inu)+   &
+                                 tau_ae_pi(i,k,id_SSSSM_phy,inu)+ tau_ae_pi(i,k,id_CIDUSTM_phy,inu)
+           tau_allaer(i,k,1,inu)=MAX(tau_allaer(i,k,1,inu),tau_min)
+         
+           piz_allaer(i,k,1,inu)=(tau_ae_pi(i,k,id_ASSO4M_phy,inu)*piz_ae(i,k,id_ASSO4M_phy,inu)+   &
+                                  tau_ae_pi(i,k,id_CSSO4M_phy,inu)*piz_ae(i,k,id_CSSO4M_phy,inu)+   &
+                                  tau_ae_pi(i,k,id_ASBCM_phy,inu)*piz_ae_pi(i,k,id_ASBCM_phy,inu)+  &
+                                  tau_ae_pi(i,k,id_AIBCM_phy,inu)*piz_ae(i,k,id_AIBCM_phy,inu)+     &
+                                  tau_ae_pi(i,k,id_ASPOMM_phy,inu)*piz_ae(i,k,id_ASPOMM_phy,inu)+   &
+                                  tau_ae_pi(i,k,id_AIPOMM_phy,inu)*piz_ae(i,k,id_AIPOMM_phy,inu)+   &
+                                  tau_ae_pi(i,k,id_ASSSM_phy,inu)*piz_ae(i,k,id_ASSSM_phy,inu)+     &
+                                  tau_ae_pi(i,k,id_CSSSM_phy,inu)*piz_ae(i,k,id_CSSSM_phy,inu)+     &
+                                  tau_ae_pi(i,k,id_SSSSM_phy,inu)*piz_ae(i,k,id_SSSSM_phy,inu)+     &
+                                  tau_ae_pi(i,k,id_CIDUSTM_phy,inu)*piz_ae(i,k,id_CIDUSTM_phy,inu)) &
+                                  /tau_allaer(i,k,1,inu)
+           piz_allaer(i,k,1,inu)=MIN(MAX(piz_allaer(i,k,1,inu),0.01),1.0)
+           IF (tau_allaer(i,k,1,inu).LE.tau_min) piz_allaer(i,k,1,inu)=1.0
+         
+           cg_allaer(i,k,1,inu)=(tau_ae_pi(i,k,id_ASSO4M_phy,inu)*piz_ae(i,k,id_ASSO4M_phy,inu)*cg_ae(i,k,id_ASSO4M_phy,inu)+    &
+                                 tau_ae_pi(i,k,id_CSSO4M_phy,inu)*piz_ae(i,k,id_CSSO4M_phy,inu)*cg_ae(i,k,id_CSSO4M_phy,inu)+    &
+                                 tau_ae_pi(i,k,id_ASBCM_phy,inu)*piz_ae_pi(i,k,id_ASBCM_phy,inu)*cg_ae_pi(i,k,id_ASBCM_phy,inu)+ &
+                                 tau_ae_pi(i,k,id_AIBCM_phy,inu)*piz_ae(i,k,id_AIBCM_phy,inu)*cg_ae(i,k,id_AIBCM_phy,inu)+       &
+                                 tau_ae_pi(i,k,id_ASPOMM_phy,inu)*piz_ae(i,k,id_ASPOMM_phy,inu)*cg_ae(i,k,id_ASPOMM_phy,inu)+    &
+                                 tau_ae_pi(i,k,id_AIPOMM_phy,inu)*piz_ae(i,k,id_AIPOMM_phy,inu)*cg_ae(i,k,id_AIPOMM_phy,inu)+    &
+                                 tau_ae_pi(i,k,id_ASSSM_phy,inu)*piz_ae(i,k,id_ASSSM_phy,inu)*cg_ae(i,k,id_ASSSM_phy,inu)+       &
+                                 tau_ae_pi(i,k,id_CSSSM_phy,inu)*piz_ae(i,k,id_CSSSM_phy,inu)*cg_ae(i,k,id_CSSSM_phy,inu)+       &
+                                 tau_ae_pi(i,k,id_SSSSM_phy,inu)*piz_ae(i,k,id_SSSSM_phy,inu)*cg_ae(i,k,id_SSSSM_phy,inu)+       &
+                                 tau_ae_pi(i,k,id_CIDUSTM_phy,inu)*piz_ae(i,k,id_CIDUSTM_phy,inu)*cg_ae(i,k,id_CIDUSTM_phy,inu))/ &
+                                 (tau_allaer(i,k,1,inu)*piz_allaer(i,k,1,inu))
+           cg_allaer(i,k,1,inu)=MIN(MAX(cg_allaer(i,k,1,inu),0.0),1.0)
+!
+         ELSE
+!
+!--this is the case for VOLMIP
+!--in this case index 1 of tau_allaer contains all (natural+anthropogenic) aerosols (same as index 2 above)
+!--but stratospheric aerosols will not be added in rrtm/readaerosolstrato2 as
+!--the objective is to have the double radiation call with and without stratospheric aerosols
+!
+           tau_allaer(i,k,1,inu)=tau_allaer(i,k,2,inu)
+            
+           piz_allaer(i,k,1,inu)=piz_allaer(i,k,2,inu)
+            
+           cg_allaer(i,k,1,inu) =cg_allaer(i,k,2,inu)
+!
+         ENDIF
         ENDDO
       ENDDO
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/radlsw.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/radlsw.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/radlsw.F90	(revision 3605)
@@ -502,5 +502,7 @@
     ELSEIF (NRADLP == 3) THEN  
 ! one uses the cloud droplet radius from newmicro
-! IKL or JK ?? - I think IKL but needs to be verified
+! IKL or JK ?? - I think IKL but needs to be verified > ref_liq_i
+! (inverted) is used in the call of RECMWF_AERO in radlwsw_m.F90,
+! so everything is fine - JBM 6/2019
         ZRADLP(JL)=PREF_LIQ(JL,IKL)
     ENDIF  
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/readaerosol_optic_rrtm.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/readaerosol_optic_rrtm.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/readaerosol_optic_rrtm.F90	(revision 3605)
@@ -1,5 +1,5 @@
 ! $Id$
 !
-SUBROUTINE readaerosol_optic_rrtm(debut, aerosol_couple, ok_alw,  &
+SUBROUTINE readaerosol_optic_rrtm(debut, aerosol_couple, ok_alw, ok_volcan, &
      new_aod, flag_aerosol, flag_bc_internal_mixture, itap, rjourvrai, &
      pdtphys, pplay, paprs, t_seri, rhcl, presnivs, &
@@ -32,4 +32,5 @@
   LOGICAL, INTENT(IN)                      :: aerosol_couple
   LOGICAL, INTENT(IN)                      :: ok_alw
+  LOGICAL, INTENT(IN)                      :: ok_volcan
   LOGICAL, INTENT(IN)                      :: new_aod
   INTEGER, INTENT(IN)                      :: flag_aerosol
@@ -313,5 +314,5 @@
        tau_aero, piz_aero, cg_aero, &
        m_allaer_pi, flag_aerosol,   &
-       flag_bc_internal_mixture, zrho ) 
+       flag_bc_internal_mixture, zrho, ok_volcan ) 
 
   ! aeropt_5wv only for validation and diagnostics
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/readaerosolstrato1_rrtm.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/readaerosolstrato1_rrtm.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/readaerosolstrato1_rrtm.F90	(revision 3605)
@@ -2,4 +2,5 @@
 ! $Id: readaerosolstrato1_rrtm.F90 2526 2016-05-26 22:13:40Z oboucher $
 !
+
 SUBROUTINE readaerosolstrato1_rrtm(debut)
 
@@ -9,7 +10,5 @@
 
     USE phys_cal_mod, ONLY : mth_cur
-    USE mod_grid_phy_lmdz, ONLY: nbp_lon, nbp_lat, klon_glo, grid2dTo1d_glo
-    USE mod_phys_lmdz_mpi_data, ONLY :  is_mpi_root
-    USE mod_phys_lmdz_omp_data, ONLY :  is_omp_root
+    USE mod_grid_phy_lmdz, ONLY: nbp_lon, nbp_lat, klon_glo, grid2dTo1d_glo, grid_type, unstructured
     USE mod_phys_lmdz_para 
     USE phys_state_var_mod
@@ -19,4 +18,7 @@
     USE YOERAD, ONLY : NLW
     USE YOMCST
+#ifdef CPP_XIOS
+    USE xios
+#endif
 
     IMPLICIT NONE
@@ -45,4 +47,5 @@
     REAL, ALLOCATABLE:: tauaerstrat_mois(:, :, :)
     REAL, ALLOCATABLE:: tauaerstrat_mois_glo(:, :)
+    REAL, ALLOCATABLE:: tauaerstrat_mpi(:, :)
 
 ! For NetCDF:
@@ -102,18 +105,25 @@
     n_lat = size(latitude)
     print *, 'LAT aerosol strato=', n_lat, latitude
-    IF (n_lat.NE.nbp_lat) THEN 
-       print *,'Le nombre de lat n est pas egal a nbp_lat'
-       STOP
-    ENDIF
-
+
+    IF (grid_type/=unstructured) THEN
+      IF (n_lat.NE.nbp_lat) THEN 
+         print *,'Le nombre de lat n est pas egal a nbp_lat'
+         STOP
+      ENDIF
+    ENDIF
+    
     CALL nf95_inq_varid(ncid_in, "LON", varid)
     CALL nf95_gw_var(ncid_in, varid, longitude)
     n_lon = size(longitude)
     print *, 'LON aerosol strato=', n_lon, longitude
-    IF (n_lon.NE.nbp_lon) THEN 
-       print *,'Le nombre de lon n est pas egal a nbp_lon'
-       STOP
-    ENDIF
-
+
+    IF (grid_type/=unstructured) THEN
+      IF (n_lon.NE.nbp_lon) THEN 
+         print *,'Le nombre de lon n est pas egal a nbp_lon'
+         STOP
+      ENDIF
+    ENDIF
+    
+    
     CALL nf95_inq_varid(ncid_in, "TIME", varid)
     CALL nf95_gw_var(ncid_in, varid, time)
@@ -144,5 +154,7 @@
 !---reduce to a klon_glo grid 
     CALL grid2dTo1d_glo(tauaerstrat_mois,tauaerstrat_mois_glo)
-
+    
+    ELSE
+      ALLOCATE(tauaerstrat_mois(0,0,0))
     ENDIF !--is_mpi_root and is_omp_root
 
@@ -153,6 +165,20 @@
 
 !--scatter on all proc
-    CALL scatter(tauaerstrat_mois_glo,tau_aer_strat)
-
+    
+    IF (grid_type==unstructured) THEN
+#ifdef CPP_XIOS
+      IF (is_omp_master) THEN
+        ALLOCATE(tauaerstrat_mpi(klon_mpi,klev))
+        CALL xios_send_field("taustrat_in",tauaerstrat_mois)
+        CALL xios_recv_field("taustrat_out",tauaerstrat_mpi)
+      ELSE
+        ALLOCATE(tauaerstrat_mpi(0,0))
+      ENDIF
+      CALL scatter_omp(tauaerstrat_mpi,tau_aer_strat)
+#endif
+    ELSE  
+      CALL scatter(tauaerstrat_mois_glo,tau_aer_strat)
+    ENDIF
+    
     IF (is_mpi_root.AND.is_omp_root) THEN
 !
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/readaerosolstrato2_rrtm.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/readaerosolstrato2_rrtm.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/readaerosolstrato2_rrtm.F90	(revision 3605)
@@ -2,5 +2,5 @@
 ! $Id: readaerosolstrato2_rrtm.F90 2526 2016-05-26 22:13:40Z oboucher $
 !
-SUBROUTINE readaerosolstrato2_rrtm(debut)
+SUBROUTINE readaerosolstrato2_rrtm(debut, ok_volcan)
 
     USE netcdf95, ONLY: nf95_close, nf95_gw_var, nf95_inq_dimid, & 
@@ -9,7 +9,7 @@
 
     USE phys_cal_mod, ONLY : mth_cur
-    USE mod_grid_phy_lmdz, ONLY: nbp_lon, nbp_lat, klon_glo, grid2dTo1d_glo
-    USE mod_phys_lmdz_mpi_data, ONLY :  is_mpi_root
-    USE mod_phys_lmdz_omp_data, ONLY :  is_omp_root
+    USE mod_grid_phy_lmdz, ONLY: nbp_lon, nbp_lat, klon_glo, grid2dTo1d_glo, grid_type, unstructured
+    USE mod_phys_lmdz_mpi_data
+    USE mod_phys_lmdz_omp_data
     USE mod_phys_lmdz_para 
     USE phys_state_var_mod
@@ -19,4 +19,7 @@
     USE YOERAD, ONLY : NLW
     USE YOMCST
+#ifdef CPP_XIOS
+    USE xios
+#endif
 
     IMPLICIT NONE
@@ -29,4 +32,5 @@
 ! Variable input
     LOGICAL, INTENT(IN) ::  debut
+    LOGICAL, INTENT(IN) ::  ok_volcan !activate volcanic diags
 
 ! Variables locales
@@ -65,4 +69,8 @@
     REAL, ALLOCATABLE:: cgaerstrat_mois_glo(:, :, :)
     REAL, ALLOCATABLE:: taulwaerstrat_mois_glo(:, :, :)
+    REAL, ALLOCATABLE:: tauaerstrat_mpi(:, :, :)
+    REAL, ALLOCATABLE:: pizaerstrat_mpi(:, :, :)
+    REAL, ALLOCATABLE:: cgaerstrat_mpi(:, :, :)
+    REAL, ALLOCATABLE:: taulwaerstrat_mpi(:, :, :)
 
 ! For NetCDF:
@@ -107,8 +115,11 @@
         CALL nf95_gw_var(ncid_in, varid, latitude)
         n_lat = size(latitude)
-        IF (n_lat.NE.nbp_lat) THEN 
-           print *, 'latitude=', n_lat, nbp_lat
-           abort_message='Le nombre de lat n est pas egal a nbp_lat'
-           CALL abort_physic(modname,abort_message,1)
+
+        IF (grid_type/=unstructured) THEN
+           IF (n_lat.NE.nbp_lat) THEN 
+             print *, 'latitude=', n_lat, nbp_lat
+             abort_message='Le nombre de lat n est pas egal a nbp_lat'
+             CALL abort_physic(modname,abort_message,1)
+           ENDIF
         ENDIF
 
@@ -134,12 +145,4 @@
         ALLOCATE(cgaerstrat(n_lat, n_lev, n_wav, n_month))
 
-        ALLOCATE(tauaerstrat_mois(n_lon, n_lat, n_lev, n_wav))
-        ALLOCATE(pizaerstrat_mois(n_lon, n_lat, n_lev, n_wav))
-        ALLOCATE(cgaerstrat_mois(n_lon, n_lat, n_lev, n_wav))
-
-        ALLOCATE(tauaerstrat_mois_glo(klon_glo, n_lev, n_wav))
-        ALLOCATE(pizaerstrat_mois_glo(klon_glo, n_lev, n_wav))
-        ALLOCATE(cgaerstrat_mois_glo(klon_glo, n_lev, n_wav))
-
 !--reading stratospheric aerosol tau per layer
         CALL nf95_inq_varid(ncid_in, "TAU_SUN", varid)
@@ -159,26 +162,36 @@
         CALL nf95_close(ncid_in)
 
+       
+        IF (grid_type/=unstructured) THEN
+          ALLOCATE(tauaerstrat_mois(n_lon, n_lat, n_lev, n_wav))
+          ALLOCATE(pizaerstrat_mois(n_lon, n_lat, n_lev, n_wav))
+          ALLOCATE(cgaerstrat_mois(n_lon, n_lat, n_lev, n_wav))
+
+          ALLOCATE(tauaerstrat_mois_glo(klon_glo, n_lev, n_wav))
+          ALLOCATE(pizaerstrat_mois_glo(klon_glo, n_lev, n_wav))
+          ALLOCATE(cgaerstrat_mois_glo(klon_glo, n_lev, n_wav))
 !--select the correct month
 !--and copy into 1st longitude
-        tauaerstrat_mois(1,:,:,:) = tauaerstrat(:,:,:,mth_cur)
-        pizaerstrat_mois(1,:,:,:) = pizaerstrat(:,:,:,mth_cur)
-        cgaerstrat_mois(1,:,:,:)  = cgaerstrat(:,:,:,mth_cur)
+          tauaerstrat_mois(1,:,:,:) = tauaerstrat(:,:,:,mth_cur)
+          pizaerstrat_mois(1,:,:,:) = pizaerstrat(:,:,:,mth_cur)
+          cgaerstrat_mois(1,:,:,:)  = cgaerstrat(:,:,:,mth_cur)
 
 !--copy longitudes
-        DO i=2, n_lon
-         tauaerstrat_mois(i,:,:,:) = tauaerstrat_mois(1,:,:,:)
-         pizaerstrat_mois(i,:,:,:) = pizaerstrat_mois(1,:,:,:)
-         cgaerstrat_mois(i,:,:,:)  = cgaerstrat_mois(1,:,:,:)
-        ENDDO
+          DO i=2, n_lon
+           tauaerstrat_mois(i,:,:,:) = tauaerstrat_mois(1,:,:,:)
+           pizaerstrat_mois(i,:,:,:) = pizaerstrat_mois(1,:,:,:)
+           cgaerstrat_mois(i,:,:,:)  = cgaerstrat_mois(1,:,:,:)
+          ENDDO
 
 !---reduce to a klon_glo grid 
-        DO band=1, NSW
-          CALL grid2dTo1d_glo(tauaerstrat_mois(:,:,:,band),tauaerstrat_mois_glo(:,:,band))
-          CALL grid2dTo1d_glo(pizaerstrat_mois(:,:,:,band),pizaerstrat_mois_glo(:,:,band))
-          CALL grid2dTo1d_glo(cgaerstrat_mois(:,:,:,band),cgaerstrat_mois_glo(:,:,band))
-        ENDDO
-
+          DO band=1, NSW
+            CALL grid2dTo1d_glo(tauaerstrat_mois(:,:,:,band),tauaerstrat_mois_glo(:,:,band))
+            CALL grid2dTo1d_glo(pizaerstrat_mois(:,:,:,band),pizaerstrat_mois_glo(:,:,band))
+            CALL grid2dTo1d_glo(cgaerstrat_mois(:,:,:,band),cgaerstrat_mois_glo(:,:,band))
+          ENDDO
+        ENDIF
 !--Now LW optical properties
 !
+
         CALL nf95_open("taulwstrat.2D.nc", nf90_nowrite, ncid_in)
 
@@ -194,9 +207,12 @@
         CALL nf95_gw_var(ncid_in, varid, latitude)
         n_lat = size(latitude)
-        IF (n_lat.NE.nbp_lat) THEN 
-           abort_message='Le nombre de lat n est pas egal a nbp_lat'
-           CALL abort_physic(modname,abort_message,1)
-        ENDIF
-
+
+        IF (grid_type/=unstructured) THEN
+          IF (n_lat.NE.nbp_lat) THEN 
+             abort_message='Le nombre de lat n est pas egal a nbp_lat'
+             CALL abort_physic(modname,abort_message,1)
+          ENDIF
+        ENDIF
+        
         CALL nf95_inq_varid(ncid_in, "TIME", varid)
         CALL nf95_gw_var(ncid_in, varid, time)
@@ -217,6 +233,4 @@
 
         ALLOCATE(taulwaerstrat(n_lat, n_lev, n_wav, n_month))
-        ALLOCATE(taulwaerstrat_mois(n_lon, n_lat, n_lev, n_wav))
-        ALLOCATE(taulwaerstrat_mois_glo(klon_glo, n_lev, n_wav))
 
 !--reading stratospheric aerosol lw tau per layer
@@ -227,17 +241,23 @@
         CALL nf95_close(ncid_in)
 
+        IF (grid_type/=unstructured) THEN
+
+          ALLOCATE(taulwaerstrat_mois(n_lon, n_lat, n_lev, n_wav))
+          ALLOCATE(taulwaerstrat_mois_glo(klon_glo, n_lev, n_wav))
+
 !--select the correct month
 !--and copy into 1st longitude
-        taulwaerstrat_mois(1,:,:,:) = taulwaerstrat(:,:,:,mth_cur)
+          taulwaerstrat_mois(1,:,:,:) = taulwaerstrat(:,:,:,mth_cur)
 !--copy longitudes
-        DO i=2, n_lon
-          taulwaerstrat_mois(i,:,:,:) = taulwaerstrat_mois(1,:,:,:)
-        ENDDO
+          DO i=2, n_lon
+            taulwaerstrat_mois(i,:,:,:) = taulwaerstrat_mois(1,:,:,:)
+          ENDDO
 
 !---reduce to a klon_glo grid 
-        DO band=1, NLW
-          CALL grid2dTo1d_glo(taulwaerstrat_mois(:,:,:,band),taulwaerstrat_mois_glo(:,:,band))
-        ENDDO
-
+          DO band=1, NLW
+            CALL grid2dTo1d_glo(taulwaerstrat_mois(:,:,:,band),taulwaerstrat_mois_glo(:,:,band))
+          ENDDO
+        ENDIF
+      
       ELSE !--proc other than mpi_root and omp_root
            !--dummy allocation needed for debug mode
@@ -248,4 +268,10 @@
         ALLOCATE(taulwaerstrat_mois_glo(1,1,1))
 
+        ALLOCATE(tauaerstrat(0,0,0,12))
+        ALLOCATE(pizaerstrat(0,0,0,12))
+        ALLOCATE(cgaerstrat(0,0,0,12))
+        ALLOCATE(taulwaerstrat(0,0,0,12))
+
+
       ENDIF !--is_mpi_root and is_omp_root
 
@@ -255,20 +281,49 @@
       mth_pre=mth_cur
 
+      IF (grid_type==unstructured) THEN
+
+#ifdef CPP_XIOS
+
+        IF (is_omp_master) THEN
+          ALLOCATE(tauaerstrat_mpi(klon_mpi, klev, NSW))
+          ALLOCATE(pizaerstrat_mpi(klon_mpi, klev, NSW))
+          ALLOCATE(cgaerstrat_mpi(klon_mpi, klev, NSW))        
+          ALLOCATE(taulwaerstrat_mpi(klon_mpi, klev, NLW))
+         
+          CALL xios_send_field("tauaerstrat_in",SPREAD(tauaerstrat(:,:,:,mth_cur),1,8))
+          CALL xios_recv_field("tauaerstrat_out",tauaerstrat_mpi)
+          CALL xios_send_field("pizaerstrat_in",SPREAD(pizaerstrat(:,:,:,mth_cur),1,8))
+          CALL xios_recv_field("pizaerstrat_out",pizaerstrat_mpi)
+          CALL xios_send_field("cgaerstrat_in",SPREAD(cgaerstrat(:,:,:,mth_cur),1,8))
+          CALL xios_recv_field("cgaerstrat_out",cgaerstrat_mpi)
+          CALL xios_send_field("taulwaerstrat_in",SPREAD(taulwaerstrat(:,:,:,mth_cur),1,8))
+          CALL xios_recv_field("taulwaerstrat_out",taulwaerstrat_mpi)
+        ELSE
+          ALLOCATE(tauaerstrat_mpi(0, 0, 0))
+          ALLOCATE(pizaerstrat_mpi(0, 0, 0))
+          ALLOCATE(cgaerstrat_mpi(0, 0, 0))        
+          ALLOCATE(taulwaerstrat_mpi(0, 0, 0))
+        ENDIF  
+        
+        CALL scatter_omp(tauaerstrat_mpi,tau_aer_strat)
+        CALL scatter_omp(pizaerstrat_mpi,piz_aer_strat)
+        CALL scatter_omp(cgaerstrat_mpi,cg_aer_strat)
+        CALL scatter_omp(taulwaerstrat_mpi,taulw_aer_strat)
+#endif
+      ELSE  
+        
 !--scatter on all proc
-      CALL scatter(tauaerstrat_mois_glo,tau_aer_strat)
-      CALL scatter(pizaerstrat_mois_glo,piz_aer_strat)
-      CALL scatter(cgaerstrat_mois_glo,cg_aer_strat)
-      CALL scatter(taulwaerstrat_mois_glo,taulw_aer_strat)
+        CALL scatter(tauaerstrat_mois_glo,tau_aer_strat)
+        CALL scatter(pizaerstrat_mois_glo,piz_aer_strat)
+        CALL scatter(cgaerstrat_mois_glo,cg_aer_strat)
+        CALL scatter(taulwaerstrat_mois_glo,taulw_aer_strat)
+        IF (is_mpi_root.AND.is_omp_root)  DEALLOCATE(tauaerstrat_mois, pizaerstrat_mois, cgaerstrat_mois, taulwaerstrat_mois)
+
+      ENDIF 
 
       IF (is_mpi_root.AND.is_omp_root) THEN
-!
-        DEALLOCATE(tauaerstrat, pizaerstrat, cgaerstrat)
-        DEALLOCATE(tauaerstrat_mois, pizaerstrat_mois, cgaerstrat_mois)
-        DEALLOCATE(taulwaerstrat,taulwaerstrat_mois)
-!
-      ENDIF !--is_mpi_root and is_omp_root
-
-      DEALLOCATE(tauaerstrat_mois_glo,pizaerstrat_mois_glo,cgaerstrat_mois_glo)
-      DEALLOCATE(taulwaerstrat_mois_glo)
+        DEALLOCATE(tauaerstrat, pizaerstrat, cgaerstrat,taulwaerstrat)
+      ENDIF
+      
 
 !$OMP BARRIER
@@ -290,8 +345,12 @@
     ENDDO
 
+    IF (.NOT. ok_volcan) THEN
+!
+!--this is the default case 
+!--stratospheric aerosols are added to both index 2 and 1 for double radiation calls
 !--weighted average for cg, piz and tau, adding strat aerosols on top of tropospheric ones
     DO band=1, NSW
       WHERE (stratomask.GT.0.999999)
-!--anthropogenic aerosols bands 1 to NSW 
+!--strat aerosols are added to index 2 : natural and anthropogenic aerosols for bands 1 to NSW 
         cg_aero_sw_rrtm(:,:,2,band)  = ( cg_aero_sw_rrtm(:,:,2,band)*piz_aero_sw_rrtm(:,:,2,band)*tau_aero_sw_rrtm(:,:,2,band) + &
                                          cg_aer_strat(:,:,band)*piz_aer_strat(:,:,band)*tau_aer_strat(:,:,band) ) /              &
@@ -302,19 +361,35 @@
                                     MAX( tau_aero_sw_rrtm(:,:,2,band) + tau_aer_strat(:,:,band), 1.e-15 )
         tau_aero_sw_rrtm(:,:,2,band)  = tau_aero_sw_rrtm(:,:,2,band) + tau_aer_strat(:,:,band)
-!--natural aerosols bands 1 to NSW
+!--strat aerosols are added to index 1 : natural aerosols only for bands 1 to NSW
         cg_aero_sw_rrtm(:,:,1,band)  = ( cg_aero_sw_rrtm(:,:,1,band)*piz_aero_sw_rrtm(:,:,1,band)*tau_aero_sw_rrtm(:,:,1,band) + &
+                cg_aer_strat(:,:,band)*piz_aer_strat(:,:,band)*tau_aer_strat(:,:,band) ) /              &
+                MAX( piz_aero_sw_rrtm(:,:,1,band)*tau_aero_sw_rrtm(:,:,1,band) +                             &
+                piz_aer_strat(:,:,band)*tau_aer_strat(:,:,band), 1.e-15 )
+        piz_aero_sw_rrtm(:,:,1,band) = ( piz_aero_sw_rrtm(:,:,1,band)*tau_aero_sw_rrtm(:,:,1,band) +                             &
+                piz_aer_strat(:,:,band)*tau_aer_strat(:,:,band) ) /                                     &
+                MAX( tau_aero_sw_rrtm(:,:,1,band) + tau_aer_strat(:,:,band), 1.e-15 )
+        tau_aero_sw_rrtm(:,:,1,band)  = tau_aero_sw_rrtm(:,:,1,band) + tau_aer_strat(:,:,band)
+    ENDWHERE
+    ENDDO
+!
+    ELSE
+!
+!--this is the VOLMIP case
+!--stratospheric aerosols are only added to index 2 in this case 
+!--weighted average for cg, piz and tau, adding strat aerosols on top of tropospheric ones
+    DO band=1, NSW
+      WHERE (stratomask.GT.0.999999)
+!--strat aerosols are added to index 2 : natural and anthropogenic aerosols for bands 1 to NSW 
+        cg_aero_sw_rrtm(:,:,2,band)  = ( cg_aero_sw_rrtm(:,:,2,band)*piz_aero_sw_rrtm(:,:,2,band)*tau_aero_sw_rrtm(:,:,2,band) + &
                                          cg_aer_strat(:,:,band)*piz_aer_strat(:,:,band)*tau_aer_strat(:,:,band) ) /              &
-                                    MAX( piz_aero_sw_rrtm(:,:,1,band)*tau_aero_sw_rrtm(:,:,1,band) +                             &
+                                    MAX( piz_aero_sw_rrtm(:,:,2,band)*tau_aero_sw_rrtm(:,:,2,band) +                             &
                                          piz_aer_strat(:,:,band)*tau_aer_strat(:,:,band), 1.e-15 )
-        piz_aero_sw_rrtm(:,:,1,band) = ( piz_aero_sw_rrtm(:,:,1,band)*tau_aero_sw_rrtm(:,:,1,band) +                             &
+        piz_aero_sw_rrtm(:,:,2,band) = ( piz_aero_sw_rrtm(:,:,2,band)*tau_aero_sw_rrtm(:,:,2,band) +                             &
                                          piz_aer_strat(:,:,band)*tau_aer_strat(:,:,band) ) /                                     &
-                                    MAX( tau_aero_sw_rrtm(:,:,1,band) + tau_aer_strat(:,:,band), 1.e-15 )
-        tau_aero_sw_rrtm(:,:,1,band)  = tau_aero_sw_rrtm(:,:,1,band) + tau_aer_strat(:,:,band)
-!--no stratospheric aerosol in index 1 for these tests
-!        cg_aero_sw_rrtm(:,:,1,band)  =  cg_aero_sw_rrtm(:,:,1,band)
-!        piz_aero_sw_rrtm(:,:,1,band)  = piz_aero_sw_rrtm(:,:,1,band)
-!        tau_aero_sw_rrtm(:,:,1,band)  = tau_aero_sw_rrtm(:,:,1,band)
-    ENDWHERE
-    ENDDO
+                                    MAX( tau_aero_sw_rrtm(:,:,2,band) + tau_aer_strat(:,:,band), 1.e-15 )
+        tau_aero_sw_rrtm(:,:,2,band)  = tau_aero_sw_rrtm(:,:,2,band) + tau_aer_strat(:,:,band)
+     ENDWHERE
+  ENDDO
+  ENDIF
 
 !--total vertical aod at 10 um
@@ -331,12 +406,28 @@
     ENDDO
 
+    IF (.NOT. ok_volcan) THEN
+!--this is the default case 
+!--stratospheric aerosols are added to both index 2 and 1
     DO band=1, NLW
       WHERE (stratomask.GT.0.999999)
         tau_aero_lw_rrtm(:,:,2,band)  = tau_aero_lw_rrtm(:,:,2,band) + taulw_aer_strat(:,:,band)
         tau_aero_lw_rrtm(:,:,1,band)  = tau_aero_lw_rrtm(:,:,1,band) + taulw_aer_strat(:,:,band)
-!--no stratospheric aerosols in index 1 for these tests
-!    tau_aero_lw_rrtm(:,:,1,band)  = tau_aero_lw_rrtm(:,:,1,band) 
       ENDWHERE
     ENDDO
+!
+    ELSE
+!
+!--this is the VOLMIP case
+    DO band=1, NLW
+!--stratospheric aerosols are not added to index 1 
+!--and we copy index 2 in index 1 because we want the same dust aerosol LW properties as above
+      tau_aero_lw_rrtm(:,:,1,band)  = tau_aero_lw_rrtm(:,:,2,band)
+!
+      WHERE (stratomask.GT.0.999999)
+!--stratospheric aerosols are only added to index 2
+        tau_aero_lw_rrtm(:,:,2,band)  = tau_aero_lw_rrtm(:,:,2,band) + taulw_aer_strat(:,:,band)
+      ENDWHERE
+    ENDDO
+    ENDIF
 
 !--default SSA value if there is no aerosol
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/recmwf_aero.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/recmwf_aero.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/recmwf_aero.F90	(revision 3605)
@@ -30,10 +30,13 @@
  & PTOPSWAIAERO,PSOLSWAIAERO,&
  & PTOPSWCFAERO,PSOLSWCFAERO,&
+ & PSWADAERO,& !--NL
 !--LW diagnostics CK
  & PTOPLWADAERO,PSOLLWADAERO,&
  & PTOPLWAD0AERO,PSOLLWAD0AERO,&
  & PTOPLWAIAERO,PSOLLWAIAERO,&
+ & PLWADAERO,& !--NL
 !..end
- & ok_ade, ok_aie, flag_aerosol,flag_aerosol_strat,flag_aer_feedback)
+ & ok_ade, ok_aie, ok_volcan, flag_aerosol,flag_aerosol_strat,&
+ & flag_aer_feedback)
 !--fin
 
@@ -82,4 +85,5 @@
 ! ok_ade---input-L- apply the Aerosol Direct Effect or not?
 ! ok_aie---input-L- apply the Aerosol Indirect Effect or not?
+! ok_volcan-input-L- activate volcanic diags (SW heat & LW cool rate, SW & LW flux)
 ! flag_aerosol-input-I- aerosol flag from 0 to 7
 ! flag_aerosol_strat-input-I- use stratospheric aerosols flag (T/F)
@@ -213,4 +217,5 @@
 REAL(KIND=JPRB)   ,INTENT(IN)    :: PREF_ICE_PI(KPROMA,KLEV)
 LOGICAL, INTENT(in)  :: ok_ade, ok_aie         ! switches whether to use aerosol direct (indirect) effects or not
+LOGICAL, INTENT(in)  :: ok_volcan              ! produce volcanic diags (SW/LW heat flux and rate)
 INTEGER, INTENT(in)  :: flag_aerosol           ! takes value 0 (no aerosol) or 1 to 6 (aerosols)
 LOGICAL, INTENT(in)  :: flag_aerosol_strat     ! use stratospheric aerosols
@@ -221,4 +226,7 @@
 REAL(KIND=JPRB)   ,INTENT(OUT)   :: PTOPSWCFAERO(KPROMA,3), PSOLSWCFAERO(KPROMA,3) !--do we keep this ?
 !--fin
+!--NL
+REAL(KIND=JPRB)   ,INTENT(OUT)   :: PSWADAERO(KPROMA, KLEV+1)                        ! SW Aerosol direct forcing
+REAL(KIND=JPRB)   ,INTENT(OUT)   :: PLWADAERO(KPROMA, KLEV+1)                        ! LW Aerosol direct forcing
 !--CK
 REAL(KIND=JPRB)   ,INTENT(out)   :: PTOPLWADAERO(KPROMA), PSOLLWADAERO(KPROMA)       ! LW Aerosol direct forcing at TOA + surface
@@ -811,4 +819,7 @@
      PSOLSWAD0AERO(:) = (ZFSDN0_AERO(:,1,4)     -ZFSUP0_AERO(:,1,4))     -(ZFSDN0_AERO(:,1,2)     -ZFSUP0_AERO(:,1,2))
      PTOPSWAD0AERO(:) = (ZFSDN0_AERO(:,KLEV+1,4)-ZFSUP0_AERO(:,KLEV+1,4))-(ZFSDN0_AERO(:,KLEV+1,2)-ZFSUP0_AERO(:,KLEV+1,2))
+     IF(ok_volcan) THEN
+        PSWADAERO(:,:)  = (ZFSDN_AERO(:,:,4) -ZFSUP_AERO(:,:,4)) -(ZFSDN_AERO(:,:,2) -ZFSUP_AERO(:,:,2)) !--NL
+     ENDIF
 
 ! indirect anthropogenic forcing
@@ -831,4 +842,7 @@
      PSOLLWAD0AERO(:) = (-LWDN0_AERO(:,1,4)     -LWUP0_AERO(:,1,4))     -(-LWDN0_AERO(:,1,2)     -LWUP0_AERO(:,1,2))
      PTOPLWAD0AERO(:) = (-LWDN0_AERO(:,KLEV+1,4)-LWUP0_AERO(:,KLEV+1,4))-(-LWDN0_AERO(:,KLEV+1,2)-LWUP0_AERO(:,KLEV+1,2))
+     IF(ok_volcan) THEN
+        PLWADAERO(:,:)  = (-LWDN_AERO(:,:,4) -LWUP_AERO(:,:,4)) -(-LWDN_AERO(:,:,2) -LWUP_AERO(:,:,2)) !--NL
+     ENDIF
 
 ! LW indirect anthropogenic forcing
@@ -845,4 +859,7 @@
      PSOLSWAD0AERO(:) = (ZFSDN0_AERO(:,1,3)     -ZFSUP0_AERO(:,1,3))     -(ZFSDN0_AERO(:,1,1)     -ZFSUP0_AERO(:,1,1))
      PTOPSWAD0AERO(:) = (ZFSDN0_AERO(:,KLEV+1,3)-ZFSUP0_AERO(:,KLEV+1,3))-(ZFSDN0_AERO(:,KLEV+1,1)-ZFSUP0_AERO(:,KLEV+1,1))
+     IF(ok_volcan) THEN
+        PSWADAERO(:,:)  = (ZFSDN_AERO(:,:,3) -ZFSUP_AERO(:,:,3)) -(ZFSDN_AERO(:,:,1) -ZFSUP_AERO(:,:,1)) !--NL
+     ENDIF
 
 ! indirect anthropogenic forcing
@@ -865,5 +882,8 @@
      PSOLLWAD0AERO(:) = (-LWDN0_AERO(:,1,3)     -LWUP0_AERO(:,1,3))     -(-LWDN0_AERO(:,1,1)     -LWUP0_AERO(:,1,1))
      PTOPLWAD0AERO(:) = (-LWDN0_AERO(:,KLEV+1,3)-LWUP0_AERO(:,KLEV+1,3))-(-LWDN0_AERO(:,KLEV+1,1)-LWUP0_AERO(:,KLEV+1,1))
-
+     IF(ok_volcan) THEN
+        PLWADAERO(:,:)  = (-LWDN_AERO(:,:,3) -LWUP_AERO(:,:,3)) -(-LWDN_AERO(:,:,1) -LWUP_AERO(:,:,1)) !--NL
+     ENDIF
+     
 ! LW indirect anthropogenic forcing
      PSOLLWAIAERO(:) = 0.0
@@ -879,5 +899,8 @@
      PSOLSWAD0AERO(:) = 0.0
      PTOPSWAD0AERO(:) = 0.0
-
+     IF(ok_volcan) THEN
+        PSWADAERO(:,:)  = 0.0 !--NL
+     ENDIF
+     
 ! indirect anthropogenic forcing
      PSOLSWAIAERO(:) = (ZFSDN_AERO(:,1,2)     -ZFSUP_AERO(:,1,2))     -(ZFSDN_AERO(:,1,1)     -ZFSUP_AERO(:,1,1))
@@ -899,5 +922,8 @@
      PSOLLWAD0AERO(:) = 0.0
      PTOPLWAD0AERO(:) = 0.0
-
+     IF(ok_volcan) THEN
+        PLWADAERO(:,:)  = 0.0 !--NL
+     ENDIF
+     
 ! LW indirect anthropogenic forcing
      PSOLLWAIAERO(:) = (-LWDN_AERO(:,1,2)     -LWUP_AERO(:,1,2))     -(-LWDN_AERO(:,1,1)     -LWUP_AERO(:,1,1))
@@ -913,5 +939,8 @@
      PSOLSWAD0AERO(:) = 0.0
      PTOPSWAD0AERO(:) = 0.0
-
+     IF(ok_volcan) THEN
+        PSWADAERO(:,:)  = 0.0 !--NL
+     ENDIF
+     
 ! indirect anthropogenic forcing
      PSOLSWAIAERO(:) = 0.0 
@@ -933,5 +962,8 @@
      PSOLLWAD0AERO(:) = 0.0
      PTOPLWAD0AERO(:) = 0.0
-
+     IF(ok_volcan) THEN
+        PLWADAERO(:,:)  = 0.0 !--NL
+     ENDIF
+     
 ! LW indirect anthropogenic forcing
      PSOLLWAIAERO(:) = 0.0 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/suinit.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/suinit.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/rrtm/suinit.F90	(revision 3605)
@@ -126,5 +126,7 @@
 ALLOCATE(VDELA  (MAX(JPMXLE,NFLEVG)))
 ALLOCATE(VDELB  (MAX(JPMXLE,NFLEVG)))
+VDELB = 0  !ym missing init
 ALLOCATE( VC      (NFLEVG) )
+VC = 0    !ym missing init
 ALLOCATE( NLOEN   (NPROMA) )
 ALLOCATE( NLOENG   (NPROMA) )
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/simu_airs.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/simu_airs.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/simu_airs.F90	(revision 3605)
@@ -2,15 +2,17 @@
         module m_simu_airs
 
+        USE print_control_mod, ONLY: prt_level,lunout
+          
         implicit none
 
-        real, parameter :: tau_thresh = 0.05 ! seuil nuages detectables
-        real, parameter :: p_thresh = 445.   ! seuil nuages hauts
-        real, parameter :: em_min = 0.2      ! seuils nuages semi-transp
-        real, parameter :: em_max = 0.85
-        real, parameter :: undef = 999.
+        REAL, PARAMETER :: tau_thresh = 0.05 ! seuil nuages detectables
+        REAL, PARAMETER :: p_thresh = 445.   ! seuil nuages hauts
+        REAL, PARAMETER :: em_min = 0.2      ! seuils nuages semi-transp
+        REAL, PARAMETER :: em_max = 0.85
+        REAL, PARAMETER :: undef = 999.
 
         contains
 
-        real function search_tropopause(P,T,alt,N) result(P_tropo)
+        REAL function search_tropopause(P,T,alt,N) result(P_tropo)
 ! this function searches for the tropopause pressure in [hPa].
 ! The search is based on ideology described in
@@ -18,11 +20,11 @@
 ! GRL, 30(20) 2042, doi:10.1029/2003GL018240, 2003
 
-        integer N,i,i_lev,first_point,exit_flag,i_dir
-        real P(N),T(N),alt(N),slope(N)
-        real P_min, P_max, slope_limit,slope_2km, &
+        INTEGER N,i,i_lev,first_point,exit_flag,i_dir
+        REAL P(N),T(N),alt(N),slope(N)
+        REAL P_min, P_max, slope_limit,slope_2km, &
      & delta_alt_limit,tmp,delta_alt
-        parameter(P_min=75.0, P_max=470.0)   ! hPa
-        parameter(slope_limit=0.002)         ! 2 K/km converted to K/m
-        parameter(delta_alt_limit=2000.0)    ! 2000 meters
+        PARAMETER(P_min=75.0, P_max=470.0)   ! hPa
+        PARAMETER(slope_limit=0.002)         ! 2 K/km converted to K/m
+        PARAMETER(delta_alt_limit=2000.0)    ! 2000 meters
 
         do i=1,N-1
@@ -93,12 +95,12 @@
 
      
-        integer :: i, n, nss
-
-        integer, intent(in) :: len_cs
-        real, dimension(:), intent(in) :: rneb_cs, temp_cs
-        real, dimension(:), intent(in) :: emis_cs, iwco_cs, rad_cs
-        real, dimension(:), intent(in) :: pres_cs, dz_cs, rhodz_cs
-
-        real, intent(out) :: cc_tot_cs, cc_hc_cs, cc_hist_cs, &
+        INTEGER :: i, n, nss
+
+        INTEGER, intent(in) :: len_cs
+        REAL, DIMENSION(:), intent(in) :: rneb_cs, temp_cs
+        REAL, DIMENSION(:), intent(in) :: emis_cs, iwco_cs, rad_cs
+        REAL, DIMENSION(:), intent(in) :: pres_cs, dz_cs, rhodz_cs
+
+        REAL, intent(out) :: cc_tot_cs, cc_hc_cs, cc_hist_cs, &
      & cc_Cb_cs, cc_ThCi_cs, cc_Anv_cs, &
      & pcld_hc_cs, tcld_hc_cs, em_hc_cs, iwp_hc_cs, &
@@ -109,15 +111,18 @@
      & deltaz_hc_cs, deltaz_hist_cs, rad_hist_cs
 
-        real, dimension(len_cs) :: rneb_ord
-        real :: rneb_min
-
-        real, dimension(:), allocatable :: s, s_hc, s_hist, rneb_max
-        real, dimension(:), allocatable :: sCb, sThCi, sAnv
-        real, dimension(:), allocatable :: iwp_ss, pcld_ss, tcld_ss,&
+        REAL, DIMENSION(len_cs) :: rneb_ord
+        REAL :: rneb_min
+
+        REAL, DIMENSION(:), allocatable :: s, s_hc, s_hist, rneb_max
+        REAL, DIMENSION(:), allocatable :: sCb, sThCi, sAnv
+        REAL, DIMENSION(:), allocatable :: iwp_ss, pcld_ss, tcld_ss,&
      & emis_ss
-        real, dimension(:), allocatable :: deltaz_ss, rad_ss
-
-
-        write(*,*) 'dans cloud_structure'
+        REAL, DIMENSION(:), allocatable :: deltaz_ss, rad_ss
+
+        CHARACTER (len = 50)      :: modname = 'simu_airs.cloud_structure'
+        CHARACTER (len = 160)     :: abort_message
+        
+
+        write(lunout,*) 'dans cloud_structure'
 
         call ordonne(len_cs, rneb_cs, rneb_ord)
@@ -300,13 +305,11 @@
         if (cc_tot_cs .gt. maxval(rneb_cs) .and. &
      & abs(cc_tot_cs-maxval(rneb_cs)) .gt. 1.e-4 )  then
-        write(*,*) 'cc_tot_cs > max rneb_cs'
-        write(*,*) cc_tot_cs, maxval(rneb_cs)
-        STOP
+          WRITE(abort_message,*) 'cc_tot_cs > max rneb_cs', cc_tot_cs, maxval(rneb_cs)
+          CALL abort_physic(modname,abort_message,1)
         endif
 
         if (iwp_hc_cs .lt. 0.) then
-        write(*,*) 'cloud_structure:'
-        write(*,*) 'iwp_hc_cs < 0'
-        STOP
+          abort_message= 'cloud_structure: iwp_hc_cs < 0'
+          CALL abort_physic(modname,abort_message,1)
         endif
  
@@ -316,6 +319,6 @@
         subroutine normal_undef(num, den)
 
-        real, intent(in) :: den
-        real, intent(inout) :: num
+        REAL, intent(in) :: den
+        REAL, intent(inout) :: num
 
         if (den .ne. 0) then
@@ -330,7 +333,7 @@
         subroutine normal2_undef(res,num,den)
 
-        real, intent(in) :: den
-        real, intent(in) :: num
-        real, intent(out) :: res
+        REAL, intent(in) :: den
+        REAL, intent(in) :: num
+        REAL, intent(out) :: res
 
         if (den .ne. 0.) then
@@ -350,18 +353,21 @@
      & emis, pcld, tcld, iwp, deltaz, rad)
 
-        integer, intent(in) :: len_cs
-        real, dimension(len_cs), intent(in) :: rneb_cs, temp_cs
-        real, dimension(len_cs), intent(in) :: emis_cs, iwco_cs, &
+        INTEGER, intent(in) :: len_cs
+        REAL, DIMENSION(len_cs), intent(in) :: rneb_cs, temp_cs
+        REAL, DIMENSION(len_cs), intent(in) :: emis_cs, iwco_cs, &
      & rneb_ord
-        real, dimension(len_cs), intent(in) :: pres_cs, dz_cs, rad_cs
-        real, dimension(len_cs), intent(in) :: rhodz_cs
-        real, dimension(len_cs) :: tau_cs, w
-        real, intent(in) :: rnebmax
-        real, intent(inout) :: stot, shc, shist
-        real, intent(inout) :: sCb, sThCi, sAnv
-        real, intent(out) :: emis, pcld, tcld, iwp, deltaz, rad
-
-        integer :: i, ideb, ibeg, iend, nuage, visible
-        real :: som, som_tau, som_iwc, som_dz, som_rad, tau
+        REAL, DIMENSION(len_cs), intent(in) :: pres_cs, dz_cs, rad_cs
+        REAL, DIMENSION(len_cs), intent(in) :: rhodz_cs
+        REAL, DIMENSION(len_cs) :: tau_cs, w
+        REAL, intent(in) :: rnebmax
+        REAL, intent(inout) :: stot, shc, shist
+        REAL, intent(inout) :: sCb, sThCi, sAnv
+        REAL, intent(out) :: emis, pcld, tcld, iwp, deltaz, rad
+
+        INTEGER :: i, ideb, ibeg, iend, nuage, visible
+        REAL :: som, som_tau, som_iwc, som_dz, som_rad, tau
+
+        CHARACTER (len = 50)      :: modname = 'simu_airs.sous_section'
+        CHARACTER (len = 160)     :: abort_message
 
 
@@ -491,16 +497,16 @@
 
         if (iwp .lt. 0.) then
-        write(*,*) 'ideb iwp =', ideb, iwp
-        STOP
+          WRITE(abort_message,*) 'ideb iwp =', ideb, iwp
+          CALL abort_physic(modname,abort_message,1)
         endif
 
         if (deltaz .lt. 0.) then
-        write(*,*) 'ideb deltaz =', ideb, deltaz
-        STOP
+          WRITE(abort_message,*)'ideb deltaz =', ideb, deltaz
+          CALL abort_physic(modname,abort_message,1)
         endif
 
         if (emis .lt. 0.048 .and. emis .ne. 0.) then
-        write(*,*) 'ideb emis =', ideb, emis
-        STOP
+          WRITE(abort_message,*) 'ideb emis =', ideb, emis
+          CALL abort_physic(modname,abort_message,1)
         endif
 
@@ -511,11 +517,11 @@
      & visible, w)
 
-        integer, intent(in) :: ibeg, iend
-        real, intent(in) :: som_tau
-
-        integer, intent(inout) :: visible
-        real, dimension(:), intent(inout) :: w
-
-        integer :: i
+        INTEGER, intent(in) :: ibeg, iend
+        REAL, intent(in) :: som_tau
+
+        INTEGER, intent(inout) :: visible
+        REAL, DIMENSION(:), intent(inout) :: w
+
+        INTEGER :: i
 
 
@@ -553,12 +559,15 @@
      & som_tau, som_iwc, som_dz, som_rad)
 
-        integer, intent(in) :: ibeg, iend
-        real, dimension(:), intent(in) :: tau_cs, iwco_cs, temp_cs
-        real, dimension(:), intent(in) :: pres_cs, dz_cs, rad_cs
-        real, dimension(:), intent(in) :: rhodz_cs
-        real, intent(out) :: som_tau, som_iwc, som_dz, som_rad
-        real , intent(out) :: pcld, tcld
-
-        integer :: i, ibase, imid
+        INTEGER, intent(in) :: ibeg, iend
+        REAL, DIMENSION(:), intent(in) :: tau_cs, iwco_cs, temp_cs
+        REAL, DIMENSION(:), intent(in) :: pres_cs, dz_cs, rad_cs
+        REAL, DIMENSION(:), intent(in) :: rhodz_cs
+        REAL, intent(out) :: som_tau, som_iwc, som_dz, som_rad
+        REAL , intent(out) :: pcld, tcld
+
+        INTEGER :: i, ibase, imid
+
+        CHARACTER (len = 50)      :: modname = 'simu_airs.caract'
+        CHARACTER (len = 160)     :: abort_message
 
 ! Somme des epaisseurs optiques et des contenus en glace sur le nuage
@@ -585,12 +594,13 @@
 
         if (som_dz .ne. 0.) then
-        som_rad = som_rad/som_dz
+          som_rad = som_rad/som_dz
         else
-        write(*,*) 'som_dez = 0 STOP'
-        write(*,*) 'ibeg, iend =', ibeg, iend
-        do i = ibeg, iend
-        write(*,*) dz_cs(i), rhodz_cs(i)
-        enddo
-        STOP
+          write(*,*) 'som_dez = 0 STOP'
+          write(*,*) 'ibeg, iend =', ibeg, iend
+          do i = ibeg, iend
+             write(*,*) dz_cs(i), rhodz_cs(i)
+          enddo
+          abort_message='see above'
+          CALL abort_physic(modname,abort_message,1)
         endif
 
@@ -611,9 +621,9 @@
         subroutine topbot(ideb,w,ibeg,iend)
 
-        integer, intent(in) :: ideb
-        real, dimension(:), intent(in) :: w
-        integer, intent(out) :: ibeg, iend
-
-        integer :: i, itest
+        INTEGER, intent(in) :: ideb
+        REAL, DIMENSION(:), intent(in) :: w
+        INTEGER, intent(out) :: ibeg, iend
+
+        INTEGER :: i, itest
 
         itest = 0
@@ -642,12 +652,12 @@
         subroutine ordonne(len_cs, rneb_cs, rneb_ord)
 
-        integer, intent(in) :: len_cs
-        real, dimension(:), intent(in) :: rneb_cs
-        real, dimension(:), intent(out) :: rneb_ord
-
-        integer :: i, j, ind_min
-
-        real, dimension(len_cs) :: rneb
-        real :: rneb_max
+        INTEGER, intent(in) :: len_cs
+        REAL, DIMENSION(:), intent(in) :: rneb_cs
+        REAL, DIMENSION(:), intent(out) :: rneb_ord
+
+        INTEGER :: i, j, ind_min
+
+        REAL, DIMENSION(len_cs) :: rneb
+        REAL :: rneb_max
 
 
@@ -689,55 +699,58 @@
        USE dimphy
 
-       real, dimension(klev), intent(in) :: rneb_1D, temp_1D, emis_1D, &
+       REAL, DIMENSION(klev), intent(in) :: rneb_1D, temp_1D, emis_1D, &
      & iwcon_1D, rad_1D
-        real, dimension(klev), intent(in) :: pres, dz, rhodz_1D
-        real, intent(out) :: cc_tot_mesh, cc_hc_mesh, cc_hist_mesh
-        real, intent(out) :: cc_Cb_mesh, cc_ThCi_mesh, cc_Anv_mesh
-        real, intent(out) :: em_hc_mesh, pcld_hc_mesh, tcld_hc_mesh, &
+        REAL, DIMENSION(klev), intent(in) :: pres, dz, rhodz_1D
+        REAL, intent(out) :: cc_tot_mesh, cc_hc_mesh, cc_hist_mesh
+        REAL, intent(out) :: cc_Cb_mesh, cc_ThCi_mesh, cc_Anv_mesh
+        REAL, intent(out) :: em_hc_mesh, pcld_hc_mesh, tcld_hc_mesh, &
      & iwp_hc_mesh
 
-        real, intent(out) :: pcld_Cb_mesh, tcld_Cb_mesh, em_Cb_mesh
-        real, intent(out) :: pcld_ThCi_mesh, tcld_ThCi_mesh, &
+        REAL, intent(out) :: pcld_Cb_mesh, tcld_Cb_mesh, em_Cb_mesh
+        REAL, intent(out) :: pcld_ThCi_mesh, tcld_ThCi_mesh, &
      & em_ThCi_mesh
-        real, intent(out) :: pcld_Anv_mesh, tcld_Anv_mesh, em_Anv_mesh
-
-        real, intent(out) :: em_hist_mesh, iwp_hist_mesh, rad_hist_mesh
-        real, intent(out) :: deltaz_hc_mesh, deltaz_hist_mesh
-
-        real, dimension(:), allocatable :: rneb_cs, temp_cs, emis_cs, &
+        REAL, intent(out) :: pcld_Anv_mesh, tcld_Anv_mesh, em_Anv_mesh
+
+        REAL, intent(out) :: em_hist_mesh, iwp_hist_mesh, rad_hist_mesh
+        REAL, intent(out) :: deltaz_hc_mesh, deltaz_hist_mesh
+
+        REAL, DIMENSION(:), allocatable :: rneb_cs, temp_cs, emis_cs, &
      & iwco_cs
-        real, dimension(:), allocatable :: pres_cs, dz_cs, rad_cs, &
+        REAL, DIMENSION(:), allocatable :: pres_cs, dz_cs, rad_cs, &
      & rhodz_cs
 
-        integer :: i,j,l
-        integer :: ltop, itop, ibot, num_cs, N_cs, len_cs, ics
-
-        real :: som_emi_hc,som_pcl_hc,som_tcl_hc,som_iwp_hc,som_hc,&
+        INTEGER :: i,j,l
+        INTEGER :: ltop, itop, ibot, num_cs, N_cs, len_cs, ics
+
+        REAL :: som_emi_hc,som_pcl_hc,som_tcl_hc,som_iwp_hc,som_hc,&
      & som_hist
-        real :: som_emi_hist, som_iwp_hist, som_deltaz_hc, &
+        REAL :: som_emi_hist, som_iwp_hist, som_deltaz_hc, &
      & som_deltaz_hist
-        real :: som_rad_hist
-        real :: som_Cb, som_ThCi, som_Anv
-        real :: som_emi_Cb, som_tcld_Cb, som_pcld_Cb
-        real :: som_emi_Anv, som_tcld_Anv, som_pcld_Anv
-        real :: som_emi_ThCi, som_tcld_ThCi, som_pcld_ThCi
-        real :: tsom_tot, tsom_hc, tsom_hist
-        real :: prod, prod_hh
-
-        real :: cc_tot_cs, cc_hc_cs, cc_hist_cs
-        real :: cc_Cb_cs, cc_ThCi_cs, cc_Anv_cs
-        real :: pcld_hc_cs, tcld_hc_cs
-        real :: em_hc_cs, iwp_hc_cs, deltaz_hc_cs
-        real :: pcld_Cb_cs, tcld_Cb_cs, em_Cb_cs
-        real :: pcld_ThCi_cs, tcld_ThCi_cs, em_ThCi_cs
-        real :: pcld_Anv_cs, tcld_Anv_cs, em_Anv_cs
-        real :: em_hist_cs, iwp_hist_cs, deltaz_hist_cs, rad_hist_cs
-
-        real, dimension(klev) :: test_tot, test_hc, test_hist
-        real, dimension(klev) :: test_pcld, test_tcld, test_em, test_iwp
-
+        REAL :: som_rad_hist
+        REAL :: som_Cb, som_ThCi, som_Anv
+        REAL :: som_emi_Cb, som_tcld_Cb, som_pcld_Cb
+        REAL :: som_emi_Anv, som_tcld_Anv, som_pcld_Anv
+        REAL :: som_emi_ThCi, som_tcld_ThCi, som_pcld_ThCi
+        REAL :: tsom_tot, tsom_hc, tsom_hist
+        REAL :: prod, prod_hh
+
+        REAL :: cc_tot_cs, cc_hc_cs, cc_hist_cs
+        REAL :: cc_Cb_cs, cc_ThCi_cs, cc_Anv_cs
+        REAL :: pcld_hc_cs, tcld_hc_cs
+        REAL :: em_hc_cs, iwp_hc_cs, deltaz_hc_cs
+        REAL :: pcld_Cb_cs, tcld_Cb_cs, em_Cb_cs
+        REAL :: pcld_ThCi_cs, tcld_ThCi_cs, em_ThCi_cs
+        REAL :: pcld_Anv_cs, tcld_Anv_cs, em_Anv_cs
+        REAL :: em_hist_cs, iwp_hist_cs, deltaz_hist_cs, rad_hist_cs
+
+        REAL, DIMENSION(klev) :: test_tot, test_hc, test_hist
+        REAL, DIMENSION(klev) :: test_pcld, test_tcld, test_em, test_iwp
+
+        CHARACTER (len = 50)      :: modname = 'simu_airs.sim_mesh'
+        CHARACTER (len = 160)     :: abort_message
+        
 
         do j = 1, klev
-        write(*,*) 'simu_airs, j, rneb_1D =', rneb_1D(j)
+          WRITE(lunout,*) 'simu_airs, j, rneb_1D =', rneb_1D(j)
         enddo
 
@@ -991,41 +1004,35 @@
        if (cc_tot_mesh .gt. tsom_tot .and. &
      & abs(cc_tot_mesh-tsom_tot) .gt. 1.e-4) then
-        write(*,*) 'cc_tot_mesh > tsom_tot'
-        write(*,*) cc_tot_mesh, tsom_tot
-        STOP
+           WRITE(abort_message,*)'cc_tot_mesh > tsom_tot', cc_tot_mesh, tsom_tot
+           CALL abort_physic(modname,abort_message,1)
         endif
 
         if (cc_tot_mesh .lt. maxval(test_tot(1:N_CS)) .and. &
      & abs(cc_tot_mesh-maxval(test_tot(1:N_CS))) .gt. 1.e-4) then
-        write(*,*) 'cc_tot_mesh < max'
-        write(*,*) cc_tot_mesh, maxval(test_tot(1:N_CS))
-        STOP
+           WRITE(abort_message,*) 'cc_tot_mesh < max', cc_tot_mesh, maxval(test_tot(1:N_CS))
+           CALL abort_physic(modname,abort_message,1)
         endif
 
         if (cc_hc_mesh .gt. tsom_hc .and. &
      & abs(cc_hc_mesh-tsom_hc) .gt. 1.e-4) then
-        write(*,*) 'cc_hc_mesh > tsom_hc'
-        write(*,*) cc_hc_mesh, tsom_hc
-        STOP
+           WRITE(abort_message,*) 'cc_hc_mesh > tsom_hc', cc_hc_mesh, tsom_hc
+           CALL abort_physic(modname,abort_message,1)
         endif
 
         if (cc_hc_mesh .lt. maxval(test_hc(1:N_CS)) .and. &
      & abs(cc_hc_mesh-maxval(test_hc(1:N_CS))) .gt. 1.e-4) then
-        write(*,*) 'cc_hc_mesh < max'
-        write(*,*) cc_hc_mesh, maxval(test_hc(1:N_CS))
-        STOP
+           WRITE(abort_message,*) 'cc_hc_mesh < max', cc_hc_mesh, maxval(test_hc(1:N_CS))
+           CALL abort_physic(modname,abort_message,1)
         endif
 
         if (cc_hist_mesh .gt. tsom_hist .and. &
      & abs(cc_hist_mesh-tsom_hist) .gt. 1.e-4) then
-        write(*,*) 'cc_hist_mesh > tsom_hist'
-        write(*,*) cc_hist_mesh, tsom_hist
-        STOP
+           WRITE(abort_message,*) 'cc_hist_mesh > tsom_hist', cc_hist_mesh, tsom_hist
+           CALL abort_physic(modname,abort_message,1)
         endif
 
         if (cc_hist_mesh .lt. 0.) then
-        write(*,*) 'cc_hist_mesh < 0'
-        write(*,*) cc_hist_mesh
-        STOP
+           WRITE(abort_message,*) 'cc_hist_mesh < 0', cc_hist_mesh
+           CALL abort_physic(modname,abort_message,1)
         endif
 
@@ -1035,8 +1042,7 @@
      & maxval(test_pcld(1:N_CS)) .ne. 999. &
      & .and. minval(test_pcld(1:N_CS)) .ne. 999.) then
-        write(*,*) 'pcld_hc_mesh est faux'
-        write(*,*) pcld_hc_mesh, maxval(test_pcld(1:N_CS)), &
+           WRITE(abort_message,*) 'pcld_hc_mesh est faux', pcld_hc_mesh, maxval(test_pcld(1:N_CS)), &
      & minval(test_pcld(1:N_CS))
-        STOP
+           CALL abort_physic(modname,abort_message,1)
         endif
 
@@ -1046,7 +1052,7 @@
      & maxval(test_tcld(1:N_CS)) .ne. 999. &
      & .and. minval(test_tcld(1:N_CS)) .ne. 999.) then
-        write(*,*) 'tcld_hc_mesh est faux'
-        write(*,*) tcld_hc_mesh, maxval(test_tcld(1:N_CS)), &
-     & minval(test_tcld(1:N_CS))
+           WRITE(abort_message,*) 'tcld_hc_mesh est faux', tcld_hc_mesh, maxval(test_tcld(1:N_CS)), &
+                & minval(test_tcld(1:N_CS))
+           CALL abort_physic(modname,abort_message,1)
         endif
 
@@ -1056,8 +1062,7 @@
      & minval(test_em(1:N_CS)) .ne. 999. .and. &
      & maxval(test_em(1:N_CS)) .ne. 999. ) then
-        write(*,*) 'em_hc_mesh est faux'
-        write(*,*) em_hc_mesh, maxval(test_em(1:N_CS)), &
+           WRITE(abort_message,*) 'em_hc_mesh est faux', em_hc_mesh, maxval(test_em(1:N_CS)), &
      & minval(test_em(1:N_CS))
-        STOP
+           CALL abort_physic(modname,abort_message,1)
         endif
 
@@ -1101,11 +1106,12 @@
         subroutine test_bornes(sx,x,bsup,binf)
 
-        real, intent(in) :: x, bsup, binf
+        REAL, intent(in) :: x, bsup, binf
         character*14, intent(in) :: sx
+        CHARACTER (len = 50)      :: modname = 'simu_airs.test_bornes'
+        CHARACTER (len = 160)     :: abort_message
 
         if (x .gt. bsup .or. x .lt. binf) then
-        write(*,*) sx, 'est faux'
-        write(*,*) sx, x
-        STOP
+          WRITE(abort_message,*) sx, 'est faux', sx, x
+          CALL abort_physic(modname,abort_message,1)
         endif
  
@@ -1134,44 +1140,44 @@
         include "YOMCST.h"
 
-        integer,intent(in) :: itap
-
-        real, dimension(klon,klev), intent(in) :: &
+        INTEGER,intent(in) :: itap
+
+        REAL, DIMENSION(klon,klev), intent(in) :: &
      & rneb_airs, temp_airs, cldemi_airs, iwcon0_airs, &
      & rad_airs, geop_airs, pplay_airs, paprs_airs
 
-       real, dimension(klon,klev) :: &
+       REAL, DIMENSION(klon,klev) :: &
      & rhodz_airs, rho_airs, iwcon_airs
 
-        real, dimension(klon),intent(out) :: alt_tropo
-
-        real, dimension(klev) :: rneb_1D, temp_1D, &
+        REAL, DIMENSION(klon),intent(out) :: alt_tropo
+
+        REAL, DIMENSION(klev) :: rneb_1D, temp_1D, &
      & emis_1D, rad_1D, pres_1D, alt_1D, &
      & rhodz_1D, dz_1D, iwcon_1D
 
-        integer :: i, j
-
-        real :: cc_tot_mesh, cc_hc_mesh, cc_hist_mesh
-        real :: cc_Cb_mesh, cc_ThCi_mesh, cc_Anv_mesh
-        real :: pcld_hc_mesh, tcld_hc_mesh, em_hc_mesh, iwp_hc_mesh
-        real :: em_hist_mesh, iwp_hist_mesh
-        real :: deltaz_hc_mesh, deltaz_hist_mesh, rad_hist_mesh
-        real :: pcld_Cb_mesh, tcld_Cb_mesh, em_Cb_mesh
-        real :: pcld_ThCi_mesh, tcld_ThCi_mesh, em_ThCi_mesh
-        real :: pcld_Anv_mesh, tcld_Anv_mesh, em_Anv_mesh
-
-        real, dimension(klon),intent(out) :: map_prop_hc, map_prop_hist
-        real, dimension(klon),intent(out) :: map_emis_hc, map_iwp_hc
-        real, dimension(klon),intent(out) :: map_deltaz_hc, map_pcld_hc
-        real, dimension(klon),intent(out) :: map_tcld_hc
-        real, dimension(klon),intent(out) :: map_emis_Cb,map_pcld_Cb,map_tcld_Cb 
-        real, dimension(klon),intent(out) :: &
+        INTEGER :: i, j
+
+        REAL :: cc_tot_mesh, cc_hc_mesh, cc_hist_mesh
+        REAL :: cc_Cb_mesh, cc_ThCi_mesh, cc_Anv_mesh
+        REAL :: pcld_hc_mesh, tcld_hc_mesh, em_hc_mesh, iwp_hc_mesh
+        REAL :: em_hist_mesh, iwp_hist_mesh
+        REAL :: deltaz_hc_mesh, deltaz_hist_mesh, rad_hist_mesh
+        REAL :: pcld_Cb_mesh, tcld_Cb_mesh, em_Cb_mesh
+        REAL :: pcld_ThCi_mesh, tcld_ThCi_mesh, em_ThCi_mesh
+        REAL :: pcld_Anv_mesh, tcld_Anv_mesh, em_Anv_mesh
+
+        REAL, DIMENSION(klon),intent(out) :: map_prop_hc, map_prop_hist
+        REAL, DIMENSION(klon),intent(out) :: map_emis_hc, map_iwp_hc
+        REAL, DIMENSION(klon),intent(out) :: map_deltaz_hc, map_pcld_hc
+        REAL, DIMENSION(klon),intent(out) :: map_tcld_hc
+        REAL, DIMENSION(klon),intent(out) :: map_emis_Cb,map_pcld_Cb,map_tcld_Cb 
+        REAL, DIMENSION(klon),intent(out) :: &
      & map_emis_ThCi,map_pcld_ThCi,map_tcld_ThCi
-        real, dimension(klon),intent(out) :: &
+        REAL, DIMENSION(klon),intent(out) :: &
      & map_emis_Anv,map_pcld_Anv,map_tcld_Anv
-        real, dimension(klon),intent(out) :: &
+        REAL, DIMENSION(klon),intent(out) :: &
      & map_emis_hist,map_iwp_hist,map_deltaz_hist,&
      & map_rad_hist
-       real, dimension(klon),intent(out) :: map_ntot,map_hc,map_hist
-       real, dimension(klon),intent(out) :: map_Cb,map_ThCi,map_Anv
+        REAL, DIMENSION(klon),intent(out) :: map_ntot,map_hc,map_hist
+        REAL, DIMENSION(klon),intent(out) :: map_Cb,map_ThCi,map_Anv
  
  
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/sisvat/surf_sisvat_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/sisvat/surf_sisvat_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/sisvat/surf_sisvat_mod.F90	(revision 3605)
@@ -1540,4 +1540,5 @@
     INTEGER isl, ikl, i, isn
     CHARACTER (len=2) :: str2
+    INTEGER           :: pass
 
       isno(:)       = 0       
@@ -1617,23 +1618,24 @@
 
       CALL open_restartphy(fichnom)
-      CALL put_field("longitude", &
+      DO pass = 1, 2
+        CALL put_field(pass,"longitude", &
                     "Longitudes de la grille physique",rlon)     
-      CALL put_field("latitude","Latitudes de la grille physique",rlat)
-
-      CALL put_field("n_snows", "number of snow/ice layers",isno)
-      CALL put_field("n_ice_top", "number of top ice layers",ispi)
-      CALL put_field("n_ice", "number of ice layers",iice)
-      CALL put_field("IR_soil", "Soil IR flux",IRs)
-      CALL put_field("LMO", "Monin-Obukhov Scale",LMO)
-      CALL put_field("surf_water", "Surficial water",rusn)
-      CALL put_field("snow_buffer", "Snow buffer layer",Bufs)
-      CALL put_field("alb_1", "albedo sw",alb1)
-      CALL put_field("alb_2", "albedo nIR",alb2)
-      CALL put_field("alb_3", "albedo fIR",alb3)
-      CALL put_field("to_ice", "Snow passed to ice",toic)
+        CALL put_field(pass,"latitude","Latitudes de la grille physique",rlat)
+  
+        CALL put_field(pass,"n_snows", "number of snow/ice layers",isno)
+        CALL put_field(pass,"n_ice_top", "number of top ice layers",ispi)
+        CALL put_field(pass,"n_ice", "number of ice layers",iice)
+        CALL put_field(pass,"IR_soil", "Soil IR flux",IRs)
+        CALL put_field(pass,"LMO", "Monin-Obukhov Scale",LMO)
+        CALL put_field(pass,"surf_water", "Surficial water",rusn)
+        CALL put_field(pass,"snow_buffer", "Snow buffer layer",Bufs)
+        CALL put_field(pass,"alb_1", "albedo sw",alb1)
+        CALL put_field(pass,"alb_2", "albedo nIR",alb2)
+        CALL put_field(pass,"alb_3", "albedo fIR",alb3)
+        CALL put_field(pass,"to_ice", "Snow passed to ice",toic)
 
  !     DO i = 1, 5
  !       WRITE(str2,'(i2.2)') i
- !       CALL put_field("turb_veloc"//str2, &
+ !       CALL put_field(pass,"turb_veloc"//str2, &
  !                      "various turbulent velocities"//str2, &
  !                      turb_vel(:,i))
@@ -1641,96 +1643,97 @@
  !     DO i = 1, 9
  !       WRITE(str2,'(i2.2)') i
- !       CALL put_field("rough_length"//str2, &
+ !       CALL put_field(pass,"rough_length"//str2, &
  !                      "various roughness lengths"//str2, &
  !                      rlength(:,i))
  !     ENDDO
-      DO isn = 1,nsno
-        IF (isn.LE.99) THEN
-          WRITE(str2,'(i2.2)') isn
-          CALL put_field("AGESNOW"//str2, &
+        DO isn = 1,nsno
+          IF (isn.LE.99) THEN
+            WRITE(str2,'(i2.2)') isn
+            CALL put_field(pass,"AGESNOW"//str2, &
                          "Age de la neige layer No."//str2, &
                          agsn(:,isn))
-        ELSE
-          PRINT*, "Trop de couches"
-          CALL abort
-        ENDIF
-      ENDDO
-      DO isn = 1,nsno
-        IF (isn.LE.99) THEN
-          WRITE(str2,'(i2.2)') isn
-          CALL put_field("DZSNOW"//str2, &
+          ELSE
+            PRINT*, "Trop de couches"
+            CALL abort
+          ENDIF
+        ENDDO
+        DO isn = 1,nsno
+          IF (isn.LE.99) THEN
+            WRITE(str2,'(i2.2)') isn
+            CALL put_field(pass,"DZSNOW"//str2, &
                          "Snow/ice thickness layer No."//str2, &
                          dzsn(:,isn))
-        ELSE
-          PRINT*, "Trop de couches"
-          CALL abort
-        ENDIF
-      ENDDO
-      DO isn = 1,nsno
-        IF (isn.LE.99) THEN
-          WRITE(str2,'(i2.2)') isn
-          CALL put_field("G2SNOW"//str2, &
+          ELSE
+            PRINT*, "Trop de couches"
+            CALL abort
+          ENDIF
+        ENDDO
+        DO isn = 1,nsno
+          IF (isn.LE.99) THEN
+            WRITE(str2,'(i2.2)') isn
+            CALL put_field(pass,"G2SNOW"//str2, &
                          "Snow Property 2, layer No."//str2, &
                          G2sn(:,isn))
-        ELSE
-          PRINT*, "Trop de couches"
-          CALL abort
-        ENDIF
-      ENDDO
-      DO isn = 1,nsno
-        IF (isn.LE.99) THEN
-          WRITE(str2,'(i2.2)') isn
-          CALL put_field("G1SNOW"//str2, &
+          ELSE
+            PRINT*, "Trop de couches"
+            CALL abort
+          ENDIF
+        ENDDO
+        DO isn = 1,nsno
+          IF (isn.LE.99) THEN
+            WRITE(str2,'(i2.2)') isn
+            CALL put_field(pass,"G1SNOW"//str2, &
                          "Snow Property 1, layer No."//str2, &
                          G1sn(:,isn))
-        ELSE
-          PRINT*, "Trop de couches"
-          CALL abort
-        ENDIF
-      ENDDO
-      DO isn = 1,nsismx
-        IF (isn.LE.99) THEN
-          WRITE(str2,'(i2.2)') isn
-          CALL put_field("ETA"//str2, &
+          ELSE
+            PRINT*, "Trop de couches"
+            CALL abort
+          ENDIF
+        ENDDO
+        DO isn = 1,nsismx
+          IF (isn.LE.99) THEN
+            WRITE(str2,'(i2.2)') isn
+            CALL put_field(pass,"ETA"//str2, &
                          "Soil/snow water content layer No."//str2, &
                          eta(:,isn))
-        ELSE
-          PRINT*, "Trop de couches"
-          CALL abort
-        ENDIF
+          ELSE
+            PRINT*, "Trop de couches"
+            CALL abort
+          ENDIF
+        ENDDO
+        DO isn = 1,nsismx   !nsno
+          IF (isn.LE.99) THEN
+            WRITE(str2,'(i2.2)') isn
+            CALL put_field(pass,"RO"//str2, &
+                           "Snow density layer No."//str2, &
+                           ro(:,isn))
+          ELSE
+            PRINT*, "Trop de couches"
+            CALL abort
+          ENDIF
+        ENDDO
+        DO isn = 1,nsismx
+          IF (isn.LE.99) THEN
+            WRITE(str2,'(i2.2)') isn
+            CALL put_field(pass,"TSS"//str2, &
+                           "Soil/snow temperature layer No."//str2, &
+                           Tsis(:,isn))
+          ELSE
+            PRINT*, "Trop de couches"
+            CALL abort
+          ENDIF
+        ENDDO
+        DO isn = 1,nsno
+          IF (isn.LE.99) THEN
+            WRITE(str2,'(i2.2)') isn
+            CALL put_field(pass,"HISTORY"//str2, &
+                           "Snow history layer No."//str2, &
+                           isto(:,isn))
+          ELSE
+            PRINT*, "Trop de couches"
+            CALL abort
+          ENDIF
+        ENDDO
       ENDDO
-      DO isn = 1,nsismx   !nsno
-        IF (isn.LE.99) THEN
-          WRITE(str2,'(i2.2)') isn
-          CALL put_field("RO"//str2, &
-                         "Snow density layer No."//str2, &
-                         ro(:,isn))
-        ELSE
-          PRINT*, "Trop de couches"
-          CALL abort
-        ENDIF
-      ENDDO
-      DO isn = 1,nsismx
-        IF (isn.LE.99) THEN
-          WRITE(str2,'(i2.2)') isn
-          CALL put_field("TSS"//str2, &
-                         "Soil/snow temperature layer No."//str2, &
-                         Tsis(:,isn))
-        ELSE
-          PRINT*, "Trop de couches"
-          CALL abort
-        ENDIF
-      ENDDO
-      DO isn = 1,nsno
-        IF (isn.LE.99) THEN
-          WRITE(str2,'(i2.2)') isn
-          CALL put_field("HISTORY"//str2, &
-                         "Snow history layer No."//str2, &
-                         isto(:,isn))
-        ELSE
-          PRINT*, "Trop de couches"
-          CALL abort
-        ENDIF
-      ENDDO
 
   END SUBROUTINE sisvatredem
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/slab_heat_transp_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/slab_heat_transp_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/slab_heat_transp_mod.F90	(revision 3605)
@@ -83,6 +83,5 @@
                                   cu_,cuvsurcv_,cv_,cvusurcu_, &
                                   aire_,apoln_,apols_, &
-                                  aireu_,airev_,rlatv)
-    USE comconst_mod, ONLY: omeg, rad
+                                  aireu_,airev_,rlatv, rad, omeg)
     ! number of points in lon, lat
     IMPLICIT NONE
@@ -104,10 +103,15 @@
     REAL,INTENT(IN) :: airev_(ip1jm)
     REAL,INTENT(IN) :: rlatv(nbp_lat-1)
-
+    REAL,INTENT(IN) :: rad
+    REAL,INTENT(IN) :: omeg
+
+    CHARACTER (len = 20) :: modname = 'slab_heat_transp'
+    CHARACTER (len = 80) :: abort_message
+    
     ! Sanity check on dimensions
     if ((ip1jm.ne.((nbp_lon+1)*(nbp_lat-1))).or. &
         (ip1jmp1.ne.((nbp_lon+1)*nbp_lat))) then
-      write(*,*) "ini_slab_transp_geom Error: wrong array sizes"
-      stop
+      abort_message="ini_slab_transp_geom Error: wrong array sizes"
+      CALL abort_physic(modname,abort_message,1)
     endif
 ! Allocations could be done only on master process/thread...
@@ -924,8 +928,11 @@
   INTEGER j,ifield,ig
 
+  CHARACTER (len = 20)                      :: modname = 'slab_heat_transp'
+  CHARACTER (len = 80)                      :: abort_message
+
   ! Sanity check:
   IF(klon_glo.NE.2+(jm-2)*(im-1)) THEN
-    WRITE(*,*) "gr_dyn_fi error, wrong sizes"
-    STOP
+    abort_message="gr_dyn_fi error, wrong sizes"
+    CALL abort_physic(modname,abort_message,1)
   ENDIF
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/suphel.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/suphel.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/suphel.F90	(revision 3605)
@@ -118,4 +118,8 @@
   rmo3 = 47.9942
   rmco2 = 44.011
+  rmch4 = 16.043
+  rmn2o = 44.013
+  rmcfc11 = 137.3686
+  rmcfc12 = 120.9140
   rmc   = 12.0107
   rmv = 18.0153
@@ -134,5 +138,9 @@
   WRITE (UNIT=6, FMT='('' Ozone   mass = '',e13.7)') rmo3
   WRITE (UNIT=6, FMT='('' CO2     mass = '',e13.7)') rmco2
-  WRITE (UNIT=6, FMT='('' CO2     mass = '',e13.7)') rmc
+  WRITE (UNIT=6, FMT='('' C       mass = '',e13.7)') rmc
+  WRITE (UNIT=6, FMT='('' CH4     mass = '',e13.7)') rmch4
+  WRITE (UNIT=6, FMT='('' N2O     mass = '',e13.7)') rmn2o
+  WRITE (UNIT=6, FMT='('' CFC11   mass = '',e13.7)') rmcfc11
+  WRITE (UNIT=6, FMT='('' CFC12   mass = '',e13.7)') rmcfc12
   WRITE (UNIT=6, FMT='('' Vapour  mass = '',e13.7)') rmv
   WRITE (UNIT=6, FMT='('' Dry air cst. = '',e13.7)') rd
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/surf_land_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/surf_land_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/surf_land_mod.F90	(revision 3605)
@@ -41,5 +41,10 @@
     USE surf_land_orchidee_nofrein_mod
 #else
+#if ORCHIDEE_NOUNSTRUCT
+    ! Compilation with cpp key ORCHIDEE_NOUNSTRUCT
+    USE surf_land_orchidee_nounstruct_mod
+#else
     USE surf_land_orchidee_mod
+#endif
 #endif
 #endif
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/surf_land_orchidee_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/surf_land_orchidee_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/surf_land_orchidee_mod.F90	(revision 3605)
@@ -4,4 +4,5 @@
 #ifndef ORCHIDEE_NOZ0H
 #ifndef ORCHIDEE_NOFREIN
+#ifndef ORCHIDEE_NOUNSTRUCT
 !
 ! This module controles the interface towards the model ORCHIDEE.
@@ -23,9 +24,10 @@
   USE cpl_mod,      ONLY : cpl_send_land_fields
   USE surface_data, ONLY : type_ocean
-  USE geometry_mod, ONLY : dx, dy
+  USE geometry_mod, ONLY : dx, dy, boundslon, boundslat,longitude, latitude, cell_area,  ind_cell_glo
   USE mod_grid_phy_lmdz
   USE mod_phys_lmdz_para, mpi_root_rank=>mpi_master
   USE carbon_cycle_mod, ONLY : nbcf_in_orc, nbcf_out, fields_in, yfields_in, yfields_out, cfname_in, cfname_out
-
+  USE nrtype, ONLY : PI
+  
   IMPLICIT NONE
 
@@ -165,4 +167,7 @@
     REAL, ALLOCATABLE, DIMENSION(:,:), SAVE   :: lalo
     !$OMP THREADPRIVATE(lalo)
+! boundaries of cells
+    REAL, ALLOCATABLE, DIMENSION(:,:,:), SAVE   :: bounds_lalo
+    !$OMP THREADPRIVATE(bounds_lalo)
 ! pts voisins
     INTEGER,ALLOCATABLE, DIMENSION(:,:), SAVE :: neighbours
@@ -178,4 +183,8 @@
     !$OMP THREADPRIVATE(lon_scat,lat_scat)
 
+! area of cells
+    REAL, ALLOCATABLE, DIMENSION (:), SAVE  :: area  
+    !$OMP THREADPRIVATE(area)
+
     LOGICAL, SAVE                             :: lrestart_read = .TRUE.
     !$OMP THREADPRIVATE(lrestart_read)
@@ -209,6 +218,17 @@
     !$OMP THREADPRIVATE(riverflow)
     
+    INTEGER :: orch_mpi_rank
+    INTEGER :: orch_mpi_size
     INTEGER :: orch_omp_rank
     INTEGER :: orch_omp_size
+
+    REAL, ALLOCATABLE, DIMENSION(:)         :: longitude_glo
+    REAL, ALLOCATABLE, DIMENSION(:)         :: latitude_glo
+    REAL, ALLOCATABLE, DIMENSION(:,:)       :: boundslon_glo
+    REAL, ALLOCATABLE, DIMENSION(:,:)       :: boundslat_glo
+    INTEGER, ALLOCATABLE, DIMENSION(:)      :: ind_cell_glo_glo
+    INTEGER, ALLOCATABLE, SAVE,DIMENSION(:) :: ind_cell
+    !$OMP THREADPRIVATE(ind_cell)
+    INTEGER :: begin, end
 !
 ! Fin definition
@@ -253,66 +273,123 @@
        jg(klon) = nbp_lat
 
-       IF ((.NOT. ALLOCATED(lalo))) THEN
-          ALLOCATE(lalo(knon,2), stat = error)
+       IF ((.NOT. ALLOCATED(area))) THEN
+          ALLOCATE(area(knon), stat = error)
           IF (error /= 0) THEN
+             abort_message='Pb allocation area'
+             CALL abort_physic(modname,abort_message,1)
+          ENDIF
+       ENDIF
+       DO igrid = 1, knon
+          area(igrid) = cell_area(knindex(igrid))
+       ENDDO
+       
+       IF (grid_type==unstructured) THEN
+
+
+         IF ((.NOT. ALLOCATED(lon_scat))) THEN
+            ALLOCATE(lon_scat(nbp_lon,nbp_lat), stat = error)
+            IF (error /= 0) THEN
+               abort_message='Pb allocation lon_scat'
+               CALL abort_physic(modname,abort_message,1)
+            ENDIF
+         ENDIF
+ 
+         IF ((.NOT. ALLOCATED(lat_scat))) THEN
+            ALLOCATE(lat_scat(nbp_lon,nbp_lat), stat = error)
+            IF (error /= 0) THEN
+               abort_message='Pb allocation lat_scat'
+               CALL abort_physic(modname,abort_message,1)
+            ENDIF
+         ENDIF
+         CALL Gather(rlon,rlon_g)
+         CALL Gather(rlat,rlat_g)
+
+         IF (is_mpi_root) THEN
+            index = 1
+            DO jj = 2, nbp_lat-1
+               DO ij = 1, nbp_lon
+                  index = index + 1
+                  lon_scat(ij,jj) = rlon_g(index)
+                  lat_scat(ij,jj) = rlat_g(index)
+               ENDDO
+            ENDDO
+            lon_scat(:,1) = lon_scat(:,2)
+            lat_scat(:,1) = rlat_g(1)
+            lon_scat(:,nbp_lat) = lon_scat(:,2)
+            lat_scat(:,nbp_lat) = rlat_g(klon_glo)
+         ENDIF
+     
+         CALL bcast(lon_scat)
+         CALL bcast(lat_scat)
+                
+       ELSE IF (grid_type==regular_lonlat) THEN
+
+         IF ((.NOT. ALLOCATED(lalo))) THEN
+            ALLOCATE(lalo(knon,2), stat = error)
+            IF (error /= 0) THEN
+               abort_message='Pb allocation lalo'
+               CALL abort_physic(modname,abort_message,1)
+            ENDIF
+         ENDIF
+       
+         IF ((.NOT. ALLOCATED(bounds_lalo))) THEN
+           ALLOCATE(bounds_lalo(knon,nvertex,2), stat = error)
+           IF (error /= 0) THEN
              abort_message='Pb allocation lalo'
              CALL abort_physic(modname,abort_message,1)
-          ENDIF
-       ENDIF
-       IF ((.NOT. ALLOCATED(lon_scat))) THEN
-          ALLOCATE(lon_scat(nbp_lon,nbp_lat), stat = error)
-          IF (error /= 0) THEN
-             abort_message='Pb allocation lon_scat'
-             CALL abort_physic(modname,abort_message,1)
-          ENDIF
-       ENDIF
-       IF ((.NOT. ALLOCATED(lat_scat))) THEN
-          ALLOCATE(lat_scat(nbp_lon,nbp_lat), stat = error)
-          IF (error /= 0) THEN
-             abort_message='Pb allocation lat_scat'
-             CALL abort_physic(modname,abort_message,1)
-          ENDIF
-       ENDIF
-       lon_scat = 0.
-       lat_scat = 0.
-       DO igrid = 1, knon
-          index = knindex(igrid)
-          lalo(igrid,2) = rlon(index)
-          lalo(igrid,1) = rlat(index)
-       ENDDO
-
-       
-       
-       CALL Gather(rlon,rlon_g)
-       CALL Gather(rlat,rlat_g)
-
-       IF (is_mpi_root) THEN
-          index = 1
-          DO jj = 2, nbp_lat-1
-             DO ij = 1, nbp_lon
-                index = index + 1
-                lon_scat(ij,jj) = rlon_g(index)
-                lat_scat(ij,jj) = rlat_g(index)
-             ENDDO
-          ENDDO
-          lon_scat(:,1) = lon_scat(:,2)
-          lat_scat(:,1) = rlat_g(1)
-          lon_scat(:,nbp_lat) = lon_scat(:,2)
-          lat_scat(:,nbp_lat) = rlat_g(klon_glo)
-       ENDIF
+           ENDIF
+         ENDIF
+       
+         IF ((.NOT. ALLOCATED(lon_scat))) THEN
+            ALLOCATE(lon_scat(nbp_lon,nbp_lat), stat = error)
+            IF (error /= 0) THEN
+               abort_message='Pb allocation lon_scat'
+               CALL abort_physic(modname,abort_message,1)
+            ENDIF
+         ENDIF
+         IF ((.NOT. ALLOCATED(lat_scat))) THEN
+            ALLOCATE(lat_scat(nbp_lon,nbp_lat), stat = error)
+            IF (error /= 0) THEN
+               abort_message='Pb allocation lat_scat'
+               CALL abort_physic(modname,abort_message,1)
+            ENDIF
+         ENDIF
+         lon_scat = 0.
+         lat_scat = 0.
+         DO igrid = 1, knon
+            index = knindex(igrid)
+            lalo(igrid,2) = rlon(index)
+            lalo(igrid,1) = rlat(index)
+            bounds_lalo(igrid,:,2)=boundslon(index,:)*180./PI
+            bounds_lalo(igrid,:,1)=boundslat(index,:)*180./PI
+         ENDDO
+
+       
+       
+         CALL Gather(rlon,rlon_g)
+         CALL Gather(rlat,rlat_g)
+
+         IF (is_mpi_root) THEN
+            index = 1
+            DO jj = 2, nbp_lat-1
+               DO ij = 1, nbp_lon
+                  index = index + 1
+                  lon_scat(ij,jj) = rlon_g(index)
+                  lat_scat(ij,jj) = rlat_g(index)
+               ENDDO
+            ENDDO
+            lon_scat(:,1) = lon_scat(:,2)
+            lat_scat(:,1) = rlat_g(1)
+            lon_scat(:,nbp_lat) = lon_scat(:,2)
+            lat_scat(:,nbp_lat) = rlat_g(klon_glo)
+         ENDIF
    
-       CALL bcast(lon_scat)
-       CALL bcast(lat_scat)
+         CALL bcast(lon_scat)
+         CALL bcast(lat_scat)
+       
+       ENDIF
 !
 ! Allouer et initialiser le tableau des voisins et des fraction de continents
 !
-       IF ( (.NOT.ALLOCATED(neighbours))) THEN
-          ALLOCATE(neighbours(knon,8), stat = error)
-          IF (error /= 0) THEN
-             abort_message='Pb allocation neighbours'
-             CALL abort_physic(modname,abort_message,1)
-          ENDIF
-       ENDIF
-       neighbours = -1.
        IF (( .NOT. ALLOCATED(contfrac))) THEN
           ALLOCATE(contfrac(knon), stat = error)
@@ -329,5 +406,29 @@
 
 
-       CALL Init_neighbours(knon,neighbours,knindex,pctsrf(:,is_ter))
+       IF (grid_type==regular_lonlat) THEN
+ 
+         IF ( (.NOT.ALLOCATED(neighbours))) THEN
+          ALLOCATE(neighbours(knon,8), stat = error)
+          IF (error /= 0) THEN
+             abort_message='Pb allocation neighbours'
+             CALL abort_physic(modname,abort_message,1)
+          ENDIF
+         ENDIF
+         neighbours = -1.
+         CALL Init_neighbours(knon,neighbours,knindex,pctsrf(:,is_ter))
+
+       ELSE IF (grid_type==unstructured) THEN
+ 
+         IF ( (.NOT.ALLOCATED(neighbours))) THEN
+          ALLOCATE(neighbours(knon,12), stat = error)
+          IF (error /= 0) THEN
+             abort_message='Pb allocation neighbours'
+             CALL abort_physic(modname,abort_message,1)
+          ENDIF
+         ENDIF
+         neighbours = -1.
+ 
+       ENDIF
+         
 
 !
@@ -340,10 +441,13 @@
           ENDIF
        ENDIF
-       DO igrid = 1, knon
-          ij = knindex(igrid)
-          resolution(igrid,1) = dx(ij)
-          resolution(igrid,2) = dy(ij)
-       ENDDO
-     
+       
+       IF (grid_type==regular_lonlat) THEN
+         DO igrid = 1, knon
+            ij = knindex(igrid)
+            resolution(igrid,1) = dx(ij)
+           resolution(igrid,2) = dy(ij)
+         ENDDO
+       ENDIF
+        
        ALLOCATE(coastalflow(klon), stat = error)
        IF (error /= 0) THEN
@@ -397,18 +501,64 @@
     IF (debut) THEN
        CALL Init_orchidee_index(knon,knindex,offset,ktindex)
-       CALL Get_orchidee_communicator(orch_comm,orch_omp_size,orch_omp_rank)
+       CALL Get_orchidee_communicator(orch_comm,orch_mpi_size,orch_mpi_rank, orch_omp_size,orch_omp_rank)
+
+       IF (grid_type==unstructured) THEN
+         IF (knon==0) THEN
+           begin=1
+           end=0
+         ELSE
+           begin=offset+1
+           end=offset+ktindex(knon)
+         ENDIF
+        
+         IF (orch_mpi_rank==orch_mpi_size-1 .AND. orch_omp_rank==orch_omp_size-1) end=nbp_lon*nbp_lat 
+          
+         ALLOCATE(lalo(end-begin+1,2))
+         ALLOCATE(bounds_lalo(end-begin+1,nvertex,2))
+         ALLOCATE(ind_cell(end-begin+1))
+         
+         ALLOCATE(longitude_glo(klon_glo))
+         CALL gather(longitude,longitude_glo)
+         CALL bcast(longitude_glo)
+         lalo(:,2)=longitude_glo(begin:end)*180./PI
+ 
+         ALLOCATE(latitude_glo(klon_glo))
+         CALL gather(latitude,latitude_glo)
+         CALL bcast(latitude_glo)
+         lalo(:,1)=latitude_glo(begin:end)*180./PI
+
+         ALLOCATE(boundslon_glo(klon_glo,nvertex))
+         CALL gather(boundslon,boundslon_glo)
+         CALL bcast(boundslon_glo)
+         bounds_lalo(:,:,2)=boundslon_glo(begin:end,:)*180./PI
+ 
+         ALLOCATE(boundslat_glo(klon_glo,nvertex))
+         CALL gather(boundslat,boundslat_glo)
+         CALL bcast(boundslat_glo)
+         bounds_lalo(:,:,1)=boundslat_glo(begin:end,:)*180./PI
+         
+         ALLOCATE(ind_cell_glo_glo(klon_glo))
+         CALL gather(ind_cell_glo,ind_cell_glo_glo)
+         CALL bcast(ind_cell_glo_glo)
+         ind_cell(:)=ind_cell_glo_glo(begin:end)
+         
+       ENDIF
        CALL Init_synchro_omp
+
+!$OMP BARRIER
        
        IF (knon > 0) THEN
 #ifdef CPP_VEGET
-         CALL Init_intersurf(nbp_lon,nbp_lat,knon,ktindex,offset,orch_omp_size,orch_omp_rank,orch_comm)
+         CALL Init_intersurf(nbp_lon,nbp_lat,knon,ktindex,offset,orch_omp_size,orch_omp_rank,orch_comm,grid=grid_type)
 #endif
        ENDIF
 
-       
-       IF (knon > 0) THEN
-
-         print *,'OB before intersurf=', SIZE(cfname_in), SIZE(cfname_out)
+       CALL Synchro_omp
+
+       
+       IF (knon > 0) THEN 
+
 #ifdef CPP_VEGET
+
          CALL intersurf_initialize_gathered (itime+itau_phy-1, nbp_lon, nbp_lat, knon, ktindex, dtime, &
                lrestart_read, lrestart_write, lalo, contfrac, neighbours, resolution, date0, &
@@ -418,9 +568,7 @@
                evap, fluxsens, fluxlat, coastalflow, riverflow, &
                tsol_rad, tsurf_new, qsurf, albedo_out, emis_new, z0m_new, &    
-! >> PC
-               !lon_scat, lat_scat, q2m, t2m, z0h_new, nvm_orch)
-               lon_scat, lat_scat, q2m, t2m, z0h_new, nvm_orch, &
+               lon_scat, lat_scat, q2m(1:knon), t2m(1:knon), z0h_new(1:knon), nvm_orch, &
+               grid=grid_type, bounds_latlon=bounds_lalo, cell_area=area, ind_cell_glo=ind_cell, &
                field_out_names=cfname_out, field_in_names=cfname_in(1:nbcf_in_orc))
-! << PC
 #endif         
        ENDIF
@@ -434,4 +582,5 @@
 !  swdown_vrai(1:knon) = swnet(1:knon)/(1. - albedo_keep(1:knon))
     swdown_vrai(1:knon) = swdown(1:knon)
+!$OMP BARRIER
 
     IF (knon > 0) THEN
@@ -450,5 +599,5 @@
             evap(1:knon), fluxsens(1:knon), fluxlat(1:knon), coastalflow(1:knon), riverflow(1:knon), &
             tsol_rad(1:knon), tsurf_new(1:knon), qsurf(1:knon), albedo_out(1:knon,:), emis_new(1:knon), z0m_new(1:knon), &
-            lon_scat, lat_scat, q2m, t2m, z0h_new(1:knon),&
+            lon_scat, lat_scat, q2m(1:knon), t2m(1:knon), z0h_new(1:knon),&
             veget(1:knon,:),lai(1:knon,:),height(1:knon,:),&
             fields_out=yfields_out(1:knon,1:nbcf_out),  &
@@ -542,5 +691,5 @@
 ! 
 
-  SUBROUTINE Get_orchidee_communicator(orch_comm,orch_omp_size,orch_omp_rank)
+  SUBROUTINE Get_orchidee_communicator(orch_comm, orch_mpi_size, orch_mpi_rank, orch_omp_size,orch_omp_rank)
   USE  mod_surf_para
       
@@ -550,4 +699,6 @@
 
     INTEGER,INTENT(OUT) :: orch_comm
+    INTEGER,INTENT(OUT) :: orch_mpi_size
+    INTEGER,INTENT(OUT) :: orch_mpi_rank
     INTEGER,INTENT(OUT) :: orch_omp_size
     INTEGER,INTENT(OUT) :: orch_omp_rank
@@ -568,4 +719,6 @@
 #ifdef CPP_MPI    
       CALL MPI_COMM_SPLIT(COMM_LMDZ_PHY,color,mpi_rank,orch_comm,ierr)
+      CALL MPI_COMM_SIZE(orch_comm,orch_mpi_size,ierr)
+      CALL MPI_COMM_RANK(orch_comm,orch_mpi_rank,ierr)
 #endif
     
@@ -696,3 +849,4 @@
 #endif
 #endif
+#endif
 END MODULE surf_land_orchidee_mod
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/surf_land_orchidee_nounstruct_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/surf_land_orchidee_nounstruct_mod.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/surf_land_orchidee_nounstruct_mod.F90	(revision 3605)
@@ -0,0 +1,682 @@
+!
+MODULE surf_land_orchidee_nounstruct_mod
+#ifndef ORCHIDEE_NOZ0H
+#ifdef ORCHIDEE_NOUNSTRUCT
+!
+! This module controles the interface towards the model ORCHIDEE.
+!
+! Compatibility with ORCHIDIEE :
+! The current version can be used with ORCHIDEE/trunk from revision xxxx.
+! This module is compiled only if cpp key ORCHIDEE_NOUNSTRUCT is defined.
+!
+! Subroutines in this module : surf_land_orchidee
+!                              Init_orchidee_index
+!                              Get_orchidee_communicator
+!                              Init_neighbours
+
+  USE dimphy
+#ifdef CPP_VEGET
+  USE intersurf     ! module d'ORCHIDEE
+#endif
+  USE cpl_mod,      ONLY : cpl_send_land_fields
+  USE surface_data, ONLY : type_ocean
+  USE geometry_mod, ONLY : dx, dy
+  USE mod_grid_phy_lmdz
+  USE mod_phys_lmdz_para, mpi_root_rank=>mpi_master
+
+  IMPLICIT NONE
+
+  PRIVATE
+  PUBLIC  :: surf_land_orchidee
+
+CONTAINS
+!
+!****************************************************************************************
+!  
+  SUBROUTINE surf_land_orchidee(itime, dtime, date0, knon, &
+       knindex, rlon, rlat, yrmu0, pctsrf, &
+       debut, lafin, &
+       plev,  u1_lay, v1_lay, gustiness, temp_air, spechum, epot_air, ccanopy, & 
+       tq_cdrag, petAcoef, peqAcoef, petBcoef, peqBcoef, &
+       precip_rain, precip_snow, lwdown, swnet, swdown, &
+       ps, q2m, t2m, &
+       evap, fluxsens, fluxlat, &              
+       tsol_rad, tsurf_new, alb1_new, alb2_new, &
+       emis_new, z0m_new, z0h_new, qsurf, &
+       veget, lai, height )
+
+
+    USE mod_surf_para
+    USE mod_synchro_omp
+    USE carbon_cycle_mod, ONLY : carbon_cycle_cpl
+    USE indice_sol_mod
+    USE print_control_mod, ONLY: lunout
+    USE mod_grid_phy_lmdz, ONLY: nbp_lon, nbp_lat
+#ifdef CPP_VEGET
+    USE time_phylmdz_mod, ONLY: itau_phy 
+#endif
+!    
+! Cette routine sert d'interface entre le modele atmospherique et le 
+! modele de sol continental. Appel a sechiba
+!
+! L. Fairhead 02/2000
+!
+! input:
+!   itime        numero du pas de temps
+!   dtime        pas de temps de la physique (en s)
+!   nisurf       index de la surface a traiter (1 = sol continental)
+!   knon         nombre de points de la surface a traiter
+!   knindex      index des points de la surface a traiter
+!   rlon         longitudes de la grille entiere
+!   rlat         latitudes de la grille entiere
+!   pctsrf       tableau des fractions de surface de chaque maille
+!   debut        logical: 1er appel a la physique (lire les restart)
+!   lafin        logical: dernier appel a la physique (ecrire les restart)
+!                     (si false calcul simplifie des fluxs sur les continents)
+!   plev         hauteur de la premiere couche (Pa)      
+!   u1_lay       vitesse u 1ere couche
+!   v1_lay       vitesse v 1ere couche
+!   temp_air     temperature de l'air 1ere couche
+!   spechum      humidite specifique 1ere couche
+!   epot_air     temp pot de l'air
+!   ccanopy      concentration CO2 canopee, correspond au co2_send de 
+!                carbon_cycle_mod ou valeur constant co2_ppm
+!   tq_cdrag     cdrag
+!   petAcoef     coeff. A de la resolution de la CL pour t
+!   peqAcoef     coeff. A de la resolution de la CL pour q
+!   petBcoef     coeff. B de la resolution de la CL pour t
+!   peqBcoef     coeff. B de la resolution de la CL pour q
+!   precip_rain  precipitation liquide
+!   precip_snow  precipitation solide
+!   lwdown       flux IR descendant a la surface
+!   swnet        flux solaire net
+!   swdown       flux solaire entrant a la surface
+!   ps           pression au sol
+!   radsol       rayonnement net aus sol (LW + SW)
+!   
+!
+! output:
+!   evap         evaporation totale
+!   fluxsens     flux de chaleur sensible
+!   fluxlat      flux de chaleur latente
+!   tsol_rad     
+!   tsurf_new    temperature au sol
+!   alb1_new     albedo in visible SW interval
+!   alb2_new     albedo in near IR interval
+!   emis_new     emissivite
+!   z0m_new      surface roughness for momentum
+!   z0h_new      surface roughness for heat
+!   qsurf        air moisture at surface
+!
+    INCLUDE "YOMCST.h"
+    INCLUDE "dimpft.h"
+
+
+  
+!
+! Parametres d'entree
+!****************************************************************************************
+    INTEGER, INTENT(IN)                       :: itime
+    REAL, INTENT(IN)                          :: dtime
+    REAL, INTENT(IN)                          :: date0
+    INTEGER, INTENT(IN)                       :: knon
+    INTEGER, DIMENSION(klon), INTENT(IN)      :: knindex
+    LOGICAL, INTENT(IN)                       :: debut, lafin
+    REAL, DIMENSION(klon,nbsrf), INTENT(IN)   :: pctsrf
+    REAL, DIMENSION(klon), INTENT(IN)         :: rlon, rlat
+    REAL, DIMENSION(klon), INTENT(IN)         :: yrmu0 ! cosine of solar zenith angle
+    REAL, DIMENSION(klon), INTENT(IN)         :: plev
+    REAL, DIMENSION(klon), INTENT(IN)         :: u1_lay, v1_lay, gustiness
+    REAL, DIMENSION(klon), INTENT(IN)         :: temp_air, spechum
+    REAL, DIMENSION(klon), INTENT(IN)         :: epot_air, ccanopy
+    REAL, DIMENSION(klon), INTENT(IN)         :: tq_cdrag
+    REAL, DIMENSION(klon), INTENT(IN)         :: petAcoef, peqAcoef
+    REAL, DIMENSION(klon), INTENT(IN)         :: petBcoef, peqBcoef
+    REAL, DIMENSION(klon), INTENT(IN)         :: precip_rain, precip_snow
+    REAL, DIMENSION(klon), INTENT(IN)         :: lwdown, swnet, swdown, ps
+    REAL, DIMENSION(klon), INTENT(IN)         :: q2m, t2m
+
+! Parametres de sortie
+!****************************************************************************************
+    REAL, DIMENSION(klon), INTENT(OUT)        :: evap, fluxsens, fluxlat, qsurf
+    REAL, DIMENSION(klon), INTENT(OUT)        :: tsol_rad, tsurf_new
+    REAL, DIMENSION(klon), INTENT(OUT)        :: alb1_new, alb2_new
+    REAL, DIMENSION(klon), INTENT(OUT)        :: emis_new, z0m_new, z0h_new
+    REAL, DIMENSION(klon,nvm_lmdz), INTENT(OUT) :: veget
+    REAL, DIMENSION(klon,nvm_lmdz), INTENT(OUT) :: lai
+    REAL, DIMENSION(klon,nvm_lmdz), INTENT(OUT) :: height
+
+
+! Local
+!****************************************************************************************
+    INTEGER                                   :: ij, jj, igrid, ireal, index
+    INTEGER                                   :: error
+    REAL, DIMENSION(klon)                     :: swdown_vrai
+    CHARACTER (len = 20)                      :: modname = 'surf_land_orchidee'
+    CHARACTER (len = 80)                      :: abort_message
+    LOGICAL,SAVE                              :: check = .FALSE.
+    !$OMP THREADPRIVATE(check)
+
+! type de couplage dans sechiba
+!  character (len=10)   :: coupling = 'implicit' 
+! drapeaux controlant les appels dans SECHIBA
+!  type(control_type), save   :: control_in
+! Preserved albedo
+    REAL, ALLOCATABLE, DIMENSION(:), SAVE     :: albedo_keep, zlev
+    !$OMP THREADPRIVATE(albedo_keep,zlev)
+! coordonnees geographiques
+    REAL, ALLOCATABLE, DIMENSION(:,:), SAVE   :: lalo
+    !$OMP THREADPRIVATE(lalo)
+! pts voisins
+    INTEGER,ALLOCATABLE, DIMENSION(:,:), SAVE :: neighbours
+    !$OMP THREADPRIVATE(neighbours)
+! fractions continents
+    REAL,ALLOCATABLE, DIMENSION(:), SAVE      :: contfrac
+    !$OMP THREADPRIVATE(contfrac)
+! resolution de la grille
+    REAL, ALLOCATABLE, DIMENSION (:,:), SAVE  :: resolution
+    !$OMP THREADPRIVATE(resolution)
+
+    REAL, ALLOCATABLE, DIMENSION (:,:), SAVE  :: lon_scat, lat_scat  
+    !$OMP THREADPRIVATE(lon_scat,lat_scat)
+
+    LOGICAL, SAVE                             :: lrestart_read = .TRUE.
+    !$OMP THREADPRIVATE(lrestart_read)
+    LOGICAL, SAVE                             :: lrestart_write = .FALSE.
+    !$OMP THREADPRIVATE(lrestart_write)
+
+    REAL, DIMENSION(knon,2)                   :: albedo_out
+
+! Pb de nomenclature
+    REAL, DIMENSION(klon)                     :: petA_orc, peqA_orc
+    REAL, DIMENSION(klon)                     :: petB_orc, peqB_orc
+! Pb de correspondances de grilles
+    INTEGER, DIMENSION(:), SAVE, ALLOCATABLE  :: ig, jg
+    !$OMP THREADPRIVATE(ig,jg)
+    INTEGER :: indi, indj
+    INTEGER, SAVE, ALLOCATABLE,DIMENSION(:)   :: ktindex
+    !$OMP THREADPRIVATE(ktindex)
+
+! Essai cdrag
+    REAL, DIMENSION(klon)                     :: cdrag
+    INTEGER,SAVE                              :: offset
+    !$OMP THREADPRIVATE(offset)
+
+    REAL, DIMENSION(klon_glo)                 :: rlon_g,rlat_g
+    INTEGER, SAVE                             :: orch_comm
+    !$OMP THREADPRIVATE(orch_comm)
+
+    REAL, ALLOCATABLE, DIMENSION(:), SAVE     :: coastalflow
+    !$OMP THREADPRIVATE(coastalflow)
+    REAL, ALLOCATABLE, DIMENSION(:), SAVE     :: riverflow
+    !$OMP THREADPRIVATE(riverflow)
+    
+    INTEGER :: orch_omp_rank
+    INTEGER :: orch_omp_size
+!
+! Fin definition
+!****************************************************************************************
+
+    IF (check) WRITE(lunout,*)'Entree ', modname
+  
+! Initialisation
+  
+    IF (debut) THEN
+! Test of coherence between variable ok_veget and cpp key CPP_VEGET
+#ifndef CPP_VEGET
+       abort_message='Pb de coherence: ok_veget = .true. mais CPP_VEGET = .false.'
+       CALL abort_physic(modname,abort_message,1)
+#endif
+
+       CALL Init_surf_para(knon)
+       ALLOCATE(ktindex(knon))
+       IF ( .NOT. ALLOCATED(albedo_keep)) THEN
+!ym          ALLOCATE(albedo_keep(klon))
+!ym bizarre que non alloué en knon precedement
+          ALLOCATE(albedo_keep(knon))
+          ALLOCATE(zlev(knon))
+       ENDIF
+! Pb de correspondances de grilles
+       ALLOCATE(ig(klon))
+       ALLOCATE(jg(klon))
+       ig(1) = 1
+       jg(1) = 1
+       indi = 0
+       indj = 2
+       DO igrid = 2, klon - 1
+          indi = indi + 1
+          IF ( indi > nbp_lon) THEN
+             indi = 1
+             indj = indj + 1
+          ENDIF
+          ig(igrid) = indi
+          jg(igrid) = indj
+       ENDDO
+       ig(klon) = 1
+       jg(klon) = nbp_lat
+
+       IF ((.NOT. ALLOCATED(lalo))) THEN
+          ALLOCATE(lalo(knon,2), stat = error)
+          IF (error /= 0) THEN
+             abort_message='Pb allocation lalo'
+             CALL abort_physic(modname,abort_message,1)
+          ENDIF
+       ENDIF
+       IF ((.NOT. ALLOCATED(lon_scat))) THEN
+          ALLOCATE(lon_scat(nbp_lon,nbp_lat), stat = error)
+          IF (error /= 0) THEN
+             abort_message='Pb allocation lon_scat'
+             CALL abort_physic(modname,abort_message,1)
+          ENDIF
+       ENDIF
+       IF ((.NOT. ALLOCATED(lat_scat))) THEN
+          ALLOCATE(lat_scat(nbp_lon,nbp_lat), stat = error)
+          IF (error /= 0) THEN
+             abort_message='Pb allocation lat_scat'
+             CALL abort_physic(modname,abort_message,1)
+          ENDIF
+       ENDIF
+       lon_scat = 0.
+       lat_scat = 0.
+       DO igrid = 1, knon
+          index = knindex(igrid)
+          lalo(igrid,2) = rlon(index)
+          lalo(igrid,1) = rlat(index)
+       ENDDO
+
+       
+       
+       CALL Gather(rlon,rlon_g)
+       CALL Gather(rlat,rlat_g)
+
+       IF (is_mpi_root) THEN
+          index = 1
+          DO jj = 2, nbp_lat-1
+             DO ij = 1, nbp_lon
+                index = index + 1
+                lon_scat(ij,jj) = rlon_g(index)
+                lat_scat(ij,jj) = rlat_g(index)
+             ENDDO
+          ENDDO
+          lon_scat(:,1) = lon_scat(:,2)
+          lat_scat(:,1) = rlat_g(1)
+          lon_scat(:,nbp_lat) = lon_scat(:,2)
+          lat_scat(:,nbp_lat) = rlat_g(klon_glo)
+       ENDIF
+   
+       CALL bcast(lon_scat)
+       CALL bcast(lat_scat)
+!
+! Allouer et initialiser le tableau des voisins et des fraction de continents
+!
+       IF ( (.NOT.ALLOCATED(neighbours))) THEN
+          ALLOCATE(neighbours(knon,8), stat = error)
+          IF (error /= 0) THEN
+             abort_message='Pb allocation neighbours'
+             CALL abort_physic(modname,abort_message,1)
+          ENDIF
+       ENDIF
+       neighbours = -1.
+       IF (( .NOT. ALLOCATED(contfrac))) THEN
+          ALLOCATE(contfrac(knon), stat = error)
+          IF (error /= 0) THEN
+             abort_message='Pb allocation contfrac'
+             CALL abort_physic(modname,abort_message,1)
+          ENDIF
+       ENDIF
+
+       DO igrid = 1, knon
+          ireal = knindex(igrid)
+          contfrac(igrid) = pctsrf(ireal,is_ter)
+       ENDDO
+
+
+       CALL Init_neighbours(knon,neighbours,knindex,pctsrf(:,is_ter))
+
+!
+!  Allocation et calcul resolutions
+       IF ( (.NOT.ALLOCATED(resolution))) THEN
+          ALLOCATE(resolution(knon,2), stat = error)
+          IF (error /= 0) THEN
+             abort_message='Pb allocation resolution'
+             CALL abort_physic(modname,abort_message,1)
+          ENDIF
+       ENDIF
+       DO igrid = 1, knon
+          ij = knindex(igrid)
+          resolution(igrid,1) = dx(ij)
+          resolution(igrid,2) = dy(ij)
+       ENDDO
+     
+       ALLOCATE(coastalflow(klon), stat = error)
+       IF (error /= 0) THEN
+          abort_message='Pb allocation coastalflow'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
+       
+       ALLOCATE(riverflow(klon), stat = error)
+       IF (error /= 0) THEN
+          abort_message='Pb allocation riverflow'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
+!
+! carbon_cycle_cpl not possible with this interface and version of ORHCHIDEE
+!
+       IF (carbon_cycle_cpl) THEN
+          abort_message='carbon_cycle_cpl not yet possible with this interface of ORCHIDEE'
+          CALL abort_physic(modname,abort_message,1)
+       END IF
+       
+    ENDIF                          ! (fin debut) 
+ 
+
+! 
+! Appel a la routine sols continentaux
+!
+    IF (lafin) lrestart_write = .TRUE.
+    IF (check) WRITE(lunout,*)'lafin ',lafin,lrestart_write
+     
+    petA_orc(1:knon) = petBcoef(1:knon) * dtime
+    petB_orc(1:knon) = petAcoef(1:knon)
+    peqA_orc(1:knon) = peqBcoef(1:knon) * dtime
+    peqB_orc(1:knon) = peqAcoef(1:knon)
+
+    cdrag = 0.
+    cdrag(1:knon) = tq_cdrag(1:knon)
+
+! zlev(1:knon) = (100.*plev(1:knon))/((ps(1:knon)/287.05*temp_air(1:knon))*9.80665)
+!    zlev(1:knon) = (100.*plev(1:knon))/((ps(1:knon)/RD*temp_air(1:knon))*RG)
+     zlev(1:knon) = plev(1:knon)*RD*temp_air(1:knon)/((ps(1:knon)*100.0)*RG)
+
+
+! PF et PASB
+!   where(cdrag > 0.01) 
+!     cdrag = 0.01
+!   endwhere
+!  write(*,*)'Cdrag = ',minval(cdrag),maxval(cdrag)
+
+  
+    IF (debut) THEN
+       CALL Init_orchidee_index(knon,knindex,offset,ktindex)
+       CALL Get_orchidee_communicator(orch_comm,orch_omp_size,orch_omp_rank)
+       CALL Init_synchro_omp
+       
+       IF (knon > 0) THEN
+#ifdef CPP_VEGET
+         CALL Init_intersurf(nbp_lon,nbp_lat,knon,ktindex,offset,orch_omp_size,orch_omp_rank,orch_comm)
+#endif
+       ENDIF
+
+       
+       IF (knon > 0) THEN
+
+#ifdef CPP_VEGET
+         CALL intersurf_initialize_gathered (itime+itau_phy-1, nbp_lon, nbp_lat, knon, ktindex, dtime, &
+               lrestart_read, lrestart_write, lalo, contfrac, neighbours, resolution, date0, &
+               zlev,  u1_lay, v1_lay, spechum, temp_air, epot_air, &
+               cdrag, petA_orc, peqA_orc, petB_orc, peqB_orc, &
+               precip_rain, precip_snow, lwdown, swnet, swdown, ps, &
+               evap, fluxsens, fluxlat, coastalflow, riverflow, &
+               tsol_rad, tsurf_new, qsurf, albedo_out, emis_new, z0m_new, &    
+               lon_scat, lat_scat, q2m, t2m, z0h_new, nvm_orch)
+#endif         
+       ENDIF
+
+       CALL Synchro_omp
+
+       albedo_keep(1:knon) = (albedo_out(1:knon,1)+albedo_out(1:knon,2))/2.
+
+    ENDIF
+
+    
+!  swdown_vrai(1:knon) = swnet(1:knon)/(1. - albedo_keep(1:knon))
+    swdown_vrai(1:knon) = swdown(1:knon)
+
+    IF (knon > 0) THEN
+#ifdef CPP_VEGET    
+       IF (nvm_orch .NE. nvm_lmdz ) THEN
+          abort_message='Pb de dimensiosn PFT: nvm_orch et nvm_lmdz differents.'
+          CALL abort_physic(modname,abort_message,1)
+       ENDIF
+
+       CALL intersurf_main_gathered (itime+itau_phy, nbp_lon, nbp_lat, knon, ktindex, dtime,  &
+            lrestart_read, lrestart_write, lalo, &
+            contfrac, neighbours, resolution, date0, &
+            zlev,  u1_lay(1:knon), v1_lay(1:knon), spechum(1:knon), temp_air(1:knon), epot_air(1:knon), ccanopy(1:knon), &
+            cdrag(1:knon), petA_orc(1:knon), peqA_orc(1:knon), petB_orc(1:knon), peqB_orc(1:knon), &
+            precip_rain(1:knon), precip_snow(1:knon), lwdown(1:knon), swnet(1:knon), swdown_vrai(1:knon), ps(1:knon), &
+            evap(1:knon), fluxsens(1:knon), fluxlat(1:knon), coastalflow(1:knon), riverflow(1:knon), &
+            tsol_rad(1:knon), tsurf_new(1:knon), qsurf(1:knon), albedo_out(1:knon,:), emis_new(1:knon), z0m_new(1:knon), &
+            lon_scat, lat_scat, q2m, t2m, z0h_new(1:knon),&
+            veget(1:knon,:),lai(1:knon,:),height(1:knon,:),&
+            coszang=yrmu0(1:knon))
+#endif       
+    ENDIF
+
+    CALL Synchro_omp
+    
+    albedo_keep(1:knon) = (albedo_out(1:knon,1)+albedo_out(1:knon,2))/2.
+
+!* Send to coupler
+!
+    IF (type_ocean=='couple') THEN
+       CALL cpl_send_land_fields(itime, knon, knindex, &
+            riverflow, coastalflow)
+    ENDIF
+
+    alb1_new(1:knon) = albedo_out(1:knon,1) 
+    alb2_new(1:knon) = albedo_out(1:knon,2)
+
+! Convention orchidee: positif vers le haut
+    fluxsens(1:knon) = -1. * fluxsens(1:knon)
+    fluxlat(1:knon)  = -1. * fluxlat(1:knon)
+    
+!  evap     = -1. * evap
+
+    IF (debut) lrestart_read = .FALSE.
+    
+    IF (debut) CALL Finalize_surf_para
+
+    
+  END SUBROUTINE surf_land_orchidee
+!
+!****************************************************************************************
+!
+  SUBROUTINE Init_orchidee_index(knon,knindex,offset,ktindex)
+  USE mod_surf_para
+  USE mod_grid_phy_lmdz
+  
+    INTEGER,INTENT(IN)    :: knon
+    INTEGER,INTENT(IN)    :: knindex(klon)    
+    INTEGER,INTENT(OUT)   :: offset
+    INTEGER,INTENT(OUT)   :: ktindex(klon)
+    
+    INTEGER               :: ktindex_glo(knon_glo)
+    INTEGER               :: offset_para(0:omp_size*mpi_size-1)
+    INTEGER               :: LastPoint
+    INTEGER               :: task
+    
+    ktindex(1:knon)=knindex(1:knon)+(klon_mpi_begin-1)+(klon_omp_begin-1)+nbp_lon-1
+    
+    CALL gather_surf(ktindex(1:knon),ktindex_glo) 
+    
+    IF (is_mpi_root .AND. is_omp_root) THEN
+      LastPoint=0
+      DO Task=0,mpi_size*omp_size-1
+        IF (knon_glo_para(Task)>0) THEN
+           offset_para(task)= LastPoint-MOD(LastPoint,nbp_lon)
+           LastPoint=ktindex_glo(knon_glo_end_para(task))
+        ENDIF
+      ENDDO
+    ENDIF
+    
+    CALL bcast(offset_para)
+    
+    offset=offset_para(omp_size*mpi_rank+omp_rank)
+    
+    ktindex(1:knon)=ktindex(1:knon)-offset
+
+  END SUBROUTINE Init_orchidee_index
+
+!
+!************************* ***************************************************************
+! 
+
+  SUBROUTINE Get_orchidee_communicator(orch_comm,orch_omp_size,orch_omp_rank)
+  USE  mod_surf_para
+      
+#ifdef CPP_MPI
+    INCLUDE 'mpif.h'
+#endif    
+
+    INTEGER,INTENT(OUT) :: orch_comm
+    INTEGER,INTENT(OUT) :: orch_omp_size
+    INTEGER,INTENT(OUT) :: orch_omp_rank
+    INTEGER             :: color
+    INTEGER             :: i,ierr
+!
+! End definition
+!****************************************************************************************
+    
+    
+    IF (is_omp_root) THEN          
+      
+      IF (knon_mpi==0) THEN 
+         color = 0
+      ELSE 
+         color = 1
+      ENDIF
+    
+#ifdef CPP_MPI    
+      CALL MPI_COMM_SPLIT(COMM_LMDZ_PHY,color,mpi_rank,orch_comm,ierr)
+#endif
+    
+    ENDIF
+    CALL bcast_omp(orch_comm)
+    
+    IF (knon_mpi /= 0) THEN
+      orch_omp_size=0
+      DO i=0,omp_size-1
+        IF (knon_omp_para(i) /=0) THEN
+          orch_omp_size=orch_omp_size+1
+          IF (i==omp_rank) orch_omp_rank=orch_omp_size-1
+        ENDIF
+      ENDDO
+    ENDIF
+   
+    
+  END SUBROUTINE Get_orchidee_communicator
+!
+!****************************************************************************************
+!  
+
+  SUBROUTINE Init_neighbours(knon,neighbours,knindex,pctsrf)
+    USE mod_grid_phy_lmdz
+    USE mod_surf_para    
+    USE indice_sol_mod
+
+#ifdef CPP_MPI
+    INCLUDE 'mpif.h'
+#endif    
+
+! Input arguments
+!****************************************************************************************
+    INTEGER, INTENT(IN)                     :: knon
+    INTEGER, DIMENSION(klon), INTENT(IN)    :: knindex
+    REAL, DIMENSION(klon), INTENT(IN)       :: pctsrf
+    
+! Output arguments
+!****************************************************************************************
+    INTEGER, DIMENSION(knon,8), INTENT(OUT) :: neighbours
+
+! Local variables
+!****************************************************************************************
+    INTEGER                              :: i, igrid, jj, ij, iglob
+    INTEGER                              :: ierr, ireal, index
+    INTEGER, DIMENSION(8,3)              :: off_ini
+    INTEGER, DIMENSION(8)                :: offset  
+    INTEGER, DIMENSION(nbp_lon,nbp_lat)  :: correspond
+    INTEGER, DIMENSION(knon_glo)         :: ktindex_glo
+    INTEGER, DIMENSION(knon_glo,8)       :: neighbours_glo
+    REAL, DIMENSION(klon_glo)            :: pctsrf_glo
+    INTEGER                              :: ktindex(klon)
+!
+! End definition
+!****************************************************************************************
+
+    ktindex(1:knon)=knindex(1:knon)+(klon_mpi_begin-1)+(klon_omp_begin-1)+nbp_lon-1
+    
+    CALL gather_surf(ktindex(1:knon),ktindex_glo)
+    CALL gather(pctsrf,pctsrf_glo)
+    
+    IF (is_mpi_root .AND. is_omp_root) THEN
+      neighbours_glo(:,:)=-1
+!  Initialisation des offset    
+!
+! offset bord ouest
+       off_ini(1,1) = - nbp_lon   ; off_ini(2,1) = - nbp_lon + 1     ; off_ini(3,1) = 1
+       off_ini(4,1) = nbp_lon + 1 ; off_ini(5,1) = nbp_lon           ; off_ini(6,1) = 2 * nbp_lon - 1
+       off_ini(7,1) = nbp_lon -1  ; off_ini(8,1) = - 1 
+! offset point normal
+       off_ini(1,2) = - nbp_lon   ; off_ini(2,2) = - nbp_lon + 1     ; off_ini(3,2) = 1
+       off_ini(4,2) = nbp_lon + 1 ; off_ini(5,2) = nbp_lon           ; off_ini(6,2) = nbp_lon - 1
+       off_ini(7,2) = -1          ; off_ini(8,2) = - nbp_lon - 1
+! offset bord   est
+       off_ini(1,3) = - nbp_lon   ; off_ini(2,3) = - 2 * nbp_lon + 1 ; off_ini(3,3) = - nbp_lon + 1
+       off_ini(4,3) =  1          ; off_ini(5,3) = nbp_lon           ; off_ini(6,3) = nbp_lon - 1
+       off_ini(7,3) = -1          ; off_ini(8,3) = - nbp_lon - 1
+!
+!
+! Attention aux poles
+!
+       DO igrid = 1, knon_glo
+          index = ktindex_glo(igrid)
+          jj = INT((index - 1)/nbp_lon) + 1
+          ij = index - (jj - 1) * nbp_lon
+          correspond(ij,jj) = igrid
+       ENDDO
+!sonia : Les mailles des voisines doivent etre toutes egales (pour couplage orchidee)
+       IF (knon_glo == 1) THEN
+         igrid = 1
+         DO i = 1,8
+           neighbours_glo(igrid, i) = igrid
+         ENDDO
+       ELSE
+       print*,'sonia : knon_glo,ij,jj', knon_glo, ij,jj
+       
+       DO igrid = 1, knon_glo
+          iglob = ktindex_glo(igrid)
+          
+          IF (MOD(iglob, nbp_lon) == 1) THEN
+             offset = off_ini(:,1)
+          ELSE IF(MOD(iglob, nbp_lon) == 0) THEN
+             offset = off_ini(:,3)
+          ELSE
+             offset = off_ini(:,2)
+          ENDIF
+          
+          DO i = 1, 8
+             index = iglob + offset(i)
+             ireal = (MIN(MAX(1, index - nbp_lon + 1), klon_glo))
+             IF (pctsrf_glo(ireal) > EPSFRA) THEN
+                jj = INT((index - 1)/nbp_lon) + 1
+                ij = index - (jj - 1) * nbp_lon
+                neighbours_glo(igrid, i) = correspond(ij, jj)
+             ENDIF
+          ENDDO
+       ENDDO
+       ENDIF !fin knon_glo == 1
+
+    ENDIF
+    
+    DO i = 1, 8
+      CALL scatter_surf(neighbours_glo(:,i),neighbours(1:knon,i))
+    ENDDO
+  END SUBROUTINE Init_neighbours
+
+!
+!****************************************************************************************
+!
+#endif
+#endif
+END MODULE surf_land_orchidee_nounstruct_mod
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/surf_land_orchidee_noz0h_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/surf_land_orchidee_noz0h_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/surf_land_orchidee_noz0h_mod.F90	(revision 3605)
@@ -440,4 +440,5 @@
     IF (knon > 0) THEN
 #ifdef CPP_VEGET    
+
        CALL intersurf_main (itime+itau_phy, nbp_lon, nbp_lat, knon, ktindex, dtime,  &
             lrestart_read, lrestart_write, lalo, &
@@ -448,5 +449,5 @@
             evap(1:knon), fluxsens(1:knon), fluxlat(1:knon), coastalflow(1:knon), riverflow(1:knon), &
             tsol_rad(1:knon), tsurf_new(1:knon), qsurf(1:knon), albedo_out(1:knon,:), emis_new(1:knon), z0_new(1:knon), &
-            lon_scat, lat_scat, q2m, t2m, coszang=yrmu0(1:knon))
+            lon_scat, lat_scat, q2m(1:knon), t2m(1:knon), coszang=yrmu0(1:knon))
 #endif       
     ENDIF
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/thermcell_main.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/thermcell_main.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/thermcell_main.F90	(revision 3605)
@@ -440,12 +440,35 @@
 !
       if (prt_level.ge.1) print*,'avant thermcell_plume ',lev_out
-!IM 140508   CALL thermcell_plume(ngrid,nlay,ptimestep,ztv,zthl,po,zl,rhobarz,  &
-
-! Gestion temporaire de plusieurs appels à thermcell_plume au travers
-! de la variable iflag_thermals
-
-!      print*,'THERM thermcell_main iflag_thermals_ed=',iflag_thermals_ed
+
+!=====================================================================
+! Old version of thermcell_plume in thermcell_plume_6A.F90
+! It includes both thermcell_plume_6A and thermcell_plume_5B corresponding
+! to the 5B and 6A versions used for CMIP5 and CMIP6.
+! The latest was previously named thermcellV1_plume.
+! The new thermcell_plume is a clean version (removing obsolete
+! options) of thermcell_plume_6A.
+! The 3 versions are controled by
+! flag_thermals_ed <= 9 thermcell_plume_6A
+!                  <= 19 thermcell_plume_5B
+!                  else thermcell_plume (default 20 for convergence with 6A)
+! Fredho
+!=====================================================================
+
       if (iflag_thermals_ed<=9) then
 !         print*,'THERM NOUVELLE/NOUVELLE Arnaud'
+         CALL thermcell_plume_6A(itap,ngrid,nlay,ptimestep,ztv,zthl,po,zl,rhobarz,&
+     &    zlev,pplev,pphi,zpspsk,alim_star,alim_star_tot,  &
+     &    lalim,f0,detr_star,entr_star,f_star,csc,ztva,  &
+     &    ztla,zqla,zqta,zha,zw2,zw_est,ztva_est,zqsatth,lmix,lmix_bis,linter &
+     &    ,lev_out,lunout1,igout)
+
+      elseif (iflag_thermals_ed<=19) then
+!        print*,'THERM RIO et al 2010, version d Arnaud'
+         CALL thermcell_plume_5B(itap,ngrid,nlay,ptimestep,ztv,zthl,po,zl,rhobarz,&
+     &    zlev,pplev,pphi,zpspsk,alim_star,alim_star_tot,  &
+     &    lalim,f0,detr_star,entr_star,f_star,csc,ztva,  &
+     &    ztla,zqla,zqta,zha,zw2,zw_est,ztva_est,zqsatth,lmix,lmix_bis,linter &
+     &    ,lev_out,lunout1,igout)
+      else
          CALL thermcell_plume(itap,ngrid,nlay,ptimestep,ztv,zthl,po,zl,rhobarz,&
      &    zlev,pplev,pphi,zpspsk,alim_star,alim_star_tot,  &
@@ -453,13 +476,4 @@
      &    ztla,zqla,zqta,zha,zw2,zw_est,ztva_est,zqsatth,lmix,lmix_bis,linter &
      &    ,lev_out,lunout1,igout)
-
-      elseif (iflag_thermals_ed>9) then
-!        print*,'THERM RIO et al 2010, version d Arnaud'
-         CALL thermcellV1_plume(itap,ngrid,nlay,ptimestep,ztv,zthl,po,zl,rhobarz,&
-     &    zlev,pplev,pphi,zpspsk,alim_star,alim_star_tot,  &
-     &    lalim,f0,detr_star,entr_star,f_star,csc,ztva,  &
-     &    ztla,zqla,zqta,zha,zw2,zw_est,ztva_est,zqsatth,lmix,lmix_bis,linter &
-     &    ,lev_out,lunout1,igout)
-
       endif
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/thermcell_plume.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/thermcell_plume.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/thermcell_plume.F90	(revision 3605)
@@ -1,4 +1,4 @@
 !
-! $Id$
+! $Id: thermcell_plume.F90 3074 2017-11-15 13:31:44Z fhourdin $
 !
       SUBROUTINE thermcell_plume(itap,ngrid,klev,ptimestep,ztv,zthl,po,zl,rhobarz,  &
@@ -9,5 +9,15 @@
 !     &           ,lev_out,lunout1,igout,zbuoy,zbuoyjam)
 !--------------------------------------------------------------------------
+! Auhtors : Catherine Rio, Frédéric Hourdin, Arnaud Jam
+!
 !thermcell_plume: calcule les valeurs de qt, thetal et w dans l ascendance
+!   This versions starts from a cleaning of thermcell_plume_6A (2019/01/20)
+!   thermcell_plume_6A is activate for flag_thermas_ed < 10
+!   thermcell_plume_5B for flag_thermas_ed < 20
+!   thermcell_plume for flag_thermals_ed>= 20
+!   Various options are controled by the flag_thermals_ed parameter
+!   = 20 : equivalent to thermcell_plume_6A with flag_thermals_ed=8
+!   = 21 : the Jam strato-cumulus modif is not activated in detrainment
+!   = 29 : an other way to compute the modified buoyancy (to be tested)
 !--------------------------------------------------------------------------
 USE IOIPSL, ONLY : getin
@@ -82,5 +92,5 @@
       real zdz,zbuoy(ngrid,klev),zalpha,gamma(ngrid,klev),zdqt(ngrid,klev),zw2m
       real zbuoyjam(ngrid,klev),zdqtjam(ngrid,klev)
-      real zbuoybis,zdz2,zdz3,lmel,entrbis,zdzbis
+      real zdz2,zdz3,lmel,entrbis,zdzbis
       real d_temp(ngrid)
       real ztv1,ztv2,factinv,zinv,zlmel
@@ -283,196 +293,33 @@
 
 !--------------------------------------------------
-        if (iflag_thermals_ed.lt.8) then
-!--------------------------------------------------
-!AJ052014: J'ai remplac?? la boucle do par un do while
-! afin de faire moins de calcul dans la boucle
-!--------------------------------------------------
-            do while (zlmelup.gt.zltup)
-               lt=lt+1
-               zlt=zlev(ig,lt)
-               zdz3=zlev(ig,lt+1)-zlt
-               zltdwn=zlt-zdz3/2
-               zltup=zlt+zdz3/2        
-            enddo
-!--------------------------------------------------
-!AJ052014: Si iflag_thermals_ed<8 (par ex 6), alors
-! on cherche o?? se trouve l'altitude d'inversion 
-! en calculant ztv1 (interpolation de la valeur de 
-! theta au niveau lt en utilisant les niveaux lt-1 et
-! lt-2) et ztv2 (interpolation avec les niveaux lt+1
-! et lt+2). Si theta r??ellement calcul??e au niveau lt
-! comprise entre ztv1 et ztv2, alors il y a inversion
-! et on calcule son altitude zinv en supposant que ztv(lt)
-! est une combinaison lineaire de ztv1 et ztv2.
-! Ensuite, on calcule la flottabilite en comparant 
-! la temperature de la couche l a celle de l'air situe 
-! l+lmel plus haut, ce qui necessite de savoir quel fraction 
-! de cet air est au-dessus ou en-dessous de l'inversion   
-!--------------------------------------------------
-            atv1=(ztv(ig,lt-1)-ztv(ig,lt-2))/(zlev(ig,lt-1)-zlev(ig,lt-2))
-            btv1=(ztv(ig,lt-2)*zlev(ig,lt-1)-ztv(ig,lt-1)*zlev(ig,lt-2)) &
-    &          /(zlev(ig,lt-1)-zlev(ig,lt-2))
-            atv2=(ztv(ig,lt+2)-ztv(ig,lt+1))/(zlev(ig,lt+2)-zlev(ig,lt+1))
-            btv2=(ztv(ig,lt+1)*zlev(ig,lt+2)-ztv(ig,lt+2)*zlev(ig,lt+1)) &
-    &          /(zlev(ig,lt+2)-zlev(ig,lt+1))
-
-             ztv1=atv1*zlt+btv1
-             ztv2=atv2*zlt+btv2
-
-             if (ztv(ig,lt).gt.ztv1.and.ztv(ig,lt).lt.ztv2) then  
-
-!--------------------------------------------------
-!AJ052014: D??calage de zinv qui est entre le haut
-!          et le bas de la couche lt
-!--------------------------------------------------
-                factinv=(ztv2-ztv(ig,lt))/(ztv2-ztv1)
-                zinv=zltdwn+zdz3*factinv
-
-          
-                if (zlmeldwn.ge.zinv) then
-                   ztv_est(ig,l)=atv2*zlmel+btv2
-                   zbuoyjam(ig,l)=fact_shell*RG*(ztva_est(ig,l)-ztv_est(ig,l))/ztv_est(ig,l) &
-    &                    +(1.-fact_shell)*zbuoy(ig,l)
-                elseif (zlmelup.ge.zinv) then
-                 ztv_est2=atv2*0.5*(zlmelup+zinv)+btv2
-                   ztv_est1=atv1*0.5*(zinv+zlmeldwn)+btv1
-                   ztv_est(ig,l)=((zlmelup-zinv)/zdz)*ztv_est2+((zinv-zlmeldwn)/zdz)*ztv_est1
-
-                   zbuoyjam(ig,l)=fact_shell*RG*(((zlmelup-zinv)/zdz)*(ztva_est(ig,l)- & 
-    &            ztv_est2)/ztv_est2+((zinv-zlmeldwn)/zdz)*(ztva_est(ig,l)- &
-    &            ztv_est1)/ztv_est1)+(1.-fact_shell)*zbuoy(ig,l)
-
-                else 
-                   ztv_est(ig,l)=atv1*zlmel+btv1
-                   zbuoyjam(ig,l)=fact_shell*RG*(ztva_est(ig,l)-ztv_est(ig,l))/ztv_est(ig,l) & 
-    &                           +(1.-fact_shell)*zbuoy(ig,l)
-                endif
-
-             else ! if (ztv(ig,lt).gt.ztv1.and.ztv(ig,lt).lt.ztv2) then
-
-                if (zlmeldwn.gt.zltdwn) then
-                   zbuoyjam(ig,l)=fact_shell*RG*((ztva_est(ig,l)- & 
-    &                ztv(ig,lt))/ztv(ig,lt))+(1.-fact_shell)*zbuoy(ig,l)
-                else
-                   zbuoyjam(ig,l)=fact_shell*RG*(((zlmelup-zltdwn)/zdz)*(ztva_est(ig,l)- & 
-    &                ztv(ig,lt))/ztv(ig,lt)+((zltdwn-zlmeldwn)/zdz)*(ztva_est(ig,l)- &
-    &                ztv(ig,lt-1))/ztv(ig,lt-1))+(1.-fact_shell)*zbuoy(ig,l)
-
-                endif
-
-!          zbuoyjam(ig,l)=fact_shell*RG*(((zlmelup-zltdwn)/zdz)*(ztva_est(ig,l)- & 
-!    &          ztv1)/ztv1+((zltdwn-zlmeldwn)/zdz)*(ztva_est(ig,l)- &
-!    &          ztv(ig,lt-1))/ztv(ig,lt-1))+(1.-fact_shell)*zbuoy(ig,l)
-!         zdqt(ig,l)=Max(0.,((lmel+zdz3-zdz2)/zdz3)*(zqta(ig,l-1)- & 
-!    &          po(ig,lt))/po(ig,lt)+((zdz2-lmel)/zdz3)*(zqta(ig,l-1)- &
-!     &          po(ig,lt-1))/po(ig,lt-1))
-          endif ! if (ztv(ig,lt).gt.ztv1.and.ztv(ig,lt).lt.ztv2) then
-
-        else  !   if (iflag_thermals_ed.lt.8) then
-           lt=l+1
+        lt=l+1
+        zlt=zlev(ig,lt)
+        zdz2=zlev(ig,lt)-zlev(ig,l)
+
+        do while (lmel.gt.zdz2)
+           lt=lt+1
            zlt=zlev(ig,lt)
-           zdz2=zlev(ig,lt)-zlev(ig,l)
-
-           do while (lmel.gt.zdz2)
-             lt=lt+1
-             zlt=zlev(ig,lt)
-             zdz2=zlt-zlev(ig,l)
-           enddo
-           zdz3=zlev(ig,lt+1)-zlt
-           zltdwn=zlev(ig,lt)-zdz3/2
-           zlmelup=zlmel+(zdz/2)
-           coefzlmel=Min(1.,(zlmelup-zltdwn)/zdz)
-           zbuoyjam(ig,l)=1.*RG*(coefzlmel*(ztva_est(ig,l)- & 
-    &          ztv(ig,lt))/ztv(ig,lt)+(1.-coefzlmel)*(ztva_est(ig,l)- &
-    &          ztv(ig,lt-1))/ztv(ig,lt-1))+0.*zbuoy(ig,l)
-        endif !   if (iflag_thermals_ed.lt.8) then
+           zdz2=zlt-zlev(ig,l)
+        enddo
+        zdz3=zlev(ig,lt+1)-zlt
+        zltdwn=zlev(ig,lt)-zdz3/2
+        zlmelup=zlmel+(zdz/2)
+        coefzlmel=Min(1.,(zlmelup-zltdwn)/zdz)
+        zbuoyjam(ig,l)=1.*RG*(coefzlmel*(ztva_est(ig,l)- & 
+    &   ztv(ig,lt))/ztv(ig,lt)+(1.-coefzlmel)*(ztva_est(ig,l)- &
+    &   ztv(ig,lt-1))/ztv(ig,lt-1))+0.*zbuoy(ig,l)
 
 !------------------------------------------------
 !AJAM:nouveau calcul de w?  
 !------------------------------------------------
-              zdz=zlev(ig,l+1)-zlev(ig,l)
-              zdzbis=zlev(ig,l)-zlev(ig,l-1)
-              zbuoy(ig,l)=RG*(ztva_est(ig,l)-ztv(ig,l))/ztv(ig,l)
-
-              zw2fact=fact_epsilon*2.*zdz/(1.+betalpha)
-              zw2factbis=fact_epsilon*2.*zdzbis/(1.+betalpha)
-              zdw2=afact*zbuoy(ig,l)/fact_epsilon
-              zdw2bis=afact*zbuoy(ig,l-1)/fact_epsilon
-!              zdw2bis=0.5*(zdw2+zdw2bis)
-              lm=Max(1,l-2)
-!              zdw2=(afact/fact_epsilon)*((zdz/zdzbis)*zbuoy(ig,l) &
-!    &              +((zdzbis-zdz)/zdzbis)*zbuoy(ig,l-1)) 
-!              zdw2bis=(afact/fact_epsilon)*((zdz/zdzbis)*zbuoy(ig,l-1) &
-!    &              +((zdzbis-zdz)/zdzbis)*zbuoy(ig,l-1))
-!             w_est(ig,l+1)=Max(0.0001,exp(-zw2fact)*(w_est(ig,l)-zdw2)+zdw2)
-!             w_est(ig,l+1)=(zdz/zdzbis)*Max(0.0001,exp(-zw2fact)* &
-!    &                     (w_est(ig,l)-zdw2)+zdw2)+(zdzbis-zdz)/zdzbis* &
-!    &                     Max(0.0001,exp(-zw2factbis)*(w_est(ig,l-1)-zdw2bis)+zdw2)
-!              w_est(ig,l+1)=Max(0.0001,(1-exp(-zw2fact))*zdw2+w_est(ig,l)*exp(-zw2fact))
-
-!--------------------------------------------------
-!AJ052014: J'ai remplac? w_est(ig,l) par zw2(ig,l)
-!--------------------------------------------------
-         if (iflag_thermals_ed==8) then
-! Ancienne version
-!             w_est(ig,l+1)=Max(0.0001,(zdz/zdzbis)*(exp(-zw2fact)* &
-!    &                     (w_est(ig,l)-zdw2)+zdw2)+(zdzbis-zdz)/zdzbis* &
-!    &                     (exp(-zw2factbis)*(w_est(ig,l-1)-zdw2bis)+zdw2))
-
-	    w_est(ig,l+1)=Max(0.0001,exp(-zw2fact)*(w_est(ig,l)-zdw2)+zdw2)
-
-! Nouvelle version Arnaud
-         else
-!             w_est(ig,l+1)=Max(0.0001,(zdz/zdzbis)*(exp(-zw2fact)* &
-!    &                     (w_est(ig,l)-zdw2)+zdw2)+(zdzbis-zdz)/zdzbis* &
-!    &                     (exp(-zw2factbis)*(w_est(ig,l-1)-zdw2bis)+zdw2))
-
-	    w_est(ig,l+1)=Max(0.0001,exp(-zw2fact)*(w_est(ig,l)-zdw2bis)+zdw2)
-
-!             w_est(ig,l+1)=Max(0.0001,(zdz/(zdzbis+zdz))*(exp(-zw2fact)* &
-!    &                     (w_est(ig,l)-zdw2bis)+zdw2)+(zdzbis/(zdzbis+zdz))* &
-!    &                     (exp(-zw2factbis)*(w_est(ig,l-1)-zdw2bis)+zdw2bis))
-
-
-
-!            w_est(ig,l+1)=Max(0.0001,(w_est(ig,l)+zdw2bis*zw2fact)*exp(-zw2fact))
-
-!             w_est(ig,l+1)=Max(0.0001,(zdz/zdzbis)*(zw2(ig,l)+zdw2*zw2fact)*exp(-zw2fact)+ &
-!    &                      (zdzbis-zdz)/zdzbis*(zw2(ig,l-1)+zdw2bis*zw2factbis)*exp(-zw2factbis))
-
-!             w_est(ig,l+1)=Max(0.0001,exp(-zw2factbis)*(w_est(ig,l-1)-zdw2bis)+zdw2)
-
-         endif
-
-
-         if (iflag_thermals_ed<6) then
-             zalpha=f0(ig)*f_star(ig,l)/sqrt(w_est(ig,l+1))/rhobarz(ig,l)
-!              fact_epsilon=0.0005/(zalpha+0.025)**0.5
-!              fact_epsilon=Min(0.003,0.0004/(zalpha)**0.5)
-              fact_epsilon=0.0002/(zalpha+0.1)
-              zw2fact=fact_epsilon*2.*zdz/(1.+betalpha)
-              zw2factbis=fact_epsilon*2.*zdzbis/(1.+betalpha)
-              zdw2=afact*zbuoy(ig,l)/fact_epsilon
-              zdw2bis=afact*zbuoy(ig,l-1)/fact_epsilon
-!              w_est(ig,l+1)=Max(0.0001,(zw2(ig,l)+zdw2*zw2fact)*exp(-zw2fact))
-
-!              w_est(ig,l+1)=Max(0.0001,(zdz/zdzbis)*(exp(-zw2fact)* &
-!    &                     (zw2(ig,l)-zdw2)+zdw2)+(zdzbis-zdz)/zdzbis* &
-!    &                     (exp(-zw2factbis)*(zw2(ig,l-1)-zdw2bis)+zdw2))
-
-	    w_est(ig,l+1)=Max(0.0001,exp(-zw2fact)*(w_est(ig,l)-zdw2bis)+zdw2)
-
-
-         endif
-!--------------------------------------------------
-!AJ052014: J'ai comment? ce if plus n?cessaire puisqu'
-!on fait max(0.0001,.....)
-!--------------------------------------------------         
-
-!             if (w_est(ig,l+1).lt.0.) then
-!               w_est(ig,l+1)=zw2(ig,l)
-!                w_est(ig,l+1)=0.0001
-!             endif
-
+        zdz=zlev(ig,l+1)-zlev(ig,l)
+        zdzbis=zlev(ig,l)-zlev(ig,l-1)
+        zbuoy(ig,l)=RG*(ztva_est(ig,l)-ztv(ig,l))/ztv(ig,l)
+        zw2fact=fact_epsilon*2.*zdz/(1.+betalpha)
+        zw2factbis=fact_epsilon*2.*zdzbis/(1.+betalpha)
+        zdw2=afact*zbuoy(ig,l)/fact_epsilon
+        zdw2bis=afact*zbuoy(ig,l-1)/fact_epsilon
+        lm=Max(1,l-2)
+        w_est(ig,l+1)=Max(0.0001,exp(-zw2fact)*(w_est(ig,l)-zdw2)+zdw2)
        endif
     enddo
@@ -488,36 +335,12 @@
 !          zw2m=max(0.5*(w_est(ig,l)+w_est(ig,l+1)),0.1)
           zw2m=w_est(ig,l+1)
-!          zw2m=zw2(ig,l)
           zdz=zlev(ig,l+1)-zlev(ig,l)
           zbuoy(ig,l)=RG*(ztva_est(ig,l)-ztv(ig,l))/ztv(ig,l)
-!          zbuoybis=zbuoy(ig,l)+RG*0.1/300.
-          zbuoybis=zbuoy(ig,l)
           zalpha=f0(ig)*f_star(ig,l)/sqrt(w_est(ig,l+1))/rhobarz(ig,l)
           zdqt(ig,l)=max(zqta(ig,l-1)-po(ig,l),0.)/po(ig,l)
 
-          
-!          entr_star(ig,l)=f_star(ig,l)*zdz*zbetalpha*MAX(0.,  &
-!    &     afact*zbuoybis/zw2m - fact_epsilon )
-
-!          entr_star(ig,l)=MAX(0.,f_star(ig,l)*zdz*zbetalpha*  &
-!    &     afact*zbuoybis/zw2m - fact_epsilon )
-
-
-
-!          zbuoyjam(ig,l)=RG*(ztva_est(ig,l)-ztv(ig,l))/ztv(ig,l)
-
 !=========================================================================
 ! 4. Calcul de l'entrainement et du detrainement
 !=========================================================================
-
-!          entr_star(ig,l)=f_star(ig,l)*zdz*zbetalpha*MAX(0.,  &
-!    &     afact*zbuoyjam(ig,l)/zw2m - fact_epsilon ) 
-!          entrbis=entr_star(ig,l)
-
-          if (iflag_thermals_ed.lt.6) then
-          fact_epsilon=0.0002/(zalpha+0.1)
-          endif
-          
-
 
           detr_star(ig,l)=f_star(ig,l)*zdz             &
@@ -526,29 +349,15 @@
     &     + detr_q_coef*(zdqt(ig,l)/zw2m)**detr_q_power))
 
-!	  detr_star(ig,l)=(zdz/zdzbis)*detr_star(ig,l)+ &
-!    &			  ((zdzbis-zdz)/zdzbis)*detr_star(ig,l-1)
-
-          zbuoy(ig,l)=RG*(ztva_est(ig,l)-ztv(ig,l))/ztv(ig,l)
-
-          entr_star(ig,l)=f_star(ig,l)*zdz* (         &
-    &       mix0 * 0.1 / (zalpha+0.001)               &
-    &     + zbetalpha*MAX(entr_min,                   &
-    &     afact*zbuoyjam(ig,l)/zw2m - fact_epsilon))
-
-
-!          entr_star(ig,l)=f_star(ig,l)*zdz* (         &
-!    &       mix0 * 0.1 / (zalpha+0.001)               &
-!    &     + MAX(entr_min,                   &
-!    &     zbetalpha*afact*zbuoyjam(ig,l)/zw2m - fact_epsilon +  & 
-!    &     detr_q_coef*(zdqt(ig,l)/zw2m)**detr_q_power))
-
-
-!	  entr_star(ig,l)=(zdz/zdzbis)*entr_star(ig,l)+ &
-!    &			  ((zdzbis-zdz)/zdzbis)*entr_star(ig,l-1)
-
-!          entr_star(ig,l)=Max(0.,f_star(ig,l)*zdz*zbetalpha*  &     
-!    &     afact*zbuoy(ig,l)/zw2m &
-!    &     - 1.*fact_epsilon)
-
+          if ( iflag_thermals_ed == 20 ) then
+             entr_star(ig,l)=f_star(ig,l)*zdz* (         &
+    &          mix0 * 0.1 / (zalpha+0.001)               &
+    &        + zbetalpha*MAX(entr_min,                   &
+    &        afact*zbuoyjam(ig,l)/zw2m - fact_epsilon))
+          else
+             entr_star(ig,l)=f_star(ig,l)*zdz* (         &
+    &          mix0 * 0.1 / (zalpha+0.001)               &
+    &        + zbetalpha*MAX(entr_min,                   &
+    &        afact*zbuoy(ig,l)/zw2m - fact_epsilon))
+          endif
           
 ! En dessous de lalim, on prend le max de alim_star et entr_star pour
@@ -558,11 +367,5 @@
           entr_star(ig,l)=0.
         endif
-!        if (l.lt.lalim(ig).and.alim_star(ig,l)>alim_star(ig,l-1)) then
-!          alim_star(ig,l)=entrbis
-!        endif
-
-!        print*,'alim0',zlev(ig,l),entr_star(ig,l),detr_star(ig,l),zw2m,zbuoy(ig,l),f_star(ig,l)
-! Calcul du flux montant normalise
-      f_star(ig,l+1)=f_star(ig,l)+alim_star(ig,l)+entr_star(ig,l)  &
+        f_star(ig,l+1)=f_star(ig,l)+alim_star(ig,l)+entr_star(ig,l)  &
      &              -detr_star(ig,l)
 
@@ -606,54 +409,13 @@
            zdzbis=zlev(ig,l)-zlev(ig,l-1)
            zeps(ig,l)=(entr_star(ig,l)+alim_star(ig,l))/(f_star(ig,l)*zdz)
-!!!!!!!          fact_epsilon=0.002
-            zw2fact=fact_epsilon*2.*zdz/(1.+betalpha)
-            zw2factbis=fact_epsilon*2.*zdzbis/(1.+betalpha)
-            zdw2= afact*zbuoy(ig,l)/(fact_epsilon)
-            zdw2bis= afact*zbuoy(ig,l-1)/(fact_epsilon)
-!              zdw2=(afact/fact_epsilon)*((zdz/zdzbis)*zbuoy(ig,l) &
-!    &              +((zdzbis-zdz)/zdzbis)*zbuoy(ig,l-1)) 
-!              lm=Max(1,l-2)
-!              zdw2bis=(afact/fact_epsilon)*((zdz/zdzbis)*zbuoy(ig,l-1) &
-!    &              +((zdzbis-zdz)/zdzbis)*zbuoy(ig,l-1))
-!            zw2(ig,l+1)=Max(0.0001,exp(-zw2fact)*(zw2(ig,l)-zdw2bis)+zdw2)
-!            zw2(ig,l+1)=Max(0.0001,(zdz/zdzbis)*(zw2(ig,l)+zdw2*zw2fact)*exp(-zw2fact)+ &
-!     &                   (zdzbis-zdz)/zdzbis*(zw2(ig,l-1)+zdw2bis*zw2factbis)*exp(-zw2factbis))
-!            zw2(ig,l+1)=Max(0.0001,(zw2(ig,l)+zdw2*zw2fact)*exp(-zw2fact))
-!            zw2(ig,l+1)=Max(0.0001,(zdz/zdzbis)*(exp(-zw2fact)* &
-!    &                     (zw2(ig,l)-zdw2)+zdw2)+(zdzbis-zdz)/zdzbis* &
-!    &                     (exp(-zw2factbis)*(zw2(ig,l-1)-zdw2bis)+zdw2))
-            if (iflag_thermals_ed==8) then
-	    zw2(ig,l+1)=Max(0.0001,exp(-zw2fact)*(zw2(ig,l)-zdw2)+zdw2)
-            else
-	    zw2(ig,l+1)=Max(0.0001,exp(-zw2fact)*(zw2(ig,l)-zdw2bis)+zdw2)
-            endif
-!            zw2(ig,l+1)=Max(0.0001,(zdz/(zdz+zdzbis))*(exp(-zw2fact)* &
-!    &                     (zw2(ig,l)-zdw2)+zdw2bis)+(zdzbis/(zdz+zdzbis))* &
-!    &                     (exp(-zw2factbis)*(zw2(ig,l-1)-zdw2bis)+zdw2bis))
-
-
-           if (iflag_thermals_ed.lt.6) then
-           zalpha=f0(ig)*f_star(ig,l)/sqrt(zw2(ig,l+1))/rhobarz(ig,l)
-!           fact_epsilon=0.0005/(zalpha+0.025)**0.5
-!           fact_epsilon=Min(0.003,0.0004/(zalpha)**0.5)
-           fact_epsilon=0.0002/(zalpha+0.1)**1
-            zw2fact=fact_epsilon*2.*zdz/(1.+betalpha)
-            zw2factbis=fact_epsilon*2.*zdzbis/(1.+betalpha)
-            zdw2= afact*zbuoy(ig,l)/(fact_epsilon)
-            zdw2bis= afact*zbuoy(ig,l-1)/(fact_epsilon)
-
-!            zw2(ig,l+1)=Max(0.0001,(zdz/zdzbis)*(exp(-zw2fact)* &
-!    &                     (zw2(ig,l)-zdw2)+zdw2)+(zdzbis-zdz)/zdzbis* &
-!    &                     (exp(-zw2factbis)*(zw2(ig,l-1)-zdw2bis)+zdw2))
-!            zw2(ig,l+1)=Max(0.0001,(zw2(ig,l)+zdw2*zw2fact)*exp(-zw2fact))
-	    zw2(ig,l+1)=Max(0.0001,exp(-zw2fact)*(zw2(ig,l)-zdw2bis)+zdw2)
-
-           endif
-
-
+           zw2fact=fact_epsilon*2.*zdz/(1.+betalpha)
+           zw2factbis=fact_epsilon*2.*zdzbis/(1.+betalpha)
+           zdw2= afact*zbuoy(ig,l)/(fact_epsilon)
+           zdw2bis= afact*zbuoy(ig,l-1)/(fact_epsilon)
+           zw2(ig,l+1)=Max(0.0001,exp(-zw2fact)*(zw2(ig,l)-zdw2)+zdw2)
       endif
    enddo
 
-        if (prt_level.ge.20) print*,'coucou calcul detr 460: ig, l',ig, l
+   if (prt_level.ge.20) print*,'coucou calcul detr 460: ig, l',ig, l
 !
 !===========================================================================
@@ -732,455 +494,2 @@
      return 
      end
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- SUBROUTINE thermcellV1_plume(itap,ngrid,klev,ptimestep,ztv,zthl,po,zl,rhobarz,  &
-&           zlev,pplev,pphi,zpspsk,alim_star,alim_star_tot,  &
-&           lalim,f0,detr_star,entr_star,f_star,csc,ztva,  &
-&           ztla,zqla,zqta,zha,zw2,w_est,ztva_est,zqsatth,lmix,lmix_bis,linter &
-&           ,lev_out,lunout1,igout)
-!&           ,lev_out,lunout1,igout,zbuoy,zbuoyjam)
-
-!--------------------------------------------------------------------------
-!thermcell_plume: calcule les valeurs de qt, thetal et w dans l ascendance
-! Version conforme a l'article de Rio et al. 2010.
-! Code ecrit par Catherine Rio, Arnaud Jam et Frederic Hourdin
-!--------------------------------------------------------------------------
-
-      USE print_control_mod, ONLY: prt_level
-      IMPLICIT NONE
-
-#include "YOMCST.h"
-#include "YOETHF.h"
-#include "FCTTRE.h"
-#include "thermcell.h"
-
-      INTEGER itap
-      INTEGER lunout1,igout
-      INTEGER ngrid,klev
-      REAL ptimestep
-      REAL ztv(ngrid,klev)
-      REAL zthl(ngrid,klev)
-      REAL po(ngrid,klev)
-      REAL zl(ngrid,klev)
-      REAL rhobarz(ngrid,klev)
-      REAL zlev(ngrid,klev+1)
-      REAL pplev(ngrid,klev+1)
-      REAL pphi(ngrid,klev)
-      REAL zpspsk(ngrid,klev)
-      REAL alim_star(ngrid,klev)
-      REAL f0(ngrid)
-      INTEGER lalim(ngrid)
-      integer lev_out                           ! niveau pour les print
-      integer nbpb
-    
-      real alim_star_tot(ngrid)
-
-      REAL ztva(ngrid,klev)
-      REAL ztla(ngrid,klev)
-      REAL zqla(ngrid,klev)
-      REAL zqta(ngrid,klev)
-      REAL zha(ngrid,klev)
-
-      REAL detr_star(ngrid,klev)
-      REAL coefc
-      REAL entr_star(ngrid,klev)
-      REAL detr(ngrid,klev)
-      REAL entr(ngrid,klev)
-
-      REAL csc(ngrid,klev)
-
-      REAL zw2(ngrid,klev+1)
-      REAL w_est(ngrid,klev+1)
-      REAL f_star(ngrid,klev+1)
-      REAL wa_moy(ngrid,klev+1)
-
-      REAL ztva_est(ngrid,klev)
-      REAL zqla_est(ngrid,klev)
-      REAL zqsatth(ngrid,klev)
-      REAL zta_est(ngrid,klev)
-      REAL zbuoyjam(ngrid,klev)
-      REAL ztemp(ngrid),zqsat(ngrid)
-      REAL zdw2
-      REAL zw2modif
-      REAL zw2fact
-      REAL zeps(ngrid,klev)
-
-      REAL linter(ngrid)
-      INTEGER lmix(ngrid)
-      INTEGER lmix_bis(ngrid)
-      REAL    wmaxa(ngrid)
-
-      INTEGER ig,l,k
-
-      real zdz,zbuoy(ngrid,klev),zalpha,gamma(ngrid,klev),zdqt(ngrid,klev),zw2m
-      real zbuoybis
-      real zcor,zdelta,zcvm5,qlbef,zdz2
-      real betalpha,zbetalpha
-      real eps, afact
-      REAL REPS,RLvCp,DDT0
-      PARAMETER (DDT0=.01)
-      logical Zsat
-      LOGICAL active(ngrid),activetmp(ngrid)
-      REAL fact_gamma,fact_epsilon,fact_gamma2,fact_epsilon2
-      REAL c2(ngrid,klev)
-      Zsat=.false.
-! Initialisation
-
-      RLvCp = RLVTT/RCPD
-      fact_epsilon=0.002
-      betalpha=0.9 
-      afact=2./3.            
-
-      zbetalpha=betalpha/(1.+betalpha)
-
-
-! Initialisations des variables reeles
-if (1==1) then
-      ztva(:,:)=ztv(:,:)
-      ztva_est(:,:)=ztva(:,:)
-      ztla(:,:)=zthl(:,:)
-      zqta(:,:)=po(:,:)
-      zha(:,:) = ztva(:,:)
-else
-      ztva(:,:)=0.
-      ztva_est(:,:)=0.
-      ztla(:,:)=0.
-      zqta(:,:)=0.
-      zha(:,:) =0.
-endif
-
-      zqla_est(:,:)=0.
-      zqsatth(:,:)=0.
-      zqla(:,:)=0.
-      detr_star(:,:)=0.
-      entr_star(:,:)=0.
-      alim_star(:,:)=0.
-      alim_star_tot(:)=0.
-      csc(:,:)=0.
-      detr(:,:)=0.
-      entr(:,:)=0.
-      zw2(:,:)=0.
-      zbuoy(:,:)=0.
-      zbuoyjam(:,:)=0.
-      gamma(:,:)=0.
-      zeps(:,:)=0.
-      w_est(:,:)=0.
-      f_star(:,:)=0.
-      wa_moy(:,:)=0.
-      linter(:)=1.
-!     linter(:)=1.
-! Initialisation des variables entieres
-      lmix(:)=1
-      lmix_bis(:)=2
-      wmaxa(:)=0.
-      lalim(:)=1
-
-
-!-------------------------------------------------------------------------
-! On ne considere comme actif que les colonnes dont les deux premieres
-! couches sont instables.
-!-------------------------------------------------------------------------
-      active(:)=ztv(:,1)>ztv(:,2)
-
-!-------------------------------------------------------------------------
-! Definition de l'alimentation a l'origine dans thermcell_init
-!-------------------------------------------------------------------------
-      do l=1,klev-1
-         do ig=1,ngrid
-            if (ztv(ig,l)> ztv(ig,l+1) .and. ztv(ig,1)>=ztv(ig,l) ) then
-               alim_star(ig,l)=MAX((ztv(ig,l)-ztv(ig,l+1)),0.)  &
-     &                       *sqrt(zlev(ig,l+1)) 
-               lalim(ig)=l+1
-               alim_star_tot(ig)=alim_star_tot(ig)+alim_star(ig,l)
-            endif
-         enddo
-      enddo
-      do l=1,klev
-         do ig=1,ngrid 
-            if (alim_star_tot(ig) > 1.e-10 ) then
-               alim_star(ig,l)=alim_star(ig,l)/alim_star_tot(ig)
-            endif
-         enddo
-      enddo
-      alim_star_tot(:)=1.
-
-
-
-!------------------------------------------------------------------------------
-! Calcul dans la premiere couche
-! On decide dans cette version que le thermique n'est actif que si la premiere
-! couche est instable.
-! Pourrait etre change si on veut que le thermiques puisse se d??clencher
-! dans une couche l>1
-!------------------------------------------------------------------------------
-do ig=1,ngrid
-! Le panache va prendre au debut les caracteristiques de l'air contenu
-! dans cette couche.
-    if (active(ig)) then
-    ztla(ig,1)=zthl(ig,1) 
-    zqta(ig,1)=po(ig,1)
-    zqla(ig,1)=zl(ig,1)
-!cr: attention, prise en compte de f*(1)=1
-    f_star(ig,2)=alim_star(ig,1)
-    zw2(ig,2)=2.*RG*(ztv(ig,1)-ztv(ig,2))/ztv(ig,2)  &
-&                     *(zlev(ig,2)-zlev(ig,1))  &
-&                     *0.4*pphi(ig,1)/(pphi(ig,2)-pphi(ig,1))
-    w_est(ig,2)=zw2(ig,2)
-    endif
-enddo
-!
-
-!==============================================================================
-!boucle de calcul de la vitesse verticale dans le thermique
-!==============================================================================
-do l=2,klev-1
-!==============================================================================
-
-
-! On decide si le thermique est encore actif ou non
-! AFaire : Il faut sans doute ajouter entr_star a alim_star dans ce test
-    do ig=1,ngrid
-       active(ig)=active(ig) &
-&                 .and. zw2(ig,l)>1.e-10 &
-&                 .and. f_star(ig,l)+alim_star(ig,l)>1.e-10
-    enddo
-
-
-
-!---------------------------------------------------------------------------
-! calcul des proprietes thermodynamiques et de la vitesse de la couche l
-! sans tenir compte du detrainement et de l'entrainement dans cette
-! couche
-! C'est a dire qu'on suppose 
-! ztla(l)=ztla(l-1) et zqta(l)=zqta(l-1)
-! Ici encore, on doit pouvoir ajouter entr_star (qui peut etre calculer
-! avant) a l'alimentation pour avoir un calcul plus propre
-!---------------------------------------------------------------------------
-
-   ztemp(:)=zpspsk(:,l)*ztla(:,l-1)
-   call thermcell_qsat(ngrid,active,pplev(:,l),ztemp,zqta(:,l-1),zqsat(:))
-
-    do ig=1,ngrid 
-!       print*,'active',active(ig),ig,l
-        if(active(ig)) then 
-        zqla_est(ig,l)=max(0.,zqta(ig,l-1)-zqsat(ig))
-        ztva_est(ig,l) = ztla(ig,l-1)*zpspsk(ig,l)+RLvCp*zqla_est(ig,l)
-        zta_est(ig,l)=ztva_est(ig,l)
-        ztva_est(ig,l) = ztva_est(ig,l)/zpspsk(ig,l)
-        ztva_est(ig,l) = ztva_est(ig,l)*(1.+RETV*(zqta(ig,l-1)  &
-     &      -zqla_est(ig,l))-zqla_est(ig,l))
-
-!------------------------------------------------
-!AJAM:nouveau calcul de w?  
-!------------------------------------------------
-              zdz=zlev(ig,l+1)-zlev(ig,l)
-              zbuoy(ig,l)=RG*(ztva_est(ig,l)-ztv(ig,l))/ztv(ig,l)
-
-              zw2fact=fact_epsilon*2.*zdz/(1.+betalpha)
-              zdw2=(afact)*zbuoy(ig,l)/(fact_epsilon)
-              w_est(ig,l+1)=Max(0.0001,exp(-zw2fact)*(w_est(ig,l)-zdw2)+zdw2)
- 
-
-             if (w_est(ig,l+1).lt.0.) then
-                w_est(ig,l+1)=zw2(ig,l)
-             endif
-       endif
-    enddo
-
-
-!-------------------------------------------------
-!calcul des taux d'entrainement et de detrainement
-!-------------------------------------------------
-
-     do ig=1,ngrid
-        if (active(ig)) then
-
-          zw2m=max(0.5*(w_est(ig,l)+w_est(ig,l+1)),0.1)
-          zw2m=w_est(ig,l+1)
-          zdz=zlev(ig,l+1)-zlev(ig,l)
-          zbuoy(ig,l)=RG*(ztva_est(ig,l)-ztv(ig,l))/ztv(ig,l)
-!          zbuoybis=zbuoy(ig,l)+RG*0.1/300.
-          zbuoybis=zbuoy(ig,l)
-          zalpha=f0(ig)*f_star(ig,l)/sqrt(w_est(ig,l+1))/rhobarz(ig,l)
-          zdqt(ig,l)=max(zqta(ig,l-1)-po(ig,l),0.)/po(ig,l)
-
-          
-          entr_star(ig,l)=f_star(ig,l)*zdz*  zbetalpha*MAX(0.,  &
-    &     afact*zbuoybis/zw2m - fact_epsilon )
-
-
-          detr_star(ig,l)=f_star(ig,l)*zdz                        &
-    &     *MAX(1.e-3, -afact*zbetalpha*zbuoy(ig,l)/zw2m          &
-    &     + 0.012*(zdqt(ig,l)/zw2m)**0.5 )
-          
-! En dessous de lalim, on prend le max de alim_star et entr_star pour
-! alim_star et 0 sinon
-        if (l.lt.lalim(ig)) then
-          alim_star(ig,l)=max(alim_star(ig,l),entr_star(ig,l))
-          entr_star(ig,l)=0.
-        endif
-
-! Calcul du flux montant normalise
-      f_star(ig,l+1)=f_star(ig,l)+alim_star(ig,l)+entr_star(ig,l)  &
-     &              -detr_star(ig,l)
-
-      endif
-   enddo
-
-
-!----------------------------------------------------------------------------
-!calcul de la vitesse verticale en melangeant Tl et qt du thermique
-!---------------------------------------------------------------------------
-   activetmp(:)=active(:) .and. f_star(:,l+1)>1.e-10
-   do ig=1,ngrid
-       if (activetmp(ig)) then 
-           Zsat=.false.
-           ztla(ig,l)=(f_star(ig,l)*ztla(ig,l-1)+  &
-     &            (alim_star(ig,l)+entr_star(ig,l))*zthl(ig,l))  &
-     &            /(f_star(ig,l+1)+detr_star(ig,l))
-           zqta(ig,l)=(f_star(ig,l)*zqta(ig,l-1)+  &
-     &            (alim_star(ig,l)+entr_star(ig,l))*po(ig,l))  &
-     &            /(f_star(ig,l+1)+detr_star(ig,l))
-
-        endif
-    enddo
-
-   ztemp(:)=zpspsk(:,l)*ztla(:,l)
-   call thermcell_qsat(ngrid,activetmp,pplev(:,l),ztemp,zqta(:,l),zqsatth(:,l))
-
-   do ig=1,ngrid
-      if (activetmp(ig)) then
-! on ecrit de maniere conservative (sat ou non)
-!          T = Tl +Lv/Cp ql
-           zqla(ig,l)=max(0.,zqta(ig,l)-zqsatth(ig,l))
-           ztva(ig,l) = ztla(ig,l)*zpspsk(ig,l)+RLvCp*zqla(ig,l)
-           ztva(ig,l) = ztva(ig,l)/zpspsk(ig,l)
-!on rajoute le calcul de zha pour diagnostiques (temp potentielle)
-           zha(ig,l) = ztva(ig,l)
-           ztva(ig,l) = ztva(ig,l)*(1.+RETV*(zqta(ig,l)  &
-     &              -zqla(ig,l))-zqla(ig,l))
-           zbuoy(ig,l)=RG*(ztva(ig,l)-ztv(ig,l))/ztv(ig,l)
-           zdz=zlev(ig,l+1)-zlev(ig,l)
-           zeps(ig,l)=(entr_star(ig,l)+alim_star(ig,l))/(f_star(ig,l)*zdz)
-
-            zw2fact=fact_epsilon*2.*zdz/(1.+betalpha)
-            zdw2=afact*zbuoy(ig,l)/(fact_epsilon)
-            zw2(ig,l+1)=Max(0.0001,exp(-zw2fact)*(zw2(ig,l)-zdw2)+zdw2) 
-      endif
-   enddo
-
-        if (prt_level.ge.20) print*,'coucou calcul detr 460: ig, l',ig, l
-!
-!---------------------------------------------------------------------------
-!initialisations pour le calcul de la hauteur du thermique, de l'inversion et de la vitesse verticale max 
-!---------------------------------------------------------------------------
-
-   nbpb=0
-   do ig=1,ngrid
-            if (zw2(ig,l+1)>0. .and. zw2(ig,l+1).lt.1.e-10) then
-!               stop'On tombe sur le cas particulier de thermcell_dry'
-!               print*,'On tombe sur le cas particulier de thermcell_plume'
-                nbpb=nbpb+1
-                zw2(ig,l+1)=0.
-                linter(ig)=l+1
-            endif
-
-        if (zw2(ig,l+1).lt.0.) then 
-           linter(ig)=(l*(zw2(ig,l+1)-zw2(ig,l))  &
-     &               -zw2(ig,l))/(zw2(ig,l+1)-zw2(ig,l))
-           zw2(ig,l+1)=0.
-        elseif (f_star(ig,l+1).lt.0.) then
-           linter(ig)=(l*(f_star(ig,l+1)-f_star(ig,l))  &
-     &               -f_star(ig,l))/(f_star(ig,l+1)-f_star(ig,l))
-!           print*,"linter plume", linter(ig)
-           zw2(ig,l+1)=0.
-        endif
-
-           wa_moy(ig,l+1)=sqrt(zw2(ig,l+1)) 
-
-        if (wa_moy(ig,l+1).gt.wmaxa(ig)) then
-!   lmix est le niveau de la couche ou w (wa_moy) est maximum
-!on rajoute le calcul de lmix_bis
-            if (zqla(ig,l).lt.1.e-10) then
-               lmix_bis(ig)=l+1
-            endif
-            lmix(ig)=l+1
-            wmaxa(ig)=wa_moy(ig,l+1)
-        endif
-   enddo
-
-   if (nbpb>0) then
-   print*,'WARNING on tombe ',nbpb,' x sur un pb pour l=',l,' dans thermcell_plume'
-   endif
-
-!=========================================================================
-! FIN DE LA BOUCLE VERTICALE
-      enddo
-!=========================================================================
-
-!on recalcule alim_star_tot
-       do ig=1,ngrid
-          alim_star_tot(ig)=0.
-       enddo
-       do ig=1,ngrid
-          do l=1,lalim(ig)-1
-          alim_star_tot(ig)=alim_star_tot(ig)+alim_star(ig,l)
-          enddo
-       enddo
-       
-
-        if (prt_level.ge.20) print*,'coucou calcul detr 470: ig, l', ig, l
-
-#undef wrgrads_thermcell
-#ifdef wrgrads_thermcell
-         call wrgradsfi(1,klev,entr_star(igout,1:klev),'esta      ','esta      ')
-         call wrgradsfi(1,klev,detr_star(igout,1:klev),'dsta      ','dsta      ')
-         call wrgradsfi(1,klev,zbuoy(igout,1:klev),'buoy      ','buoy      ')
-         call wrgradsfi(1,klev,zdqt(igout,1:klev),'dqt      ','dqt      ')
-         call wrgradsfi(1,klev,w_est(igout,1:klev),'w_est     ','w_est     ')
-         call wrgradsfi(1,klev,w_est(igout,2:klev+1),'w_es2     ','w_es2     ')
-         call wrgradsfi(1,klev,zw2(igout,1:klev),'zw2A      ','zw2A      ')
-#endif
-
-
-     return 
-     end
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/thermcell_plume_6A.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/thermcell_plume_6A.F90	(revision 3605)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/thermcell_plume_6A.F90	(revision 3605)
@@ -0,0 +1,1186 @@
+!
+! $Id$
+!
+      SUBROUTINE thermcell_plume_6A(itap,ngrid,klev,ptimestep,ztv,zthl,po,zl,rhobarz,  &
+     &           zlev,pplev,pphi,zpspsk,alim_star,alim_star_tot,  &
+     &           lalim,f0,detr_star,entr_star,f_star,csc,ztva,  &
+     &           ztla,zqla,zqta,zha,zw2,w_est,ztva_est,zqsatth,lmix,lmix_bis,linter &
+    &           ,lev_out,lunout1,igout)
+!     &           ,lev_out,lunout1,igout,zbuoy,zbuoyjam)
+!--------------------------------------------------------------------------
+!thermcell_plume: calcule les valeurs de qt, thetal et w dans l ascendance
+!--------------------------------------------------------------------------
+USE IOIPSL, ONLY : getin
+USE ioipsl_getin_p_mod, ONLY : getin_p
+
+       USE print_control_mod, ONLY: prt_level
+       IMPLICIT NONE
+
+#include "YOMCST.h"
+#include "YOETHF.h"
+#include "FCTTRE.h"
+#include "thermcell.h"
+
+      INTEGER itap
+      INTEGER lunout1,igout
+      INTEGER ngrid,klev
+      REAL ptimestep
+      REAL ztv(ngrid,klev)
+      REAL zthl(ngrid,klev)
+      REAL po(ngrid,klev)
+      REAL zl(ngrid,klev)
+      REAL rhobarz(ngrid,klev)
+      REAL zlev(ngrid,klev+1)
+      REAL pplev(ngrid,klev+1)
+      REAL pphi(ngrid,klev)
+      REAL zpspsk(ngrid,klev)
+      REAL alim_star(ngrid,klev)
+      REAL f0(ngrid)
+      INTEGER lalim(ngrid)
+      integer lev_out                           ! niveau pour les print
+      integer nbpb
+    
+      real alim_star_tot(ngrid)
+
+      REAL ztva(ngrid,klev)
+      REAL ztla(ngrid,klev)
+      REAL zqla(ngrid,klev)
+      REAL zqta(ngrid,klev)
+      REAL zha(ngrid,klev)
+
+      REAL detr_star(ngrid,klev)
+      REAL coefc
+      REAL entr_star(ngrid,klev)
+      REAL detr(ngrid,klev)
+      REAL entr(ngrid,klev)
+
+      REAL csc(ngrid,klev)
+
+      REAL zw2(ngrid,klev+1)
+      REAL w_est(ngrid,klev+1)
+      REAL f_star(ngrid,klev+1)
+      REAL wa_moy(ngrid,klev+1)
+
+      REAL ztva_est(ngrid,klev)
+      REAL ztv_est(ngrid,klev)
+      REAL zqla_est(ngrid,klev)
+      REAL zqsatth(ngrid,klev)
+      REAL zta_est(ngrid,klev)
+      REAL ztemp(ngrid),zqsat(ngrid)
+      REAL zdw2,zdw2bis
+      REAL zw2modif
+      REAL zw2fact,zw2factbis
+      REAL zeps(ngrid,klev)
+
+      REAL linter(ngrid)
+      INTEGER lmix(ngrid)
+      INTEGER lmix_bis(ngrid)
+      REAL    wmaxa(ngrid)
+
+      INTEGER ig,l,k,lt,it,lm
+
+      real zdz,zbuoy(ngrid,klev),zalpha,gamma(ngrid,klev),zdqt(ngrid,klev),zw2m
+      real zbuoyjam(ngrid,klev),zdqtjam(ngrid,klev)
+      real zbuoybis,zdz2,zdz3,lmel,entrbis,zdzbis
+      real d_temp(ngrid)
+      real ztv1,ztv2,factinv,zinv,zlmel
+      real zlmelup,zlmeldwn,zlt,zltdwn,zltup
+      real atv1,atv2,btv1,btv2
+      real ztv_est1,ztv_est2
+      real zcor,zdelta,zcvm5,qlbef
+      real zbetalpha, coefzlmel
+      real eps
+      REAL REPS,RLvCp,DDT0
+      PARAMETER (DDT0=.01)
+      logical Zsat
+      LOGICAL active(ngrid),activetmp(ngrid)
+      REAL fact_gamma,fact_gamma2,fact_epsilon2
+
+      REAL, SAVE :: fact_epsilon=0.002
+      REAL, SAVE :: betalpha=0.9
+      REAL, SAVE :: afact=2./3.
+      REAL, SAVE :: fact_shell=1.
+      REAL,SAVE :: detr_min=1.e-5
+      REAL,SAVE :: entr_min=1.e-5
+      REAL,SAVE :: detr_q_coef=0.012
+      REAL,SAVE :: detr_q_power=0.5
+      REAL,SAVE :: mix0=0.
+      INTEGER,SAVE :: thermals_flag_alim=0
+
+!$OMP THREADPRIVATE(fact_epsilon, betalpha, afact, fact_shell)
+!$OMP THREADPRIVATE(detr_min, entr_min, detr_q_coef, detr_q_power)
+!$OMP THREADPRIVATE( mix0, thermals_flag_alim)
+
+      LOGICAL, SAVE :: first=.true.
+  !$OMP THREADPRIVATE(first)
+
+
+      REAL c2(ngrid,klev)
+
+      if (ngrid==1) print*,'THERMCELL PLUME MODIFIE 2014/07/11'
+      Zsat=.false.
+! Initialisation
+
+      RLvCp = RLVTT/RCPD
+      IF (first) THEN
+
+     CALL getin_p('thermals_fact_epsilon',fact_epsilon)
+     CALL getin_p('thermals_betalpha',betalpha)
+     CALL getin_p('thermals_afact',afact)
+     CALL getin_p('thermals_fact_shell',fact_shell)
+     CALL getin_p('thermals_detr_min',detr_min)
+     CALL getin_p('thermals_entr_min',entr_min)
+     CALL getin_p('thermals_detr_q_coef',detr_q_coef)
+     CALL getin_p('thermals_detr_q_power',detr_q_power)
+     CALL getin_p('thermals_mix0',mix0)
+     CALL getin_p('thermals_flag_alim',thermals_flag_alim)
+
+
+      first=.false.
+      ENDIF
+
+      zbetalpha=betalpha/(1.+betalpha)
+
+
+! Initialisations des variables r?elles
+if (1==1) then
+      ztva(:,:)=ztv(:,:)
+      ztva_est(:,:)=ztva(:,:)
+      ztv_est(:,:)=ztv(:,:)
+      ztla(:,:)=zthl(:,:)
+      zqta(:,:)=po(:,:)
+      zqla(:,:)=0.
+      zha(:,:) = ztva(:,:)
+else
+      ztva(:,:)=0.
+      ztv_est(:,:)=0.
+      ztva_est(:,:)=0.
+      ztla(:,:)=0.
+      zqta(:,:)=0.
+      zha(:,:) =0.
+endif
+
+      zqla_est(:,:)=0.
+      zqsatth(:,:)=0.
+      zqla(:,:)=0.
+      detr_star(:,:)=0.
+      entr_star(:,:)=0.
+      alim_star(:,:)=0.
+      alim_star_tot(:)=0.
+      csc(:,:)=0.
+      detr(:,:)=0.
+      entr(:,:)=0.
+      zw2(:,:)=0.
+      zbuoy(:,:)=0.
+      zbuoyjam(:,:)=0.
+      gamma(:,:)=0.
+      zeps(:,:)=0.
+      w_est(:,:)=0.
+      f_star(:,:)=0.
+      wa_moy(:,:)=0.
+      linter(:)=1.
+!     linter(:)=1.
+! Initialisation des variables entieres
+      lmix(:)=1
+      lmix_bis(:)=2
+      wmaxa(:)=0.
+
+
+!-------------------------------------------------------------------------
+! On ne considere comme actif que les colonnes dont les deux premieres
+! couches sont instables.
+!-------------------------------------------------------------------------
+
+      active(:)=ztv(:,1)>ztv(:,2)
+      d_temp(:)=0. ! Pour activer un contraste de temperature a la base
+                   ! du panache
+!  Cet appel pourrait être fait avant thermcell_plume dans thermcell_main
+      CALL thermcell_alim(thermals_flag_alim,ngrid,klev,ztv,d_temp,zlev,alim_star,lalim)
+
+!------------------------------------------------------------------------------
+! Calcul dans la premiere couche
+! On decide dans cette version que le thermique n'est actif que si la premiere
+! couche est instable.
+! Pourrait etre change si on veut que le thermiques puisse se d??clencher
+! dans une couche l>1
+!------------------------------------------------------------------------------
+do ig=1,ngrid
+! Le panache va prendre au debut les caracteristiques de l'air contenu
+! dans cette couche.
+    if (active(ig)) then
+    ztla(ig,1)=zthl(ig,1) 
+    zqta(ig,1)=po(ig,1)
+    zqla(ig,1)=zl(ig,1)
+!cr: attention, prise en compte de f*(1)=1
+    f_star(ig,2)=alim_star(ig,1)
+    zw2(ig,2)=2.*RG*(ztv(ig,1)-ztv(ig,2))/ztv(ig,2)  &
+&                     *(zlev(ig,2)-zlev(ig,1))  &
+&                     *0.4*pphi(ig,1)/(pphi(ig,2)-pphi(ig,1))
+    w_est(ig,2)=zw2(ig,2)
+    endif
+enddo
+!
+
+!==============================================================================
+!boucle de calcul de la vitesse verticale dans le thermique
+!==============================================================================
+do l=2,klev-1
+!==============================================================================
+
+
+! On decide si le thermique est encore actif ou non
+! AFaire : Il faut sans doute ajouter entr_star a alim_star dans ce test
+    do ig=1,ngrid
+       active(ig)=active(ig) &
+&                 .and. zw2(ig,l)>1.e-10 &
+&                 .and. f_star(ig,l)+alim_star(ig,l)>1.e-10
+    enddo
+
+
+
+!---------------------------------------------------------------------------
+! calcul des proprietes thermodynamiques et de la vitesse de la couche l
+! sans tenir compte du detrainement et de l'entrainement dans cette
+! couche
+! C'est a dire qu'on suppose 
+! ztla(l)=ztla(l-1) et zqta(l)=zqta(l-1)
+! Ici encore, on doit pouvoir ajouter entr_star (qui peut etre calculer
+! avant) a l'alimentation pour avoir un calcul plus propre
+!---------------------------------------------------------------------------
+
+   ztemp(:)=zpspsk(:,l)*ztla(:,l-1)
+   call thermcell_qsat(ngrid,active,pplev(:,l),ztemp,zqta(:,l-1),zqsat(:))
+    do ig=1,ngrid 
+!       print*,'active',active(ig),ig,l
+        if(active(ig)) then 
+        zqla_est(ig,l)=max(0.,zqta(ig,l-1)-zqsat(ig))
+        ztva_est(ig,l) = ztla(ig,l-1)*zpspsk(ig,l)+RLvCp*zqla_est(ig,l)
+        zta_est(ig,l)=ztva_est(ig,l)
+        ztva_est(ig,l) = ztva_est(ig,l)/zpspsk(ig,l)
+        ztva_est(ig,l) = ztva_est(ig,l)*(1.+RETV*(zqta(ig,l-1)  &
+     &      -zqla_est(ig,l))-zqla_est(ig,l))
+ 
+
+!Modif AJAM
+
+        zbuoy(ig,l)=RG*(ztva_est(ig,l)-ztv(ig,l))/ztv(ig,l) 
+        zdz=zlev(ig,l+1)-zlev(ig,l)         
+        lmel=fact_thermals_ed_dz*zlev(ig,l)
+!        lmel=0.09*zlev(ig,l)
+        zlmel=zlev(ig,l)+lmel
+        zlmelup=zlmel+(zdz/2)
+        zlmeldwn=zlmel-(zdz/2)
+
+        lt=l+1
+        zlt=zlev(ig,lt)
+        zdz3=zlev(ig,lt+1)-zlt
+        zltdwn=zlt-zdz3/2
+        zltup=zlt+zdz3/2
+         
+!=========================================================================
+! 3. Calcul de la flotabilite modifie par melange avec l'air au dessus
+!=========================================================================
+
+!--------------------------------------------------
+        if (iflag_thermals_ed.lt.8) then
+!--------------------------------------------------
+!AJ052014: J'ai remplac?? la boucle do par un do while
+! afin de faire moins de calcul dans la boucle
+!--------------------------------------------------
+            do while (zlmelup.gt.zltup)
+               lt=lt+1
+               zlt=zlev(ig,lt)
+               zdz3=zlev(ig,lt+1)-zlt
+               zltdwn=zlt-zdz3/2
+               zltup=zlt+zdz3/2        
+            enddo
+!--------------------------------------------------
+!AJ052014: Si iflag_thermals_ed<8 (par ex 6), alors
+! on cherche o?? se trouve l'altitude d'inversion 
+! en calculant ztv1 (interpolation de la valeur de 
+! theta au niveau lt en utilisant les niveaux lt-1 et
+! lt-2) et ztv2 (interpolation avec les niveaux lt+1
+! et lt+2). Si theta r??ellement calcul??e au niveau lt
+! comprise entre ztv1 et ztv2, alors il y a inversion
+! et on calcule son altitude zinv en supposant que ztv(lt)
+! est une combinaison lineaire de ztv1 et ztv2.
+! Ensuite, on calcule la flottabilite en comparant 
+! la temperature de la couche l a celle de l'air situe 
+! l+lmel plus haut, ce qui necessite de savoir quel fraction 
+! de cet air est au-dessus ou en-dessous de l'inversion   
+!--------------------------------------------------
+            atv1=(ztv(ig,lt-1)-ztv(ig,lt-2))/(zlev(ig,lt-1)-zlev(ig,lt-2))
+            btv1=(ztv(ig,lt-2)*zlev(ig,lt-1)-ztv(ig,lt-1)*zlev(ig,lt-2)) &
+    &          /(zlev(ig,lt-1)-zlev(ig,lt-2))
+            atv2=(ztv(ig,lt+2)-ztv(ig,lt+1))/(zlev(ig,lt+2)-zlev(ig,lt+1))
+            btv2=(ztv(ig,lt+1)*zlev(ig,lt+2)-ztv(ig,lt+2)*zlev(ig,lt+1)) &
+    &          /(zlev(ig,lt+2)-zlev(ig,lt+1))
+
+             ztv1=atv1*zlt+btv1
+             ztv2=atv2*zlt+btv2
+
+             if (ztv(ig,lt).gt.ztv1.and.ztv(ig,lt).lt.ztv2) then  
+
+!--------------------------------------------------
+!AJ052014: D??calage de zinv qui est entre le haut
+!          et le bas de la couche lt
+!--------------------------------------------------
+                factinv=(ztv2-ztv(ig,lt))/(ztv2-ztv1)
+                zinv=zltdwn+zdz3*factinv
+
+          
+                if (zlmeldwn.ge.zinv) then
+                   ztv_est(ig,l)=atv2*zlmel+btv2
+                   zbuoyjam(ig,l)=fact_shell*RG*(ztva_est(ig,l)-ztv_est(ig,l))/ztv_est(ig,l) &
+    &                    +(1.-fact_shell)*zbuoy(ig,l)
+                elseif (zlmelup.ge.zinv) then
+                 ztv_est2=atv2*0.5*(zlmelup+zinv)+btv2
+                   ztv_est1=atv1*0.5*(zinv+zlmeldwn)+btv1
+                   ztv_est(ig,l)=((zlmelup-zinv)/zdz)*ztv_est2+((zinv-zlmeldwn)/zdz)*ztv_est1
+
+                   zbuoyjam(ig,l)=fact_shell*RG*(((zlmelup-zinv)/zdz)*(ztva_est(ig,l)- & 
+    &            ztv_est2)/ztv_est2+((zinv-zlmeldwn)/zdz)*(ztva_est(ig,l)- &
+    &            ztv_est1)/ztv_est1)+(1.-fact_shell)*zbuoy(ig,l)
+
+                else 
+                   ztv_est(ig,l)=atv1*zlmel+btv1
+                   zbuoyjam(ig,l)=fact_shell*RG*(ztva_est(ig,l)-ztv_est(ig,l))/ztv_est(ig,l) & 
+    &                           +(1.-fact_shell)*zbuoy(ig,l)
+                endif
+
+             else ! if (ztv(ig,lt).gt.ztv1.and.ztv(ig,lt).lt.ztv2) then
+
+                if (zlmeldwn.gt.zltdwn) then
+                   zbuoyjam(ig,l)=fact_shell*RG*((ztva_est(ig,l)- & 
+    &                ztv(ig,lt))/ztv(ig,lt))+(1.-fact_shell)*zbuoy(ig,l)
+                else
+                   zbuoyjam(ig,l)=fact_shell*RG*(((zlmelup-zltdwn)/zdz)*(ztva_est(ig,l)- & 
+    &                ztv(ig,lt))/ztv(ig,lt)+((zltdwn-zlmeldwn)/zdz)*(ztva_est(ig,l)- &
+    &                ztv(ig,lt-1))/ztv(ig,lt-1))+(1.-fact_shell)*zbuoy(ig,l)
+
+                endif
+
+!          zbuoyjam(ig,l)=fact_shell*RG*(((zlmelup-zltdwn)/zdz)*(ztva_est(ig,l)- & 
+!    &          ztv1)/ztv1+((zltdwn-zlmeldwn)/zdz)*(ztva_est(ig,l)- &
+!    &          ztv(ig,lt-1))/ztv(ig,lt-1))+(1.-fact_shell)*zbuoy(ig,l)
+!         zdqt(ig,l)=Max(0.,((lmel+zdz3-zdz2)/zdz3)*(zqta(ig,l-1)- & 
+!    &          po(ig,lt))/po(ig,lt)+((zdz2-lmel)/zdz3)*(zqta(ig,l-1)- &
+!     &          po(ig,lt-1))/po(ig,lt-1))
+          endif ! if (ztv(ig,lt).gt.ztv1.and.ztv(ig,lt).lt.ztv2) then
+
+        else  !   if (iflag_thermals_ed.lt.8) then
+           lt=l+1
+           zlt=zlev(ig,lt)
+           zdz2=zlev(ig,lt)-zlev(ig,l)
+
+           do while (lmel.gt.zdz2)
+             lt=lt+1
+             zlt=zlev(ig,lt)
+             zdz2=zlt-zlev(ig,l)
+           enddo
+           zdz3=zlev(ig,lt+1)-zlt
+           zltdwn=zlev(ig,lt)-zdz3/2
+           zlmelup=zlmel+(zdz/2)
+           coefzlmel=Min(1.,(zlmelup-zltdwn)/zdz)
+           zbuoyjam(ig,l)=1.*RG*(coefzlmel*(ztva_est(ig,l)- & 
+    &          ztv(ig,lt))/ztv(ig,lt)+(1.-coefzlmel)*(ztva_est(ig,l)- &
+    &          ztv(ig,lt-1))/ztv(ig,lt-1))+0.*zbuoy(ig,l)
+        endif !   if (iflag_thermals_ed.lt.8) then
+
+!------------------------------------------------
+!AJAM:nouveau calcul de w?  
+!------------------------------------------------
+              zdz=zlev(ig,l+1)-zlev(ig,l)
+              zdzbis=zlev(ig,l)-zlev(ig,l-1)
+              zbuoy(ig,l)=RG*(ztva_est(ig,l)-ztv(ig,l))/ztv(ig,l)
+
+              zw2fact=fact_epsilon*2.*zdz/(1.+betalpha)
+              zw2factbis=fact_epsilon*2.*zdzbis/(1.+betalpha)
+              zdw2=afact*zbuoy(ig,l)/fact_epsilon
+              zdw2bis=afact*zbuoy(ig,l-1)/fact_epsilon
+!              zdw2bis=0.5*(zdw2+zdw2bis)
+              lm=Max(1,l-2)
+!              zdw2=(afact/fact_epsilon)*((zdz/zdzbis)*zbuoy(ig,l) &
+!    &              +((zdzbis-zdz)/zdzbis)*zbuoy(ig,l-1)) 
+!              zdw2bis=(afact/fact_epsilon)*((zdz/zdzbis)*zbuoy(ig,l-1) &
+!    &              +((zdzbis-zdz)/zdzbis)*zbuoy(ig,l-1))
+!             w_est(ig,l+1)=Max(0.0001,exp(-zw2fact)*(w_est(ig,l)-zdw2)+zdw2)
+!             w_est(ig,l+1)=(zdz/zdzbis)*Max(0.0001,exp(-zw2fact)* &
+!    &                     (w_est(ig,l)-zdw2)+zdw2)+(zdzbis-zdz)/zdzbis* &
+!    &                     Max(0.0001,exp(-zw2factbis)*(w_est(ig,l-1)-zdw2bis)+zdw2)
+!              w_est(ig,l+1)=Max(0.0001,(1-exp(-zw2fact))*zdw2+w_est(ig,l)*exp(-zw2fact))
+
+!--------------------------------------------------
+!AJ052014: J'ai remplac? w_est(ig,l) par zw2(ig,l)
+!--------------------------------------------------
+         if (iflag_thermals_ed==8) then
+! Ancienne version
+!             w_est(ig,l+1)=Max(0.0001,(zdz/zdzbis)*(exp(-zw2fact)* &
+!    &                     (w_est(ig,l)-zdw2)+zdw2)+(zdzbis-zdz)/zdzbis* &
+!    &                     (exp(-zw2factbis)*(w_est(ig,l-1)-zdw2bis)+zdw2))
+
+	    w_est(ig,l+1)=Max(0.0001,exp(-zw2fact)*(w_est(ig,l)-zdw2)+zdw2)
+
+! Nouvelle version Arnaud
+         else
+!             w_est(ig,l+1)=Max(0.0001,(zdz/zdzbis)*(exp(-zw2fact)* &
+!    &                     (w_est(ig,l)-zdw2)+zdw2)+(zdzbis-zdz)/zdzbis* &
+!    &                     (exp(-zw2factbis)*(w_est(ig,l-1)-zdw2bis)+zdw2))
+
+	    w_est(ig,l+1)=Max(0.0001,exp(-zw2fact)*(w_est(ig,l)-zdw2bis)+zdw2)
+
+!             w_est(ig,l+1)=Max(0.0001,(zdz/(zdzbis+zdz))*(exp(-zw2fact)* &
+!    &                     (w_est(ig,l)-zdw2bis)+zdw2)+(zdzbis/(zdzbis+zdz))* &
+!    &                     (exp(-zw2factbis)*(w_est(ig,l-1)-zdw2bis)+zdw2bis))
+
+
+
+!            w_est(ig,l+1)=Max(0.0001,(w_est(ig,l)+zdw2bis*zw2fact)*exp(-zw2fact))
+
+!             w_est(ig,l+1)=Max(0.0001,(zdz/zdzbis)*(zw2(ig,l)+zdw2*zw2fact)*exp(-zw2fact)+ &
+!    &                      (zdzbis-zdz)/zdzbis*(zw2(ig,l-1)+zdw2bis*zw2factbis)*exp(-zw2factbis))
+
+!             w_est(ig,l+1)=Max(0.0001,exp(-zw2factbis)*(w_est(ig,l-1)-zdw2bis)+zdw2)
+
+         endif
+
+
+         if (iflag_thermals_ed<6) then
+             zalpha=f0(ig)*f_star(ig,l)/sqrt(w_est(ig,l+1))/rhobarz(ig,l)
+!              fact_epsilon=0.0005/(zalpha+0.025)**0.5
+!              fact_epsilon=Min(0.003,0.0004/(zalpha)**0.5)
+              fact_epsilon=0.0002/(zalpha+0.1)
+              zw2fact=fact_epsilon*2.*zdz/(1.+betalpha)
+              zw2factbis=fact_epsilon*2.*zdzbis/(1.+betalpha)
+              zdw2=afact*zbuoy(ig,l)/fact_epsilon
+              zdw2bis=afact*zbuoy(ig,l-1)/fact_epsilon
+!              w_est(ig,l+1)=Max(0.0001,(zw2(ig,l)+zdw2*zw2fact)*exp(-zw2fact))
+
+!              w_est(ig,l+1)=Max(0.0001,(zdz/zdzbis)*(exp(-zw2fact)* &
+!    &                     (zw2(ig,l)-zdw2)+zdw2)+(zdzbis-zdz)/zdzbis* &
+!    &                     (exp(-zw2factbis)*(zw2(ig,l-1)-zdw2bis)+zdw2))
+
+	    w_est(ig,l+1)=Max(0.0001,exp(-zw2fact)*(w_est(ig,l)-zdw2bis)+zdw2)
+
+
+         endif
+!--------------------------------------------------
+!AJ052014: J'ai comment? ce if plus n?cessaire puisqu'
+!on fait max(0.0001,.....)
+!--------------------------------------------------         
+
+!             if (w_est(ig,l+1).lt.0.) then
+!               w_est(ig,l+1)=zw2(ig,l)
+!                w_est(ig,l+1)=0.0001
+!             endif
+
+       endif
+    enddo
+
+
+!-------------------------------------------------
+!calcul des taux d'entrainement et de detrainement
+!-------------------------------------------------
+
+     do ig=1,ngrid
+        if (active(ig)) then
+
+!          zw2m=max(0.5*(w_est(ig,l)+w_est(ig,l+1)),0.1)
+          zw2m=w_est(ig,l+1)
+!          zw2m=zw2(ig,l)
+          zdz=zlev(ig,l+1)-zlev(ig,l)
+          zbuoy(ig,l)=RG*(ztva_est(ig,l)-ztv(ig,l))/ztv(ig,l)
+!          zbuoybis=zbuoy(ig,l)+RG*0.1/300.
+          zbuoybis=zbuoy(ig,l)
+          zalpha=f0(ig)*f_star(ig,l)/sqrt(w_est(ig,l+1))/rhobarz(ig,l)
+          zdqt(ig,l)=max(zqta(ig,l-1)-po(ig,l),0.)/po(ig,l)
+
+          
+!          entr_star(ig,l)=f_star(ig,l)*zdz*zbetalpha*MAX(0.,  &
+!    &     afact*zbuoybis/zw2m - fact_epsilon )
+
+!          entr_star(ig,l)=MAX(0.,f_star(ig,l)*zdz*zbetalpha*  &
+!    &     afact*zbuoybis/zw2m - fact_epsilon )
+
+
+
+!          zbuoyjam(ig,l)=RG*(ztva_est(ig,l)-ztv(ig,l))/ztv(ig,l)
+
+!=========================================================================
+! 4. Calcul de l'entrainement et du detrainement
+!=========================================================================
+
+!          entr_star(ig,l)=f_star(ig,l)*zdz*zbetalpha*MAX(0.,  &
+!    &     afact*zbuoyjam(ig,l)/zw2m - fact_epsilon ) 
+!          entrbis=entr_star(ig,l)
+
+          if (iflag_thermals_ed.lt.6) then
+          fact_epsilon=0.0002/(zalpha+0.1)
+          endif
+          
+
+
+          detr_star(ig,l)=f_star(ig,l)*zdz             &
+    &     *( mix0 * 0.1 / (zalpha+0.001)               &
+    &     + MAX(detr_min, -afact*zbetalpha*zbuoyjam(ig,l)/zw2m   &
+    &     + detr_q_coef*(zdqt(ig,l)/zw2m)**detr_q_power))
+
+!	  detr_star(ig,l)=(zdz/zdzbis)*detr_star(ig,l)+ &
+!    &			  ((zdzbis-zdz)/zdzbis)*detr_star(ig,l-1)
+
+          zbuoy(ig,l)=RG*(ztva_est(ig,l)-ztv(ig,l))/ztv(ig,l)
+
+          entr_star(ig,l)=f_star(ig,l)*zdz* (         &
+    &       mix0 * 0.1 / (zalpha+0.001)               &
+    &     + zbetalpha*MAX(entr_min,                   &
+    &     afact*zbuoyjam(ig,l)/zw2m - fact_epsilon))
+
+
+!          entr_star(ig,l)=f_star(ig,l)*zdz* (         &
+!    &       mix0 * 0.1 / (zalpha+0.001)               &
+!    &     + MAX(entr_min,                   &
+!    &     zbetalpha*afact*zbuoyjam(ig,l)/zw2m - fact_epsilon +  & 
+!    &     detr_q_coef*(zdqt(ig,l)/zw2m)**detr_q_power))
+
+
+!	  entr_star(ig,l)=(zdz/zdzbis)*entr_star(ig,l)+ &
+!    &			  ((zdzbis-zdz)/zdzbis)*entr_star(ig,l-1)
+
+!          entr_star(ig,l)=Max(0.,f_star(ig,l)*zdz*zbetalpha*  &     
+!    &     afact*zbuoy(ig,l)/zw2m &
+!    &     - 1.*fact_epsilon)
+
+          
+! En dessous de lalim, on prend le max de alim_star et entr_star pour
+! alim_star et 0 sinon
+        if (l.lt.lalim(ig)) then
+          alim_star(ig,l)=max(alim_star(ig,l),entr_star(ig,l))
+          entr_star(ig,l)=0.
+        endif
+!        if (l.lt.lalim(ig).and.alim_star(ig,l)>alim_star(ig,l-1)) then
+!          alim_star(ig,l)=entrbis
+!        endif
+
+!        print*,'alim0',zlev(ig,l),entr_star(ig,l),detr_star(ig,l),zw2m,zbuoy(ig,l),f_star(ig,l)
+! Calcul du flux montant normalise
+      f_star(ig,l+1)=f_star(ig,l)+alim_star(ig,l)+entr_star(ig,l)  &
+     &              -detr_star(ig,l)
+
+      endif
+   enddo
+
+
+!============================================================================
+! 5. calcul de la vitesse verticale en melangeant Tl et qt du thermique
+!===========================================================================
+
+   activetmp(:)=active(:) .and. f_star(:,l+1)>1.e-10
+   do ig=1,ngrid
+       if (activetmp(ig)) then 
+           Zsat=.false.
+           ztla(ig,l)=(f_star(ig,l)*ztla(ig,l-1)+  &
+     &            (alim_star(ig,l)+entr_star(ig,l))*zthl(ig,l))  &
+     &            /(f_star(ig,l+1)+detr_star(ig,l))
+           zqta(ig,l)=(f_star(ig,l)*zqta(ig,l-1)+  &
+     &            (alim_star(ig,l)+entr_star(ig,l))*po(ig,l))  &
+     &            /(f_star(ig,l+1)+detr_star(ig,l))
+
+        endif
+    enddo
+
+   ztemp(:)=zpspsk(:,l)*ztla(:,l)
+   call thermcell_qsat(ngrid,activetmp,pplev(:,l),ztemp,zqta(:,l),zqsatth(:,l))
+   do ig=1,ngrid
+      if (activetmp(ig)) then
+! on ecrit de maniere conservative (sat ou non)
+!          T = Tl +Lv/Cp ql
+           zqla(ig,l)=max(0.,zqta(ig,l)-zqsatth(ig,l))
+           ztva(ig,l) = ztla(ig,l)*zpspsk(ig,l)+RLvCp*zqla(ig,l)
+           ztva(ig,l) = ztva(ig,l)/zpspsk(ig,l)
+!on rajoute le calcul de zha pour diagnostiques (temp potentielle)
+           zha(ig,l) = ztva(ig,l)
+           ztva(ig,l) = ztva(ig,l)*(1.+RETV*(zqta(ig,l)  &
+     &              -zqla(ig,l))-zqla(ig,l))
+           zbuoy(ig,l)=RG*(ztva(ig,l)-ztv(ig,l))/ztv(ig,l)
+           zdz=zlev(ig,l+1)-zlev(ig,l)
+           zdzbis=zlev(ig,l)-zlev(ig,l-1)
+           zeps(ig,l)=(entr_star(ig,l)+alim_star(ig,l))/(f_star(ig,l)*zdz)
+!!!!!!!          fact_epsilon=0.002
+            zw2fact=fact_epsilon*2.*zdz/(1.+betalpha)
+            zw2factbis=fact_epsilon*2.*zdzbis/(1.+betalpha)
+            zdw2= afact*zbuoy(ig,l)/(fact_epsilon)
+            zdw2bis= afact*zbuoy(ig,l-1)/(fact_epsilon)
+!              zdw2=(afact/fact_epsilon)*((zdz/zdzbis)*zbuoy(ig,l) &
+!    &              +((zdzbis-zdz)/zdzbis)*zbuoy(ig,l-1)) 
+!              lm=Max(1,l-2)
+!              zdw2bis=(afact/fact_epsilon)*((zdz/zdzbis)*zbuoy(ig,l-1) &
+!    &              +((zdzbis-zdz)/zdzbis)*zbuoy(ig,l-1))
+!            zw2(ig,l+1)=Max(0.0001,exp(-zw2fact)*(zw2(ig,l)-zdw2bis)+zdw2)
+!            zw2(ig,l+1)=Max(0.0001,(zdz/zdzbis)*(zw2(ig,l)+zdw2*zw2fact)*exp(-zw2fact)+ &
+!     &                   (zdzbis-zdz)/zdzbis*(zw2(ig,l-1)+zdw2bis*zw2factbis)*exp(-zw2factbis))
+!            zw2(ig,l+1)=Max(0.0001,(zw2(ig,l)+zdw2*zw2fact)*exp(-zw2fact))
+!            zw2(ig,l+1)=Max(0.0001,(zdz/zdzbis)*(exp(-zw2fact)* &
+!    &                     (zw2(ig,l)-zdw2)+zdw2)+(zdzbis-zdz)/zdzbis* &
+!    &                     (exp(-zw2factbis)*(zw2(ig,l-1)-zdw2bis)+zdw2))
+            if (iflag_thermals_ed==8) then
+	    zw2(ig,l+1)=Max(0.0001,exp(-zw2fact)*(zw2(ig,l)-zdw2)+zdw2)
+            else
+	    zw2(ig,l+1)=Max(0.0001,exp(-zw2fact)*(zw2(ig,l)-zdw2bis)+zdw2)
+            endif
+!            zw2(ig,l+1)=Max(0.0001,(zdz/(zdz+zdzbis))*(exp(-zw2fact)* &
+!    &                     (zw2(ig,l)-zdw2)+zdw2bis)+(zdzbis/(zdz+zdzbis))* &
+!    &                     (exp(-zw2factbis)*(zw2(ig,l-1)-zdw2bis)+zdw2bis))
+
+
+           if (iflag_thermals_ed.lt.6) then
+           zalpha=f0(ig)*f_star(ig,l)/sqrt(zw2(ig,l+1))/rhobarz(ig,l)
+!           fact_epsilon=0.0005/(zalpha+0.025)**0.5
+!           fact_epsilon=Min(0.003,0.0004/(zalpha)**0.5)
+           fact_epsilon=0.0002/(zalpha+0.1)**1
+            zw2fact=fact_epsilon*2.*zdz/(1.+betalpha)
+            zw2factbis=fact_epsilon*2.*zdzbis/(1.+betalpha)
+            zdw2= afact*zbuoy(ig,l)/(fact_epsilon)
+            zdw2bis= afact*zbuoy(ig,l-1)/(fact_epsilon)
+
+!            zw2(ig,l+1)=Max(0.0001,(zdz/zdzbis)*(exp(-zw2fact)* &
+!    &                     (zw2(ig,l)-zdw2)+zdw2)+(zdzbis-zdz)/zdzbis* &
+!    &                     (exp(-zw2factbis)*(zw2(ig,l-1)-zdw2bis)+zdw2))
+!            zw2(ig,l+1)=Max(0.0001,(zw2(ig,l)+zdw2*zw2fact)*exp(-zw2fact))
+	    zw2(ig,l+1)=Max(0.0001,exp(-zw2fact)*(zw2(ig,l)-zdw2bis)+zdw2)
+
+           endif
+
+
+      endif
+   enddo
+
+        if (prt_level.ge.20) print*,'coucou calcul detr 460: ig, l',ig, l
+!
+!===========================================================================
+! 6. initialisations pour le calcul de la hauteur du thermique, de l'inversion et de la vitesse verticale max 
+!===========================================================================
+
+   nbpb=0
+   do ig=1,ngrid
+            if (zw2(ig,l+1)>0. .and. zw2(ig,l+1).lt.1.e-10) then
+!               stop'On tombe sur le cas particulier de thermcell_dry'
+!               print*,'On tombe sur le cas particulier de thermcell_plume'
+                nbpb=nbpb+1
+                zw2(ig,l+1)=0.
+                linter(ig)=l+1
+            endif
+
+        if (zw2(ig,l+1).lt.0.) then 
+           linter(ig)=(l*(zw2(ig,l+1)-zw2(ig,l))  &
+     &               -zw2(ig,l))/(zw2(ig,l+1)-zw2(ig,l))
+           zw2(ig,l+1)=0.
+!+CR:04/05/12:correction calcul linter pour calcul de zmax continu
+        elseif (f_star(ig,l+1).lt.0.) then
+           linter(ig)=(l*(f_star(ig,l+1)-f_star(ig,l))  &
+     &               -f_star(ig,l))/(f_star(ig,l+1)-f_star(ig,l))
+           zw2(ig,l+1)=0.
+!fin CR:04/05/12
+        endif
+
+           wa_moy(ig,l+1)=sqrt(zw2(ig,l+1)) 
+
+        if (wa_moy(ig,l+1).gt.wmaxa(ig)) then
+!   lmix est le niveau de la couche ou w (wa_moy) est maximum
+!on rajoute le calcul de lmix_bis
+            if (zqla(ig,l).lt.1.e-10) then
+               lmix_bis(ig)=l+1
+            endif
+            lmix(ig)=l+1
+            wmaxa(ig)=wa_moy(ig,l+1)
+        endif
+   enddo
+
+   if (nbpb>0) then
+   print*,'WARNING on tombe ',nbpb,' x sur un pb pour l=',l,' dans thermcell_plume'
+   endif
+
+!=========================================================================
+! FIN DE LA BOUCLE VERTICALE
+      enddo
+!=========================================================================
+
+!on recalcule alim_star_tot
+       do ig=1,ngrid
+          alim_star_tot(ig)=0.
+       enddo
+       do ig=1,ngrid
+          do l=1,lalim(ig)-1
+          alim_star_tot(ig)=alim_star_tot(ig)+alim_star(ig,l)
+          enddo
+       enddo
+       
+
+        if (prt_level.ge.20) print*,'coucou calcul detr 470: ig, l', ig, l
+
+#undef wrgrads_thermcell
+#ifdef wrgrads_thermcell
+         call wrgradsfi(1,klev,entr_star(igout,1:klev),'esta      ','esta      ')
+         call wrgradsfi(1,klev,detr_star(igout,1:klev),'dsta      ','dsta      ')
+         call wrgradsfi(1,klev,zbuoy(igout,1:klev),'buoy      ','buoy      ')
+         call wrgradsfi(1,klev,zdqt(igout,1:klev),'dqt      ','dqt      ')
+         call wrgradsfi(1,klev,w_est(igout,1:klev),'w_est     ','w_est     ')
+         call wrgradsfi(1,klev,w_est(igout,2:klev+1),'w_es2     ','w_es2     ')
+         call wrgradsfi(1,klev,zw2(igout,1:klev),'zw2A      ','zw2A      ')
+#endif
+
+
+     return 
+     end
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ SUBROUTINE thermcell_plume_5B(itap,ngrid,klev,ptimestep,ztv,zthl,po,zl,rhobarz,  &
+&           zlev,pplev,pphi,zpspsk,alim_star,alim_star_tot,  &
+&           lalim,f0,detr_star,entr_star,f_star,csc,ztva,  &
+&           ztla,zqla,zqta,zha,zw2,w_est,ztva_est,zqsatth,lmix,lmix_bis,linter &
+&           ,lev_out,lunout1,igout)
+!&           ,lev_out,lunout1,igout,zbuoy,zbuoyjam)
+
+!--------------------------------------------------------------------------
+!thermcell_plume: calcule les valeurs de qt, thetal et w dans l ascendance
+! Version conforme a l'article de Rio et al. 2010.
+! Code ecrit par Catherine Rio, Arnaud Jam et Frederic Hourdin
+!--------------------------------------------------------------------------
+
+      USE print_control_mod, ONLY: prt_level
+      IMPLICIT NONE
+
+#include "YOMCST.h"
+#include "YOETHF.h"
+#include "FCTTRE.h"
+#include "thermcell.h"
+
+      INTEGER itap
+      INTEGER lunout1,igout
+      INTEGER ngrid,klev
+      REAL ptimestep
+      REAL ztv(ngrid,klev)
+      REAL zthl(ngrid,klev)
+      REAL po(ngrid,klev)
+      REAL zl(ngrid,klev)
+      REAL rhobarz(ngrid,klev)
+      REAL zlev(ngrid,klev+1)
+      REAL pplev(ngrid,klev+1)
+      REAL pphi(ngrid,klev)
+      REAL zpspsk(ngrid,klev)
+      REAL alim_star(ngrid,klev)
+      REAL f0(ngrid)
+      INTEGER lalim(ngrid)
+      integer lev_out                           ! niveau pour les print
+      integer nbpb
+    
+      real alim_star_tot(ngrid)
+
+      REAL ztva(ngrid,klev)
+      REAL ztla(ngrid,klev)
+      REAL zqla(ngrid,klev)
+      REAL zqta(ngrid,klev)
+      REAL zha(ngrid,klev)
+
+      REAL detr_star(ngrid,klev)
+      REAL coefc
+      REAL entr_star(ngrid,klev)
+      REAL detr(ngrid,klev)
+      REAL entr(ngrid,klev)
+
+      REAL csc(ngrid,klev)
+
+      REAL zw2(ngrid,klev+1)
+      REAL w_est(ngrid,klev+1)
+      REAL f_star(ngrid,klev+1)
+      REAL wa_moy(ngrid,klev+1)
+
+      REAL ztva_est(ngrid,klev)
+      REAL zqla_est(ngrid,klev)
+      REAL zqsatth(ngrid,klev)
+      REAL zta_est(ngrid,klev)
+      REAL zbuoyjam(ngrid,klev)
+      REAL ztemp(ngrid),zqsat(ngrid)
+      REAL zdw2
+      REAL zw2modif
+      REAL zw2fact
+      REAL zeps(ngrid,klev)
+
+      REAL linter(ngrid)
+      INTEGER lmix(ngrid)
+      INTEGER lmix_bis(ngrid)
+      REAL    wmaxa(ngrid)
+
+      INTEGER ig,l,k
+
+      real zdz,zbuoy(ngrid,klev),zalpha,gamma(ngrid,klev),zdqt(ngrid,klev),zw2m
+      real zbuoybis
+      real zcor,zdelta,zcvm5,qlbef,zdz2
+      real betalpha,zbetalpha
+      real eps, afact
+      REAL REPS,RLvCp,DDT0
+      PARAMETER (DDT0=.01)
+      logical Zsat
+      LOGICAL active(ngrid),activetmp(ngrid)
+      REAL fact_gamma,fact_epsilon,fact_gamma2,fact_epsilon2
+      REAL c2(ngrid,klev)
+      Zsat=.false.
+! Initialisation
+
+      RLvCp = RLVTT/RCPD
+      fact_epsilon=0.002
+      betalpha=0.9 
+      afact=2./3.            
+
+      zbetalpha=betalpha/(1.+betalpha)
+
+
+! Initialisations des variables reeles
+if (1==1) then
+      ztva(:,:)=ztv(:,:)
+      ztva_est(:,:)=ztva(:,:)
+      ztla(:,:)=zthl(:,:)
+      zqta(:,:)=po(:,:)
+      zha(:,:) = ztva(:,:)
+else
+      ztva(:,:)=0.
+      ztva_est(:,:)=0.
+      ztla(:,:)=0.
+      zqta(:,:)=0.
+      zha(:,:) =0.
+endif
+
+      zqla_est(:,:)=0.
+      zqsatth(:,:)=0.
+      zqla(:,:)=0.
+      detr_star(:,:)=0.
+      entr_star(:,:)=0.
+      alim_star(:,:)=0.
+      alim_star_tot(:)=0.
+      csc(:,:)=0.
+      detr(:,:)=0.
+      entr(:,:)=0.
+      zw2(:,:)=0.
+      zbuoy(:,:)=0.
+      zbuoyjam(:,:)=0.
+      gamma(:,:)=0.
+      zeps(:,:)=0.
+      w_est(:,:)=0.
+      f_star(:,:)=0.
+      wa_moy(:,:)=0.
+      linter(:)=1.
+!     linter(:)=1.
+! Initialisation des variables entieres
+      lmix(:)=1
+      lmix_bis(:)=2
+      wmaxa(:)=0.
+      lalim(:)=1
+
+
+!-------------------------------------------------------------------------
+! On ne considere comme actif que les colonnes dont les deux premieres
+! couches sont instables.
+!-------------------------------------------------------------------------
+      active(:)=ztv(:,1)>ztv(:,2)
+
+!-------------------------------------------------------------------------
+! Definition de l'alimentation a l'origine dans thermcell_init
+!-------------------------------------------------------------------------
+      do l=1,klev-1
+         do ig=1,ngrid
+            if (ztv(ig,l)> ztv(ig,l+1) .and. ztv(ig,1)>=ztv(ig,l) ) then
+               alim_star(ig,l)=MAX((ztv(ig,l)-ztv(ig,l+1)),0.)  &
+     &                       *sqrt(zlev(ig,l+1)) 
+               lalim(ig)=l+1
+               alim_star_tot(ig)=alim_star_tot(ig)+alim_star(ig,l)
+            endif
+         enddo
+      enddo
+      do l=1,klev
+         do ig=1,ngrid 
+            if (alim_star_tot(ig) > 1.e-10 ) then
+               alim_star(ig,l)=alim_star(ig,l)/alim_star_tot(ig)
+            endif
+         enddo
+      enddo
+      alim_star_tot(:)=1.
+
+
+
+!------------------------------------------------------------------------------
+! Calcul dans la premiere couche
+! On decide dans cette version que le thermique n'est actif que si la premiere
+! couche est instable.
+! Pourrait etre change si on veut que le thermiques puisse se d??clencher
+! dans une couche l>1
+!------------------------------------------------------------------------------
+do ig=1,ngrid
+! Le panache va prendre au debut les caracteristiques de l'air contenu
+! dans cette couche.
+    if (active(ig)) then
+    ztla(ig,1)=zthl(ig,1) 
+    zqta(ig,1)=po(ig,1)
+    zqla(ig,1)=zl(ig,1)
+!cr: attention, prise en compte de f*(1)=1
+    f_star(ig,2)=alim_star(ig,1)
+    zw2(ig,2)=2.*RG*(ztv(ig,1)-ztv(ig,2))/ztv(ig,2)  &
+&                     *(zlev(ig,2)-zlev(ig,1))  &
+&                     *0.4*pphi(ig,1)/(pphi(ig,2)-pphi(ig,1))
+    w_est(ig,2)=zw2(ig,2)
+    endif
+enddo
+!
+
+!==============================================================================
+!boucle de calcul de la vitesse verticale dans le thermique
+!==============================================================================
+do l=2,klev-1
+!==============================================================================
+
+
+! On decide si le thermique est encore actif ou non
+! AFaire : Il faut sans doute ajouter entr_star a alim_star dans ce test
+    do ig=1,ngrid
+       active(ig)=active(ig) &
+&                 .and. zw2(ig,l)>1.e-10 &
+&                 .and. f_star(ig,l)+alim_star(ig,l)>1.e-10
+    enddo
+
+
+
+!---------------------------------------------------------------------------
+! calcul des proprietes thermodynamiques et de la vitesse de la couche l
+! sans tenir compte du detrainement et de l'entrainement dans cette
+! couche
+! C'est a dire qu'on suppose 
+! ztla(l)=ztla(l-1) et zqta(l)=zqta(l-1)
+! Ici encore, on doit pouvoir ajouter entr_star (qui peut etre calculer
+! avant) a l'alimentation pour avoir un calcul plus propre
+!---------------------------------------------------------------------------
+
+   ztemp(:)=zpspsk(:,l)*ztla(:,l-1)
+   call thermcell_qsat(ngrid,active,pplev(:,l),ztemp,zqta(:,l-1),zqsat(:))
+
+    do ig=1,ngrid 
+!       print*,'active',active(ig),ig,l
+        if(active(ig)) then 
+        zqla_est(ig,l)=max(0.,zqta(ig,l-1)-zqsat(ig))
+        ztva_est(ig,l) = ztla(ig,l-1)*zpspsk(ig,l)+RLvCp*zqla_est(ig,l)
+        zta_est(ig,l)=ztva_est(ig,l)
+        ztva_est(ig,l) = ztva_est(ig,l)/zpspsk(ig,l)
+        ztva_est(ig,l) = ztva_est(ig,l)*(1.+RETV*(zqta(ig,l-1)  &
+     &      -zqla_est(ig,l))-zqla_est(ig,l))
+
+!------------------------------------------------
+!AJAM:nouveau calcul de w?  
+!------------------------------------------------
+              zdz=zlev(ig,l+1)-zlev(ig,l)
+              zbuoy(ig,l)=RG*(ztva_est(ig,l)-ztv(ig,l))/ztv(ig,l)
+
+              zw2fact=fact_epsilon*2.*zdz/(1.+betalpha)
+              zdw2=(afact)*zbuoy(ig,l)/(fact_epsilon)
+              w_est(ig,l+1)=Max(0.0001,exp(-zw2fact)*(w_est(ig,l)-zdw2)+zdw2)
+ 
+
+             if (w_est(ig,l+1).lt.0.) then
+                w_est(ig,l+1)=zw2(ig,l)
+             endif
+       endif
+    enddo
+
+
+!-------------------------------------------------
+!calcul des taux d'entrainement et de detrainement
+!-------------------------------------------------
+
+     do ig=1,ngrid
+        if (active(ig)) then
+
+          zw2m=max(0.5*(w_est(ig,l)+w_est(ig,l+1)),0.1)
+          zw2m=w_est(ig,l+1)
+          zdz=zlev(ig,l+1)-zlev(ig,l)
+          zbuoy(ig,l)=RG*(ztva_est(ig,l)-ztv(ig,l))/ztv(ig,l)
+!          zbuoybis=zbuoy(ig,l)+RG*0.1/300.
+          zbuoybis=zbuoy(ig,l)
+          zalpha=f0(ig)*f_star(ig,l)/sqrt(w_est(ig,l+1))/rhobarz(ig,l)
+          zdqt(ig,l)=max(zqta(ig,l-1)-po(ig,l),0.)/po(ig,l)
+
+          
+          entr_star(ig,l)=f_star(ig,l)*zdz*  zbetalpha*MAX(0.,  &
+    &     afact*zbuoybis/zw2m - fact_epsilon )
+
+
+          detr_star(ig,l)=f_star(ig,l)*zdz                        &
+    &     *MAX(1.e-3, -afact*zbetalpha*zbuoy(ig,l)/zw2m          &
+    &     + 0.012*(zdqt(ig,l)/zw2m)**0.5 )
+          
+! En dessous de lalim, on prend le max de alim_star et entr_star pour
+! alim_star et 0 sinon
+        if (l.lt.lalim(ig)) then
+          alim_star(ig,l)=max(alim_star(ig,l),entr_star(ig,l))
+          entr_star(ig,l)=0.
+        endif
+
+! Calcul du flux montant normalise
+      f_star(ig,l+1)=f_star(ig,l)+alim_star(ig,l)+entr_star(ig,l)  &
+     &              -detr_star(ig,l)
+
+      endif
+   enddo
+
+
+!----------------------------------------------------------------------------
+!calcul de la vitesse verticale en melangeant Tl et qt du thermique
+!---------------------------------------------------------------------------
+   activetmp(:)=active(:) .and. f_star(:,l+1)>1.e-10
+   do ig=1,ngrid
+       if (activetmp(ig)) then 
+           Zsat=.false.
+           ztla(ig,l)=(f_star(ig,l)*ztla(ig,l-1)+  &
+     &            (alim_star(ig,l)+entr_star(ig,l))*zthl(ig,l))  &
+     &            /(f_star(ig,l+1)+detr_star(ig,l))
+           zqta(ig,l)=(f_star(ig,l)*zqta(ig,l-1)+  &
+     &            (alim_star(ig,l)+entr_star(ig,l))*po(ig,l))  &
+     &            /(f_star(ig,l+1)+detr_star(ig,l))
+
+        endif
+    enddo
+
+   ztemp(:)=zpspsk(:,l)*ztla(:,l)
+   call thermcell_qsat(ngrid,activetmp,pplev(:,l),ztemp,zqta(:,l),zqsatth(:,l))
+
+   do ig=1,ngrid
+      if (activetmp(ig)) then
+! on ecrit de maniere conservative (sat ou non)
+!          T = Tl +Lv/Cp ql
+           zqla(ig,l)=max(0.,zqta(ig,l)-zqsatth(ig,l))
+           ztva(ig,l) = ztla(ig,l)*zpspsk(ig,l)+RLvCp*zqla(ig,l)
+           ztva(ig,l) = ztva(ig,l)/zpspsk(ig,l)
+!on rajoute le calcul de zha pour diagnostiques (temp potentielle)
+           zha(ig,l) = ztva(ig,l)
+           ztva(ig,l) = ztva(ig,l)*(1.+RETV*(zqta(ig,l)  &
+     &              -zqla(ig,l))-zqla(ig,l))
+           zbuoy(ig,l)=RG*(ztva(ig,l)-ztv(ig,l))/ztv(ig,l)
+           zdz=zlev(ig,l+1)-zlev(ig,l)
+           zeps(ig,l)=(entr_star(ig,l)+alim_star(ig,l))/(f_star(ig,l)*zdz)
+
+            zw2fact=fact_epsilon*2.*zdz/(1.+betalpha)
+            zdw2=afact*zbuoy(ig,l)/(fact_epsilon)
+            zw2(ig,l+1)=Max(0.0001,exp(-zw2fact)*(zw2(ig,l)-zdw2)+zdw2) 
+      endif
+   enddo
+
+        if (prt_level.ge.20) print*,'coucou calcul detr 460: ig, l',ig, l
+!
+!---------------------------------------------------------------------------
+!initialisations pour le calcul de la hauteur du thermique, de l'inversion et de la vitesse verticale max 
+!---------------------------------------------------------------------------
+
+   nbpb=0
+   do ig=1,ngrid
+            if (zw2(ig,l+1)>0. .and. zw2(ig,l+1).lt.1.e-10) then
+!               stop'On tombe sur le cas particulier de thermcell_dry'
+!               print*,'On tombe sur le cas particulier de thermcell_plume'
+                nbpb=nbpb+1
+                zw2(ig,l+1)=0.
+                linter(ig)=l+1
+            endif
+
+        if (zw2(ig,l+1).lt.0.) then 
+           linter(ig)=(l*(zw2(ig,l+1)-zw2(ig,l))  &
+     &               -zw2(ig,l))/(zw2(ig,l+1)-zw2(ig,l))
+           zw2(ig,l+1)=0.
+        elseif (f_star(ig,l+1).lt.0.) then
+           linter(ig)=(l*(f_star(ig,l+1)-f_star(ig,l))  &
+     &               -f_star(ig,l))/(f_star(ig,l+1)-f_star(ig,l))
+!           print*,"linter plume", linter(ig)
+           zw2(ig,l+1)=0.
+        endif
+
+           wa_moy(ig,l+1)=sqrt(zw2(ig,l+1)) 
+
+        if (wa_moy(ig,l+1).gt.wmaxa(ig)) then
+!   lmix est le niveau de la couche ou w (wa_moy) est maximum
+!on rajoute le calcul de lmix_bis
+            if (zqla(ig,l).lt.1.e-10) then
+               lmix_bis(ig)=l+1
+            endif
+            lmix(ig)=l+1
+            wmaxa(ig)=wa_moy(ig,l+1)
+        endif
+   enddo
+
+   if (nbpb>0) then
+   print*,'WARNING on tombe ',nbpb,' x sur un pb pour l=',l,' dans thermcell_plume'
+   endif
+
+!=========================================================================
+! FIN DE LA BOUCLE VERTICALE
+      enddo
+!=========================================================================
+
+!on recalcule alim_star_tot
+       do ig=1,ngrid
+          alim_star_tot(ig)=0.
+       enddo
+       do ig=1,ngrid
+          do l=1,lalim(ig)-1
+          alim_star_tot(ig)=alim_star_tot(ig)+alim_star(ig,l)
+          enddo
+       enddo
+       
+
+        if (prt_level.ge.20) print*,'coucou calcul detr 470: ig, l', ig, l
+
+#undef wrgrads_thermcell
+#ifdef wrgrads_thermcell
+         call wrgradsfi(1,klev,entr_star(igout,1:klev),'esta      ','esta      ')
+         call wrgradsfi(1,klev,detr_star(igout,1:klev),'dsta      ','dsta      ')
+         call wrgradsfi(1,klev,zbuoy(igout,1:klev),'buoy      ','buoy      ')
+         call wrgradsfi(1,klev,zdqt(igout,1:klev),'dqt      ','dqt      ')
+         call wrgradsfi(1,klev,w_est(igout,1:klev),'w_est     ','w_est     ')
+         call wrgradsfi(1,klev,w_est(igout,2:klev+1),'w_es2     ','w_es2     ')
+         call wrgradsfi(1,klev,zw2(igout,1:klev),'zw2A      ','zw2A      ')
+#endif
+
+
+     return 
+     end
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/tracco2i_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/tracco2i_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/tracco2i_mod.F90	(revision 3605)
@@ -2,4 +2,13 @@
 !
 ! This module does the work for the interactive CO2 tracers
+! Authors: Patricia Cadule and Olivier Boucher
+!
+! Purpose and description:
+!  -----------------------
+! Main routine for the interactive carbon cycle
+! Gather all carbon fluxes and emissions from ORCHIDEE, PISCES and fossil fuel
+! Compute the net flux in source field which is used in phytrac
+! Compute global CO2 mixing ratio for radiation scheme if option is activated
+! Redistribute CO2 evenly over the atmosphere if transport is desactivated
 !
 CONTAINS
@@ -10,11 +19,18 @@
 
     USE dimphy
-    USE infotrac
-    USE geometry_mod, ONLY : cell_area
-    USE carbon_cycle_mod, ONLY : nbcf_in, fields_in, cfname_in, fco2_ocn_day, fco2_ff, fco2_bb
+    USE infotrac_phy
+    USE geometry_mod, ONLY: cell_area
+    USE carbon_cycle_mod, ONLY: carbon_cycle_init
+    USE carbon_cycle_mod, ONLY: id_CO2, nbcf_in, fields_in, cfname_in
+    USE carbon_cycle_mod, ONLY: fco2_ocn_day, fco2_ff, fco2_bb, fco2_land, fco2_ocean
+    USE carbon_cycle_mod, ONLY: fco2_land_nbp, fco2_land_nep, fco2_land_fLuc
+    USE carbon_cycle_mod, ONLY: fco2_land_fwoodharvest, fco2_land_fHarvest
+    USE carbon_cycle_mod, ONLY: carbon_cycle_cpl, carbon_cycle_tr, carbon_cycle_rad, RCO2_glo, RCO2_tot
     USE mod_grid_phy_lmdz
-    USE mod_phys_lmdz_mpi_data, ONLY :  is_mpi_root
+    USE mod_phys_lmdz_mpi_data, ONLY: is_mpi_root
     USE mod_phys_lmdz_para, ONLY: gather, bcast, scatter
     USE phys_cal_mod
+    USE phys_state_var_mod, ONLY: pctsrf
+    USE indice_sol_mod, ONLY: nbsrf, is_ter, is_lic, is_oce, is_sic
 
     IMPLICIT NONE
@@ -45,17 +61,13 @@
 !----------------
 
-    INTEGER, PARAMETER :: id_CO2=1              !--temporaire OB -- to be changed 
     INTEGER                        :: it, k, i, nb
     REAL, DIMENSION(klon,klev)     :: m_air     ! mass of air in every grid box [kg]
-    REAL, DIMENSION(klon)          :: co2land   ! surface land CO2 emissions [kg CO2/m2/s]
-    REAL, DIMENSION(klon)          :: co2ocean  ! surface ocean CO2 emissions [kg CO2/m2/s]
     REAL, DIMENSION(klon_glo,klev) :: co2_glo   ! variable temporaire sur la grille global
     REAL, DIMENSION(klon_glo,klev) :: m_air_glo ! variable temporaire sur la grille global
 
-
-    INTEGER, SAVE :: mth_pre=0
-!$OMP THREADPRIVATE(mth_pre)
-    REAL, SAVE :: RCO2_glo
-!$OMP THREADPRIVATE(RCO2_glo)
+    LOGICAL, SAVE :: check_fCO2_nbp_in_cfname
+!$OMP THREADPRIVATE(check_fCO2_nbp_in_cfname)
+    INTEGER, SAVE :: day_pre=-1
+!$OMP THREADPRIVATE(day_pre)
 
     IF (is_mpi_root) THEN
@@ -67,7 +79,21 @@
 !--convert 280 ppm into kg CO2 / kg air
     IF (debutphy) THEN
+
+! Initialisation de module carbon_cycle_mod
+      IF (carbon_cycle_cpl) THEN
+        CALL carbon_cycle_init()
+      ENDIF
+
+! Initialisation de tr_seri(id_CO2) si pas initialise
       IF (MAXVAL(tr_seri(:,:,id_CO2)).LT.1.e-15) THEN 
-        tr_seri(:,:,id_CO2)=280.e-6/RMD*RMCO2
+        tr_seri(:,:,id_CO2)=co2_ppm0*1.e-6/RMD*RMCO2 !--initialised from co2_ppm0 in rdem
       ENDIF 
+
+!--check if fCO2_nbp is in 
+      check_fCO2_nbp_in_cfname=.FALSE.
+      DO nb=1, nbcf_in
+        IF (cfname_in(nb)=="fCO2_nbp") check_fCO2_nbp_in_cfname=.TRUE.
+      ENDDO
+
     ENDIF
 
@@ -85,32 +111,82 @@
 
 !--retrieving land and ocean CO2 flux
-!--fCO2_nep comes in unit of g CO2 m-2 dt_stomate-1 
-!--this needs to be changed in ORCHIDEE
-    co2land(:)=0.0
-    co2ocean(:)=0.0
+    fco2_land(:)=0.0
+    fco2_ocean(:)=0.0
+    fco2_land_nbp(:)=0.
+    fco2_land_nep(:)=0.
+    fco2_land_fLuc(:)=0.
+    fco2_land_fwoodharvest(:)=0.
+    fco2_land_fHarvest(:)=0.
+
     DO nb=1, nbcf_in
-      IF (cfname_in(nb) == "fCO2_nep" )   co2land(:)=fields_in(:,nb)*RMCO2/RMC/86400./1000.
-      !!IF (cfname_in(nb) == "fCO2_fgco2" ) co2ocean(:)=fco2_ocn_day(:) !--for now
+
+      SELECT CASE(cfname_in(nb))
+!--dealing with the different fluxes coming from ORCHIDEE
+!--fluxes come in unit of kg C m-2 s-1 is converted into kg CO2 m-2 s-1
+      CASE("fCO2_nep")
+          fco2_land_nep(:)=fields_in(:,nb)*RMCO2/RMC*pctsrf(:,is_ter)
+      CASE("fCO2_fLuc")
+          fco2_land_fLuc(:)=fields_in(:,nb)*RMCO2/RMC*pctsrf(:,is_ter)
+      CASE("fCO2_fwoodharvest")
+          fco2_land_fwoodharvest(:)=fields_in(:,nb)*RMCO2/RMC*pctsrf(:,is_ter)
+      CASE("fCO2_fHarvest")
+          fco2_land_fHarvest(:)=fields_in(:,nb)*RMCO2/RMC*pctsrf(:,is_ter)
+      CASE("fCO2_nbp")
+          fco2_land_nbp(:)=fields_in(:,nb)*RMCO2/RMC*pctsrf(:,is_ter)
+!--fCO2_fco2_ocn comes in unit of mol C02 m-2 s-1 is converted into kg CO2 m-2 s-1 + change sign
+      CASE("fCO2_fgco2") 
+          fco2_ocean(:)=-1.*fco2_ocn_day(:)*RMCO2/1.e3*(pctsrf(:,is_oce)+pctsrf(:,is_sic))
+      END SELECT
+
     ENDDO
 
-!--preparing the net anthropogenic flux at the surface for mixing layer 
-!--unit kg CO2 / m2 / s
-    source(:,id_CO2)=fco2_ff(:)+fco2_bb(:)+co2land(:)+co2ocean(:)
+!--if fCO2_nbp is transferred we use it, otherwise we use the sum of what has been passed from ORCHIDEE
+    IF (check_fCO2_nbp_in_cfname)  THEN
+       fco2_land(:)=fco2_land_nbp(:)
+    ELSE
+       fco2_land(:)=fco2_land_nep(:)+fco2_land_fLuc(:)+fco2_land_fwoodharvest(:)+fco2_land_fHarvest(:)
+    ENDIF
+
+!!--preparing the net anthropogenic flux at the surface for mixing layer
+!!--unit kg CO2 / m2 / s
+!    PRINT *, 'tracco2i_mod.F90 --- MAXVAL(fco2_ff) ',MAXVAL(fco2_ff)
+!    PRINT *, 'tracco2i_mod.F90 --- MINVAL(fco2_ff) ',MINVAL(fco2_ff)
+!    PRINT *, 'tracco2i_mod.F90 --- MAXVAL(fco2_bb) ',MAXVAL(fco2_bb)
+!    PRINT *, 'tracco2i_mod.F90 --- MINVAL(fco2_bb) ',MINVAL(fco2_bb)
+!    PRINT *, 'tracco2i_mod.F90 --- MAXVAL(fco2_land) ',MAXVAL(fco2_land)
+!    PRINT *, 'tracco2i_mod.F90 --- MINVAL(fco2_land) ',MINVAL(fco2_land)
+!    PRINT *, 'tracco2i_mod.F90 --- MAXVAL(fco2_ocean) ',MAXVAL(fco2_ocean)
+!    PRINT *, 'tracco2i_mod.F90 --- MINVAL(fco2_ocean) ',MINVAL(fco2_ocean)
+!    PRINT *, 'tracco2i_mod.F90 --- MAXVAL(source(:,id_CO2)) ',MAXVAL(source(:,id_CO2))
+!    PRINT *, 'tracco2i_mod.F90 --- MINVAL(source(:,id_CO2)) ',MINVAL(source(:,id_CO2))
+!
+!--build final source term for CO2
+    source(:,id_CO2)=fco2_ff(:)+fco2_bb(:)+fco2_land(:)+fco2_ocean(:)
 
 !--computing global mean CO2 for radiation
-!--every timestep for now but enough every month
-!    IF (debutphy.OR.mth_cur.NE.mth_pre) THEN
+!--for every timestep comment out the IF ENDIF statements 
+!--otherwise this is updated every day
+    IF (debutphy.OR.day_cur.NE.day_pre) THEN
+
       CALL gather(tr_seri(:,:,id_CO2),co2_glo)
       CALL gather(m_air,m_air_glo)
+
 !$OMP MASTER
-!--conversion from kg CO2/kg air into ppm
+
+!--compute a global mean CO2 value and print its value in ppm
        IF (is_mpi_root) THEN
-         RCO2_glo=SUM(co2_glo*m_air_glo)/SUM(m_air_glo)*1.e6*RMD/RMCO2
+         RCO2_tot=SUM(co2_glo*m_air_glo)  !--unit kg CO2
+         RCO2_glo=RCO2_tot/SUM(m_air_glo) !--unit kg CO2 / kg air
+         PRINT *,'tracco2i: global CO2 in ppm =', RCO2_glo*1.e6*RMD/RMCO2
+         PRINT *,'tracco2i: total CO2 in kg =', RCO2_tot
        ENDIF
-       PRINT *,'toto in tracco2i: global CO2 in ppm =', RCO2_glo
 !$OMP END MASTER
        CALL bcast(RCO2_glo)
-       mth_pre=mth_cur
-!    ENDIF
+       day_pre=day_cur
+!--if not carbon_cycle_tr, then we reinitialize the CO2 each day to its global mean value
+       IF (.NOT.carbon_cycle_tr) THEN 
+         tr_seri(:,:,id_CO2)=RCO2_glo
+       ENDIF
+    ENDIF
 
   END SUBROUTINE tracco2i
@@ -119,5 +195,5 @@
 
     USE dimphy
-    USE infotrac
+    USE infotrac_phy
     USE geometry_mod, ONLY : cell_area
     USE mod_grid_phy_lmdz
@@ -129,5 +205,5 @@
     USE netcdf, ONLY: nf90_get_var, nf90_noerr, nf90_nowrite
 
-    USE carbon_cycle_mod, ONLY : fco2_ff, fco2_bb
+    USE carbon_cycle_mod, ONLY : fco2_ff, fco2_bb, fco2_land, fco2_ocean
 
     IMPLICIT NONE
@@ -150,5 +226,10 @@
 !! may be controlled via the .def later on
 !! also co2bb for now comes from ORCHIDEE
-    LOGICAL, PARAMETER :: readco2ff=.TRUE., readco2bb=.FALSE. 
+    LOGICAL, PARAMETER :: readco2ff=.TRUE.
+!! this should be left to FALSE for now
+    LOGICAL, PARAMETER :: readco2bb=.FALSE. 
+
+    CHARACTER (len = 20) :: modname = 'tracco2i.co2_emissions'
+    CHARACTER (len = 80) :: abort_message
 
     IF (debutphy) THEN 
@@ -173,6 +254,6 @@
         n_glo = size(vector)
         IF (n_glo.NE.klon_glo) THEN
-           PRINT *,'sflx_lmdz_co2_ff: le nombre de points n est pas egal a klon_glo'
-           STOP
+           abort_message='sflx_lmdz_co2_ff: le nombre de points n est pas egal a klon_glo'
+           CALL abort_physic(modname,abort_message,1)
         ENDIF
 
@@ -181,6 +262,6 @@
         n_month = size(time)
         IF (n_month.NE.12) THEN
-           PRINT *,'sflx_lmdz_co2_ff: le nombre de month n est pas egal a 12'
-           STOP
+           abort_message='sflx_lmdz_co2_ff: le nombre de month n est pas egal a 12'
+           CALL abort_physic(modname,abort_message,1)
         ENDIF
 
@@ -196,4 +277,5 @@
 
 !--reading CO2 biomass burning emissions
+!--using it will be inconsistent with treatment in ORCHIDEE
       IF (readco2bb) THEN 
 
@@ -205,6 +287,6 @@
       n_glo = size(vector)
       IF (n_glo.NE.klon_glo) THEN
-         PRINT *,'sflx_lmdz_co2_bb: le nombre de points n est pas egal a klon_glo'
-         STOP
+         abort_message='sflx_lmdz_co2_bb: le nombre de points n est pas egal a klon_glo'
+         CALL abort_physic(modname,abort_message,1)
       ENDIF
 
@@ -213,6 +295,6 @@
       n_month = size(time)
       IF (n_month.NE.12) THEN
-         PRINT *,'sflx_lmdz_co2_bb: le nombre de month n est pas egal a 12'
-         STOP
+         abort_message='sflx_lmdz_co2_bb: le nombre de month n est pas egal a 12'
+         CALL abort_physic(modname,abort_message,1)
       ENDIF
 
@@ -247,6 +329,5 @@
     PRINT *,'probleme avec le mois dans co2_ini =', mth_cur
   ENDIF
-  IF (.NOT.ALLOCATED(fco2_ff)) ALLOCATE(fco2_ff(klon))
-  IF (.NOT.ALLOCATED(fco2_bb)) ALLOCATE(fco2_bb(klon))
+
   fco2_ff(:) = flx_co2ff(:,mth_cur)
   fco2_bb(:) = flx_co2bb(:,mth_cur)
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/traclmdz_mod.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/traclmdz_mod.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/traclmdz_mod.F90	(revision 3605)
@@ -92,5 +92,4 @@
     USE regr_pr_comb_coefoz_m, ONLY: alloc_coefoz
     USE press_coefoz_m, ONLY: press_coefoz
-    USE carbon_cycle_mod, ONLY : carbon_cycle_init, carbon_cycle_tr, carbon_cycle_cpl
     USE mod_grid_phy_lmdz
     USE mod_phys_lmdz_para
@@ -285,10 +284,4 @@
 
 !
-! Initialisation de module carbon_cycle_mod
-! ----------------------------------------------
-    IF (carbon_cycle_tr .OR. carbon_cycle_cpl) THEN
-       CALL carbon_cycle_init(tr_seri, pdtphys, aerosol, radio)
-    END IF
-
 ! Check if all tracers have restart values
 ! ----------------------------------------------
@@ -346,5 +339,4 @@
     USE regr_pr_comb_coefoz_m, ONLY: regr_pr_comb_coefoz
     USE o3_chem_m, ONLY: o3_chem
-    USE carbon_cycle_mod, ONLY : carbon_cycle, carbon_cycle_tr, carbon_cycle_cpl
     USE indice_sol_mod
 
@@ -612,11 +604,4 @@
     END IF
 
-!======================================================================
-!   Calcul de cycle de carbon
-!======================================================================
-    IF (carbon_cycle_tr .OR. carbon_cycle_cpl) THEN
-       CALL carbon_cycle(nstep, pdtphys, pctsrf, tr_seri, source)
-    END IF
-
   END SUBROUTINE traclmdz
 
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/undefSTD.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/undefSTD.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/undefSTD.F90	(revision 3605)
@@ -43,5 +43,4 @@
   ! PARAMETER(klevSTD=17)
   INTEGER itap
-  ! REAL dtime
 
   ! variables locales
@@ -67,8 +66,8 @@
 
 
-    ! calcul variables tous les freq_calNMC(n)/dtime pas de temps
+    ! calcul variables tous les freq_calNMC(n)/phys_tstep pas de temps
     ! de la physique
 
-    IF (mod(itap,nint(freq_calnmc(n)/dtime))==0) THEN
+    IF (mod(itap,nint(freq_calnmc(n)/phys_tstep))==0) THEN
       DO k = 1, nlevstd
         DO i = 1, klon
@@ -103,5 +102,5 @@
       END DO !k
 
-    END IF !MOD(itap,NINT(freq_calNMC(n)/dtime)).EQ.0
+    END IF !MOD(itap,NINT(freq_calNMC(n)/phys_tstep)).EQ.0
 
   END DO !n
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/wake.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/wake.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/wake.F90	(revision 3605)
@@ -196,9 +196,12 @@
   INTEGER                                               :: nsub
   REAL                                                  :: dtimesub
-  REAL                                                  :: wdensmin
+  REAL, SAVE                                            :: wdensmin
+  !$OMP THREADPRIVATE(wdensmin)
   REAL, SAVE                                            :: sigmad, hwmin, wapecut, cstart
   !$OMP THREADPRIVATE(sigmad, hwmin, wapecut, cstart)
-  REAL                                                  :: sigmaw_max
-  REAL                                                  :: dens_rate
+  REAL, SAVE                                            :: sigmaw_max
+  !$OMP THREADPRIVATE(sigmaw_max)  
+  REAL, SAVE                                            :: dens_rate
+  !$OMP THREADPRIVATE(dens_rate)
   REAL                                                  :: wdens0
   ! IM 080208
@@ -1015,4 +1018,7 @@
 
     IF (iflag_wk_pop_dyn >= 1) THEN
+!    The variable "death_rate" is significant only when iflag_wk_pop_dyn = 0.
+!    Here, it has to be set to zero.
+      death_rate(:) = 0.
 
       IF (iflag_wk_act ==2) THEN
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/write_histrac.h
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/write_histrac.h	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/write_histrac.h	(revision 3605)
@@ -8,5 +8,5 @@
      
      CALL histwrite_phy(nid_tra,.FALSE.,"phis",itau_w,pphis)
-     CALL histwrite_phy(nid_tra,.FALSE.,"aire",itau_w,airephy)
+     CALL histwrite_phy(nid_tra,.FALSE.,"aire",itau_w,cell_area)
      CALL histwrite_phy(nid_tra,.FALSE.,"zmasse",itau_w,zmasse)
 ! RomP >>>
Index: /LMDZ6/branches/Ocean_skin/libf/phylmd/yamada4.F90
===================================================================
--- /LMDZ6/branches/Ocean_skin/libf/phylmd/yamada4.F90	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/libf/phylmd/yamada4.F90	(revision 3605)
@@ -152,4 +152,7 @@
   !$OMP THREADPRIVATE(firstcall)
 
+  CHARACTER (len = 20) :: modname = 'yamada4'
+  CHARACTER (len = 80) :: abort_message
+
 
 
@@ -199,5 +202,5 @@
     ENDIF
 
-    PRINT*,'YAMADA4 RIc, RIfc, Sm_min, Alpha_min',ric,rifc,seuilsm,seuilalpha
+    WRITE(lunout,*)'YAMADA4 RIc, RIfc, Sm_min, Alpha_min',ric,rifc,seuilsm,seuilalpha
     firstcall = .FALSE.
     CALL getin_p('lmixmin',lmixmin)
@@ -216,5 +219,6 @@
 
   IF (.NOT. (iflag_pbl>=6 .AND. iflag_pbl<=12)) THEN
-    STOP 'probleme de coherence dans appel a MY'
+    abort_message='probleme de coherence dans appel a MY'
+    CALL abort_physic(modname,abort_message,1)
   END IF
 
@@ -537,5 +541,6 @@
 
   ELSE
-    STOP 'Cas nom prevu dans yamada4'
+     abort_message='Cas nom prevu dans yamada4'
+     CALL abort_physic(modname,abort_message,1)
 
   END IF ! Fin du cas 8
@@ -590,5 +595,5 @@
 
   IF (prt_level>1) THEN
-    PRINT *, 'YAMADA4 0'
+    WRITE(lunout,*) 'YAMADA4 0'
   END IF 
 
@@ -660,5 +665,5 @@
 
   IF (prt_level>1) THEN
-    PRINT *, 'YAMADA4 1'
+    WRITE(lunout,*)'YAMADA4 1'
   END IF !(prt_level>1) THEN
 
@@ -734,6 +739,4 @@
   IMPLICIT NONE
  
-  include "dimensions.h"
-
 !    vdif_q2: subroutine qui calcule la diffusion de la TKE par la TKE
 !             avec un schema implicite en temps avec 
@@ -825,6 +828,4 @@
   IMPLICIT NONE
 
-  include "dimensions.h"
-!
 ! vdif_q2e: subroutine qui calcule la diffusion de TKE par la TKE
 !           avec un schema explicite en temps
Index: /LMDZ6/branches/Ocean_skin/makegcm
===================================================================
--- /LMDZ6/branches/Ocean_skin/makegcm	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/makegcm	(revision 3605)
@@ -40,4 +40,5 @@
 set cosp=false
 set cosp2=false
+set cospv2=false
 set sisvat=false
 
@@ -202,4 +203,5 @@
 set lcosp=""
 set lcosp2=""
+set lcospv2=""
 set opt_dep=""
 set libchimie=""
@@ -447,4 +449,7 @@
            Pour compiler avec cosp2
 
+-cospv2 true|false
+           Pour compiler avec cospv2
+
 -filtre  filtre
            Pour choisir le filtre en longitude dans les regions polaires.
@@ -509,4 +514,6 @@
         set cosp2="$2"; shift ; shift ; goto top
 
+     case -cospv2
+        set cospv2="$2"; shift ; shift ; goto top
      case -sisvat
         set sisvat="$2" ; shift ; shift ; goto top
@@ -598,4 +605,16 @@
 endif
 
+if ( "$cospv2" == 'true' ) then
+    set cppflags="$cppflags -DCPP_COSPV2"
+    set include="$include"' -I$(LIBF)/cospv2 '
+    set opt_dep="$opt_dep cospv2"
+     set lcospv2="-lcospv2 "
+   if ( $XNEC || $X8BRODIE || $X6NEC) then
+     set lcospv2="-lsxcospv2 "
+   endif
+   set opt_link="$lcospv2 $opt_link"
+endif
+
+
 if ( "$sisvat" == 'true' ) then
     set cppflags="$cppflags -DCPP_SISVAT"
@@ -1105,4 +1124,5 @@
 L_COSP="$lcosp" \
 L_COSP2="$lcosp2" \
+L_COSPV2="$lcospv2" \
 L_CHIMIE="$libchimie" \
 LOCAL_DIR="$localdir"  \
@@ -1133,4 +1153,5 @@
 L_COSP="$lcosp" \
 L_COSP2="$lcosp2" \
+L_COSPV2="$lcospv2" \
 L_CHIMIE="$libchimie" \
 LOCAL_DIR="$localdir"  \
Index: /LMDZ6/branches/Ocean_skin/makelmdz
===================================================================
--- /LMDZ6/branches/Ocean_skin/makelmdz	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/makelmdz	(revision 3605)
@@ -26,4 +26,5 @@
 cosp=false
 cosp2=false
+cospv2=false
 sisvat=false
 rrtm=false
@@ -42,7 +43,7 @@
 ## try to recognise machine and infer arch from it
 machine=`hostname`
-if [[ "${machine:0:3}" == "ada" ]]
-then
-  arch="X64_ADA"
+if [[ "${machine:0:4}" == "jean" ]]
+then
+  arch="X64_JEANZAY"
 fi
 if [[ "${machine:0:7}" == "platine" ]]
@@ -112,4 +113,5 @@
 [-v false/orchidee2.0/orchidee1.9/true] : version of the vegetation model to include (default: false)
           false       : no vegetation model
+          orchidee2.1 : compile using ORCHIDEE 2.1 (or more recent version)
           orchidee2.0 : compile using ORCHIDEE 2.0 (or more recent version)
           orchidee1.9 : compile using ORCHIDEE up to the version including OpenMP in ORCHIDEE : tag 1.9-1.9.5(version AR5)-1.9.6
@@ -118,4 +120,5 @@
 [-cosp true/false]    : compile with/without cosp package (default: false)
 [-cosp2 true/false]    : compile with/without cosp2 package (default: false)
+[-cospv2 true/false]    : compile with/without cospv2 package (default: false)
 [-sisvat true/false]  : compile with/without sisvat package (default: false)
 [-rrtm true/false]    : compile with/without rrtm package (default: false)
@@ -183,4 +186,7 @@
       "-cosp2")
           cosp2="$2" ; shift ; shift ;;
+
+      "-cosp2")
+          cospv2="$2" ; shift ; shift ;;
       
       "-sisvat")
@@ -432,5 +438,5 @@
 
 #==============================================================================
-if [ "$veget" = "true" -o "$veget" = "orchidee1.9" -o "$veget" = "orchidee2.0" ]
+if [ "$veget" = "true" -o "$veget" = "orchidee1.9" -o "$veget" = "orchidee2.0" -o "$veget" = "orchidee2.1" ]
 then
 
@@ -442,4 +448,7 @@
    fi
    if [[ "$veget" == "orchidee2.0" ]] ; then
+      orch_libs="sechiba parameters stomate parallel orglob orchidee"
+      CPP_KEY="$CPP_KEY ORCHIDEE_NOUNSTRUCT"
+   elif [[ "$veget" == "orchidee2.1" ]] ; then
       orch_libs="sechiba parameters stomate parallel orglob orchidee"
    else
@@ -494,4 +503,11 @@
    src_dirs="$src_dirs phy${physique}/cosp2"
    INCLUDE="$INCLUDE"' -I$(LIBF)/'phy${physique}'/cosp2'
+fi
+
+if [[ "$cospv2" == "true" ]]
+then
+   CPP_KEY="$CPP_KEY CPP_COSPV2"
+   src_dirs="$src_dirs phy${physique}/cospv2"
+   INCLUDE="$INCLUDE"' -I$(LIBF)/'phy${physique}'/cospv2'
 fi
 
@@ -772,4 +788,5 @@
 L_COSP="$lcosp" \
 L_COSP2="$lcosp2" \
+L_COSPV2="$lcospv2" \
 L_CHIMIE="$libchimie" \
 LOCAL_DIR="$localdir"  \
@@ -806,4 +823,5 @@
 L_COSP="$lcosp" \
 L_COSP2="$lcosp2" \
+L_COSPV2="$lcospv2" \
 L_CHIMIE="$libchimie" \
 LOCAL_DIR="$localdir"  \
Index: /LMDZ6/branches/Ocean_skin/makelmdz_fcm
===================================================================
--- /LMDZ6/branches/Ocean_skin/makelmdz_fcm	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/makelmdz_fcm	(revision 3605)
@@ -35,4 +35,5 @@
 cosp=false
 cosp2=false
+cospv2=false
 job=1
 full=''
@@ -44,5 +45,5 @@
 
 LMDGCM=`/bin/pwd`
-LIBOGCM=$LMDGCM/libo
+LIBOGCM=$WORK/build/LMDZ_ocean_skin
 LIBFGCM=$LMDGCM/libf
 DYN_COMMON_PATH=$LIBFGCM/dyn3d_common
@@ -57,5 +58,4 @@
 SISVAT_PATH=$LMDGCM/.void_dir
 COSP_PATH=$LMDGCM/.void_dir
-COSP2_PATH=$LMDGCM/.void_dir
 fcm_path=$LMDGCM/tools/fcm/bin
 
@@ -90,5 +90,6 @@
 [-v false/orchidee2.0/orchidee1.9/true] : version of the vegetation model to include (default: false)
           false       : no vegetation model
-          orchidee2.0 : compile using ORCHIDEE 2.0 (or more recent version)
+          orchidee2.1 : compile using ORCHIDEE 2.1 (or more recent version)
+          orchidee2.0 : compile using ORCHIDEE 2.0
           orchidee1.9 : compile using ORCHIDEE up to the version including OpenMP in ORCHIDEE : tag 1.9-1.9.5(version AR5)-1.9.6
           true        : (obsolete; for backward compatibility) use ORCHIDEE tag 1.9-1.9.6
@@ -96,4 +97,5 @@
 [-cosp true/false]    : compile with/without cosp package (default: false)
 [-cosp2 true/false]    : compile with/without cosp2 package (default: false)
+[-cospv2 true/false]    : compile with/without cospv2 package (default: false)
 [-sisvat true/false]  : compile with/without sisvat package (default: false)
 [-rrtm true/false]    : compile with/without rrtm package (default: false)
@@ -181,4 +183,7 @@
       "-cosp2")
           cosp2="$2" ; shift ; shift ;;
+
+      "-cospv2")
+          cospv2="$2" ; shift ; shift ;;
       
       "-mem")
@@ -373,5 +378,5 @@
 fi
 
-if [ "$veget" = "true" -o "$veget" = "orchidee1.9" -o "$veget" = "orchidee2.0" ]
+if [ "$veget" = "true" -o "$veget" = "orchidee1.9" -o "$veget" = "orchidee2.0" -o "$veget" = "orchidee2.1" ]
 then
 #NB: option 'true': for backward compatibility. To be used with ORCHIDEE tag 1.9-1.9.6
@@ -385,4 +390,7 @@
    fi
    if [[ "$veget" == "orchidee2.0" ]] ; then
+      orch_libs="sechiba parameters stomate parallel orglob orchidee"
+      CPP_KEY="$CPP_KEY ORCHIDEE_NOUNSTRUCT"
+   elif [[ "$veget" == "orchidee2.1" ]] ; then
       orch_libs="sechiba parameters stomate parallel orglob orchidee"
    else
@@ -457,4 +465,12 @@
 #   LIB="${LIB} -l${LIBPREFIX}cosp2"
 fi
+
+if [[ "$cospv2" == "true" ]]
+then
+   CPP_KEY="$CPP_KEY CPP_COSPV2"
+   COSP_PATH="$LIBFGCM/phylmd/cospv2"
+#   LIB="${LIB} -l${LIBPREFIX}cosp2"
+fi
+
 
 
@@ -666,5 +682,4 @@
 echo "%SISVAT        $SISVAT_PATH"   >> $config_fcm
 echo "%COSP          $COSP_PATH"     >> $config_fcm
-echo "%COSP2          $COSP2_PATH"     >> $config_fcm
 echo "%CPP_KEY       $CPP_KEY"       >> $config_fcm
 echo "%EXEC          $code"          >> $config_fcm
Index: /LMDZ6/branches/Ocean_skin/tools/fcm/lib/Fcm/CfgFile.pm
===================================================================
--- /LMDZ6/branches/Ocean_skin/tools/fcm/lib/Fcm/CfgFile.pm	(revision 3604)
+++ /LMDZ6/branches/Ocean_skin/tools/fcm/lib/Fcm/CfgFile.pm	(revision 3605)
@@ -19,4 +19,5 @@
 # Standard pragma
 use warnings;
+no warnings 'uninitialized';
 use strict;
 
