Index: unk/LMDZ.GENERIC/RADTRANGUIDE
===================================================================
--- /trunk/LMDZ.GENERIC/RADTRANGUIDE	(revision 252)
+++ 	(revision )
@@ -1,25 +1,0 @@
-# The purpose of this readme file is to give a guide to creating your
-  own radiative transfer coefficients for the universal code. It is
-  not designed as a substitute for the kspectrum or LMDZ GCM manuals,
-  which can be found elsewhere.
-
-
-1. Creating the high resolution spectral data
-
-   To do this we use 'kspectrum', which was written by Vincent Eymet
-   and is freely available online at: ''. See the manual on the
-   website for a guide to installation. Once the code is installed,
-
-   decide p, T arrays
-
-2. Converting to correlated-k coefficients
-
-   There are two ways to do this: with Vincent Eymet's code
-   'kdistribution', or with a simpler code written by Robin Wordsworth
-   called 'generate_kmatrix'. The latter code is less sophisticated
-   and probably a little less accurate, but it has an advantage in
-   that it works.
-
-3. Running the GCM with the new data
-
-   planck limits
Index: /trunk/LMDZ.GENERIC/README
===================================================================
--- /trunk/LMDZ.GENERIC/README	(revision 252)
+++ /trunk/LMDZ.GENERIC/README	(revision 253)
@@ -400,5 +400,5 @@
 
 == 31/03/2010 ==
-==> call this version LMDZ.GENERIC.v0.5 
+==> call this version LMDZ.GENERIC.v0.5
 -- OLR --
    The .nc functions were implemented and tested. It was necessary to add
@@ -441,2 +441,89 @@
    major change, but there are enough cases where it will be useful to
    make it worthwhile in the universal code. I have done the same with rcp.
+
+== 10/10/2010 ==
+==> call this version LMDZ.GENERIC.v0.6
+-- startup --
+   We now check water tracers exist in newstart.F before all watery initialisation options.
+   Added an option 'autozlevs' to run.def (and logic.h). When true this recalculates the scale
+   height in z2sig.def in order to get the same minimum pressure for any resolution.
+   Currently, this is only useful for one-d simulations.
+   Pressure is now distributed better in newstart.F. There was a bug before when the global mean of phi
+   was not equal to zero and the surface pressure was changed with topography still present.
+   In initracer, we no longer automatically set h2o_vap=h2o_ice.   
+
+-- general --
+   periheli, apheli --> periastr, apoastr. Note this necessitates a change in start_planet too.
+   testphys1d.F --> rcm1d.F
+   physiq.F, callcorrk.F upgraded to Fortran 90 to remove evil zerophys.
+   I cleaned up the method of displaying energy balance and temperature range in the model a bit.
+   Pure H2 atmospheres are now permitted, although the code is _untested_. Rayleigh scattering,
+   specific heat capacities and molar masses are varied, and the H2-H2 collision-induced data 
+   of Grushka et al. is used for the radiative transfer.
+
+-- boundary layer --
+   An improved version of vdifc.F has been created that includes the latent heat effect of water vapor,
+   following the method used in 'clmain' in the LMDZ terrestrial model.
+
+-- water cycle --
+   Benjamin's improvements have been added, namely the hydrology, and reevaporation.
+   Variable cloud fractions are allowed, or a global fixed value may be chosen
+   for use in aeropacity. Surface wetness (beta) is now calculated in a simple way, and
+   outputed as a diagnostic, along with the atmospheric relative humidity.
+  
+   mol/mol to kg/kg bug in callcorrk corrected.
+
+-- radiative transfer --
+   A major bug in gfluxv.F was corrected. It involved BSURF, the radiation reflected upwards from 
+   the ground.
+   In aeropacity, we now set the cloud opacity in the top layer of the atmosphere to zero. This solves
+   an instability problem that was occurring when CO2 clouds formed.
+   Dust is back! Only fixed profiles allowed for now. It is assigned "naerkind=3" in aeropacity.F90.
+   If 'CLFvarying' is enabled, the corrk subroutine is now called twice per timestep - once for clear
+   skies and once for cloudy. This slows things down but is effective for Earth-like simulations.
+   An optional Newtonian cooling scheme has been implemented that can replace the correlated-k method
+   for dynamical tests etc. It is pretty experimental and has not been extensively tested.
+
+-- Dynamics --
+   callgroupeun in gcm.F has been set to FALSE, as it does not conserve tracers.
+   The coefficient facup has been set to 1 in inidissip.F. We may need to mess
+   with this later if it makes the model too unstable.
+
+== 1/08/2011 ==
+==> call this version LMDZ.GENERIC.v0.7
+
+   Main change: a new file 'gases.def' now required at startup. This tells us which gases are in
+   the planet's atmosphere. It is used to calculate fundamental quantities like cpp and mugaz.
+   A check is made against the radiative transfer data to make sure they correspond.
+
+   Code has been tested successfully using the 'gfortran compiler'.
+
+-- startup --
+   a bug involving tsoil interpolation in lect_start_archive.F was corrected.   
+
+-- aerosols --
+   gauss integration number 5-->10 in aeroptproperties.F90
+
+-- water cycle --
+   Big fat bug in rain.F90 corrected. The routine internally updated the temperature 
+   with new tendencies before it was supposed to happen!
+   Bug in oborealis where phi not properly updated was corrected.
+   Improvements to hydrol.F90: zdtsurf_hyd --> pdtsurf_hyd
+   A 'sourceevol' option was added (accessed in callphys.def) that allows us to track the
+   evolution of the surface distribution over time.
+   Another bug in rain corrected involving evaporation - it was heating the atmosphere
+   rather than cooling it...
+
+-- convection --
+   I found a bug in convadj.F that breaks tracer conservation when convection stops at one layer 
+   and immediately restarts in the next one.
+
+-- diagnostics --
+   Some bugs corrected in the computation of 3D averages for the H2O / energy conservation 
+   diagnostics.
+
+-- radiative transfer --
+   A bug involving continuum opacities (variable DCONT) was corrected in optci.F90 and optcv.F0.
+   H2-H2 warming now in theory reliable and correct (60-1000 K).
+   A bug involving the definition of the Planck function boundaries was corrected in sfluxi.F90
+   and gfluxi.F.
Index: unk/LMDZ.GENERIC/README~
===================================================================
--- /trunk/LMDZ.GENERIC/README~	(revision 252)
+++ 	(revision )
@@ -1,442 +1,0 @@
-== 17/09/08 ==
->>> Build a version with new soil but old radiative transfer,
-    but keeping possibility of switching back to new radiative transfer),
-    which incorporates changes & improvements currently included in the
-    'reference version' GCM (see /u/emlmd/LMDZ.MARS.mixdyn)
-
->>> start by modifying makegcm as in /u/emlmd/LMDZ.MARS.mixdyn, so that it runs
-    without environment variables and set LIBOGCM to /tmp15/emlmd/libo
-
->>> directory contents of 'aeronomars', 'grid' and 'filtrez' are simillar
-    to those in /u/emlmd/LMDZ.MARS.mixdyn
-
->>> in bibio , only file mxva.F needed be upgraded
-
->>> get phymars and dyn3d contents from /u/emlmd/LMDZ.MARS.mixdyn
-    (and remove all *old files)
-
->>> check differences between dyn3d and /u/emlmd/LMDZ.MARS.170908/libf/dyn3d
-    and upgrade when necessary:
-    - removed 'netcdf.inc' file (has nothing to do there!)
-    - comgeom.h and comgeom.h : made fortran90 compliant
-    - control.h : made fortran90 compliant
-    - dynredem.F : more read/write controls + comments in english
-    - ini_archive.F : new soil/thermal inertia changes
-    - integrd.F : added additional information to output when crashing
-    - lect_start_archive.F : new soil/thermal inertia changes
-    - newstart.F : new soil/thermal inertia changes + comments in english
-    - start2archive.F : new soil/thermal inertia changes
-    - vanleer.F : removed inapropriate 'external' statement
-    - write_archive.F : enable writting a subterranean field
-
->>> check differences between phymars and /u/emlmd/LMDZ.MARS.170908/libf/phymars
-    and upgrade when necessary:
-    New soil stuff:
-    - added comsoil.h
-    - iniwrite.F : new soil changes
-    - added iniwritesoil.F90 and writediagsoil.F90 for subterranean fields
-    - added interp_line.F (for subterranean grid interpolation)
-    - adapted phyetat0.F for subterranean temperature & inertia
-    - adapted physdem1.F to include new soil stuff
-    - physiq.F : added calls to writediagsoil 
-    - soil.F : new routine (fixed vertical grid + variable thermal inertia)
-    - added soil_settings.F (to read/initialize/interpolate soil properties)
-    - updated surfdat.h (since thermal inertia is now in comsoil.h)
-    - updated tabfi.F : include new soil properties
-    - updated testphys1d.F
-    - updated dimphys.h (set nsoil=18 as default)
-
-== 18/09/08 ==
->>> add the possibility of easily switching to Tran radiative transfert
-    - updated aerdust.h.ocke97 (changed some variables name) so it can
-      replace aerdust.h (which is currently the same as aerdust.h.clan91).
-    - imported Tran's 'gfluxv.F' routine
-    - imported Trans' version of 'swr.F' routine, saved it as 'swr.F.toon'
-
->>> Backup of 'old' Morcrette swr.F is 'swr.F.morc'
-    NB: to switch from one radiative transfer to the other, just copy
-    swr.F.morc or swr.F.toon to swr.F (and eventually 'touch swr.F' so that
-    makegcm recompiles swr.F)
-    No other dependencies (swr.F.toon uses 'gfluxv.F' and swr.F.morc uses
-    'dedd.F').
-
->>> Changed the latter, so that users can switch from one to the other
-    - modified swr.F.toon to become swr_toon.F (and to include gfluxv.F)
-    - modified swr.F.morc to become swr_fouquart.F (and to include dedd.F)
-    - added a flag in callkeys.h, swrtype (parameter to be set/changed by
-      the user 1=Fouquart and 2=Toon)
-    - update readtesassim so that the coefficient by which opacity
-      is multiplied is set according to the 'swrtype' parameter
-
-== 25/09/08 ==
->>> Implement the use of tracer-by-name in physics
-    - in phymars/tracer.h set 'noms' length to 20 (instead of 10)
-    - in phymars/callsedim2q.F and phymars/callsedim.F, use tracers by name
-    - in phymars/dustopacity.F, use tracers by name
-    - in phymars/vdifc.F, use tracers by name
-
-== 26/09/08 ==
->>> Change implementation strategy (for now); don't move surface tracer around
-    i.e.: surface ice remains equivalent to qsurf(nqmx)=qsurf(i_h2o_vap)
-          and likewise for surface tendencies ...
-    - modified vdifc.F and callsedim.F back
-    - modified initracer.F (so that water names are h2o_vap & h2o_ice)
-    
-== 29/09/08 ==
-    - modified aeronomars/init_chimie_B (cosmetics)
-    - corrected aeronomars/moldiff.F internal routine tridag; changed
-      "pause" error messages to 'stop' messages
-    - modified phymars/watercloud.F to use tracers by name
-    - corrected aeronomars/molvis.F (undefined 'fac' and 'Akk' written to 
-       output at first call)
-    
-== 30/09/08 ==
-    - modified aeronomars/calchim.F to use tracers by name
-    - adapted aeronomars/photochemist_B.F to use tracers by name
-    - adapted aeronomars/chemtermos.F to use tracers by name
-    - adapted aeronomars/concentrations.F to use tracers by name
-    - corrected aeronomars/conduction.F (undefined 'Akk' written to output
-      at first call)
-    - adapted aeronomars/euvheat.F to use tracers by name
-    - adapted aeronomars/moldiff.F and moldiffcoeff.F to use tracers by name
-
-== 01/10/08 ==
-    - For more compatibility with LMDZ4; mimic reading a 'traceur.def' file
-      in the dynamics via a call to a routine 'iniadvtrac.F' and saving
-      tracers names in 'advtrac.h'
-     -> created 'iniadvtrac.F', 'advtrac.h' and modified gcm.F
-    - modified 'dynetat0.F' so that tracers are loaded from 'start.nc' by name
-    - modified 'dynredem.F' so that tracers are written to 'restart.nc'
-      by name
-    - modified 'initracer.F' tu use tracers by name
-
-== 02/10/08 ==
-    - removed use of 'nqchem_min' everywhere:
-      adapted 'euvheat.F','inifis.F','physiq.F'
-      (leave 'inichim.F' for later)
-    - updated 'phyetat0' and 'physdem1.F' to read/write surface tracers by name
-    - modify things so that surface water ice index is the same as
-      atmospheric water ice (except when running without water ice; then
-      simply set i_h2o_ice=i_h2o_vap).
-      NB: the easiest is to have global storage of tracer names/indexes in
-      tracer.h
-      => changed initracer.F & tracer.h to have global igcm_something indexes
-
-== 03/10/08 ==
-    - adaptations for surface ice index, modified files:
-      phyetat0.F : if there is a dynamical tracer 'h2o_vap' then load
-                   surface tracer called 'h2o_ice' instead
-      initracer.F : in 'old' tracer name case: move qsurf(nqmx)->qsurf(nqmx-1)
-                    and set i_h2o_ice=i_h2o_vap if iceparty=.false.
-      physdem1.F : if old tracer names: move qsurf(nqmx-1)->qsurf(nqmx)
-                   if iceparty=.false., write surface tracer 'h2o_ice'
-                   (and not 'h2o_vap') to file.
-      adapted vdifc.F, callsedim.F & watercloud.F & physiq.F so that surface
-      ice is now identified as qsurf(i_h2o_ice)
-    - updated aeronomars/perosat.F (cosmetics)
-
-== 06/10/08 ==
-    - modify newstart.F and lect_start_archive.F to use tracers by name
-== 07/10/08 ==
-    - adapted inichim_newstart.F (added qsurf to arguments)
-      and inichim_readcallphys.F
-== 08/10/08 ==
-    - implement reading traceur.def in dyn3d/iniadvtrac.F
-
-== 16/10/08==
-    -small change in inifis.F (only warn if too many tracers, compared
-     to the expected number, not stop).
-     - corrected bug in initracer.F
-== 21/10/08 ==
-    - modified newstart.F to load B.Diez subsurface ice maps.
-    - corrected small bug (uninitialized variable) in interp_horiz.F
-== 22/10/08 ==
-    - updated iniwritediagsoil.F so that thermal inertia is written to
-      diagsoil.nc
-== 31/10/08 ==
-    - changed xvik.F program so it works even if we don't have atmospheric
-     temperature at hand (then it uses a 10km reference scale height) and so
-     that it does surface pressure interpolation log-wise.
-== 03/11/08 ==
-    - modified physiq to compute (and output) co2 column.
-    - added improvement by Francois in newcondens.F about computing CO2
-      partial pressure. This behavior is turned on by setting internal logical
-      flag 'improved_ztcond' to '.true.' (and running with a co2 tracer)
-    - updated 'start2archive' to work with 'new' gcm output (soil, tracers ...)
-== 04/11/08 ==
-    - upgraded xvik program to look for temperature in 7th layer variable if
-     there is no global atmospheric temperature field at hand.
-== 05/11/08 ==
-    - more modifs to newcondens.F: added another internal flag 'bound_qco2' to
-     enforce (if set to .true.) that co2 mass mixing ratio remains bounded.
-== 07/11/08 ==
-    - corrected 'writediagfi' & 'writediagsoil' so that an error message is 
-      issued if called with a variable name which is too long.
-== 18/12/08 ==
-    - corrected bug in dyn3d 'addfi.F', (dimensions of local array p())
-== 23/02/09 ==
-    - modified "aeronomars/param_read.F" to do strictly fortran data
-     initialization (otherwise xlf compiler complains)
-    - changed a few '1.e-30' to '1.d-30' in aeronomars/photochemist_B.F
-     so that max functions has 2 doubles as arguments (otherwise xlf
-     compiler complains)
-
-==07/04/09 ==
-    -cosmetic changes/minor improvements in the handling of tracers in:
-     aeronomars/photochemist_B.F
-     aeronomars/perosat.F
-     aeronomoars/euvheat.F
-     aeronomars/moldiffcoeff.F
-     aeronomars/moldiff.F
-     aeronomars/cocentrations.F
-     aeronomars/chemtermos.F
-     aeronomars/calchim.F
-
---> NB: still there are differences in outputs when order of tracers is changed
-
-== 09/04/09 ==
->>> fixed problem in 'vdifc.F' which lead to different results when moving
-    tracers around.
-
-== 10/04/09 ==
->>> corrected small bug in diagnostic outputs of 'watercloud.F' (tendencies were
-    not added to tracer values).
-
-== 21/04/09 ==
->>> corrected small bug in "physdem1.F" about writing water ice surface tracer
-    to file
-
-== 07/05/09 ==
->>> very minor correction (firstcall not set to true after first call
-    if no tracers) in convadj.F
-
-== 30/06/09 ==
->>> Implement reading *def files with IOIPSL ersatz 'getin' function
-   - import "ioipsl_errioipsl.F90","ioipsl_getincom.F90","ioipsl_stringop.F90"
-     in bibio
-   - adapted 'dyn3d/defrun_new.F' to use "getin" function
-   - adapted 'phymars/inifis.F' to use "getin" function
-
-== 01/07/09 ==
->>> Adapted 'create_make_gcm' so that the "use" in *.F files is identified and
-    corresponding dependencies included in the makefile rules.
-
->>> Added the 3D scattering from aerosols by JB Madeleine:
-    - minor changes in aerave.F
-    - added the calls to aeropacity.F, and aeroptproperties.F in callradite.F
-    - changed the calls to lwu.F and swr.F in lwmain.F and swmain.F, respectively
-    - added 3D scattering properties in lwu.F and swr.F
-    - added the new aeroptproperties.F, aeropacity.F and suaer.F90 routines
-        (removed dustopacity.F)
-    - updated aeropacity.F with new tracer names
-    - changed the call to callradite.F in physiq.F, added the initialization 
-        of reffrad and nueffrad (aerosol effective radius and variance)
-    - removed all the lines relative to the old "activice" option, including
-        temperature variation due to latent heat release (now in comments)
-    - renamed nsize into naersize in watercloud.F, watersat.F and newsedim.F,
-        to avoid conflicts with another "nsize" variable in the radiative transfer
-    - added the statement of nuice in watercloud.F, which is the effective variance
-        of the log-normal distribution for ice
-    - updated yomaer.h and removed aerice.h (and corresponding "includes")
-
-== 02/07/09 ==
->>> Adapted 'aeronomars/inichim_readcallphys.F' (called by newstart)
-     to use "getin" routine.
-    + minor correction in 'inifis.F' (close 'iradia.def' file)
->>> Minor correction in 'dyn3d/dynetat0.F' and 'phymars/phyetat0.F'; do not
-    attempt to reindex tracers if none were found.
-
->>> in 'deftank' added examples of 'traceur.def' files (traceur.def.co2 : 1
-    co2 tracer; traceur.def.watercycle : 2 traceurs, water vapour and water ice
-    tracer.def.chemistry : all 15 species)
-
-== 06/07/09 ==
->>> Modified 'makegcm' and makegcm_g95' so that modules files are put 
-    with libraries (and not in current directory)
-    
-    
-    
-    
-== 01/08/09 ==
->>> Old Martian radiative transfer removed completely, new correlated-k
-    scheme implemented in its place. Central function is callcorrk.F.
-    Radiative properties are no longer stored in dimradmars.h, but in the two
-    files radinc_h.F90 and radcommon_h.F90. 3D aerosol scheme
-    incorporated into callcorrk.F. dustopacity.F renamed aeropacity.F
-    and substantially simplified. For now the option to include dust
-    as an aerosol has been removed.
-
->>> newcondense.F replaced by condense_co2cloud.F90. This is basically
-    Francois' routine from the old model, adapted to work with the new
-    generalised tracer scheme.
-
->>> Options added in physiq.F and tabfi.F to allow for planets with
-    varying orbital parameters, radii, gravity etc. For the moment we
-    select the planet using the variable 'planettype' in
-    callphys.def. This could probably be improved in the future.
-
->>> Many new options added to callphys.def.
-
-    
-    
-    
-    
-== 25/11/2009 ==
->>>> List of changes and modifications
-- modified watercloud.F: added sanity check (i.e. do we have a water tracer?)
-- modified dyn3d/dynetat0.F --> removed possibility of reindexing tracers
-- modified phyetat0.F --> removed possibility of reindexing tracers
-
--- removed using a "co2ice" array to store surface CO2 ice
-  -> adapted surfini.F & physiq.F to use qsurf(:,igcm_co2_ice)
-     instead of co2ice(:)
-  -> modified initracer.F & tracer.h to properly initialize (and store)
-     a "co2_ice" tracer.
-  -> removed 'co2ice' from vdifc.F (it was not used there anyway)
-     and from phsdem1.F
-  -> removed possibility of calling 'newcondens' from physiq.F
-  -> cleaned up newstart.F, lect_start_archive.F, start2archive.F to not use
-  "co2ice" field but qsurf(igcm_co2_ice)
-
--- adapted 'create_make_gcm' and 'makegcm' scripts so that we don't need
-   to have and (unused) 'aeronomars' directory around.
- 
--- shifted to reading traceur.def (dyn3d/iniadvtrac.F) in an Earth-LMDZ4-like
-   fashion:
-   first line == number of tracers
-   and then tracer name (1 per line; later we'll also add advection scheme type)
--- NOTE BY RW: Here would be a good place to also note which tracer (if any) is
-   the 'variable gas' in the radiative transfer
-
--- Made some changes in tabfi.F to let user change planet parameters
-   such as rotation rate, molar mass of atmosphere, ...
-   (NB: note however that we seem to lose dynamics/physics coherence ...
-    we should probably read these values from a planet.def file) 
-
--- Changed condens_co2cloud.F : added a check for presence of CO2 gas and output
-   of corresponding tendency.
-
-
-== 15/12/2009 ==
->>> Correlated-k radiative transfer now reads spectral bands and p-T
-    matrix values from ascii files; the code checks that the number of
-    bands and matrix elements in the files match those written in
-    radinc.F90 on the first call.
-
->>> Water vapour tracer coupled to variable gas species in radiative
-    transfer; option also given to run with fixed relative humidity
-    profiles. 'Variable gas species' option added to callphys.def.
-
->>> Surface albedo updated to be one band everywhere.
-
->>> suaer_corrk.F90 modified to use different ep, omeg, g variables in
-    the visible and infrared. This is necessary because the number of
-    bands is, in general, different.
-
->>> suaer_corrk.F90 has an option to accept Francois' new CO2 ice
-    values (and convert wvl to metres!!).
-
->>> optci.F --> optci.F90 so that water vapour continuum subroutine
-    can be included.
-
-== 08/01/10 ==
->>> Option to change pref for hybrid coordinates added to newstart.F.
-
-
-== 15/01/2010 ==
->>> Upgraded newstart.F: added possibility to reset refrence surface pressure
-   "preff" (and pa)
->>> tabfi.F: added possibility of changing value of "year_day"
->>> cosmetic change in callphys.def : separate "universal" parameters
-    and planet-specific parameters (in a separate file, e.g. earlymars.def)
-    
-== 22/01/2010 ==
-==> call this version LMDZ.GENERIC
->>> Some cleanup & upgrades:
--- split parameters in callphys.def into generic stuff (stays in callphys.def)
-   and another more specific file (e.g. earlymars.def).
--- added 'output_olr' key (in callkeys.h; read in physiq.F) to trigger
-   output of fluxes in ascii file 'olr.txt'
--- removed (non-generic) 'kastprof' and 'nearcond' keys/options in physiq.F
-  (also removed file kastprof_fn.F)
--- had to set 'fixh2ovap  =.false. in callcorrk.F to avoid
-   "out of range subscript" pb in callcorrk.F
-   ==> this should be improved / better controlled in the future
--- updated newsedim.F to use "molrad, visc, avogado values from comcstfi.h
-   (and not local versions of these constants)
--- fixed buggy -O option in makegcm (and makegcm_g95);
-
-== 22/02/2010 ==
-==> call this version LMDZ.GENERIC.v0.31
--- rain.F, manabe.F and largescale.F subroutines added to water cycle
--- several new toggles added to earlymars.def
-
-== 28/03/2010 ==
-==> call this version LMDZ.GENERIC.v0.4
--- many changes for this version!
--- radiative transfer --
-   A new system was implemented that automatically reads the p, T, g,
-   Q and band values from files. The dataset required is now specified
-   in callphys.def. We still need to edit radinc_h when the corrk array
-   sizes change - think about improving this in the future.
--- water cycle --
-   A watercommon_h mod file was created, several files were renamed
-   and moist convection and precipitation subroutines were added.
-   Still needs some testing!
--- OLR --
-   Two new functions were added: one to produce .nc files of the OLR
-   by band, and the other to save the upgoing radiation by band in 1D
-   as a .txt file. 
--- general structure --
-   tabfi.F, newstart.F etc. cleaned up + it was checked that they pass
-   variables correctly. Several new options added to run.def for 1D,
-   in order to allow truly arbitrary planet simulations. The
-   'planettype' option has been removed as it screwed things up completely.
--- energy conservation --
-   I found that the planckir function in the radiative transfer did not
-   always produce values that summed to sigma T^4. A new test was implemented
-   to check for this problem and the standard band widths in the IR
-   were increased.
-
-== 31/03/2010 ==
-==> call this version LMDZ.GENERIC.v0.5 (in progress...)
--- OLR --
-   The .nc functions were implemented and tested. It was necessary to add
-   new functions 'writediagspec.F' and 'iniwrite_spec.F'.
--- CO2 condensation --
-   In 1D we now exit automatically if CO2 is condensing on the
-   surface.
--- G1D --
-   We can now choose at the beginning of physiq.F, using saveG1D, how
-   many times we want to save per day in 1D (rather than every single
-   time that physiq is called).
--- water cycle --
-   I corrected a nasty bug in callcorrk involving varfixed, real*8 and
-   epsi. I corrected a simple bug in the writing of qsurf in g1d.dat.
-   rain.F has been tested and the algorithm for precipitation evaporation
-   modified to that written in the manual of Larent Li. Cloud fraction
-   variable is now included. activice and iceparty are gone, ~replaced
-   by watercond and waterrain.
--- orbit --
-   nres and tlocked were added as basic options to callphys.def
--- radiative transfer --
-   I added error checking for out-of-bounds temperature in
-   callcorrk.F. I added a new file calc_rayleigh.F90 to calculate
-   Rayleigh scattering using a weighted mean, as opposed to simply the
-   midpoint band values. Band discretisation is now even more
-   automated than before: the coefficients are stored in directories
-   like /earth/32x36/, and we can compile the GCM like this:
-   makegcm -d 32x24x20 -b 32x36 -p std gcm.
-   A bug was fixed involving emissivity not being properly passed from
-   newstart.e to the main part of the code.
-   Stellar spectra are now calculated automatically for any range of
-   bands from high resolution data (originally from the VPL website).
--- vertical discretisation --
-   I corrected a bug in testphys1d that used a fixed value of
-   temperature to compute the altitude levels in the model. Now we use
-   the scale height from z2sig.def instead. Values of preff and pa are
-   no longer defined in testphys1d (they're not needed).
--- Non-ideal gases --
-   I have replaced cpp in many places with cpp_3D in physiq. This is a
-   major change, but there are enough cases where it will be useful to
-   make it worthwhile in the universal code. I have done the same with rcp.
Index: /trunk/LMDZ.GENERIC/deftank/autocontinue
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/autocontinue	(revision 253)
+++ /trunk/LMDZ.GENERIC/deftank/autocontinue	(revision 253)
@@ -0,0 +1,16 @@
+# @ job_name=gcm_3D
+# @ output = $(job_name).$(jobid)
+# @ error = $(output)
+# @ job_type = serial
+# @ class = D
+# @ queue
+
+#grep "^# @" $0
+#set -vx
+#
+
+echo "Running for multiple years to reach equilibrium."
+cp -f run_normal.def run.def
+
+run0
+
Index: /trunk/LMDZ.GENERIC/deftank/autospinup
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/autospinup	(revision 252)
+++ /trunk/LMDZ.GENERIC/deftank/autospinup	(revision 253)
@@ -1,36 +1,23 @@
-#!/bin/bash
+# @ job_name=gcm_3D
+# @ output = $(job_name).$(jobid)
+# @ error = $(output)
+# @ job_type = serial
+# @ class = D
+# @ queue
 
-#DEF_DIR=/san/home/rdword/gcm/spinups
-DEF_DIR=/u/rwlmd/spinups/
+#grep "^# @" $0
+#set -vx
+#
 
-#makegcm -d 32x24x20 -b 32x36 -t 2 -p std gcm
-#makegcm -d 32x24x20 -b 32x36 -t 2 -p std newstart
-
-newstart.e < start_earth
+cp -f run_spinup.def run.def
+newstart.e < start_earlymars
 startrestart
 
-echo "Starting short GCM spinup run #1..."
-cp -f $DEF_DIR/run1.def run.def
-gcm.e > lruns1
-startrestart
-
-echo "Starting short GCM spinup run #2..."
-cp -f $DEF_DIR/run2.def run.def
-gcm.e > lruns2
-startrestart
-
-echo "Finishing GCM spinup year..."
-cp -f $DEF_DIR/run_1styr_earth.def run.def
-gcm.e > lrun0
+echo "Starting GCM spinup year..."
+gcm.e
 startrestart0
 
-exit 0
+echo "Running for multiple years to reach equilibrium."
+cp -f run_normal.def run.def
+run0
 
-# run for many years to reach equilibrium
-#cp -f run_1yr_earth.def run.def
-#rm -f num_run
-#run0
-
-# start the final 1-yr run with intensive OLR save
-#cp -f run_1yr_earth_OLR.def run.def
-#run_OLR
Index: /trunk/LMDZ.GENERIC/deftank/callphys.GJ581d
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/callphys.GJ581d	(revision 253)
+++ /trunk/LMDZ.GENERIC/deftank/callphys.GJ581d	(revision 253)
@@ -0,0 +1,129 @@
+## Orbit / general options
+## ~~~~~~~~~~~~~~~~~~~~~~~
+# Run with or without tracer transport ?
+tracer    = .true.
+# Diurnal cycle ?  if diurnal=false, diurnally averaged solar heating
+diurnal   = .false.
+# Seasonal cycle ? if season=false, Ls stays constant, to value set in "start"
+season    = .true. 
+# Tidally resonant orbit ? must have diurnal=false, correct rotation rate in newstart
+tlocked   = .true.
+# Tidal resonance ratio ? ratio T_orbit to T_rotation
+nres      = 10
+# Write some more output on the screen ?
+lwrite    = .false.
+# Save statistics in file "stats.nc" ?
+callstats = .false.
+# Test energy conservation of model physics ?
+enertest  = .true.
+
+## Radiative transfer options
+## ~~~~~~~~~~~~~~~~~~~~~~~~~~
+# call radiative transfer?
+callrad    = .true.
+# the rad. transfer is computed every "iradia" physical timestep
+iradia     = 4
+# call multilayer correlated-k radiative transfer ?
+corrk      = .true.
+# folder in which correlated-k data is stored ?
+corrkdir   = CO2_H2Ovar
+# call visible gaseous absorption in radiative transfer ?
+callgasvis = .true.
+# Include Rayleigh scattering in the visible ?
+rayleigh   = .true.
+# Characteristic planetary equilibrium (black body) temperature
+# This is used only in the aerosol radiative transfer setup. (see aerave.F)
+tplanet    = 215.
+# Output spectral OLR in 1D/3D?
+specOLR    = .false.
+# Output global radiative balance in file 'rad_bal.out' - slow for 1D!!
+meanOLR    = .true.
+# Variable gas species: Radiatively active ?
+varactive  = .true.
+# Variable gas species: Fixed vertical distribution ?
+varfixed   = .false.
+# Variable gas species: Saturation percentage value at ground ?
+satval     = 0.0
+
+## Star type
+## ~~~~~~~~~
+startype = 2
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# The choices are:
+#
+#	startype = 1		Sol        (G2V-class main sequence)
+#	startype = 2		Ad Leo     (M-class, synthetic)
+#       startype = 3            GJ644
+#       startype = 4            HD128167
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# Stellar flux at 1 AU. Examples:
+# 1366.0 W m-2		Sol today
+# 1024.5 W m-2		Sol today x 0.75 = weak early Sun
+# 18.462 W m-2		The feeble Gl581
+# 19.960 W m-2		Gl581 with e=0.38 orbital average
+Fat1AU = 18.46
+
+## Tracer and aerosol options 
+## ~~~~~~~~~~~~~~~~~~~~~~~~~~
+# Gravitational sedimentation of tracers (KEEP FALSE FOR NOW) ?
+sedimentation = .false.
+
+## Other physics options
+## ~~~~~~~~~~~~~~~~~~~~~
+# call turbulent vertical diffusion ?
+calldifv = .true.
+# call convective adjustment ?
+calladj  = .true.
+# call thermal conduction in the soil ?
+callsoil = .true.
+
+#########################################################################
+## extra non-standard definitions for Gliese 581d
+#########################################################################
+ 
+## Radiative transfer options 
+## ~~~~~~~~~~~~~~~~~~~~~~~~~~
+# Parameterized Earth-like ozone absorption ?
+ozone         = .false.
+
+## Tracer and aerosol options 
+## ~~~~~~~~~~~~~~~~~~~~~~~~~~
+# Fixed aerosol distributions?
+aerofixed     = .true.
+# Varying H2O cloud fraction?
+CLFvarying    = .false.
+# H2O cloud fraction?
+CLFfixval     = 1.0
+# number mixing ratio of CO2 ice particles
+Nmix_co2      = 100000.
+# number mixing ratio of water ice particles
+Nmix_h2o      = 100000.
+
+## Water options 
+## ~~~~~~~~~~~~~
+# Model water cycle
+water         = .true.
+# Model water cloud formation
+watercond     = .true.
+# Model water precipitation (including coagulation etc.)
+waterrain     = .true.
+# WATER: Precipitation threshold (simple scheme only) ?
+rainthreshold = 0.0
+# Include hydrology ?
+hydrology     = .true.
+# H2O snow (and ice) albedo ?
+albedosnow    = 0.5
+# Maximum sea ice thickness ?
+maxicethick   = 0.05
+# Freezing point of seawater (degrees C) ?
+Tsaldiff      = 0.0
+
+## CO2 options 
+## ~~~~~~~~~~~
+# gas is non-ideal CO2 ?
+nonideal      = .false.
+# call CO2 condensation ?
+co2cond       = .true.
+# Set initial temperature profile to 1 K above CO2 condensation everywhere?
+nearco2cond   = .false.
+
Index: /trunk/LMDZ.GENERIC/deftank/callphys.earlymars
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/callphys.earlymars	(revision 252)
+++ /trunk/LMDZ.GENERIC/deftank/callphys.earlymars	(revision 253)
@@ -4,5 +4,5 @@
 tracer    = .true.
 # Diurnal cycle ?  if diurnal=false, diurnally averaged solar heating
-diurnal   = .false.
+diurnal   = .true.
 # Seasonal cycle ? if season=false, Ls stays constant, to value set in "start"
 season    = .true. 
@@ -14,5 +14,5 @@
 lwrite    = .false.
 # Save statistics in file "stats.nc" ?
-callstats = .false.
+callstats = .true.
 # Test energy conservation of model physics ?
 enertest  = .false.
@@ -35,14 +35,14 @@
 # This is used only in the aerosol radiative transfer setup. (see aerave.F)
 tplanet    = 215.
-# Output spectral OLR in 3D?
+# Output spectral OLR in 1D/3D?
 specOLR    = .false.
-# Output global radiative balance in file 'olr.txt' - slow for 1D!!
-meanOLR    = .false.
+# Output global radiative balance in file 'rad_bal.out' - slow for 1D!!
+meanOLR    = .true.
 # Variable gas species: Radiatively active ?
-varactive  = .false.
+varactive  = .true.
 # Variable gas species: Fixed vertical distribution ?
-varfixed   = .true.
+varfixed   = .false.
 # Variable gas species: Saturation percentage value at ground ?
-satval     = 0.8
+satval     = 0.0
 
 ## Star type
@@ -58,8 +58,9 @@
 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 # Stellar flux at 1 AU. Examples:
-# 1356.0 W m-2		Sol today
-# 1017.0 W m-2		Sol today x 0.75 = weak early Sun
-# 18.462 W m-2		The feeble Gl581
-Fat1AU = 1017.0
+# 1366.0 W m-2		Sol today
+# 1024.5 W m-2		Sol today x 0.75 = weak Sun 3.8 GYa
+# 18.462 W m-2		The feeble GJ581
+# 19.960 W m-2		GJ581 with e=0.38 orbital average
+Fat1AU = 1024.5
 
 ## Tracer and aerosol options 
@@ -78,16 +79,15 @@
 
 #########################################################################
-## extra non-standard definitions for Earth / Early Mars
+## extra non-standard definitions for Gliese 581d
 #########################################################################
- 
-## Radiative transfer options 
-## ~~~~~~~~~~~~~~~~~~~~~~~~~~
-# Parameterized Earth-like ozone absorption ?
-ozone         = .false.
 
 ## Tracer and aerosol options 
 ## ~~~~~~~~~~~~~~~~~~~~~~~~~~
 # Fixed aerosol distributions?
-aerofixed     = .true.
+aerofixed     = .false.
+# Varying H2O cloud fraction?
+CLFvarying    = .false.
+# H2O cloud fraction?
+CLFfixval     = 0.5
 # number mixing ratio of CO2 ice particles
 Nmix_co2      = 100000.
@@ -105,4 +105,6 @@
 # WATER: Precipitation threshold (simple scheme only) ?
 rainthreshold = 0.011
+# WATER: hydrology ?
+hydrology     = .true.
 
 ## CO2 options 
@@ -114,2 +116,15 @@
 # Set initial temperature profile to 1 K above CO2 condensation everywhere?
 nearco2cond   = .false.
+
+## N2 options
+## ~~~~~~~~~~
+# include N2 in cp and Rayleigh scattering calculation ?
+addn2 = .false.
+# N2 mixing ratio
+n2mixratio = 0.0
+
+## H2 options
+## ~~~~~~~~~~
+# include H2 in cp and Rayleigh scattering calculation ?
+# for now we assume H2 dominant if included
+addh2 = .false.
Index: /trunk/LMDZ.GENERIC/deftank/callphys.earth
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/callphys.earth	(revision 252)
+++ /trunk/LMDZ.GENERIC/deftank/callphys.earth	(revision 253)
@@ -23,9 +23,9 @@
 callrad    = .true.
 # the rad. transfer is computed every "iradia" physical timestep
-iradia     = 4
+iradia     = 6
 # call multilayer correlated-k radiative transfer ?
 corrk      = .true.
 # folder in which correlated-k data is stored ?
-corrkdir   = earth
+corrkdir   = N2CO2poor_H2Ovar
 # call visible gaseous absorption in radiative transfer ?
 callgasvis = .true.
@@ -37,12 +37,12 @@
 # Output spectral OLR in 3D?
 specOLR    = .false.
-# Output global radiative balance in file 'olr.txt' - slow for 1D!!
-meanOLR    = .false.
+# Output global radiative balance in file 'rad_bal.out' - slow for 1D!!
+meanOLR    = .true.
 # Variable gas species: Radiatively active ?
-varactive  = .false.
+varactive  = .true.
 # Variable gas species: Fixed vertical distribution ?
-varfixed   = .true.
+varfixed   = .false.
 # Variable gas species: Saturation percentage value at ground ?
-satval     = 0.8
+satval     = 0.0
 
 ## Star type
@@ -58,8 +58,8 @@
 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 # Stellar flux at 1 AU. Examples:
-# 1356.0 W m-2		Sol today
-# 1017.0 W m-2		Sol today x 0.75 = weak early Sun
+# 1366.0 W m-2		Sol today
+# 1024.5 W m-2		Sol today x 0.75 = weak early Sun
 # 18.462 W m-2		The feeble Gl581
-Fat1AU = 1356.0
+Fat1AU = 1366.0
 
 ## Tracer and aerosol options 
@@ -78,16 +78,15 @@
 
 #########################################################################
-## extra non-standard definitions for Earth / Early Mars
+## extra non-standard definitions for Earth
 #########################################################################
  
-## Radiative transfer options 
-## ~~~~~~~~~~~~~~~~~~~~~~~~~~
-# Parameterized Earth-like ozone absorption ?
-ozone         = .false.
-
 ## Tracer and aerosol options 
 ## ~~~~~~~~~~~~~~~~~~~~~~~~~~
 # Fixed aerosol distributions?
-aerofixed     = .true.
+aerofixed     = .false.
+# Varying H2O cloud fraction?
+CLFvarying    = .true.
+# H2O cloud fraction if fixed?
+CLFfixval     = 0.5
 # number mixing ratio of CO2 ice particles
 Nmix_co2      = 100000.
@@ -105,4 +104,6 @@
 # WATER: Precipitation threshold (simple scheme only) ?
 rainthreshold = 0.011
+# WATER: hydrology ?
+hydrology     = .true.
 
 ## CO2 options 
@@ -114,2 +115,15 @@
 # Set initial temperature profile to 1 K above CO2 condensation everywhere?
 nearco2cond   = .false.
+
+## N2 options
+## ~~~~~~~~~~
+# include N2 in cp and Rayleigh scattering calculation ?
+addn2 = .false.
+# N2 mixing ratio
+n2mixratio = 0.0
+
+## H2 options
+## ~~~~~~~~~~
+# include H2 in cp and Rayleigh scattering calculation ?
+# for now we assume H2 dominant if included
+addh2 = .false.
Index: unk/LMDZ.GENERIC/deftank/run.def.32x24x32
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/run.def.32x24x32	(revision 252)
+++ 	(revision )
@@ -1,112 +1,0 @@
-#
-#----------------------------------------------------------------------- 
-#Parametres de controle du run:                                          
-#------------------------------                                          
-
-# Nombre de jours d'integration                                         
-     nday=9999
-
-# nombre de pas par jour (multiple de iperiod) ( ici pour  dt = 1 min )      
- day_step = 480
-
-# periode pour le pas Matsuno (en pas)                                  
-  iperiod=5
-
-# periode de sortie des variables de controle (en pas)                  
-  iconser=120
-
-# periode d'ecriture du fichier histoire (en jour)                      
-    iecri=100
-
-# periode de stockage fichier histmoy (en jour)                         
- periodav=60.
-
-# periode de la dissipation (en pas)                                    
-  idissip=1
-
-# choix de l'operateur de dissipation (star ou  non star )              
- lstardis=.true.
-
-# avec ou sans coordonnee hybrides
- hybrid=.true.
-
-# nombre d'iterations de l'operateur de dissipation   gradiv            
-nitergdiv=1
-
-# nombre d'iterations de l'operateur de dissipation  nxgradrot          
-nitergrot=2
-
-# nombre d'iterations de l'operateur de dissipation  divgrad            
-   niterh=2
-
-# temps de dissipation des plus petites long.d ondes pour u,v (gradiv)  
- tetagdiv= 3000.
-
-# temps de dissipation des plus petites long.d ondes pour u,v(nxgradrot)
- tetagrot=9000.
-
-# temps de dissipation des plus petites long.d ondes pour  h ( divgrad) 
- tetatemp=9000.
-
-# coefficient pour gamdissip                                            
-  coefdis=0.
-
-# choix du shema d'integration temporelle (Matsuno ou Matsuno-leapfrog) 
-  purmats=.false.
-
-# avec ou sans physique                                                 
-   physic=.true.
-
-# periode de la physique (en pas)                                       
-  iphysiq=10
-
-# choix d'une grille reguliere                                          
-  grireg=.true.
-
-# frequence (en pas) de l'ecriture du fichier diagfi               
- ecritphy=120
-
-# longitude en degres du centre du zoom                                 
-   clon=63.
-
-# latitude en degres du centre du zoom                                  
-   clat=0.
-
-# facteur de grossissement du zoom,selon longitude                      
-  grossismx=1.
-
-# facteur de grossissement du zoom ,selon latitude                      
- grossismy=1.
-
-#  Fonction  f(y)  hyperbolique  si = .true.  , sinon  sinusoidale         
-  fxyhypb=.false.
-
-# extension en longitude  de la zone du zoom  ( fraction de la zone totale)
-   dzoomx= 0.
-
-# extension en latitude de la zone  du zoom  ( fraction de la zone totale)
-   dzoomy=0.
-
-#  raideur du zoom en  X
-    taux=2.
-
-#  raideur du zoom en  Y
-    tauy=2.
-
-#  Fonction  f(y) avec y = Sin(latit.) si = .TRUE. ,  Sinon  y = latit.
-  ysinus= .false.
-
-# Avec sponge layer
-  callsponge  = .true.
- 
-# Sponge:  mode0(u=v=0), mode1(u=umoy,v=0), mode2(u=umoy,v=vmoy)
-  mode_sponge= 2
-
-# Sponge:  hauteur de sponge (km)
-  hsponge= 130
-
-# Sponge:  tetasponge (secondes)
-  tetasponge = 50000
-
-# some definitions for the physics, in file 'callphys.def'
-INCLUDEDEF=callphys.def
Index: unk/LMDZ.GENERIC/deftank/run.def.64x48x32
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/run.def.64x48x32	(revision 252)
+++ 	(revision )
@@ -1,112 +1,0 @@
-#
-#----------------------------------------------------------------------- 
-#Parametres de controle du run:                                          
-#------------------------------                                          
-
-# Nombre de jours d'integration                                         
-     nday=9999
-
-# nombre de pas par jour (multiple de iperiod) ( ici pour  dt = 1 min )      
- day_step = 960
-
-# periode pour le pas Matsuno (en pas)                                  
-  iperiod=5
-
-# periode de sortie des variables de controle (en pas)                  
-  iconser=120
-
-# periode d'ecriture du fichier histoire (en jour)                      
-    iecri=100
-
-# periode de stockage fichier histmoy (en jour)                         
- periodav=60.
-
-# periode de la dissipation (en pas)                                    
-  idissip=5
-
-# choix de l'operateur de dissipation (star ou  non star )              
- lstardis=.true.
-
-# avec ou sans coordonnee hybrides
- hybrid=.true.
-
-# nombre d'iterations de l'operateur de dissipation   gradiv            
-nitergdiv=1
-
-# nombre d'iterations de l'operateur de dissipation  nxgradrot          
-nitergrot=2
-
-# nombre d'iterations de l'operateur de dissipation  divgrad            
-   niterh=2
-
-# temps de dissipation des plus petites long.d ondes pour u,v (gradiv)  
- tetagdiv= 4000.
-
-# temps de dissipation des plus petites long.d ondes pour u,v(nxgradrot)
- tetagrot=5000.
-
-# temps de dissipation des plus petites long.d ondes pour  h ( divgrad) 
- tetatemp=5000.
-
-# coefficient pour gamdissip                                            
-  coefdis=0.
-
-# choix du shema d'integration temporelle (Matsuno ou Matsuno-leapfrog) 
-  purmats=.false.
-
-# avec ou sans physique                                                 
-   physic=.true.
-
-# periode de la physique (en pas)                                       
-  iphysiq=20
-
-# choix d'une grille reguliere                                          
-  grireg=.true.
-
-# frequence (en pas) de l'ecriture du fichier diagfi               
- ecritphy=240
-
-# longitude en degres du centre du zoom                                 
-   clon=63.
-
-# latitude en degres du centre du zoom                                  
-   clat=0.
-
-# facteur de grossissement du zoom,selon longitude                      
-  grossismx=1.
-
-# facteur de grossissement du zoom ,selon latitude                      
- grossismy=1.
-
-#  Fonction  f(y)  hyperbolique  si = .true.  , sinon  sinusoidale         
-  fxyhypb=.false.
-
-# extension en longitude  de la zone du zoom  ( fraction de la zone totale)
-   dzoomx= 0.
-
-# extension en latitude de la zone  du zoom  ( fraction de la zone totale)
-   dzoomy=0.
-
-#  raideur du zoom en  X
-    taux=2.
-
-#  raideur du zoom en  Y
-    tauy=2.
-
-#  Fonction  f(y) avec y = Sin(latit.) si = .TRUE. ,  Sinon  y = latit.
-  ysinus= .false.
-
-# Avec sponge layer
-  callsponge  = .true.
- 
-# Sponge:  mode0(u=v=0), mode1(u=umoy,v=0), mode2(u=umoy,v=vmoy)
-  mode_sponge= 2
-
-# Sponge:  hauteur de sponge (km)
-  hsponge= 130
-
-# Sponge:  tetasponge (secondes)
-  tetasponge = 50000
-
-# some definitions for the physics, in file 'callphys.def'
-INCLUDEDEF=callphys.def
Index: unk/LMDZ.GENERIC/deftank/run.def.64x48x50
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/run.def.64x48x50	(revision 252)
+++ 	(revision )
@@ -1,112 +1,0 @@
-#
-#----------------------------------------------------------------------- 
-#Parametres de controle du run:                                          
-#------------------------------                                          
-
-# Nombre de jours d'integration                                         
-     nday=9999
-
-# nombre de pas par jour (multiple de iperiod) ( ici pour  dt = 1 min )      
- day_step = 960
-
-# periode pour le pas Matsuno (en pas)                                  
-  iperiod=5
-
-# periode de sortie des variables de controle (en pas)                  
-  iconser=120
-
-# periode d'ecriture du fichier histoire (en jour)                      
-    iecri=100
-
-# periode de stockage fichier histmoy (en jour)                         
- periodav=60.
-
-# periode de la dissipation (en pas)                                    
-  idissip=1
-
-# choix de l'operateur de dissipation (star ou  non star )              
- lstardis=.true.
-
-# avec ou sans coordonnee hybrides
- hybrid=.true.
-
-# nombre d'iterations de l'operateur de dissipation   gradiv            
-nitergdiv=1
-
-# nombre d'iterations de l'operateur de dissipation  nxgradrot          
-nitergrot=2
-
-# nombre d'iterations de l'operateur de dissipation  divgrad            
-   niterh=2
-
-# temps de dissipation des plus petites long.d ondes pour u,v (gradiv)  
- tetagdiv= 3000.
-
-# temps de dissipation des plus petites long.d ondes pour u,v(nxgradrot)
- tetagrot=20000.
-
-# temps de dissipation des plus petites long.d ondes pour  h ( divgrad) 
- tetatemp=20000.
-
-# coefficient pour gamdissip                                            
-  coefdis=0.
-
-# choix du shema d'integration temporelle (Matsuno ou Matsuno-leapfrog) 
-  purmats=.false.
-
-# avec ou sans physique                                                 
-   physic=.true.
-
-# periode de la physique (en pas)                                       
-  iphysiq=20
-
-# choix d'une grille reguliere                                          
-  grireg=.true.
-
-# frequence (en pas) de l'ecriture du fichier diagfi               
- ecritphy=240
-
-# longitude en degres du centre du zoom                                 
-   clon=63.
-
-# latitude en degres du centre du zoom                                  
-   clat=0.
-
-# facteur de grossissement du zoom,selon longitude                      
-  grossismx=1.
-
-# facteur de grossissement du zoom ,selon latitude                      
- grossismy=1.
-
-#  Fonction  f(y)  hyperbolique  si = .true.  , sinon  sinusoidale         
-  fxyhypb=.false.
-
-# extension en longitude  de la zone du zoom  ( fraction de la zone totale)
-   dzoomx= 0.
-
-# extension en latitude de la zone  du zoom  ( fraction de la zone totale)
-   dzoomy=0.
-
-#  raideur du zoom en  X
-    taux=2.
-
-#  raideur du zoom en  Y
-    tauy=2.
-
-#  Fonction  f(y) avec y = Sin(latit.) si = .TRUE. ,  Sinon  y = latit.
-  ysinus= .false.
-
-# Avec sponge layer
-  callsponge  = .true.
- 
-# Sponge:  mode0(u=v=0), mode1(u=umoy,v=0), mode2(u=umoy,v=vmoy)
-  mode_sponge= 2
-
-# Sponge:  hauteur de sponge (km)
-  hsponge= 230
-
-# Sponge:  tetasponge (secondes)
-  tetasponge = 30000
-
-# some definitions for the physics, in file 'callphys.def'
-INCLUDEDEF=callphys.def
Index: /trunk/LMDZ.GENERIC/deftank/run.def.earlymars_hires
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/run.def.earlymars_hires	(revision 253)
+++ /trunk/LMDZ.GENERIC/deftank/run.def.earlymars_hires	(revision 253)
@@ -0,0 +1,112 @@
+#
+#----------------------------------------------------------------------- 
+#Parametres de controle du run:                                          
+#------------------------------                                          
+
+# Nombre de jours d'integration                                         
+     nday=669
+
+# nombre de pas par jour (multiple de iperiod) ( ici pour  dt = 1 min )      
+ day_step = 960
+
+# periode pour le pas Matsuno (en pas)                                  
+  iperiod=5
+
+# periode de sortie des variables de controle (en pas)                  
+  iconser=120
+
+# periode d'ecriture du fichier histoire (en jour)                      
+    iecri=100
+
+# periode de stockage fichier histmoy (en jour)                         
+ periodav=60.
+
+# periode de la dissipation (en pas)                                    
+  idissip=5
+
+# choix de l'operateur de dissipation (star ou  non star )              
+ lstardis=.true.
+
+# avec ou sans coordonnee hybrides
+ hybrid=.true.
+
+# nombre d'iterations de l'operateur de dissipation   gradiv            
+nitergdiv=1
+
+# nombre d'iterations de l'operateur de dissipation  nxgradrot          
+nitergrot=2
+
+# nombre d'iterations de l'operateur de dissipation  divgrad            
+   niterh=2
+
+# temps de dissipation des plus petites long.d ondes pour u,v (gradiv)  
+ tetagdiv=10000.
+
+# temps de dissipation des plus petites long.d ondes pour u,v(nxgradrot)
+ tetagrot=10000.
+
+# temps de dissipation des plus petites long.d ondes pour  h ( divgrad) 
+ tetatemp=10000.
+
+# coefficient pour gamdissip                                            
+  coefdis=0.
+
+# choix du shema d'integration temporelle (Matsuno ou Matsuno-leapfrog) 
+  purmats=.false.
+
+# avec ou sans physique                                                 
+   physic=.true.
+
+# periode de la physique (en pas)                                       
+  iphysiq=20
+
+# choix d'une grille reguliere                                          
+  grireg=.true.
+
+# frequence (en pas) de l'ecriture du fichier diagfi               
+ ecritphy=1920
+
+# longitude en degres du centre du zoom                                 
+   clon=63.
+
+# latitude en degres du centre du zoom                                  
+   clat=0.
+
+# facteur de grossissement du zoom,selon longitude                      
+  grossismx=1.
+
+# facteur de grossissement du zoom ,selon latitude                      
+ grossismy=1.
+
+#  Fonction  f(y)  hyperbolique  si = .true.  , sinon  sinusoidale         
+  fxyhypb=.false.
+
+# extension en longitude  de la zone du zoom  ( fraction de la zone totale)
+   dzoomx= 0.
+
+# extension en latitude de la zone  du zoom  ( fraction de la zone totale)
+   dzoomy=0.
+
+#  raideur du zoom en  X
+    taux=2.
+
+#  raideur du zoom en  Y
+    tauy=2.
+
+#  Fonction  f(y) avec y = Sin(latit.) si = .TRUE. ,  Sinon  y = latit.
+  ysinus= .false.
+
+# Avec sponge layer
+  callsponge  = .true.
+ 
+# Sponge:  mode0(u=v=0), mode1(u=umoy,v=0), mode2(u=umoy,v=vmoy)
+  mode_sponge= 2
+
+# Sponge:  hauteur de sponge (km)
+  hsponge= 90
+
+# Sponge:  tetasponge (secondes)
+  tetasponge = 50000
+
+# some definitions for the physics, in file 'callphys.def'
+INCLUDEDEF=callphys.def
Index: /trunk/LMDZ.GENERIC/deftank/run.def.earth_hires
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/run.def.earth_hires	(revision 253)
+++ /trunk/LMDZ.GENERIC/deftank/run.def.earth_hires	(revision 253)
@@ -0,0 +1,110 @@
+#
+#----------------------------------------------------------------------- 
+#Parametres de controle du run:                                          
+#------------------------------                                          
+
+# Nombre de jours d'integration                                         
+  nday = 365
+# nombre de pas par jour (multiple de iperiod) ( ici pour dt = 1 min )      
+ day_step = 360
+# periode pour le pas Matsuno (en pas)                                  
+  iperiod=5
+
+# periode de sortie des variables de controle (en pas)                  
+  iconser=120
+
+# periode d'ecriture du fichier histoire (en jour)                      
+    iecri=1000
+
+# periode de stockage fichier histmoy (en jour)                         
+ periodav=10.
+
+# periode de la dissipation (en pas)                                    
+  idissip=1
+
+# choix de l'operateur de dissipation (star ou  non star )              
+ lstardis=.true.
+
+# avec ou sans coordonnee hybrides
+ hybrid=.true.
+
+# nombre d'iterations de l'operateur de dissipation   gradiv            
+nitergdiv=1
+
+# nombre d'iterations de l'operateur de dissipation  nxgradrot          
+nitergrot=2
+
+# nombre d'iterations de l'operateur de dissipation  divgrad            
+   niterh=2
+
+# temps de dissipation des plus petites long.d ondes pour u,v (gradiv)  
+ tetagdiv=5400.
+
+# temps de dissipation des plus petites long.d ondes pour u,v(nxgradrot)
+ tetagrot=10000.
+
+# temps de dissipation des plus petites long.d ondes pour  h ( divgrad) 
+ tetatemp=10000.
+
+# coefficient pour gamdissip                                            
+  coefdis=0.
+
+# choix du shema d'integration temporelle (Matsuno ou Matsuno-leapfrog) 
+  purmats=.false.
+
+# avec ou sans physique                                                 
+   physic=.true.
+
+# periode de la physique (en pas)                                       
+  iphysiq=5
+
+# choix d'une grille reguliere                                          
+  grireg=.true.
+
+# frequence (en pas) de l'ecriture du fichier diagfi               
+ ecritphy=360
+
+# longitude en degres du centre du zoom                                 
+   clon=0.
+
+# latitude en degres du centre du zoom                                  
+   clat=0.
+
+# facteur de grossissement du zoom,selon longitude                      
+  grossismx=1.
+
+# facteur de grossissement du zoom ,selon latitude                      
+ grossismy=1.
+
+#  Fonction  f(y)  hyperbolique  si = .true.  , sinon  sinusoidale         
+  fxyhypb=.false.
+
+# extension en longitude  de la zone du zoom  ( fraction de la zone totale)
+   dzoomx= 0.
+
+# extension en latitude de la zone  du zoom  ( fraction de la zone totale)
+   dzoomy=0.
+
+#  raideur du zoom en  X
+    taux=2.
+
+#  raideur du zoom en  Y
+    tauy=2.
+
+#  Fonction  f(y) avec y = Sin(latit.) si = .TRUE. ,  Sinon  y = latit.
+  ysinus= .false.
+
+# Avec sponge layer
+  callsponge  = .true.
+ 
+# Sponge:  mode0(u=v=0), mode1(u=umoy,v=0), mode2(u=umoy,v=vmoy)
+  mode_sponge= 2
+
+# Sponge:  hauteur de sponge (km)
+  hsponge= 50
+
+# Sponge:  tetasponge (secondes)
+  tetasponge = 50000
+
+# some definitions for the physics, in file 'callphys.def'
+INCLUDEDEF=callphys.def
Index: /trunk/LMDZ.GENERIC/deftank/run0
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/run0	(revision 252)
+++ /trunk/LMDZ.GENERIC/deftank/run0	(revision 253)
@@ -4,5 +4,5 @@
 # SET HERE the maximum total number of simulations
 
-set nummax=2
+set nummax=5
 
 ###########################################################################
@@ -49,5 +49,5 @@
 
 # Run GCM
-nice gcm.e >! lrun${numnew} 
+gcm.e >! lrun${numnew} 
 
 
@@ -66,8 +66,8 @@
   endif
  echo 99999 >! num_run
-############## To receive an Email message if the run crashes ########
-mail -s "crash run GCM" $address <<ENDMAIL
-The run on $machine in $dir has just crashed.
-ENDMAIL
+############## To receive an email message if the run crashes ########
+#mail -s "crash run GCM" $address <<ENDMAIL
+#The run on $machine in $dir has just crashed.
+#ENDMAIL
 ############################################"" 
  exit
@@ -77,4 +77,7 @@
 if ( -f diagfi.nc ) then
   \mv -f diagfi.nc diagfi${numnew}.nc
+endif
+if ( -f diagspec.nc ) then
+  \mv -f diagspec.nc diagspec${numnew}.nc
 endif
 if ( -f diagsoil.nc ) then
@@ -95,7 +98,10 @@
 
 if ( -f rad_bal.out ) then
-    mv rad_bal.out radbal${numnew}
+    mv rad_bal.out rad_bal${numnew}.out
 endif
 
+if ( -f h2o_bal.out ) then
+    mv h2o_bal.out h2o_bal${numnew}.out
+endif
 
 # If we are over nummax : stop
Index: /trunk/LMDZ.GENERIC/deftank/run1d.earlymars
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/run1d.earlymars	(revision 252)
+++ /trunk/LMDZ.GENERIC/deftank/run1d.earlymars	(revision 253)
@@ -1,5 +1,5 @@
 #
 #----------------------------------------------------------------------- 
-# Run parameters for the 1D 'testphys1d.e' model                                          
+# Run parameters for the 1D 'rcm1d.e' model                                          
 #-----------------------------------------------------------------------                                         
 
Index: /trunk/LMDZ.GENERIC/deftank/run1d.earth
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/run1d.earth	(revision 252)
+++ /trunk/LMDZ.GENERIC/deftank/run1d.earth	(revision 253)
@@ -1,5 +1,5 @@
 #
 #----------------------------------------------------------------------- 
-# Run parameters for the 1D 'testphys1d.e' model                                          
+# Run parameters for the 1D 'rcm1d.e' model                                          
 #-----------------------------------------------------------------------                                         
 
@@ -11,7 +11,7 @@
 time=0
 # Number of time steps per sol
-day_step=48
+day_step=24 
 # Number of sols to run 
-ndt=2000
+ndt =2000
 
 #### Physical parameters
@@ -23,17 +23,17 @@
 # Molar mass of atmosphere (g)
 mugaz=28.97
-# Specific heat capacity of atmosphere (J kg-1 K-1)
+# Specific heat capacity of atmosphere?
 cpp=1003.0
 # latitude (in degrees)
 latitude=60.0
 # orbital distance at perihelion (AU)
-periheli=1.0
+periastr=1.0
 # orbital distance at aphelion (AU)
-aphelie=1.0
+apoastr=1.0
 # obliquity (degrees)
 obliquit=0.0
 
 # Albedo of bare ground
-albedo=0.1
+albedo=0.16
 # Emissivity of bare ground
 emis=1.0
@@ -48,5 +48,6 @@
 # hybrid vertical coordinate ? (.true. for hybrid and .false. for sigma levels)
 hybrid=.false.
-
+# autocompute vertical discretisation? (useful for exoplanet runs)
+autozlevs=.true.
 
 ###### Initial atmospheric temperature profile
@@ -73,5 +74,4 @@
 hauteur=30.
 
-
 # some definitions for the physics, in file 'callphys.def'
 INCLUDEDEF=callphys.def
Index: unk/LMDZ.GENERIC/deftank/run_farm
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/run_farm	(revision 252)
+++ 	(revision )
@@ -1,28 +1,0 @@
-# Script to submit simulations with the LMD MARS GCM on 
-# a farm of computers using the run manager named "Torque".
-# To run it, just type 
-# > qsub run_farm
-
-# Shell
-#PBS -S /bin/bash
-# Job Name
-#PBS -N run_mars
-# Merge output and error logs
-#PBS -j oe
-
-####################################
-# SELECT HERE THE RUN DURATION CLASS :
-# Queue std(6h) / day / week /infini
-
-#PBS -q std
-
-# Go to present working directory
-cd  $PBS_O_WORKDIR
-
-# SELECT HERE THE TYPE OF SCRIPT TO USE : "run0" OR "run_mcd"
-
-run0
-
-####################################
-
-
Index: /trunk/LMDZ.GENERIC/deftank/start_earlymars
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/start_earlymars	(revision 252)
+++ /trunk/LMDZ.GENERIC/deftank/start_earlymars	(revision 253)
@@ -7,7 +7,7 @@
 peri_day
 0.0
-periheli
+periastr
 227.9
-aphelie
+apoastr
 227.9
 year_day
@@ -25,4 +25,7 @@
 daysec
 88775.00
+albedice
+0.5
+0.5
 
 surface_mars.nc
@@ -32,5 +35,5 @@
 250
 ptot
-200000.0
+500000.0
 y
 n
@@ -38,9 +41,8 @@
 1.0
 isotherm
-260
+260.0
 co2ice=0
 q=0
-watercapn
-watercaps
+oborealis
 
 exit 0
Index: /trunk/LMDZ.GENERIC/deftank/start_earth
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/start_earth	(revision 252)
+++ /trunk/LMDZ.GENERIC/deftank/start_earth	(revision 253)
@@ -7,10 +7,12 @@
 peri_day
 0.0
-periheli
+periastr
 149.0
-aphelie
+apoastr
 149.0
 year_day
 365
+rad
+6378137.0
 omeg
 7.2722E-05
@@ -26,7 +28,4 @@
 surface_earth.nc
 0
-bilball
-0.1
-250
 ptot
 101325.0
@@ -34,11 +33,6 @@
 y
 101325.0
-emis
-1.0
-isotherm
-300
+radequi
 q=0
-watercapn
-watercaps
 
 exit 0
Index: /trunk/LMDZ.GENERIC/deftank/z2sig.earth
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/z2sig.earth	(revision 252)
+++ /trunk/LMDZ.GENERIC/deftank/z2sig.earth	(revision 253)
@@ -20,2 +20,10 @@
    3.6962495e+01
    4.0453872e+01
+   45
+   50
+   55
+   60
+   65
+   70
+   80
+   90
Index: /trunk/LMDZ.GENERIC/deftank/z2sig.mars
===================================================================
--- /trunk/LMDZ.GENERIC/deftank/z2sig.mars	(revision 252)
+++ /trunk/LMDZ.GENERIC/deftank/z2sig.mars	(revision 253)
@@ -1,4 +1,3 @@
-10.00000     H: atmospheric scale height (km) (used as a reference only)
-0.0040       Typical pseudo-altitude (m) for 1st layer (z=H*log(sigma))
+8.00000     H: atmospheric scale height (km) (used as a reference only)
 0.018       ,, ,,  ,, ,, ,, ,,  ,, ,, ,,  2nd layer, etc...
 0.0400
Index: /trunk/LMDZ.GENERIC/libf/dyn3d/addfi.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/dyn3d/addfi.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/dyn3d/addfi.F	(revision 253)
@@ -135,12 +135,15 @@
 c     ENDDO
 
+! increment tracers
       DO iq = 1, nq
          DO k = 1,llm
             DO j = 1,ip1jmp1
+!               pq(j,k,iq)=  pdqfi(j,k,iq) * pdt
                pq(j,k,iq)= pq(j,k,iq) + pdqfi(j,k,iq) * pdt
-               pq(j,k,iq)= AMAX1( pq(j,k,iq), qtestt )
+               pq(j,k,iq)= AMAX1( pq(j,k,iq), qtestt ) ! forbid negative tracer values
             ENDDO
          ENDDO
       ENDDO
+!      print*,'MAJOR TRACER MOD in addfi for test'
                                        
 
Index: /trunk/LMDZ.GENERIC/libf/dyn3d/disvert.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/dyn3d/disvert.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/dyn3d/disvert.F	(revision 253)
@@ -1,3 +1,6 @@
       SUBROUTINE disvert 
+
+! to use  'getin'
+      USE ioipsl_getincom 
 
 c    Auteur :  F. Forget Y. Wanherdrick, P. Levan
@@ -11,4 +14,8 @@
 #include "comconst.h"
 #include "logic.h"
+
+#include "callkeys.h"
+
+
 c
 c=======================================================================
@@ -26,5 +33,5 @@
       REAL zsig(llm)
       INTEGER np,ierr
-      integer :: ierr1,ierr2,ierr3,ierr4
+      integer :: ierr1,ierr2,ierr3,ierr4 
       REAL x
 
@@ -39,4 +46,7 @@
       real z, ps,p
 
+
+      real psurf, hmax ! for autozlevs
+
 c
 c-----------------------------------------------------------------------
@@ -44,74 +54,53 @@
       pi=2.*ASIN(1.)
 
-! Ouverture possible de fichiers typiquement E.T.
-
-         open(99,file="esasig.def",status='old',form='formatted',
-     s   iostat=ierr2)
-         if(ierr2.ne.0) then
-              close(99)
-              open(99,file="z2sig.def",status='old',form='formatted',
-     s        iostat=ierr4)
-         endif
-
-c-----------------------------------------------------------------------
-c   cas 1 on lit les options dans esasig.def:
-c   ----------------------------------------
-
-      IF(ierr2.eq.0) then
-
-c        Lecture de esasig.def :
-c        Systeme peu souple, mais qui respecte en theorie
-c        La conservation de l'energie (conversion Energie potentielle
-c        <-> energie cinetique, d'apres la note de Frederic Hourdin...
-
-         PRINT*,'*****************************'
-         PRINT*,'WARNING Lecture de esasig.def'
-         PRINT*,'*****************************'
-         READ(99,*) h
-         READ(99,*) dz0
-         READ(99,*) dz1
-         READ(99,*) nhaut
-         CLOSE(99)
-
-         dz0=dz0/h
-         dz1=dz1/h
-
-         sig1=(1.-dz1)/tanh(.5*(llm-1)/nhaut)
-
-         esig=1.
-
-         do l=1,20
-            esig=-log((1./sig1-1.)*exp(-dz0)/esig)/(llm-1.)
-         enddo
-         csig=(1./sig1-1.)/(exp(esig)-1.)
-
-         DO L = 2, llm
-            zz=csig*(exp(esig*(l-1.))-1.)
-            sig(l) =1./(1.+zz)
-     &      * tanh(.5*(llm+1-l)/nhaut)
-         ENDDO
-         sig(1)=1.
-         sig(llm+1)=0.
-         quoi      = 1. + 2.* kappa
-         s( llm )  = 1.
-         s(llm-1) = quoi
-         IF( llm.gt.2 )  THEN
-            DO  ll = 2, llm-1
-               l         = llm+1 - ll
-               quand     = sig(l+1)/ sig(l)
-               s(l-1)    = quoi * (1.-quand) * s(l)  + quand * s(l+1)
-            ENDDO
-         END IF
-c
-         snorm=(1.-.5*sig(2)+kappa*(1.-sig(2)))*s(1)+.5*sig(2)*s(2)
-         DO l = 1, llm
-            s(l)    = s(l)/ snorm
-         ENDDO
-
-c-----------------------------------------------------------------------
-c   cas 2 on lit les options dans z2sig.def:
-c   ----------------------------------------
-
-      ELSE IF(ierr4.eq.0) then
+      open(99,file="z2sig.def",status='old',form='formatted',
+     s     iostat=ierr4)
+
+
+      autozlevs=.false.
+      PRINT *,'Auto-discretise vertical levels ?'
+      call getin("autozlevs",autozlevs)
+      write(*,*) " autozlevs = ", autozlevs
+
+      write(*,*)"Operate in kastprof mode?"
+      kastprof=.false.
+      call getin("kastprof",kastprof)
+      write(*,*)" kastprof = ",kastprof
+
+      print*,'kast=',kastprof
+
+      pceil=100.0 ! Pascals
+      PRINT *,'Ceiling pressure (Pa) ?'
+      call getin("pceil",pceil)
+      write(*,*) " pceil = ", pceil
+
+      if(autozlevs.and.iim.gt.1)then
+         print*,'autozlevs no good in 3D...'
+         call abort
+      endif
+
+      if(kastprof.and.iim.gt.1)then
+         print*,'kastprof no good in 3D...'
+         call abort
+      endif
+
+      psurf=610. ! default value for psurf
+      PRINT *,'Surface pressure (Pa) ?'
+      call getin("psurf",psurf)
+      write(*,*) " psurf = ",psurf
+
+      if(kastprof)then
+
+        sig(1)=1
+        do l=2,llm
+                                !sig(l)=1. - real(l-1)/real(llm) ! uses linear sigma spacing
+                                !sig(l)=exp(-real(l-1)*h/real(llm)) ! uses log sigma spacing
+                                !sig(l)=exp(-real(l-1)*Hmax/real(llm)) ! uses log sigma spacing
+           sig(l)=(pceil/psurf)**(real(l-1)/real(llm)) ! uses log sigma spacing
+           
+        end do
+        sig(llm+1)=0
+
+      elseIF(ierr4.eq.0)then
          PRINT*,'****************************'
          PRINT*,'Lecture de z2sig.def'
@@ -124,14 +113,30 @@
          CLOSE(99)
 
-         sig(1) =1
-         do l=2,llm
+
+         if(autozlevs)then
+            open(91,file="z2sig.def",form='formatted')
+            read(91,*) h
+            DO l=1,llm-2
+               read(91,*) Hmax
+            enddo
+            close(91)
+
+            print*,'Hmax = ',Hmax,' km'
+            print*,'Auto-shifting h in disvert.F to:'
+!            h = Hmax / log(psurf/100.0)
+            h = Hmax / log(psurf/pceil)
+            print*,'h = ',h,' km'
+        endif
+       
+        sig(1)=1
+        do l=2,llm
            sig(l) = 0.5 * ( exp(-zsig(l)/h) + exp(-zsig(l-1)/h) )
-         end do
-         sig(llm+1) =0
+        end do
+        sig(llm+1)=0
 
 c-----------------------------------------------------------------------
       ELSE
-         write(*,*) 'didn t you forget something ??? '
-         write(*,*) 'We need the file  z2sig.def ! (OR esasig.def) '
+         write(*,*) 'didn_t you forget something?'
+         write(*,*) 'We need the file  z2sig.def!'! (OR esasig.def) '
          stop
       ENDIF
@@ -206,5 +211,5 @@
       else
          bps(llm) = bps(llm-1)**2 / bps(llm-2) 
-         aps(llm) = 0.
+         aps(llm) = 0. ! what the hell is this???
       end if
 
@@ -213,4 +218,5 @@
       PRINT *,' APs'
       PRINT *,  aps
+
 
       DO l = 1, llm
Index: /trunk/LMDZ.GENERIC/libf/dyn3d/dynetat0.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/dyn3d/dynetat0.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/dyn3d/dynetat0.F	(revision 253)
@@ -51,4 +51,9 @@
       INTEGER ierr, nid, nvarid, nqold
       CHARACTER  str3*3,yes*1
+
+
+!     added by RW for test
+      real pmean,airetot
+      integer ij
 
 c-----------------------------------------------------------------------
@@ -421,4 +426,9 @@
      *rrage est differente de la valeur  dtinteg =',i4//)
 
+
+
+
+
+
       RETURN
       END
Index: /trunk/LMDZ.GENERIC/libf/dyn3d/gcm.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/dyn3d/gcm.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/dyn3d/gcm.F	(revision 253)
@@ -132,5 +132,5 @@
 ! flag to set/remove calls to groupeun
       logical callgroupeun
-      parameter (callgroupeun = .true.)
+      parameter (callgroupeun = .false.)
 
 !     added by RDW for tests without dynamics
@@ -138,4 +138,17 @@
       parameter (calldyn = .true.)
 
+!     added by RW for test
+!      real pmean,airetot
+
+!     added by FF for dissipation / energy conservation tests
+      logical dissip_conservative
+      parameter (dissip_conservative = .false.)
+      REAL ecin(ip1jmp1,llm),ecin0(ip1jmp1,llm)
+!     d (theta)/ d t (pot. temperature) due to the creation 
+!     of thermal energy by dissipation
+      REAL dtetaecdt(ip1jmp1,llm)
+      REAL vcont(ip1jm,llm),ucont(ip1jmp1,llm)
+      REAL vnat(ip1jm,llm),unat(ip1jmp1,llm)
+
 
 c-----------------------------------------------------------------------
@@ -151,9 +164,9 @@
       CALL iniadvtrac(nq,numvanle)
 
+
       CALL dynetat0("start.nc",nqmx,vcov,ucov,
      .              teta,q,masse,ps,phis, time_0)
 
       CALL defrun_new( 99, .TRUE. )
-
 
 c  on recalcule eventuellement le pas de temps
@@ -176,5 +189,4 @@
       CALL iniconst
       CALL inigeom
-
       CALL inifilr
 
@@ -192,5 +204,5 @@
       CALL exner_hyb( ip1jmp1, ps, p,beta, pks, pk, pkf )
 
-c
+
 c  numero de stockage pour les fichiers de redemarrage:
 
@@ -303,5 +315,4 @@
       CALL geopot  ( ip1jmp1, teta  , pk , pks,  phis  , phi   )
 
-
       if(calldyn)then
          CALL caldyn 
@@ -314,4 +325,6 @@
 c   -------------------------------------------------------------
 
+
+
       if (tracer) then
        IF( forward. OR . leapf )  THEN
@@ -360,4 +373,6 @@
      $            dv,du,dteta,dq,dp,vcov,ucov,teta,q,ps,masse,phis,
      $            finvmaold)
+          else
+             print*,'Currently no dynamics in this GCM...'
           endif
 
@@ -407,7 +422,11 @@
 c      ajout des tendances physiques:
 c      ------------------------------
+!        if(1.eq.2)then
           CALL addfi( nqmx, dtphys, leapf, forward   ,
      $                  ucov, vcov, teta , q   ,ps , masse,
      $                 dufi, dvfi, dhfi , dqfi ,dpfi  )
+!       else
+!          print*,'Currently no physics in this GCM...'
+!       endif
 c
        ENDIF
@@ -436,8 +455,27 @@
 c        Dissipation horizontale
 c        ~~~~~~~~~~~~~~~~~~~~~~~
+
+
+         if(dissip_conservative) then
+!     calculate kinetic energy before dissipation
+            call covcont(llm,ucov,vcov,ucont,vcont)
+            call enercin(vcov,ucov,vcont,ucont,ecin0)
+         end if
+
          CALL dissip(vcov,ucov,teta,p,dvdis,dudis,dhdis)
 
          CALL addit( ijp1llm,ucov ,dudis,ucov )
          CALL addit( ijmllm ,vcov ,dvdis,vcov )
+
+
+         if (dissip_conservative) then
+C           On rajoute la tendance due a la transform. Ec -> E therm. cree
+C           lors de la dissipation
+            call covcont(llm,ucov,vcov,ucont,vcont)
+            call enercin(vcov,ucov,vcont,ucont,ecin)
+            dtetaecdt(:,:) = (ecin0(:,:)-ecin(:,:))/ pk(:,:)
+            dhdis(:,:)     = dhdis(:,:) + dtetaecdt(:,:)
+         endif
+
          CALL addit( ijp1llm,teta ,dhdis,teta )
 
Index: /trunk/LMDZ.GENERIC/libf/dyn3d/iniadvtrac.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/dyn3d/iniadvtrac.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/dyn3d/iniadvtrac.F	(revision 253)
@@ -48,10 +48,9 @@
 
 
-!     MODIFICATION TO TEST WITHOUT TRACER ADVECTION BY RDW
-        !do iq=1,nq
-        !  iadv(iq)=0
-        !enddo
-        !print*,'TRACERS ARE NO LONGER ADVECTED IN THE GCM!!!!!!'
-
+!     MODIFICATION TO TEST OTHER SCHEMES BY RDW
+!        do iq=1,nq
+!           iadv(iq)=1
+!        enddo
+!        print*,'IADV SET TO 1 IN iniadvtrac!!!!'
 
         do iq=1,nq
Index: /trunk/LMDZ.GENERIC/libf/dyn3d/inidissip.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/dyn3d/inidissip.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/dyn3d/inidissip.F	(revision 253)
@@ -51,8 +51,15 @@
 c         FF 2004       
          if (pseudoalt(llm).lt.160.) then 
+!     currently disabled for the universal model!!!
              fac_mid=2  ! coeff  pour dissipation aux basses/moyennes altitudes
              fac_up=10 ! coeff multiplicateur pour dissipation hautes altitudes
              startalt=90. ! altitude en Km de la transition mid / up
              delta=20.! Intervalle (km) pour le changement mid / up
+
+!             fac_mid=1  ! coeff  pour dissipation aux basses/moyennes altitudes
+!             fac_up=1 ! coeff multiplicateur pour dissipation hautes altitudes
+!             startalt=100. ! altitude en Km de la transition mid / up
+!             delta=20.! Intervalle (km) pour le changement mid / up
+
          else ! thermosphere model
              fac_mid=2 ! coeff pour dissipation aux basses/moyennes altitudes
Index: /trunk/LMDZ.GENERIC/libf/dyn3d/lect_start_archive.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/dyn3d/lect_start_archive.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/dyn3d/lect_start_archive.F	(revision 253)
@@ -2,4 +2,5 @@
      &     t,ucov,vcov,ps,h,phisold_newgrid,
      &     q,qsurf,surfith,nid)
+
 c=======================================================================
 c
@@ -1102,4 +1103,8 @@
 c-----------------------------------------------------------------------
 !      write(*,*) 'Soil'
+
+      !print*,'Problem in lect_start_archive interpolating'
+      !print*,'to new resolution!!'
+
       ! Recast temperatures along soil depth, if necessary
       if (olddepthdef) then
@@ -1109,6 +1114,14 @@
         do i=1,imold+1
 	 do j=1,jmold+1
+
+            !if(i.gt.iip1 .or. j.gt.jjp1)then
+               !print*,'Problem in lect_start_archive interpolating'
+               !print*,'to new resolution!!'
+               !call abort
+            !endif
+
 	   ! copy values
-	   oldval(1)=tsurfS(i,j)
+	   oldval(1)=tsurfold(i,j)
+!	   oldval(1)=tsurfS(i,j)
 	   oldval(2:nsoilold+1)=tsoilold(i,j,1:nsoilold)
 	   ! build vertical coordinate
@@ -1142,5 +1155,6 @@
 	 do j=1,jmold+1
 	   ! copy values
-	   oldval(1)=tsurfS(i,j)
+	   oldval(1)=tsurfold(i,j)
+!	   oldval(1)=tsurfS(i,j)
 	   oldval(2:nsoilold+1)=tsoilold(i,j,1:nsoilold)
 	  ! interpolate
Index: /trunk/LMDZ.GENERIC/libf/dyn3d/logic.h
===================================================================
--- /trunk/LMDZ.GENERIC/libf/dyn3d/logic.h	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/dyn3d/logic.h	(revision 253)
@@ -3,8 +3,8 @@
 
       COMMON/logic/ purmats,physic,forward,leapf,apphys,grireg,
-     *  statcl,conser,apdiss,apdelq,saison,ecripar,fxyhypb,ysinus,hybrid
+     *  statcl,conser,apdiss,apdelq,saison,ecripar,fxyhypb,ysinus,hybrid,autozlevs
 
       LOGICAL purmats,physic,forward,leapf,apphys,grireg,statcl,conser,
-     * apdiss,apdelq,saison,ecripar,fxyhypb,ysinus,hybrid
+     * apdiss,apdelq,saison,ecripar,fxyhypb,ysinus,hybrid,autozlevs
 
 c-----------------------------------------------------------------------
Index: /trunk/LMDZ.GENERIC/libf/dyn3d/newstart.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/dyn3d/newstart.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/dyn3d/newstart.F	(revision 253)
@@ -154,4 +154,19 @@
       real :: MONS_coeffN ! coeff for northern hemisphere
 !      real,parameter :: icedepthmin=1.e-3 ! Ice begins at most at that depth
+
+!     added by RW for test
+      real pmean, phi0
+
+!     added by BC for equilibrium temperature startup
+      real teque
+
+!     added by BC for cloud fraction setup
+      REAL hice(ngridmx),cloudfrac(ngridmx,nlayermx)
+      REAL totalfrac(ngridmx)
+
+!     added by RW for nuketharsis
+      real fact1
+      real fact2
+
 
 c sortie visu pour les champs dynamiques
@@ -425,6 +440,7 @@
         CALL phyetat0 (fichnom,tab0,Lmodif,nsoilmx,nqmx,
      .        day_ini,time,
-     .        tsurf,tsoil,emis,q2,qsurf)
-        
+     .        tsurf,tsoil,emis,q2,qsurf,   !) ! temporary modif by RDW
+     .        cloudfrac,totalfrac,hice)
+
         ! copy albedo and soil thermal inertia
         do i=1,ngridmx
@@ -457,4 +473,5 @@
       write(*,*)
       write(*,*) 'flat : no topography ("aquaplanet")'
+      write(*,*) 'nuketharsis : no Tharsis bulge'
       write(*,*) 'bilball : uniform albedo and thermal inertia'
       write(*,*) 'coldspole : cold subsurface and high albedo at S.pole'
@@ -471,7 +488,11 @@
       write(*,*) 'watercapn : H20 ice on permanent N polar cap '
       write(*,*) 'watercaps : H20 ice on permanent S polar cap '
+      write(*,*) 'noacglac  : H2O ice across Noachis Terra'
       write(*,*) 'oborealis : H2O ice across Vastitas Borealis'
+      write(*,*) 'iceball   : Thick ice layer all over surface'
       write(*,*) 'wetstart  : start with a wet atmosphere'
-      write(*,*) 'isotherm : Isothermal Temperatures, wind set to zero'
+      write(*,*) 'isotherm  : Isothermal Temperatures, wind set to zero'
+      write(*,*) 'radequi   : Earth-like radiative equilibrium temperature
+     $ profile (lat-alt) and winds set to zero'
       write(*,*) 'coldstart : Start X K above the CO2 frost point and 
      $set wind to zero (assumes 100% CO2)'
@@ -479,12 +500,12 @@
       write(*,*) 'ptot : change total pressure'
       write(*,*) 'emis : change surface emissivity'
-      write(*,*) 'therm_ini_s: Set soil thermal inertia to reference sur
+      write(*,*) 'therm_ini_s : Set soil thermal inertia to reference sur
      &face values'
-      write(*,*) 'subsoilice_n: Put deep underground ice layer in northe
-     &rn hemisphere'
-      write(*,*) 'subsoilice_s: Put deep underground ice layer in southe
-     &rn hemisphere'
-      write(*,*) 'mons_ice: Put underground ice layer according to MONS-
-     &derived data'
+!      write(*,*) 'subsoilice_n : Put deep underground ice layer in northe
+!     &rn hemisphere'
+!      write(*,*) 'subsoilice_s : Put deep underground ice layer in southe
+!     &rn hemisphere'
+!      write(*,*) 'mons_ice : Put underground ice layer according to MONS-
+!     &derived data'
 
         write(*,*)
@@ -510,5 +531,5 @@
      &    ' were not set to zero ! => set calllott to F'                    
 
-c        Choice for surface pressure
+c        Choice of surface pressure
          yes=' '
          do while ((yes.ne.'y').and.(yes.ne.'n'))
@@ -533,6 +554,33 @@
          end if
 
-c       bilball : albedo, inertie thermique uniforme
-c       --------------------------------------------
+c       'nuketharsis : no tharsis bulge for Early Mars'
+c       ---------------------------------------------
+        else if (modif(1:len_trim(modif)) .eq. 'nuketharsis') then
+
+           DO j=1,jjp1        
+              DO i=1,iim
+                 ig=1+(j-2)*iim +i
+                 if(j.eq.1) ig=1
+                 if(j.eq.jjp1) ig=ngridmx
+
+                 fact1=(((rlonv(i)*180./pi)+100)**2 + 
+     &                (rlatu(j)*180./pi)**2)/65**2 
+                 fact2=exp( -fact1**2.5 )
+
+                 phis(i,j) = phis(i,j) - (phis(i,j)+4000.*g)*fact2
+
+!                 if(phis(i,j).gt.2500.*g)then
+!                    if(rlatu(j)*180./pi.gt.-80.)then ! avoid chopping south polar cap
+!                       phis(i,j)=2500.*g
+!                    endif
+!                 endif
+
+              ENDDO
+           ENDDO
+          CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,phis,phisfi)
+
+
+c       bilball : uniform albedo, thermal inertia
+c       -----------------------------------------
         else if (modif(1:len_trim(modif)) .eq. 'bilball') then
           write(*,*) 'constante albedo and iner.therm:'
@@ -654,4 +702,6 @@
              enddo
           enddo
+
+
 
 c        Correction pour la conservation des traceurs
@@ -908,4 +958,8 @@
 c      --------------------------------------------------
         else if (modif(1:len_trim(modif)) .eq. 'noglacier') then
+           if (igcm_h2o_ice.eq.0) then
+             write(*,*) "No water ice tracer! Can't use this option"
+             stop
+           endif
            do ig=1,ngridmx
              j=(ig-2)/iim +2
@@ -921,34 +975,89 @@
 c      --------------------------------------------------
         else if (modif(1:len_trim(modif)) .eq. 'watercapn') then
-           do ig=1,ngridmx
-             j=(ig-2)/iim +2
-              if(ig.eq.1) j=1
-              if (rlatu(j)*180./pi.gt.80.) then
-                   qsurf(ig,igcm_h2o_ice)=1.e5
-                   write(*,*) 'ig=',ig,'    H2O ice mass (kg/m2)= ',
-     &              qsurf(ig,igcm_h2o_ice)
-                   write(*,*)'     ==> Ice mesh South boundary (deg)= ',
-     &              rlatv(j)*180./pi
-                end if
-           enddo
+           if (igcm_h2o_ice.eq.0) then
+             write(*,*) "No water ice tracer! Can't use this option"
+             stop
+           endif
+
+           DO j=1,jjp1        
+              DO i=1,iim
+                 ig=1+(j-2)*iim +i
+                 if(j.eq.1) ig=1
+                 if(j.eq.jjp1) ig=ngridmx
+
+                 if (rlatu(j)*180./pi.gt.80.) then
+                    do isoil=1,nsoilmx
+                       ith(i,j,isoil) = 18000. ! thermal inertia
+                    enddo
+                   write(*,*)'     ==> Ice mesh North boundary (deg)= ',
+     &                   rlatv(j-1)*180./pi
+                 end if
+              ENDDO
+           ENDDO
+           CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
+
+c$$$           do ig=1,ngridmx
+c$$$             j=(ig-2)/iim +2
+c$$$              if(ig.eq.1) j=1
+c$$$              if (rlatu(j)*180./pi.gt.80.) then
+c$$$
+c$$$                   qsurf(ig,igcm_h2o_ice)=1.e5
+c$$$                   qsurf(ig,igcm_h2o_vap)=0.0!1.e5
+c$$$
+c$$$                   write(*,*) 'ig=',ig,'    H2O ice mass (kg/m2)= ',
+c$$$     &              qsurf(ig,igcm_h2o_ice)
+c$$$
+c$$$                   write(*,*)'     ==> Ice mesh South boundary (deg)= ',
+c$$$     &              rlatv(j)*180./pi
+c$$$                end if
+c$$$           enddo
 
 c      watercaps : H20 ice on permanent southern cap
 c      -------------------------------------------------
         else if (modif(1:len_trim(modif)) .eq. 'watercaps') then
-           do ig=1,ngridmx
-               j=(ig-2)/iim +2
-               if(ig.eq.1) j=1
-               if (rlatu(j)*180./pi.lt.-80.) then
-                   qsurf(ig,igcm_h2o_ice)=1.e5
-                   write(*,*) 'ig=',ig,'   H2O ice mass (kg/m2)= ',
-     &              qsurf(ig,igcm_h2o_ice)
-                   write(*,*)'     ==> Ice mesh North boundary (deg)= ',
-     &              rlatv(j-1)*180./pi
-               end if
-           enddo
-
-c       oborealis : H2O ice across Vastitas Borealis
+           if (igcm_h2o_ice.eq.0) then
+              write(*,*) "No water ice tracer! Can't use this option"
+              stop
+           endif
+
+           DO j=1,jjp1        
+              DO i=1,iim
+                 ig=1+(j-2)*iim +i
+                 if(j.eq.1) ig=1
+                 if(j.eq.jjp1) ig=ngridmx
+
+                 if (rlatu(j)*180./pi.lt.-80.) then
+                    do isoil=1,nsoilmx
+                       ith(i,j,isoil) = 18000. ! thermal inertia
+                    enddo
+                   write(*,*)'     ==> Ice mesh South boundary (deg)= ',
+     &                   rlatv(j-1)*180./pi
+                 end if
+              ENDDO
+           ENDDO
+           CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
+
+c$$$           do ig=1,ngridmx
+c$$$               j=(ig-2)/iim +2
+c$$$               if(ig.eq.1) j=1
+c$$$               if (rlatu(j)*180./pi.lt.-80.) then
+c$$$                  qsurf(ig,igcm_h2o_ice)=1.e5
+c$$$                  qsurf(ig,igcm_h2o_vap)=0.0 !1.e5
+c$$$
+c$$$                  write(*,*) 'ig=',ig,'   H2O ice mass (kg/m2)= ',
+c$$$     &                 qsurf(ig,igcm_h2o_ice)
+c$$$                  write(*,*)'     ==> Ice mesh North boundary (deg)= ',
+c$$$     &                 rlatv(j-1)*180./pi
+c$$$               end if
+c$$$           enddo
+
+
+c       noacglac : H2O ice across highest terrain
 c       --------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'oborealis') then
+        else if (modif(1:len_trim(modif)) .eq. 'noacglac') then
+           if (igcm_h2o_ice.eq.0) then
+             write(*,*) "No water ice tracer! Can't use this option"
+             stop
+           endif
           DO j=1,jjp1        
              DO i=1,iim
@@ -957,13 +1066,133 @@
                 if(j.eq.jjp1) ig=ngridmx
 
-                if(phis(i,j).lt.-4000.)then
-                    qsurf(ig,igcm_h2o_ice)=1.e5
-                    phis(i,j)=-4000.0
+                if(phis(i,j).gt.1000.*g)then
+                    alb(i,j) = 0.5 ! snow value
+                    do isoil=1,nsoilmx
+                       ith(i,j,isoil) = 18000. ! thermal inertia
+                       ! this leads to rnat set to 'ocean' in physiq.F90
+                       ! actually no, because it is soil not surface
+                    enddo
                 endif
              ENDDO
           ENDDO
+          CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
+          CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,alb,albfi)
+          CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,phis,phisfi)
+
+
+
+c       oborealis : H2O oceans across Vastitas Borealis
+c       -----------------------------------------------
+        else if (modif(1:len_trim(modif)) .eq. 'oborealis') then
+           if (igcm_h2o_ice.eq.0) then
+             write(*,*) "No water ice tracer! Can't use this option"
+             stop
+           endif
+          DO j=1,jjp1        
+             DO i=1,iim
+                ig=1+(j-2)*iim +i
+                if(j.eq.1) ig=1
+                if(j.eq.jjp1) ig=ngridmx
+
+                if(phis(i,j).lt.-4000.*g)then
+!                if( (phis(i,j).lt.-4000.*g)
+!     &               .and. (rlatu(j)*180./pi.lt.0.) )then ! south hemisphere only
+!                    phis(i,j)=-8000.0*g ! proper ocean
+                    phis(i,j)=-4000.0*g ! scanty ocean
+
+                    alb(i,j) = 0.07 ! oceanic value
+                    do isoil=1,nsoilmx
+                       ith(i,j,isoil) = 18000. ! thermal inertia
+                       ! this leads to rnat set to 'ocean' in physiq.F90
+                       ! actually no, because it is soil not surface
+                    enddo
+                endif
+             ENDDO
+          ENDDO
+          CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
+          CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,alb,albfi)
+          CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,phis,phisfi)
+
+c       iborealis : H2O ice in Northern plains
+c       --------------------------------------
+        else if (modif(1:len_trim(modif)) .eq. 'iborealis') then
+           if (igcm_h2o_ice.eq.0) then
+             write(*,*) "No water ice tracer! Can't use this option"
+             stop
+           endif
+          DO j=1,jjp1        
+             DO i=1,iim
+                ig=1+(j-2)*iim +i
+                if(j.eq.1) ig=1
+                if(j.eq.jjp1) ig=ngridmx
+
+                if(phis(i,j).lt.-4000.*g)then
+                   qsurf(ig,igcm_h2o_ice)=1.e3
+                endif
+             ENDDO
+          ENDDO
+          CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
+          CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,alb,albfi)
+          CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,phis,phisfi)
+
+
+c       oceanball : H2O liquid everywhere
+c       ----------------------------
+        else if (modif(1:len_trim(modif)) .eq. 'oceanball') then
+           if (igcm_h2o_ice.eq.0) then
+             write(*,*) "No water ice tracer! Can't use this option"
+             stop
+           endif
+          DO j=1,jjp1        
+             DO i=1,iim
+                ig=1+(j-2)*iim +i
+                if(j.eq.1) ig=1
+                if(j.eq.jjp1) ig=ngridmx
+
+                qsurf(ig,igcm_h2o_vap)=0.0    ! for ocean, this is infinite source
+                qsurf(ig,igcm_h2o_ice)=0.0
+                alb(i,j) = 0.07 ! ocean value
+
+                do isoil=1,nsoilmx
+                   ith(i,j,isoil) = 18000. ! thermal inertia
+                   !ith(i,j,isoil) = 50. ! extremely low for test
+                   ! this leads to rnat set to 'ocean' in physiq.F90
+                enddo
+
+             ENDDO
+          ENDDO
+          CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
+          CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,alb,albfi)
+          CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,phis,phisfi)
+
+c       iceball : H2O ice everywhere
+c       ----------------------------
+        else if (modif(1:len_trim(modif)) .eq. 'iceball') then
+           if (igcm_h2o_ice.eq.0) then
+             write(*,*) "No water ice tracer! Can't use this option"
+             stop
+           endif
+          DO j=1,jjp1        
+             DO i=1,iim
+                ig=1+(j-2)*iim +i
+                if(j.eq.1) ig=1
+                if(j.eq.jjp1) ig=ngridmx
+
+                qsurf(ig,igcm_h2o_vap)=-50.    ! for ocean, this is infinite source
+                qsurf(ig,igcm_h2o_ice)=50.     ! == to 0.05 m of oceanic ice
+                alb(i,j) = 0.6 ! ice albedo value
+
+                do isoil=1,nsoilmx
+                   !ith(i,j,isoil) = 18000. ! thermal inertia
+                   ! this leads to rnat set to 'ocean' in physiq.F90
+                enddo
+
+             ENDDO
+          ENDDO
+          CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
+          CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,alb,albfi)
 
 c       isotherm : Isothermal temperatures and no winds
-c       ------------------------------------------------
+c       -----------------------------------------------
         else if (modif(1:len_trim(modif)) .eq. 'isotherm') then
 
@@ -994,4 +1223,33 @@
           call initial0(ngridmx*(llm+1),q2)
 
+c       radequi : Radiative equilibrium profile of temperatures and no winds
+c       --------------------------------------------------------------------
+        else if (modif(1:len_trim(modif)) .eq. 'radequi') then
+
+          write(*,*)'radiative equilibrium temperature profile'       
+
+          do ig=1, ngridmx
+             teque= 335.0-60.0*sin(latfi(ig))*sin(latfi(ig))-
+     &            10.0*cos(latfi(ig))*cos(latfi(ig))
+             tsurf(ig) = MAX(220.0,teque)
+          end do
+          do l=2,nsoilmx
+             do ig=1, ngridmx
+                tsoil(ig,l) = tsurf(ig)
+             end do
+          end do
+          DO j=1,jjp1
+             DO i=1,iim
+                Do l=1,llm
+                   teque=335.-60.0*sin(rlatu(j))*sin(rlatu(j))-
+     &                  10.0*cos(rlatu(j))*cos(rlatu(j))
+                   Tset(i,j,l)=MAX(220.0,teque)
+                end do
+             end do
+          end do
+          flagtset=.true.
+          call initial0(llm*ip1jmp1,ucov)
+          call initial0(llm*ip1jm,vcov)
+          call initial0(ngridmx*(llm+1),q2)
 
 c       coldstart : T set 1K above CO2 frost point and no winds
@@ -1069,317 +1327,331 @@
 !	 enddo
 
-!       subsoilice_n: Put deep ice layer in northern hemisphere soil
-!       ------------------------------------------------------------
-
-	else if (modif(1:len_trim(modif)).eq.'subsoilice_n') then
-
-         write(*,*)'From which latitude (in deg.), up to the north pole,
-     &should we put subterranean ice?'
-	 ierr=1
-	 do while (ierr.ne.0)
-	  read(*,*,iostat=ierr) val
-	  if (ierr.eq.0) then ! got a value
-	    ! do a sanity check
-	    if((val.lt.0.).or.(val.gt.90)) then
-	      write(*,*)'Latitude should be between 0 and 90 deg. !!!'
-	      ierr=1
-	    else ! find corresponding jref (nearest latitude)
-	      ! note: rlatu(:) contains decreasing values of latitude
-	      !       starting from PI/2 to -PI/2
-	      do j=1,jjp1
-	        if ((rlatu(j)*180./pi.ge.val).and.
-     &              (rlatu(j+1)*180./pi.le.val)) then
-		  ! find which grid point is nearest to val:
-		  if (abs(rlatu(j)*180./pi-val).le.
-     &                abs((rlatu(j+1)*180./pi-val))) then
-		   jref=j
-		  else
-		   jref=j+1
-		  endif
-		 
-		 write(*,*)'Will use nearest grid latitude which is:',
-     &                     rlatu(jref)*180./pi
-		endif
-	      enddo ! of do j=1,jjp1
-	    endif ! of if((val.lt.0.).or.(val.gt.90))
-	  endif !of if (ierr.eq.0)
-	 enddo ! of do while
-
-         ! Build layers() (as in soil_settings.F)
-	 val2=sqrt(mlayer(0)*mlayer(1))
-	 val3=mlayer(1)/mlayer(0)
-	 do isoil=1,nsoilmx
-	   layer(isoil)=val2*(val3**(isoil-1))
-	 enddo
-
-         write(*,*)'At which depth (in m.) does the ice layer begin?'
-         write(*,*)'(currently, the deepest soil layer extends down to:'
-     &              ,layer(nsoilmx),')'
-	 ierr=1
-	 do while (ierr.ne.0)
-	  read(*,*,iostat=ierr) val2
-!	  write(*,*)'val2:',val2,'ierr=',ierr
-	  if (ierr.eq.0) then ! got a value, but do a sanity check
-	    if(val2.gt.layer(nsoilmx)) then
-	      write(*,*)'Depth should be less than ',layer(nsoilmx)
-	      ierr=1
-	    endif
-	    if(val2.lt.layer(1)) then
-	      write(*,*)'Depth should be more than ',layer(1)
-	      ierr=1
-	    endif
-	  endif
-         enddo ! of do while
-	 
-	 ! find the reference index iref the depth corresponds to
-!	 if (val2.lt.layer(1)) then
-!	  iref=1
-!	 else
-	  do isoil=1,nsoilmx-1
-	   if((val2.gt.layer(isoil)).and.(val2.lt.layer(isoil+1)))
-     &       then
-	     iref=isoil
-	     exit
-	   endif
-	  enddo
-!	 endif
-	 
-!	 write(*,*)'iref:',iref,'  jref:',jref
-!	 write(*,*)'layer',layer
-!	 write(*,*)'mlayer',mlayer
-         
-	 ! thermal inertia of the ice:
-	 ierr=1
-	 do while (ierr.ne.0)
-          write(*,*)'What is the value of subterranean ice thermal inert
-     &ia? (e.g.: 2000)'
-          read(*,*,iostat=ierr)iceith
-	 enddo ! of do while
-	 
-	 ! recast ithfi() onto ith()
-	 call gr_fi_dyn(nsoilmx,ngridmx,iip1,jjp1,ithfi,ith)
-	 
-	 do j=1,jref
-!	    write(*,*)'j:',j,'rlatu(j)*180./pi:',rlatu(j)*180./pi
-	    do i=1,iip1 ! loop on longitudes
-	     ! Build "equivalent" thermal inertia for the mixed layer
-	     ith(i,j,iref+1)=sqrt((layer(iref+1)-layer(iref))/
-     &                     (((val2-layer(iref))/(ith(i,j,iref)**2))+
-     &                      ((layer(iref+1)-val2)/(iceith)**2)))
-	     ! Set thermal inertia of lower layers
-	     do isoil=iref+2,nsoilmx
-	      ith(i,j,isoil)=iceith ! ice
-	     enddo
-	    enddo ! of do i=1,iip1 
-	 enddo ! of do j=1,jjp1
-	 
-
-	 CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
-
-!         do i=1,nsoilmx
-!	  write(*,*)'i:',i,'ithfi(1,i):',ithfi(1,i)
-!	 enddo
+
+
+
+c$$$!       subsoilice_n: Put deep ice layer in northern hemisphere soil
+c$$$!       ------------------------------------------------------------
+c$$$
+c$$$	else if (modif(1:len_trim(modif)).eq.'subsoilice_n') then
+c$$$
+c$$$         write(*,*)'From which latitude (in deg.), up to the north pole,
+c$$$     &should we put subterranean ice?'
+c$$$	 ierr=1
+c$$$	 do while (ierr.ne.0)
+c$$$	  read(*,*,iostat=ierr) val
+c$$$	  if (ierr.eq.0) then ! got a value
+c$$$	    ! do a sanity check
+c$$$	    if((val.lt.0.).or.(val.gt.90)) then
+c$$$	      write(*,*)'Latitude should be between 0 and 90 deg. !!!'
+c$$$	      ierr=1
+c$$$	    else ! find corresponding jref (nearest latitude)
+c$$$	      ! note: rlatu(:) contains decreasing values of latitude
+c$$$	      !       starting from PI/2 to -PI/2
+c$$$	      do j=1,jjp1
+c$$$	        if ((rlatu(j)*180./pi.ge.val).and.
+c$$$     &              (rlatu(j+1)*180./pi.le.val)) then
+c$$$		  ! find which grid point is nearest to val:
+c$$$		  if (abs(rlatu(j)*180./pi-val).le.
+c$$$     &                abs((rlatu(j+1)*180./pi-val))) then
+c$$$		   jref=j
+c$$$		  else
+c$$$		   jref=j+1
+c$$$		  endif
+c$$$		 
+c$$$		 write(*,*)'Will use nearest grid latitude which is:',
+c$$$     &                     rlatu(jref)*180./pi
+c$$$		endif
+c$$$	      enddo ! of do j=1,jjp1
+c$$$	    endif ! of if((val.lt.0.).or.(val.gt.90))
+c$$$	  endif !of if (ierr.eq.0)
+c$$$	 enddo ! of do while
+c$$$
+c$$$         ! Build layers() (as in soil_settings.F)
+c$$$	 val2=sqrt(mlayer(0)*mlayer(1))
+c$$$	 val3=mlayer(1)/mlayer(0)
+c$$$	 do isoil=1,nsoilmx
+c$$$	   layer(isoil)=val2*(val3**(isoil-1))
+c$$$	 enddo
+c$$$
+c$$$         write(*,*)'At which depth (in m.) does the ice layer begin?'
+c$$$         write(*,*)'(currently, the deepest soil layer extends down to:'
+c$$$     &              ,layer(nsoilmx),')'
+c$$$	 ierr=1
+c$$$	 do while (ierr.ne.0)
+c$$$	  read(*,*,iostat=ierr) val2
+c$$$!	  write(*,*)'val2:',val2,'ierr=',ierr
+c$$$	  if (ierr.eq.0) then ! got a value, but do a sanity check
+c$$$	    if(val2.gt.layer(nsoilmx)) then
+c$$$	      write(*,*)'Depth should be less than ',layer(nsoilmx)
+c$$$	      ierr=1
+c$$$	    endif
+c$$$	    if(val2.lt.layer(1)) then
+c$$$	      write(*,*)'Depth should be more than ',layer(1)
+c$$$	      ierr=1
+c$$$	    endif
+c$$$	  endif
+c$$$         enddo ! of do while
+c$$$	 
+c$$$	 ! find the reference index iref the depth corresponds to
+c$$$!	 if (val2.lt.layer(1)) then
+c$$$!	  iref=1
+c$$$!	 else
+c$$$	  do isoil=1,nsoilmx-1
+c$$$	   if((val2.gt.layer(isoil)).and.(val2.lt.layer(isoil+1)))
+c$$$     &       then
+c$$$	     iref=isoil
+c$$$	     exit
+c$$$	   endif
+c$$$	  enddo
+c$$$!	 endif
+c$$$	 
+c$$$!	 write(*,*)'iref:',iref,'  jref:',jref
+c$$$!	 write(*,*)'layer',layer
+c$$$!	 write(*,*)'mlayer',mlayer
+c$$$         
+c$$$	 ! thermal inertia of the ice:
+c$$$	 ierr=1
+c$$$	 do while (ierr.ne.0)
+c$$$          write(*,*)'What is the value of subterranean ice thermal inert
+c$$$     &ia? (e.g.: 2000)'
+c$$$          read(*,*,iostat=ierr)iceith
+c$$$	 enddo ! of do while
+c$$$	 
+c$$$	 ! recast ithfi() onto ith()
+c$$$	 call gr_fi_dyn(nsoilmx,ngridmx,iip1,jjp1,ithfi,ith)
+c$$$	 
+c$$$	 do j=1,jref
+c$$$!	    write(*,*)'j:',j,'rlatu(j)*180./pi:',rlatu(j)*180./pi
+c$$$	    do i=1,iip1 ! loop on longitudes
+c$$$	     ! Build "equivalent" thermal inertia for the mixed layer
+c$$$	     ith(i,j,iref+1)=sqrt((layer(iref+1)-layer(iref))/
+c$$$     &                     (((val2-layer(iref))/(ith(i,j,iref)**2))+
+c$$$     &                      ((layer(iref+1)-val2)/(iceith)**2)))
+c$$$	     ! Set thermal inertia of lower layers
+c$$$	     do isoil=iref+2,nsoilmx
+c$$$	      ith(i,j,isoil)=iceith ! ice
+c$$$	     enddo
+c$$$	    enddo ! of do i=1,iip1 
+c$$$	 enddo ! of do j=1,jjp1
+c$$$	 
+c$$$
+c$$$	 CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
+c$$$
+c$$$!         do i=1,nsoilmx
+c$$$!	  write(*,*)'i:',i,'ithfi(1,i):',ithfi(1,i)
+c$$$!	 enddo
 
 	
-!       subsoilice_s: Put deep ice layer in southern hemisphere soil
-!       ------------------------------------------------------------
-
-	else if (modif(1:len_trim(modif)).eq.'subsoilice_s') then
-
-         write(*,*)'From which latitude (in deg.), down to the south pol
-     &e, should we put subterranean ice?'
-	 ierr=1
-	 do while (ierr.ne.0)
-	  read(*,*,iostat=ierr) val
-	  if (ierr.eq.0) then ! got a value
-	    ! do a sanity check
-	    if((val.gt.0.).or.(val.lt.-90)) then
-	      write(*,*)'Latitude should be between 0 and -90 deg. !!!'
-	      ierr=1
-	    else ! find corresponding jref (nearest latitude)
-	      ! note: rlatu(:) contains decreasing values of latitude
-	      !       starting from PI/2 to -PI/2
-	      do j=1,jjp1
-	        if ((rlatu(j)*180./pi.ge.val).and.
-     &              (rlatu(j+1)*180./pi.le.val)) then
-		  ! find which grid point is nearest to val:
-		  if (abs(rlatu(j)*180./pi-val).le.
-     &                abs((rlatu(j+1)*180./pi-val))) then
-		   jref=j
-		  else
-		   jref=j+1
-		  endif
-		 
-		 write(*,*)'Will use nearest grid latitude which is:',
-     &                     rlatu(jref)*180./pi
-		endif
-	      enddo ! of do j=1,jjp1
-	    endif ! of if((val.lt.0.).or.(val.gt.90))
-	  endif !of if (ierr.eq.0)
-	 enddo ! of do while
-
-         ! Build layers() (as in soil_settings.F)
-	 val2=sqrt(mlayer(0)*mlayer(1))
-	 val3=mlayer(1)/mlayer(0)
-	 do isoil=1,nsoilmx
-	   layer(isoil)=val2*(val3**(isoil-1))
-	 enddo
-
-         write(*,*)'At which depth (in m.) does the ice layer begin?'
-         write(*,*)'(currently, the deepest soil layer extends down to:'
-     &              ,layer(nsoilmx),')'
-	 ierr=1
-	 do while (ierr.ne.0)
-	  read(*,*,iostat=ierr) val2
-!	  write(*,*)'val2:',val2,'ierr=',ierr
-	  if (ierr.eq.0) then ! got a value, but do a sanity check
-	    if(val2.gt.layer(nsoilmx)) then
-	      write(*,*)'Depth should be less than ',layer(nsoilmx)
-	      ierr=1
-	    endif
-	    if(val2.lt.layer(1)) then
-	      write(*,*)'Depth should be more than ',layer(1)
-	      ierr=1
-	    endif
-	  endif
-         enddo ! of do while
-	 
-	 ! find the reference index iref the depth corresponds to
-	  do isoil=1,nsoilmx-1
-	   if((val2.gt.layer(isoil)).and.(val2.lt.layer(isoil+1)))
-     &       then
-	     iref=isoil
-	     exit
-	   endif
-	  enddo
-	 
-!	 write(*,*)'iref:',iref,'  jref:',jref
-         
-	 ! thermal inertia of the ice:
-	 ierr=1
-	 do while (ierr.ne.0)
-          write(*,*)'What is the value of subterranean ice thermal inert
-     &ia? (e.g.: 2000)'
-          read(*,*,iostat=ierr)iceith
-	 enddo ! of do while
-	 
-	 ! recast ithfi() onto ith()
-	 call gr_fi_dyn(nsoilmx,ngridmx,iip1,jjp1,ithfi,ith)
-	 
-	 do j=jref,jjp1
-!	    write(*,*)'j:',j,'rlatu(j)*180./pi:',rlatu(j)*180./pi
-	    do i=1,iip1 ! loop on longitudes
-	     ! Build "equivalent" thermal inertia for the mixed layer
-	     ith(i,j,iref+1)=sqrt((layer(iref+1)-layer(iref))/
-     &                     (((val2-layer(iref))/(ith(i,j,iref)**2))+
-     &                      ((layer(iref+1)-val2)/(iceith)**2)))
-	     ! Set thermal inertia of lower layers
-	     do isoil=iref+2,nsoilmx
-	      ith(i,j,isoil)=iceith ! ice
-	     enddo
-	    enddo ! of do i=1,iip1 
-	 enddo ! of do j=jref,jjp1
-	 
-
-	 CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
-
-c       'mons_ice' : use MONS data to build subsurface ice table
-c       --------------------------------------------------------
-        else if (modif(1:len_trim(modif)).eq.'mons_ice') then
-        
-       ! 1. Load MONS data
-        call load_MONS_data(MONS_Hdn,MONS_d21)
-        
-        ! 2. Get parameters from user
-        ierr=1
-	do while (ierr.ne.0)
-          write(*,*) "Coefficient to apply to MONS 'depth' in Northern",
-     &               " Hemisphere?"
-          write(*,*) " (should be somewhere between 3.2e-4 and 1.3e-3)"
-          read(*,*,iostat=ierr) MONS_coeffN
-        enddo
-        ierr=1
-	do while (ierr.ne.0)
-          write(*,*) "Coefficient to apply to MONS 'depth' in Southern",
-     &               " Hemisphere?"
-          write(*,*) " (should be somewhere between 3.2e-4 and 1.3e-3)"
-          read(*,*,iostat=ierr) MONS_coeffS
-        enddo
-        ierr=1
-        do while (ierr.ne.0)
-          write(*,*) "Value of subterranean ice thermal inertia?"
-          write(*,*) " (e.g.: 2000, or perhaps 2290)"
-          read(*,*,iostat=ierr) iceith
-        enddo
-        
-        ! 3. Build subterranean thermal inertia
-        
-        ! initialise subsurface inertia with reference surface values
-        do isoil=1,nsoilmx
-          ithfi(1:ngridmx,isoil)=surfithfi(1:ngridmx)
-        enddo
-        ! recast ithfi() onto ith()
-	call gr_fi_dyn(nsoilmx,ngridmx,iip1,jjp1,ithfi,ith)
-        
-        do i=1,iip1 ! loop on longitudes
-          do j=1,jjp1 ! loop on latitudes
-            ! set MONS_coeff
-            if (rlatu(j).ge.0) then ! northern hemisphere
-              ! N.B: rlatu(:) contains decreasing values of latitude
-	      !       starting from PI/2 to -PI/2
-              MONS_coeff=MONS_coeffN
-            else ! southern hemisphere
-              MONS_coeff=MONS_coeffS
-            endif
-            ! check if we should put subterranean ice
-            if (MONS_Hdn(i,j).ge.14.0) then ! no ice if Hdn<14%
-              ! compute depth at which ice lies:
-              val=MONS_d21(i,j)*MONS_coeff
-              ! compute val2= the diurnal skin depth of surface inertia
-              ! assuming a volumetric heat cap. of C=1.e6 J.m-3.K-1
-              val2=ith(i,j,1)*1.e-6*sqrt(88775./3.14159)
-              if (val.lt.val2) then
-                ! ice must be below the (surface inertia) diurnal skin depth
-                val=val2
-              endif
-              if (val.lt.layer(nsoilmx)) then ! subterranean ice
-                ! find the reference index iref that depth corresponds to
-                iref=0
-                do isoil=1,nsoilmx-1
-                 if ((val.ge.layer(isoil)).and.(val.lt.layer(isoil+1)))
-     &             then
-	           iref=isoil
-	           exit
-	         endif
-                enddo
-                ! Build "equivalent" thermal inertia for the mixed layer
-                ith(i,j,iref+1)=sqrt((layer(iref+1)-layer(iref))/
-     &                     (((val-layer(iref))/(ith(i,j,iref+1)**2))+
-     &                      ((layer(iref+1)-val)/(iceith)**2)))
-	        ! Set thermal inertia of lower layers
-                do isoil=iref+2,nsoilmx
-                  ith(i,j,isoil)=iceith 
-                enddo
-              endif ! of if (val.lt.layer(nsoilmx))
-            endif ! of if (MONS_Hdn(i,j).lt.14.0)
-          enddo ! do j=1,jjp1
-        enddo ! do i=1,iip1
-        
-! Check:
-!         do i=1,iip1
-!           do j=1,jjp1
-!             do isoil=1,nsoilmx
-!               write(77,*) i,j,isoil,"  ",ith(i,j,isoil)
-!             enddo
-!           enddo
-!	 enddo
-
-        ! recast ith() into ithfi()
-        CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
-        
-	else
-          write(*,*) '       Unknown (misspelled?) option!!!'
+c$$$!       subsoilice_s: Put deep ice layer in southern hemisphere soil
+c$$$!       ------------------------------------------------------------
+c$$$
+c$$$	else if (modif(1:len_trim(modif)).eq.'subsoilice_s') then
+c$$$
+c$$$         write(*,*)'From which latitude (in deg.), down to the south pol
+c$$$     &e, should we put subterranean ice?'
+c$$$	 ierr=1
+c$$$	 do while (ierr.ne.0)
+c$$$	  read(*,*,iostat=ierr) val
+c$$$	  if (ierr.eq.0) then ! got a value
+c$$$	    ! do a sanity check
+c$$$	    if((val.gt.0.).or.(val.lt.-90)) then
+c$$$	      write(*,*)'Latitude should be between 0 and -90 deg. !!!'
+c$$$	      ierr=1
+c$$$	    else ! find corresponding jref (nearest latitude)
+c$$$	      ! note: rlatu(:) contains decreasing values of latitude
+c$$$	      !       starting from PI/2 to -PI/2
+c$$$	      do j=1,jjp1
+c$$$	        if ((rlatu(j)*180./pi.ge.val).and.
+c$$$     &              (rlatu(j+1)*180./pi.le.val)) then
+c$$$		  ! find which grid point is nearest to val:
+c$$$		  if (abs(rlatu(j)*180./pi-val).le.
+c$$$     &                abs((rlatu(j+1)*180./pi-val))) then
+c$$$		   jref=j
+c$$$		  else
+c$$$		   jref=j+1
+c$$$		  endif
+c$$$		 
+c$$$		 write(*,*)'Will use nearest grid latitude which is:',
+c$$$     &                     rlatu(jref)*180./pi
+c$$$		endif
+c$$$	      enddo ! of do j=1,jjp1
+c$$$	    endif ! of if((val.lt.0.).or.(val.gt.90))
+c$$$	  endif !of if (ierr.eq.0)
+c$$$	 enddo ! of do while
+c$$$
+c$$$         ! Build layers() (as in soil_settings.F)
+c$$$	 val2=sqrt(mlayer(0)*mlayer(1))
+c$$$	 val3=mlayer(1)/mlayer(0)
+c$$$	 do isoil=1,nsoilmx
+c$$$	   layer(isoil)=val2*(val3**(isoil-1))
+c$$$	 enddo
+c$$$
+c$$$         write(*,*)'At which depth (in m.) does the ice layer begin?'
+c$$$         write(*,*)'(currently, the deepest soil layer extends down to:'
+c$$$     &              ,layer(nsoilmx),')'
+c$$$	 ierr=1
+c$$$	 do while (ierr.ne.0)
+c$$$	  read(*,*,iostat=ierr) val2
+c$$$!	  write(*,*)'val2:',val2,'ierr=',ierr
+c$$$	  if (ierr.eq.0) then ! got a value, but do a sanity check
+c$$$	    if(val2.gt.layer(nsoilmx)) then
+c$$$	      write(*,*)'Depth should be less than ',layer(nsoilmx)
+c$$$	      ierr=1
+c$$$	    endif
+c$$$	    if(val2.lt.layer(1)) then
+c$$$	      write(*,*)'Depth should be more than ',layer(1)
+c$$$	      ierr=1
+c$$$	    endif
+c$$$	  endif
+c$$$         enddo ! of do while
+c$$$	 
+c$$$	 ! find the reference index iref the depth corresponds to
+c$$$	  do isoil=1,nsoilmx-1
+c$$$	   if((val2.gt.layer(isoil)).and.(val2.lt.layer(isoil+1)))
+c$$$     &       then
+c$$$	     iref=isoil
+c$$$	     exit
+c$$$	   endif
+c$$$	  enddo
+c$$$	 
+c$$$!	 write(*,*)'iref:',iref,'  jref:',jref
+c$$$         
+c$$$	 ! thermal inertia of the ice:
+c$$$	 ierr=1
+c$$$	 do while (ierr.ne.0)
+c$$$          write(*,*)'What is the value of subterranean ice thermal inert
+c$$$     &ia? (e.g.: 2000)'
+c$$$          read(*,*,iostat=ierr)iceith
+c$$$	 enddo ! of do while
+c$$$	 
+c$$$	 ! recast ithfi() onto ith()
+c$$$	 call gr_fi_dyn(nsoilmx,ngridmx,iip1,jjp1,ithfi,ith)
+c$$$	 
+c$$$	 do j=jref,jjp1
+c$$$!	    write(*,*)'j:',j,'rlatu(j)*180./pi:',rlatu(j)*180./pi
+c$$$	    do i=1,iip1 ! loop on longitudes
+c$$$	     ! Build "equivalent" thermal inertia for the mixed layer
+c$$$	     ith(i,j,iref+1)=sqrt((layer(iref+1)-layer(iref))/
+c$$$     &                     (((val2-layer(iref))/(ith(i,j,iref)**2))+
+c$$$     &                      ((layer(iref+1)-val2)/(iceith)**2)))
+c$$$	     ! Set thermal inertia of lower layers
+c$$$	     do isoil=iref+2,nsoilmx
+c$$$	      ith(i,j,isoil)=iceith ! ice
+c$$$	     enddo
+c$$$	    enddo ! of do i=1,iip1 
+c$$$	 enddo ! of do j=jref,jjp1
+c$$$	 
+c$$$
+c$$$	 CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
+
+
+c$$$c       'mons_ice' : use MONS data to build subsurface ice table
+c$$$c       --------------------------------------------------------
+c$$$        else if (modif(1:len_trim(modif)).eq.'mons_ice') then
+c$$$        
+c$$$       ! 1. Load MONS data
+c$$$        call load_MONS_data(MONS_Hdn,MONS_d21)
+c$$$        
+c$$$        ! 2. Get parameters from user
+c$$$        ierr=1
+c$$$	do while (ierr.ne.0)
+c$$$          write(*,*) "Coefficient to apply to MONS 'depth' in Northern",
+c$$$     &               " Hemisphere?"
+c$$$          write(*,*) " (should be somewhere between 3.2e-4 and 1.3e-3)"
+c$$$          read(*,*,iostat=ierr) MONS_coeffN
+c$$$        enddo
+c$$$        ierr=1
+c$$$	do while (ierr.ne.0)
+c$$$          write(*,*) "Coefficient to apply to MONS 'depth' in Southern",
+c$$$     &               " Hemisphere?"
+c$$$          write(*,*) " (should be somewhere between 3.2e-4 and 1.3e-3)"
+c$$$          read(*,*,iostat=ierr) MONS_coeffS
+c$$$        enddo
+c$$$        ierr=1
+c$$$        do while (ierr.ne.0)
+c$$$          write(*,*) "Value of subterranean ice thermal inertia?"
+c$$$          write(*,*) " (e.g.: 2000, or perhaps 2290)"
+c$$$          read(*,*,iostat=ierr) iceith
+c$$$        enddo
+c$$$        
+c$$$        ! 3. Build subterranean thermal inertia
+c$$$        
+c$$$        ! initialise subsurface inertia with reference surface values
+c$$$        do isoil=1,nsoilmx
+c$$$          ithfi(1:ngridmx,isoil)=surfithfi(1:ngridmx)
+c$$$        enddo
+c$$$        ! recast ithfi() onto ith()
+c$$$	call gr_fi_dyn(nsoilmx,ngridmx,iip1,jjp1,ithfi,ith)
+c$$$        
+c$$$        do i=1,iip1 ! loop on longitudes
+c$$$          do j=1,jjp1 ! loop on latitudes
+c$$$            ! set MONS_coeff
+c$$$            if (rlatu(j).ge.0) then ! northern hemisphere
+c$$$              ! N.B: rlatu(:) contains decreasing values of latitude
+c$$$	      !       starting from PI/2 to -PI/2
+c$$$              MONS_coeff=MONS_coeffN
+c$$$            else ! southern hemisphere
+c$$$              MONS_coeff=MONS_coeffS
+c$$$            endif
+c$$$            ! check if we should put subterranean ice
+c$$$            if (MONS_Hdn(i,j).ge.14.0) then ! no ice if Hdn<14%
+c$$$              ! compute depth at which ice lies:
+c$$$              val=MONS_d21(i,j)*MONS_coeff
+c$$$              ! compute val2= the diurnal skin depth of surface inertia
+c$$$              ! assuming a volumetric heat cap. of C=1.e6 J.m-3.K-1
+c$$$              val2=ith(i,j,1)*1.e-6*sqrt(88775./3.14159)
+c$$$              if (val.lt.val2) then
+c$$$                ! ice must be below the (surface inertia) diurnal skin depth
+c$$$                val=val2
+c$$$              endif
+c$$$              if (val.lt.layer(nsoilmx)) then ! subterranean ice
+c$$$                ! find the reference index iref that depth corresponds to
+c$$$                iref=0
+c$$$                do isoil=1,nsoilmx-1
+c$$$                 if ((val.ge.layer(isoil)).and.(val.lt.layer(isoil+1)))
+c$$$     &             then
+c$$$	           iref=isoil
+c$$$	           exit
+c$$$	         endif
+c$$$                enddo
+c$$$                ! Build "equivalent" thermal inertia for the mixed layer
+c$$$                ith(i,j,iref+1)=sqrt((layer(iref+1)-layer(iref))/
+c$$$     &                     (((val-layer(iref))/(ith(i,j,iref+1)**2))+
+c$$$     &                      ((layer(iref+1)-val)/(iceith)**2)))
+c$$$	        ! Set thermal inertia of lower layers
+c$$$                do isoil=iref+2,nsoilmx
+c$$$                  ith(i,j,isoil)=iceith 
+c$$$                enddo
+c$$$              endif ! of if (val.lt.layer(nsoilmx))
+c$$$            endif ! of if (MONS_Hdn(i,j).lt.14.0)
+c$$$          enddo ! do j=1,jjp1
+c$$$        enddo ! do i=1,iip1
+c$$$        
+c$$$! Check:
+c$$$!         do i=1,iip1
+c$$$!           do j=1,jjp1
+c$$$!             do isoil=1,nsoilmx
+c$$$!               write(77,*) i,j,isoil,"  ",ith(i,j,isoil)
+c$$$!             enddo
+c$$$!           enddo
+c$$$!	 enddo
+c$$$
+c$$$        ! recast ith() into ithfi()
+c$$$        CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
+c$$$        
+c$$$	else
+c$$$          write(*,*) '       Unknown (misspelled?) option!!!'
         end if ! of if (modif(1:len_trim(modif)) .eq. '...') elseif ...
 	
+
+
+
+
+
+
+
+
+
+
        enddo ! of do ! infinite loop on liste of changes
 
@@ -1387,4 +1659,24 @@
 
  
+c=======================================================================
+c   Initialisation for cloud fraction and oceanic ice (added by BC 2010)
+c=======================================================================
+      DO ig=1, ngridmx
+         totalfrac(ig)=0.5
+         DO l=1,llm
+            cloudfrac(ig,l)=0.5
+         ENDDO
+      ENDDO
+      
+c========================================================
+
+!      DO ig=1,ngridmx
+!         IF(tsurf(ig) .LT. 273.16-1.8) THEN
+!            hice(ig)=(273.16-1.8-tsurf(ig))/(273.16-1.8-240)*1.
+!            hice(ig)=min(hice(ig),1.0)
+!         ENDIF
+!      ENDDO
+
+
 c=======================================================================
 c   Correct pressure on the new grid (menu 0)
@@ -1393,4 +1685,12 @@
       if ((choix_1.eq.0).and.(.not.flagps0)) then
         r = 1000.*8.31/mugaz
+
+        phi0=0.0
+        do j=1,jjp1
+          do i=1,iip1
+             phi0 = phi0+phis(i,j)*aire(i,j)
+          end do
+        end do
+        phi0=phi0/airetot
 
         do j=1,jjp1
@@ -1398,15 +1698,30 @@
              ps(i,j) = ps(i,j) * 
 !     .            exp((phisold_newgrid(i,j)-phis(i,j)) /
-     .            exp((-phis(i,j)) /
+     .            exp((phi0-phis(i,j)) /
      .                                  (t(i,j,1) * r))
           end do
         end do
   
-c periodicity of surface ps in longitude
+!     we must renormalise pressures AGAIN, because exp(-phi) is nonlinear
+        ptot=0.0
         do j=1,jjp1
-          ps(1,j) = ps(iip1,j)
+           do i=1,iip1
+              ptot=ptot+ps(i,j)*aire(i,j)
+           enddo
+        enddo
+        do j=1,jjp1
+           do i=1,iip1
+              ps(i,j)=ps(i,j)*ptotn/ptot
+           enddo
+        enddo
+        
+!     periodicity of surface ps in longitude
+        do j=1,jjp1
+           ps(1,j) = ps(iip1,j)
         end do
+        
       end if
 
+
 c=======================================================================
 c=======================================================================
@@ -1415,5 +1730,4 @@
 c    Initialisation de la physique / ecriture de newstartfi :
 c=======================================================================
-
 
       CALL inifilr 
@@ -1447,4 +1761,5 @@
       endif
 
+
 C Calcul intermediaire
 c
@@ -1490,8 +1805,16 @@
 C
 
+!      do ig=1,ngridmx
+!         print*,'surface ice in newstart=',qsurf(ig,igcm_h2o_ice)
+!         print*,'surface liq in newstart=',qsurf(ig,igcm_h2o_vap)
+!      enddo
+!      stop
+
+
       call physdem1("restartfi.nc",lonfi,latfi,nsoilmx,nqmx,
      .              dtphys,float(day_ini),
      .              time,tsurf,tsoil,emis,q2,qsurf,
-     .              airefi,albfi,ithfi,zmea,zstd,zsig,zgam,zthe)
+     .              airefi,albfi,ithfi,zmea,zstd,zsig,zgam,zthe,
+     .              cloudfrac,totalfrac,hice)
 
 c=======================================================================
Index: unk/LMDZ.GENERIC/libf/dyn3d/newstart.old
===================================================================
--- /trunk/LMDZ.GENERIC/libf/dyn3d/newstart.old	(revision 252)
+++ 	(revision )
@@ -1,1540 +1,0 @@
-C======================================================================
-      PROGRAM newstart
-c=======================================================================
-c
-c
-c   Auteur:   Christophe Hourdin/Francois Forget/Yann Wanherdrick
-c   ------
-c             Derniere modif : 12/03
-c
-c
-c   Objet:  Create or modify the initial state for the LMD Mars GCM
-c   -----           (fichiers NetCDF start et startfi)
-c
-c
-c=======================================================================
-
-      implicit none
-
-#include "dimensions.h"
-#include "dimphys.h"
-#include "surfdat.h"
-#include "comsoil.h"
-#include "planete.h"
-#include "paramet.h"
-#include "comconst.h"
-#include "comvert.h"
-#include "comgeom2.h"
-#include "control.h"
-#include "logic.h"
-#include "description.h"
-#include "ener.h"
-#include "temps.h"
-#include "lmdstd.h"
-#include "comdissnew.h"
-#include "clesph0.h"
-#include "serre.h"
-#include "netcdf.inc"
-#include "advtrac.h"
-#include "tracer.h"
-c=======================================================================
-c   Declarations
-c=======================================================================
-
-c Variables dimension du fichier "start_archive"
-c------------------------------------
-      CHARACTER	relief*3
-
-
-c Variables pour les lectures NetCDF des fichiers "start_archive" 
-c--------------------------------------------------
-      INTEGER nid_dyn, nid_fi,nid,nvarid
-      INTEGER length
-      parameter (length = 100)
-      INTEGER tab0
-      INTEGER   NB_ETATMAX
-      parameter (NB_ETATMAX = 100)
-
-      REAL  date
-      REAL p_rad,p_omeg,p_g,p_mugaz,p_daysec
-
-c Variable histoire 
-c------------------
-      REAL vcov(iip1,jjm,llm),ucov(iip1,jjp1,llm) ! vents covariants
-      REAL phis(iip1,jjp1)
-      REAL q(iip1,jjp1,llm,nqmx)               ! champs advectes
-
-c autre variables dynamique nouvelle grille
-c------------------------------------------
-      REAL pks(iip1,jjp1)
-      REAL w(iip1,jjp1,llm+1)
-      REAL pbaru(ip1jmp1,llm),pbarv(ip1jm,llm)
-!      REAL dv(ip1jm,llm),du(ip1jmp1,llm)
-!      REAL dh(ip1jmp1,llm),dp(ip1jmp1)
-      REAL phi(iip1,jjp1,llm)
-
-      integer klatdat,klongdat
-      PARAMETER (klatdat=180,klongdat=360)
-
-c Physique sur grille scalaire 
-c----------------------------
-      real zmeaS(iip1,jjp1),zstdS(iip1,jjp1)
-      real zsigS(iip1,jjp1),zgamS(iip1,jjp1),ztheS(iip1,jjp1)
-
-c variable physique
-c------------------
-      REAL tsurf(ngridmx)	! surface temperature
-      REAL tsoil(ngridmx,nsoilmx) ! soil temperature
-!      REAL co2ice(ngridmx)	! CO2 ice layer
-      REAL emis(ngridmx)	! surface emissivity
-      REAL qsurf(ngridmx,nqmx)
-      REAL q2(ngridmx,nlayermx+1)
-!      REAL rnaturfi(ngridmx)
-      real alb(iip1,jjp1),albfi(ngridmx) ! albedos
-      real ith(iip1,jjp1,nsoilmx),ithfi(ngridmx,nsoilmx) ! thermal inertia (3D)
-      real surfith(iip1,jjp1),surfithfi(ngridmx) ! surface thermal inertia (2D)
-      REAL latfi(ngridmx),lonfi(ngridmx),airefi(ngridmx)
-
-      INTEGER i,j,l,isoil,ig,idum
-      real mugaz ! molar mass of the atmosphere
-
-      integer ierr 
-
-c Variables on the new grid along scalar points 
-c------------------------------------------------------
-!      REAL p(iip1,jjp1)
-      REAL t(iip1,jjp1,llm)
-      REAL tset(iip1,jjp1,llm)
-      real phisold_newgrid(iip1,jjp1)
-      REAL :: teta(iip1, jjp1, llm)
-      REAL :: pk(iip1,jjp1,llm)
-      REAL :: pkf(iip1,jjp1,llm)
-      REAL :: ps(iip1, jjp1)
-      REAL :: masse(iip1,jjp1,llm)
-      REAL :: xpn,xps,xppn(iim),xpps(iim)
-      REAL :: p3d(iip1, jjp1, llm+1)
-      REAL :: beta(iip1,jjp1,llm)
-!      REAL dteta(ip1jmp1,llm)
-
-c Variable de l'ancienne grille 
-c------------------------------
-      real time
-      real tab_cntrl(100)
-      real tab_cntrl_bis(100)
-
-c variables diverses
-c-------------------
-      real choix_1,pp
-      character*80      fichnom
-      integer Lmodif,iq,thermo
-      character modif*20
-      real z_reel(iip1,jjp1)
-      real tsud,albsud,alb_bb,ith_bb,Tiso,Tabove
-      real ptoto,pcap,patm,airetot,ptotn,patmn
-!      real ssum
-      character*1 yes
-      logical :: flagtset=.false. ,  flagps0=.false.
-      real val, val2, val3 ! to store temporary variables
-      real :: iceith=2000 ! thermal inertia of subterranean ice
-      integer iref,jref
-
-      INTEGER :: itau
-      
-      INTEGER :: nq,numvanle
-      character(len=20) :: txt ! to store some text
-      integer :: count
-
-! MONS data:
-      real :: MONS_Hdn(iip1,jjp1) ! Hdn: %WEH=Mass fraction of H2O
-      real :: MONS_d21(iip1,jjp1) ! ice table "depth" (in kg/m2)
-      ! coefficient to apply to convert d21 to 'true' depth (m)
-      real :: MONS_coeff
-      real :: MONS_coeffS ! coeff for southern hemisphere
-      real :: MONS_coeffN ! coeff for northern hemisphere
-!      real,parameter :: icedepthmin=1.e-3 ! Ice begins at most at that depth
-
-c sortie visu pour les champs dynamiques
-c---------------------------------------
-!      INTEGER :: visuid
-!      real :: time_step,t_ops,t_wrt
-!      CHARACTER*80 :: visu_file
-
-      cpp    = 744.499 ! for Mars, instead of 1004.70885 (Earth)
-
-
-      preff  = 610.    ! for Mars, instead of 101325. (Earth)
-      pa= 20           ! for Mars, instead of 500 (Earth)
-
-c=======================================================================
-c   Choice of the start file(s) to use
-c=======================================================================
-
-      write(*,*) 'From which kind of files do you want to create new',
-     .  'start and startfi files'
-      write(*,*) '    0 - from a file start_archive'
-      write(*,*) '    1 - from files start and startfi'
- 
-c-----------------------------------------------------------------------
-c   Open file(s) to modify (start or start_archive)
-c-----------------------------------------------------------------------
-
-      DO
-         read(*,*,iostat=ierr) choix_1
-         if ((choix_1 /= 0).OR.(choix_1 /=1)) EXIT
-      ENDDO
-
-c     Open start_archive
-c     ~~~~~~~~~~~~~~~~~~~~~~~~~~
-      if (choix_1.eq.0) then
-
-        write(*,*) 'Creating start files from:'
-        write(*,*) './start_archive.nc'
-        write(*,*)
-        fichnom = 'start_archive.nc'
-        ierr = NF_OPEN (fichnom, NF_NOWRITE,nid)
-        IF (ierr.NE.NF_NOERR) THEN
-          write(6,*)' Problem opening file:',fichnom
-          write(6,*)' ierr = ', ierr
-          CALL ABORT
-        ENDIF
-        tab0 = 50 
-        Lmodif = 1
-
-c     OR open start and startfi files
-c     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-      else
-        write(*,*) 'Creating start files from:'
-        write(*,*) './start.nc and ./startfi.nc'
-        write(*,*)
-        fichnom = 'start.nc'
-        ierr = NF_OPEN (fichnom, NF_NOWRITE,nid_dyn)
-        IF (ierr.NE.NF_NOERR) THEN
-          write(6,*)' Problem opening file:',fichnom
-          write(6,*)' ierr = ', ierr
-          CALL ABORT
-        ENDIF
- 
-        fichnom = 'startfi.nc'
-        ierr = NF_OPEN (fichnom, NF_NOWRITE,nid_fi)
-        IF (ierr.NE.NF_NOERR) THEN
-          write(6,*)' Problem opening file:',fichnom
-          write(6,*)' ierr = ', ierr
-          CALL ABORT
-        ENDIF
-
-        tab0 = 0 
-        Lmodif = 0
-
-      endif
-
-c-----------------------------------------------------------------------
-c Lecture du tableau des parametres du run (pour la dynamique)
-c-----------------------------------------------------------------------
-
-      if (choix_1.eq.0) then
-
-        write(*,*) 'reading tab_cntrl START_ARCHIVE'
-c
-        ierr = NF_INQ_VARID (nid, "controle", nvarid)
-#ifdef NC_DOUBLE
-        ierr = NF_GET_VAR_DOUBLE(nid, nvarid, tab_cntrl)
-#else
-        ierr = NF_GET_VAR_REAL(nid, nvarid, tab_cntrl)
-#endif
-c
-      else if (choix_1.eq.1) then
-
-        write(*,*) 'reading tab_cntrl START'
-c
-        ierr = NF_INQ_VARID (nid_dyn, "controle", nvarid)
-#ifdef NC_DOUBLE
-        ierr = NF_GET_VAR_DOUBLE(nid_dyn, nvarid, tab_cntrl)
-#else
-        ierr = NF_GET_VAR_REAL(nid_dyn, nvarid, tab_cntrl)
-#endif
-c
-        write(*,*) 'reading tab_cntrl STARTFI'
-c
-        ierr = NF_INQ_VARID (nid_fi, "controle", nvarid)
-#ifdef NC_DOUBLE
-        ierr = NF_GET_VAR_DOUBLE(nid_fi, nvarid, tab_cntrl_bis)
-#else
-        ierr = NF_GET_VAR_REAL(nid_fi, nvarid, tab_cntrl_bis)
-#endif
-c
-        do i=1,50
-          tab_cntrl(i+50)=tab_cntrl_bis(i)
-        enddo
-      write(*,*) 'printing tab_cntrl', tab_cntrl
-      do i=1,100
-        write(*,*) i,tab_cntrl(i)
-      enddo
-      
-      endif
-c-----------------------------------------------------------------------
-c		Initialisation des constantes dynamique
-c-----------------------------------------------------------------------
-
-      kappa = tab_cntrl(9) 
-      etot0 = tab_cntrl(12)
-      ptot0 = tab_cntrl(13)
-      ztot0 = tab_cntrl(14)
-      stot0 = tab_cntrl(15)
-      ang0 = tab_cntrl(16)
-      write(*,*) "Newstart: kappa,etot0,ptot0,ztot0,stot0,ang0"
-      write(*,*) kappa,etot0,ptot0,ztot0,stot0,ang0
-
-c-----------------------------------------------------------------------
-c   Lecture du tab_cntrl et initialisation des constantes physiques
-c  - pour start:  Lmodif = 0 => pas de modifications possibles
-c                  (modif dans le tabfi de readfi + loin)
-c  - pour start_archive:  Lmodif = 1 => modifications possibles
-c-----------------------------------------------------------------------
-      if (choix_1.eq.0) then
-         call tabfi (nid,Lmodif,tab0,day_ini,lllm,p_rad,
-     .            p_omeg,p_g,p_mugaz,p_daysec,time)
-      else if (choix_1.eq.1) then
-         call tabfi (nid_fi,Lmodif,tab0,day_ini,lllm,p_rad,
-     .            p_omeg,p_g,p_mugaz,p_daysec,time)
-      endif
-
-      rad = p_rad
-      omeg = p_omeg
-      g = p_g
-      mugaz = p_mugaz
-      daysec = p_daysec
-
-!      print*,'daysec=',p_daysec
-!      stop
-
-!      write(*,*) 'aire',aire
-
-
-c=======================================================================
-c  INITIALISATIONS DIVERSES
-c=======================================================================
-! Load tracer names:
-      call iniadvtrac(nq,numvanle)
-      ! tnom(:) now contains tracer names
-! Initialize global tracer indexes (stored in tracer.h)
-      call initracer()
-! Load parameters from run.def file
-      CALL defrun_new( 99, .TRUE. )
-      CALL iniconst 
-      CALL inigeom
-      idum=-1
-      idum=0
-
-c Initialisation coordonnees /aires
-c -------------------------------
-! Note: rlatu(:) and rlonv(:) are commons defined in "comgeom.h"
-!       rlatu() and rlonv() are given in radians
-      latfi(1)=rlatu(1)
-      lonfi(1)=0.
-      DO j=2,jjm
-         DO i=1,iim
-            latfi((j-2)*iim+1+i)=rlatu(j)
-            lonfi((j-2)*iim+1+i)=rlonv(i)
-         ENDDO
-      ENDDO
-      latfi(ngridmx)=rlatu(jjp1)
-      lonfi(ngridmx)=0.
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,aire,airefi)
-
-c=======================================================================
-c   lecture topographie, albedo, inertie thermique, relief sous-maille
-c=======================================================================
-
-      if (choix_1.ne.1) then  ! pour ne pas avoir besoin du fichier 
-                              ! surface.dat dans le cas des start
-
-c do while((relief(1:3).ne.'mol').AND.(relief(1:3).ne.'pla'))
-c       write(*,*)
-c       write(*,*) 'choix du relief (mola,pla)'
-c       write(*,*) '(Topographie MGS MOLA, plat)'
-c       read(*,fmt='(a3)') relief
-        relief="mola"
-c     enddo
-
-      CALL datareadnc(relief,phis,alb,surfith,zmeaS,zstdS,zsigS,zgamS,
-     .          ztheS)
-
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,phis,phisfi)
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,surfith,surfithfi)
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,alb,albfi)
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,zmeaS,zmea)
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,zstdS,zstd)
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,zsigS,zsig)
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,zgamS,zgam)
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,ztheS,zthe)
-
-      endif ! of if (choix_1.ne.1)
-
-
-c=======================================================================
-c  Lecture des fichiers (start ou start_archive)
-c=======================================================================
-
-      if (choix_1.eq.0) then
-
-        write(*,*) 'Reading file START_ARCHIVE'
-        CALL lect_start_archive(date,tsurf,tsoil,emis,q2,
-     .   t,ucov,vcov,ps,teta,phisold_newgrid,q,qsurf,
-     &   surfith,nid)
-        write(*,*) "OK, read start_archive file"
-	! copy soil thermal inertia
-	ithfi(:,:)=inertiedat(:,:)
-	
-        ierr= NF_CLOSE(nid)
-
-      else if (choix_1.eq.1) then !  c'est l'appel a tabfi de phyeta0 qui
-                                  !  permet de changer les valeurs du 
-                                  !  tab_cntrl Lmodif=1
-        tab0=0
-        Lmodif=1 ! Lmodif set to 1 to allow modifications in phyeta0                           
-        write(*,*) 'Reading file START'
-        fichnom = 'start.nc'
-        CALL dynetat0(fichnom,nqmx,vcov,ucov,teta,q,masse,
-     .       ps,phis,time)
-
-        write(*,*) 'Reading file STARTFI'
-        fichnom = 'startfi.nc'
-        CALL phyetat0 (fichnom,tab0,Lmodif,nsoilmx,nqmx,
-     .        day_ini,time,
-     .        tsurf,tsoil,emis,q2,qsurf)
-        
-        ! copy albedo and soil thermal inertia
-        do i=1,ngridmx
-          albfi(i) = albedodat(i)
-	  do j=1,nsoilmx
-           ithfi(i,j) = inertiedat(i,j)
-	  enddo
-        ! build a surfithfi(:) using 1st layer of ithfi(:), which might
-        ! be neede later on if reinitializing soil thermal inertia
-          surfithfi(i)=ithfi(i,1)
-        enddo
-
-      else 
-        CALL exit(1)
-      endif
-
-      dtvr   = daysec/FLOAT(day_step)
-      dtphys   = dtvr * FLOAT(iphysiq)
-
-c=======================================================================
-c 
-c=======================================================================
-
-      do ! infinite loop on list of changes
-
-      write(*,*)
-      write(*,*)
-      write(*,*) 'List of possible changes :'
-      write(*,*) '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
-      write(*,*)
-      write(*,*) 'flat : no topography ("aquaplanet")'
-      write(*,*) 'bilball : uniform albedo and thermal inertia'
-      write(*,*) 'coldspole : cold subsurface and high albedo at S.pole'
-      write(*,*) 'qname : change tracer name'
-      write(*,*) 'q=0 : ALL tracer =zero'
-      write(*,*) 'q=x : give a specific uniform value to one tracer'
-      write(*,*) 'ini_q : tracers initialisation for chemistry, water an
-     $d ice   '
-      write(*,*) 'ini_q-H2O : tracers initialisation for chemistry and 
-     $ice '
-      write(*,*) 'ini_q-iceH2O : tracers initialisation for chemistry on
-     $ly '
-      write(*,*) 'noglacier : Remove tropical H2O ice if |lat|<45'
-      write(*,*) 'watercapn : H20 ice on permanent N polar cap '
-      write(*,*) 'watercaps : H20 ice on permanent S polar cap '
-      write(*,*) 'wetstart  : start with a wet atmosphere'
-      write(*,*) 'isotherm : Isothermal Temperatures, wind set to zero'
-      write(*,*) 'coldstart : Start X K above the CO2 frost point and 
-     $set wind to zero (assumes 100% CO2)'
-      write(*,*) 'co2ice=0 : remove CO2 polar cap'
-      write(*,*) 'ptot : change total pressure'
-      write(*,*) 'therm_ini_s: Set soil thermal inertia to reference sur
-     &face values'
-      write(*,*) 'subsoilice_n: Put deep underground ice layer in northe
-     &rn hemisphere'
-      write(*,*) 'subsoilice_s: Put deep underground ice layer in southe
-     &rn hemisphere'
-      write(*,*) 'mons_ice: Put underground ice layer according to MONS-
-     &derived data'
-
-        write(*,*)
-        write(*,*) 'Change to perform ?'
-        write(*,*) '   (enter keyword or return to end)'
-        write(*,*)
-
-        read(*,fmt='(a20)') modif
-        if (modif(1:1) .eq. ' ') exit ! exit loop on changes
-
-        write(*,*)
-        write(*,*) trim(modif) , ' : '
-
-c       'flat : no topography ("aquaplanet")'
-c       -------------------------------------
-        if (modif(1:len_trim(modif)) .eq. 'flat') then
-c         set topo to zero 
-          CALL initial0(ip1jmp1,z_reel)
-          CALL multscal(ip1jmp1,z_reel,g,phis)
-          CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,phis,phisfi)
-          write(*,*) 'topography set to zero.'
-          write(*,*) 'WARNING : the subgrid topography parameters',
-     &    ' were not set to zero ! => set calllott to F'                    
-
-c        Choice for surface pressure
-         yes=' '
-         do while ((yes.ne.'y').and.(yes.ne.'n'))
-            write(*,*) 'Do you wish to choose homogeneous surface',
-     &                 'pressure (y) or let newstart interpolate ',
-     &                 ' the previous field  (n)?'
-             read(*,fmt='(a)') yes
-         end do
-         if (yes.eq.'y') then
-           flagps0=.true.
-           write(*,*) 'New value for ps (Pa) ?'
- 201       read(*,*,iostat=ierr) patm
-            if(ierr.ne.0) goto 201
-             write(*,*)
-             write(*,*) ' new ps everywhere (Pa) = ', patm
-             write(*,*)
-             do j=1,jjp1
-               do i=1,iip1
-                 ps(i,j)=patm
-               enddo
-             enddo
-         end if
-
-c       bilball : albedo, inertie thermique uniforme
-c       --------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'bilball') then
-          write(*,*) 'constante albedo and iner.therm:'
-          write(*,*) 'New value for albedo (ex: 0.25) ?'
- 101      read(*,*,iostat=ierr) alb_bb
-          if(ierr.ne.0) goto 101
-          write(*,*)
-          write(*,*) ' uniform albedo (new value):',alb_bb
-          write(*,*)
-
-          write(*,*) 'New value for thermal inertia (eg: 247) ?'
- 102      read(*,*,iostat=ierr) ith_bb
-          if(ierr.ne.0) goto 102
-          write(*,*) 'uniform thermal inertia (new value):',ith_bb
-          DO j=1,jjp1
-             DO i=1,iip1
-                alb(i,j) = alb_bb	! albedo
-		do isoil=1,nsoilmx
-                  ith(i,j,isoil) = ith_bb	! thermal inertia
-		enddo
-             END DO
-          END DO
-!          CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,ith,ithfi)
-          CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
-          CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,alb,albfi)
-
-c       coldspole : sous-sol de la calotte sud toujours froid
-c       -----------------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'coldspole') then
-          write(*,*)'new value for the subsurface temperature',
-     &   ' beneath the permanent southern polar cap ? (eg: 141 K)'
- 103      read(*,*,iostat=ierr) tsud
-          if(ierr.ne.0) goto 103
-          write(*,*)
-          write(*,*) ' new value of the subsurface temperature:',tsud
-c         nouvelle temperature sous la calotte permanente
-          do l=2,nsoilmx
-               tsoil(ngridmx,l) =  tsud
-          end do
-
-
-          write(*,*)'new value for the albedo',
-     &   'of the permanent southern polar cap ? (eg: 0.75)'
- 104      read(*,*,iostat=ierr) albsud
-          if(ierr.ne.0) goto 104
-          write(*,*)
-
-c         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-c         Option 1:  only the albedo of the pole is modified :    
-          albfi(ngridmx)=albsud
-          write(*,*) 'ig=',ngridmx,'   albedo perennial cap ',
-     &    albfi(ngridmx)
-
-c         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
-c          Option 2 A haute resolution : coordonnee de la vrai calotte ~    
-c           DO j=1,jjp1
-c             DO i=1,iip1
-c                ig=1+(j-2)*iim +i
-c                if(j.eq.1) ig=1
-c                if(j.eq.jjp1) ig=ngridmx
-c                if ((rlatu(j)*180./pi.lt.-84.).and.
-c     &            (rlatu(j)*180./pi.gt.-91.).and.
-c     &            (rlonv(i)*180./pi.gt.-91.).and.
-c     &            (rlonv(i)*180./pi.lt.0.))         then
-cc    albedo de la calotte permanente fixe a albsud
-c                   alb(i,j)=albsud
-c                   write(*,*) 'lat=',rlatu(j)*180./pi,
-c     &                      ' lon=',rlonv(i)*180./pi
-cc     fin de la condition sur les limites de la calotte permanente
-c                end if
-c             ENDDO
-c          ENDDO
-c      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-c         CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,alb,albfi)
-
-
-c       ptot : Modification of the total pressure: ice + current atmosphere 
-c       -------------------------------------------------------------------
-        else if (modif(1:len_trim(modif)).eq.'ptot') then
-
-          ! check if we have a co2_ice surface tracer:
-          if (igcm_co2_ice.eq.0) then
-            write(*,*) " No surface CO2 ice !"
-            write(*,*) " only atmospheric pressure will be considered!"
-          endif
-c         calcul de la pression totale glace + atm actuelle
-          patm=0.
-          airetot=0.
-          pcap=0.
-          DO j=1,jjp1
-             DO i=1,iim
-                ig=1+(j-2)*iim +i
-                if(j.eq.1) ig=1
-                if(j.eq.jjp1) ig=ngridmx
-                patm = patm + ps(i,j)*aire(i,j)
-                airetot= airetot + aire(i,j)
-                if (igcm_co2_ice.ne.0) then
-                  !pcap = pcap + aire(i,j)*co2ice(ig)*g
-                  pcap = pcap + aire(i,j)*qsurf(ig,igcm_co2_ice)*g
-                endif
-             ENDDO
-          ENDDO
-          ptoto = pcap + patm
-
-          print*,'Current total pressure at surface (co2 ice + atm) ',
-     &       ptoto/airetot
-
-          print*,'new value?'
-          read(*,*) ptotn
-          ptotn=ptotn*airetot
-          patmn=ptotn-pcap
-          print*,'ptoto,patm,ptotn,patmn'
-          print*,ptoto,patm,ptotn,patmn
-          print*,'Mult. factor for pressure (atm only)', patmn/patm
-          do j=1,jjp1
-             do i=1,iip1
-                ps(i,j)=ps(i,j)*patmn/patm
-             enddo
-          enddo
-
-c        Correction pour la conservation des traceurs
-         yes=' '
-         do while ((yes.ne.'y').and.(yes.ne.'n'))
-            write(*,*) 'Do you wish to conserve tracer total mass (y)',
-     &              ' or tracer mixing ratio (n) ?'
-             read(*,fmt='(a)') yes
-         end do
-
-         if (yes.eq.'y') then
-           write(*,*) 'OK : conservation of tracer total mass'
-           DO iq =1, nqmx
-             DO l=1,llm
-               DO j=1,jjp1
-                  DO i=1,iip1
-                    q(i,j,l,iq)=q(i,j,l,iq)*patm/patmn
-                  ENDDO
-               ENDDO
-             ENDDO
-           ENDDO
-          else
-            write(*,*) 'OK : conservation of tracer mixing ratio'
-          end if
-
-c       qname : change tracer name
-c       --------------------------
-        else if (trim(modif).eq.'qname') then
-         yes='y'
-         do while (yes.eq.'y')
-          write(*,*) 'Which tracer name do you want to change ?'
-          do iq=1,nqmx
-            write(*,'(i3,a3,a20)')iq,' : ',trim(tnom(iq))
-          enddo
-          write(*,'(a35,i3)')
-     &            '(enter tracer number; between 1 and ',nqmx
-          write(*,*)' or any other value to quit this option)'
-          read(*,*) iq
-          if ((iq.ge.1).and.(iq.le.nqmx)) then
-            write(*,*)'Change tracer name ',trim(tnom(iq)),' to ?'
-            read(*,*) txt
-            tnom(iq)=txt
-            write(*,*)'Do you want to change another tracer name (y/n)?'
-            read(*,'(a)') yes 
-          else
-! inapropiate value of iq; quit this option
-            yes='n'
-          endif ! of if ((iq.ge.1).and.(iq.le.nqmx))
-         enddo ! of do while (yes.ne.'y')
-
-c       q=0 : set tracers to zero
-c       -------------------------
-        else if (modif(1:len_trim(modif)).eq.'q=0') then
-c          mise a 0 des q (traceurs)
-          write(*,*) 'Tracers set to 0 (1.E-30 in fact)'
-           DO iq =1, nqmx
-             DO l=1,llm
-               DO j=1,jjp1
-                  DO i=1,iip1
-                    q(i,j,l,iq)=1.e-30
-                  ENDDO
-               ENDDO
-             ENDDO
-           ENDDO
-
-c          set surface tracers to zero
-           DO iq =1, nqmx
-             DO ig=1,ngridmx
-                 qsurf(ig,iq)=0.
-             ENDDO
-           ENDDO
-
-c       q=x : initialise tracer manually 
-c       --------------------------------
-        else if (modif(1:len_trim(modif)).eq.'q=x') then
-             write(*,*) 'Which tracer do you want to modify ?'
-             do iq=1,nqmx
-               write(*,*)iq,' : ',trim(tnom(iq))
-             enddo
-             write(*,*) '(choose between 1 and ',nqmx,')'
-             read(*,*) iq 
-             write(*,*)'mixing ratio of tracer ',trim(tnom(iq)),
-     &                 ' ? (kg/kg)'
-             read(*,*) val
-             DO l=1,llm
-               DO j=1,jjp1
-                  DO i=1,iip1
-                    q(i,j,l,iq)=val
-                  ENDDO
-               ENDDO
-             ENDDO
-             write(*,*) 'SURFACE value of tracer ',trim(tnom(iq)),
-     &                   ' ? (kg/m2)'
-             read(*,*) val
-             DO ig=1,ngridmx
-                 qsurf(ig,iq)=val
-             ENDDO
-
-c       ini_q : Initialize tracers for chemistry
-c       -----------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'ini_q') then
-c         For more than 32 layers, possible to initiate thermosphere only     
-          thermo=0
-          yes=' '
-          if (llm.gt.32) then 
-            do while ((yes.ne.'y').and.(yes.ne.'n'))
-            write(*,*)'',
-     &     'initialisation for thermosphere only? (y/n)'
-            read(*,fmt='(a)') yes
-            if (yes.eq.'y') then
-            thermo=1 
-            else
-            thermo=0
-            endif
-            enddo  
-          endif
-          
-c             call inichim_newstart(q,ps,sig,nqmx,latfi,lonfi,airefi,
-c    $   thermo,qsurf)
-          write(*,*) 'Chemical species initialized'
-
-        if (thermo.eq.0) then 
-c          mise a 0 des qsurf (traceurs a la surface)
-           DO iq =1, nqmx
-             DO ig=1,ngridmx
-                 qsurf(ig,iq)=0.
-             ENDDO
-           ENDDO
-        endif   
-
-c       ini_q-H2O : as above exept for the water vapour tracer 
-c       ------------------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'ini_q-H2O') then
-          ! for more than 32 layers, possible to initiate thermosphere only     
-          thermo=0
-          yes=' '
-          if(llm.gt.32) then
-            do while ((yes.ne.'y').and.(yes.ne.'n'))
-            write(*,*)'',
-     &      'initialisation for thermosphere only? (y/n)'
-            read(*,fmt='(a)') yes
-            if (yes.eq.'y') then 
-            thermo=1 
-            else
-            thermo=0
-            endif
-            enddo
-          endif
-c             call inichim_newstart(q,ps,sig,nqmx-1,latfi,lonfi,airefi,
-c    $   thermo,qsurf)
-c         write(*,*) 'Initialized chem. species exept last (H2O)'
-
-        if (thermo.eq.0) then 
-c          set surface tracers to zero, except water ice
-           DO iq =1, nqmx
-            if (iq.ne.igcm_h2o_ice) then
-             DO ig=1,ngridmx
-                 qsurf(ig,iq)=0.
-             ENDDO
-            endif
-           ENDDO
-        endif
-
-c       ini_q-iceH2O : as above exept for ice et H2O
-c       -----------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'ini_q-iceH2O') then
-c         For more than 32 layers, possible to initiate thermosphere only     
-          thermo=0
-          yes=' '
-          if(llm.gt.32) then
-            do while ((yes.ne.'y').and.(yes.ne.'n'))
-            write(*,*)'',
-     &      'initialisation for thermosphere only? (y/n)'
-            read(*,fmt='(a)') yes
-            if (yes.eq.'y') then 
-            thermo=1 
-            else
-            thermo=0
-            endif
-            enddo
-          endif
-     
-c        call inichim_newstart(q,ps,sig,nqmx-2,latfi,lonfi,airefi,
-c    $   thermo,qsurf)
-c         write(*,*) 'Initialized chem. species exept ice and H2O'
-
-        if (thermo.eq.0) then 
-c          set surface tracers to zero, except water ice
-           DO iq =1, nqmx
-            if (iq.ne.igcm_h2o_ice) then
-             DO ig=1,ngridmx
-                 qsurf(ig,iq)=0.
-             ENDDO 
-            endif
-           ENDDO
-        endif
-
-c      wetstart : wet atmosphere with a north to south gradient
-c      --------------------------------------------------------
-       else if (modif(1:len_trim(modif)) .eq. 'wetstart') then
-        ! check that there is indeed a water vapor tracer
-        if (igcm_h2o_vap.eq.0) then
-          write(*,*) "No water vapour tracer! Can't use this option"
-          stop
-        endif
-          DO l=1,llm
-            DO j=1,jjp1
-              DO i=1,iip1
-                q(i,j,l,igcm_h2o_vap)=150.e-6 * (rlatu(j)+pi/2.) / pi
-              ENDDO
-            ENDDO
-          ENDDO
-
-         write(*,*) 'Water mass mixing ratio at north pole='
-     *               ,q(1,1,1,igcm_h2o_vap)
-         write(*,*) '---------------------------south pole='
-     *               ,q(1,jjp1,1,igcm_h2o_vap)
-
-c      noglacier : remove tropical water ice (to initialize high res sim)
-c      --------------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'noglacier') then
-           do ig=1,ngridmx
-             j=(ig-2)/iim +2
-              if(ig.eq.1) j=1
-              write(*,*) 'OK: remove surface ice for |lat|<45'
-              if (abs(rlatu(j)*180./pi).lt.45.) then
-                   qsurf(ig,igcm_h2o_ice)=0.
-              end if
-           end do
-
-
-c      watercapn : H20 ice on permanent northern cap
-c      --------------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'watercapn') then
-           do ig=1,ngridmx
-             j=(ig-2)/iim +2
-              if(ig.eq.1) j=1
-              if (rlatu(j)*180./pi.gt.80.) then
-                   qsurf(ig,igcm_h2o_ice)=1.e5
-                   write(*,*) 'ig=',ig,'    H2O ice mass (kg/m2)= ',
-     &              qsurf(ig,igcm_h2o_ice)
-                   write(*,*)'     ==> Ice mesh South boundary (deg)= ',
-     &              rlatv(j)*180./pi
-                end if
-           enddo
-
-c      watercaps : H20 ice on permanent southern cap
-c      -------------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'watercaps') then
-           do ig=1,ngridmx
-               j=(ig-2)/iim +2
-               if(ig.eq.1) j=1
-               if (rlatu(j)*180./pi.lt.-80.) then
-                   qsurf(ig,igcm_h2o_ice)=1.e5
-                   write(*,*) 'ig=',ig,'   H2O ice mass (kg/m2)= ',
-     &              qsurf(ig,igcm_h2o_ice)
-                   write(*,*)'     ==> Ice mesh North boundary (deg)= ',
-     &              rlatv(j-1)*180./pi
-               end if
-           enddo
-
-c       isotherm : Isothermal temperatures and no winds
-c       ------------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'isotherm') then
-
-          write(*,*)'Isothermal temperature of the atmosphere, 
-     &           surface and subsurface'
-          write(*,*) 'Value of this temperature ? :'
- 203      read(*,*,iostat=ierr) Tiso
-          if(ierr.ne.0) goto 203
-
-          do ig=1, ngridmx
-            tsurf(ig) = Tiso
-          end do
-          do l=2,nsoilmx
-            do ig=1, ngridmx
-              tsoil(ig,l) = Tiso
-            end do
-          end do
-          DO j=1,jjp1
-           DO i=1,iim
-            Do l=1,llm
-               Tset(i,j,l)=Tiso
-            end do
-           end do
-          end do
-          flagtset=.true.
-          call initial0(llm*ip1jmp1,ucov)
-          call initial0(llm*ip1jm,vcov)
-          call initial0(ngridmx*(llm+1),q2)
-
-
-c       coldstart : T set 1K above CO2 frost point and no winds
-c       ------------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'coldstart') then
-
-          write(*,*)'set temperature of the atmosphere,' 
-     &,'surface and subsurface how many degrees above CO2 frost point?'
- 204      read(*,*,iostat=ierr) Tabove
-          if(ierr.ne.0) goto 204
-
-            DO j=1,jjp1
-             DO i=1,iim
-                ig=1+(j-2)*iim +i
-                if(j.eq.1) ig=1
-                if(j.eq.jjp1) ig=ngridmx
-            tsurf(ig) = (-3167.8)/(log(.01*ps(i,j))-23.23)+Tabove
-             END DO
-            END DO
-          do l=1,nsoilmx
-            do ig=1, ngridmx
-              tsoil(ig,l) = tsurf(ig)
-            end do
-          end do
-          DO j=1,jjp1
-           DO i=1,iim
-            Do l=1,llm
-               pp = aps(l) +bps(l)*ps(i,j) 
-               Tset(i,j,l)=(-3167.8)/(log(.01*pp)-23.23)+Tabove
-            end do
-           end do
-          end do
-
-          flagtset=.true.
-          call initial0(llm*ip1jmp1,ucov)
-          call initial0(llm*ip1jm,vcov)
-          call initial0(ngridmx*(llm+1),q2)
-
-
-c       co2ice=0 : remove CO2 polar ice caps'
-c       ------------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'co2ice=0') then
-         ! check that there is indeed a co2_ice tracer ...
-          if (igcm_co2_ice.ne.0) then
-           do ig=1,ngridmx
-              !co2ice(ig)=0
-              qsurf(ig,igcm_co2_ice)=0
-              emis(ig)=emis(ngridmx/2)
-           end do
-          else
-            write(*,*) "Can't remove CO2 ice!! (no co2_ice tracer)"
-          endif
-        
-!       therm_ini_s: (re)-set soil thermal inertia to reference surface values
-!       ----------------------------------------------------------------------
-
-	else if (modif(1:len_trim(modif)).eq.'therm_ini_s') then
-!          write(*,*)"surfithfi(1):",surfithfi(1)
-	  do isoil=1,nsoilmx
-	    inertiedat(1:ngridmx,isoil)=surfithfi(1:ngridmx)
-	  enddo
-          write(*,*)'OK: Soil thermal inertia has been reset to referenc
-     &e surface values'
-!	  write(*,*)"inertiedat(1,1):",inertiedat(1,1)
-	  ithfi(:,:)=inertiedat(:,:)
-	 ! recast ithfi() onto ith()
-	 call gr_fi_dyn(nsoilmx,ngridmx,iip1,jjp1,ithfi,ith)
-! Check:
-!         do i=1,iip1
-!           do j=1,jjp1
-!             do isoil=1,nsoilmx
-!               write(77,*) i,j,isoil,"  ",ith(i,j,isoil)
-!             enddo
-!           enddo
-!	 enddo
-
-!       subsoilice_n: Put deep ice layer in northern hemisphere soil
-!       ------------------------------------------------------------
-
-	else if (modif(1:len_trim(modif)).eq.'subsoilice_n') then
-
-         write(*,*)'From which latitude (in deg.), up to the north pole,
-     &should we put subterranean ice?'
-	 ierr=1
-	 do while (ierr.ne.0)
-	  read(*,*,iostat=ierr) val
-	  if (ierr.eq.0) then ! got a value
-	    ! do a sanity check
-	    if((val.lt.0.).or.(val.gt.90)) then
-	      write(*,*)'Latitude should be between 0 and 90 deg. !!!'
-	      ierr=1
-	    else ! find corresponding jref (nearest latitude)
-	      ! note: rlatu(:) contains decreasing values of latitude
-	      !       starting from PI/2 to -PI/2
-	      do j=1,jjp1
-	        if ((rlatu(j)*180./pi.ge.val).and.
-     &              (rlatu(j+1)*180./pi.le.val)) then
-		  ! find which grid point is nearest to val:
-		  if (abs(rlatu(j)*180./pi-val).le.
-     &                abs((rlatu(j+1)*180./pi-val))) then
-		   jref=j
-		  else
-		   jref=j+1
-		  endif
-		 
-		 write(*,*)'Will use nearest grid latitude which is:',
-     &                     rlatu(jref)*180./pi
-		endif
-	      enddo ! of do j=1,jjp1
-	    endif ! of if((val.lt.0.).or.(val.gt.90))
-	  endif !of if (ierr.eq.0)
-	 enddo ! of do while
-
-         ! Build layers() (as in soil_settings.F)
-	 val2=sqrt(mlayer(0)*mlayer(1))
-	 val3=mlayer(1)/mlayer(0)
-	 do isoil=1,nsoilmx
-	   layer(isoil)=val2*(val3**(isoil-1))
-	 enddo
-
-         write(*,*)'At which depth (in m.) does the ice layer begin?'
-         write(*,*)'(currently, the deepest soil layer extends down to:'
-     &              ,layer(nsoilmx),')'
-	 ierr=1
-	 do while (ierr.ne.0)
-	  read(*,*,iostat=ierr) val2
-!	  write(*,*)'val2:',val2,'ierr=',ierr
-	  if (ierr.eq.0) then ! got a value, but do a sanity check
-	    if(val2.gt.layer(nsoilmx)) then
-	      write(*,*)'Depth should be less than ',layer(nsoilmx)
-	      ierr=1
-	    endif
-	    if(val2.lt.layer(1)) then
-	      write(*,*)'Depth should be more than ',layer(1)
-	      ierr=1
-	    endif
-	  endif
-         enddo ! of do while
-	 
-	 ! find the reference index iref the depth corresponds to
-!	 if (val2.lt.layer(1)) then
-!	  iref=1
-!	 else
-	  do isoil=1,nsoilmx-1
-	   if((val2.gt.layer(isoil)).and.(val2.lt.layer(isoil+1)))
-     &       then
-	     iref=isoil
-	     exit
-	   endif
-	  enddo
-!	 endif
-	 
-!	 write(*,*)'iref:',iref,'  jref:',jref
-!	 write(*,*)'layer',layer
-!	 write(*,*)'mlayer',mlayer
-         
-	 ! thermal inertia of the ice:
-	 ierr=1
-	 do while (ierr.ne.0)
-          write(*,*)'What is the value of subterranean ice thermal inert
-     &ia? (e.g.: 2000)'
-          read(*,*,iostat=ierr)iceith
-	 enddo ! of do while
-	 
-	 ! recast ithfi() onto ith()
-	 call gr_fi_dyn(nsoilmx,ngridmx,iip1,jjp1,ithfi,ith)
-	 
-	 do j=1,jref
-!	    write(*,*)'j:',j,'rlatu(j)*180./pi:',rlatu(j)*180./pi
-	    do i=1,iip1 ! loop on longitudes
-	     ! Build "equivalent" thermal inertia for the mixed layer
-	     ith(i,j,iref+1)=sqrt((layer(iref+1)-layer(iref))/
-     &                     (((val2-layer(iref))/(ith(i,j,iref)**2))+
-     &                      ((layer(iref+1)-val2)/(iceith)**2)))
-	     ! Set thermal inertia of lower layers
-	     do isoil=iref+2,nsoilmx
-	      ith(i,j,isoil)=iceith ! ice
-	     enddo
-	    enddo ! of do i=1,iip1 
-	 enddo ! of do j=1,jjp1
-	 
-
-	 CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
-
-!         do i=1,nsoilmx
-!	  write(*,*)'i:',i,'ithfi(1,i):',ithfi(1,i)
-!	 enddo
-
-	
-!       subsoilice_s: Put deep ice layer in southern hemisphere soil
-!       ------------------------------------------------------------
-
-	else if (modif(1:len_trim(modif)).eq.'subsoilice_s') then
-
-         write(*,*)'From which latitude (in deg.), down to the south pol
-     &e, should we put subterranean ice?'
-	 ierr=1
-	 do while (ierr.ne.0)
-	  read(*,*,iostat=ierr) val
-	  if (ierr.eq.0) then ! got a value
-	    ! do a sanity check
-	    if((val.gt.0.).or.(val.lt.-90)) then
-	      write(*,*)'Latitude should be between 0 and -90 deg. !!!'
-	      ierr=1
-	    else ! find corresponding jref (nearest latitude)
-	      ! note: rlatu(:) contains decreasing values of latitude
-	      !       starting from PI/2 to -PI/2
-	      do j=1,jjp1
-	        if ((rlatu(j)*180./pi.ge.val).and.
-     &              (rlatu(j+1)*180./pi.le.val)) then
-		  ! find which grid point is nearest to val:
-		  if (abs(rlatu(j)*180./pi-val).le.
-     &                abs((rlatu(j+1)*180./pi-val))) then
-		   jref=j
-		  else
-		   jref=j+1
-		  endif
-		 
-		 write(*,*)'Will use nearest grid latitude which is:',
-     &                     rlatu(jref)*180./pi
-		endif
-	      enddo ! of do j=1,jjp1
-	    endif ! of if((val.lt.0.).or.(val.gt.90))
-	  endif !of if (ierr.eq.0)
-	 enddo ! of do while
-
-         ! Build layers() (as in soil_settings.F)
-	 val2=sqrt(mlayer(0)*mlayer(1))
-	 val3=mlayer(1)/mlayer(0)
-	 do isoil=1,nsoilmx
-	   layer(isoil)=val2*(val3**(isoil-1))
-	 enddo
-
-         write(*,*)'At which depth (in m.) does the ice layer begin?'
-         write(*,*)'(currently, the deepest soil layer extends down to:'
-     &              ,layer(nsoilmx),')'
-	 ierr=1
-	 do while (ierr.ne.0)
-	  read(*,*,iostat=ierr) val2
-!	  write(*,*)'val2:',val2,'ierr=',ierr
-	  if (ierr.eq.0) then ! got a value, but do a sanity check
-	    if(val2.gt.layer(nsoilmx)) then
-	      write(*,*)'Depth should be less than ',layer(nsoilmx)
-	      ierr=1
-	    endif
-	    if(val2.lt.layer(1)) then
-	      write(*,*)'Depth should be more than ',layer(1)
-	      ierr=1
-	    endif
-	  endif
-         enddo ! of do while
-	 
-	 ! find the reference index iref the depth corresponds to
-	  do isoil=1,nsoilmx-1
-	   if((val2.gt.layer(isoil)).and.(val2.lt.layer(isoil+1)))
-     &       then
-	     iref=isoil
-	     exit
-	   endif
-	  enddo
-	 
-!	 write(*,*)'iref:',iref,'  jref:',jref
-         
-	 ! thermal inertia of the ice:
-	 ierr=1
-	 do while (ierr.ne.0)
-          write(*,*)'What is the value of subterranean ice thermal inert
-     &ia? (e.g.: 2000)'
-          read(*,*,iostat=ierr)iceith
-	 enddo ! of do while
-	 
-	 ! recast ithfi() onto ith()
-	 call gr_fi_dyn(nsoilmx,ngridmx,iip1,jjp1,ithfi,ith)
-	 
-	 do j=jref,jjp1
-!	    write(*,*)'j:',j,'rlatu(j)*180./pi:',rlatu(j)*180./pi
-	    do i=1,iip1 ! loop on longitudes
-	     ! Build "equivalent" thermal inertia for the mixed layer
-	     ith(i,j,iref+1)=sqrt((layer(iref+1)-layer(iref))/
-     &                     (((val2-layer(iref))/(ith(i,j,iref)**2))+
-     &                      ((layer(iref+1)-val2)/(iceith)**2)))
-	     ! Set thermal inertia of lower layers
-	     do isoil=iref+2,nsoilmx
-	      ith(i,j,isoil)=iceith ! ice
-	     enddo
-	    enddo ! of do i=1,iip1 
-	 enddo ! of do j=jref,jjp1
-	 
-
-	 CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
-
-c       'mons_ice' : use MONS data to build subsurface ice table
-c       --------------------------------------------------------
-        else if (modif(1:len_trim(modif)).eq.'mons_ice') then
-        
-       ! 1. Load MONS data
-        call load_MONS_data(MONS_Hdn,MONS_d21)
-        
-        ! 2. Get parameters from user
-        ierr=1
-	do while (ierr.ne.0)
-          write(*,*) "Coefficient to apply to MONS 'depth' in Northern",
-     &               " Hemisphere?"
-          write(*,*) " (should be somewhere between 3.2e-4 and 1.3e-3)"
-          read(*,*,iostat=ierr) MONS_coeffN
-        enddo
-        ierr=1
-	do while (ierr.ne.0)
-          write(*,*) "Coefficient to apply to MONS 'depth' in Southern",
-     &               " Hemisphere?"
-          write(*,*) " (should be somewhere between 3.2e-4 and 1.3e-3)"
-          read(*,*,iostat=ierr) MONS_coeffS
-        enddo
-        ierr=1
-        do while (ierr.ne.0)
-          write(*,*) "Value of subterranean ice thermal inertia?"
-          write(*,*) " (e.g.: 2000, or perhaps 2290)"
-          read(*,*,iostat=ierr) iceith
-        enddo
-        
-        ! 3. Build subterranean thermal inertia
-        
-        ! initialise subsurface inertia with reference surface values
-        do isoil=1,nsoilmx
-          ithfi(1:ngridmx,isoil)=surfithfi(1:ngridmx)
-        enddo
-        ! recast ithfi() onto ith()
-	call gr_fi_dyn(nsoilmx,ngridmx,iip1,jjp1,ithfi,ith)
-        
-        do i=1,iip1 ! loop on longitudes
-          do j=1,jjp1 ! loop on latitudes
-            ! set MONS_coeff
-            if (rlatu(j).ge.0) then ! northern hemisphere
-              ! N.B: rlatu(:) contains decreasing values of latitude
-	      !       starting from PI/2 to -PI/2
-              MONS_coeff=MONS_coeffN
-            else ! southern hemisphere
-              MONS_coeff=MONS_coeffS
-            endif
-            ! check if we should put subterranean ice
-            if (MONS_Hdn(i,j).ge.14.0) then ! no ice if Hdn<14%
-              ! compute depth at which ice lies:
-              val=MONS_d21(i,j)*MONS_coeff
-              ! compute val2= the diurnal skin depth of surface inertia
-              ! assuming a volumetric heat cap. of C=1.e6 J.m-3.K-1
-              val2=ith(i,j,1)*1.e-6*sqrt(88775./3.14159)
-              if (val.lt.val2) then
-                ! ice must be below the (surface inertia) diurnal skin depth
-                val=val2
-              endif
-              if (val.lt.layer(nsoilmx)) then ! subterranean ice
-                ! find the reference index iref that depth corresponds to
-                iref=0
-                do isoil=1,nsoilmx-1
-                 if ((val.ge.layer(isoil)).and.(val.lt.layer(isoil+1)))
-     &             then
-	           iref=isoil
-	           exit
-	         endif
-                enddo
-                ! Build "equivalent" thermal inertia for the mixed layer
-                ith(i,j,iref+1)=sqrt((layer(iref+1)-layer(iref))/
-     &                     (((val-layer(iref))/(ith(i,j,iref+1)**2))+
-     &                      ((layer(iref+1)-val)/(iceith)**2)))
-	        ! Set thermal inertia of lower layers
-                do isoil=iref+2,nsoilmx
-                  ith(i,j,isoil)=iceith 
-                enddo
-              endif ! of if (val.lt.layer(nsoilmx))
-            endif ! of if (MONS_Hdn(i,j).lt.14.0)
-          enddo ! do j=1,jjp1
-        enddo ! do i=1,iip1
-        
-! Check:
-!         do i=1,iip1
-!           do j=1,jjp1
-!             do isoil=1,nsoilmx
-!               write(77,*) i,j,isoil,"  ",ith(i,j,isoil)
-!             enddo
-!           enddo
-!	 enddo
-
-        ! recast ith() into ithfi()
-        CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
-        
-	else
-          write(*,*) '       Unknown (misspelled?) option!!!'
-        end if ! of if (modif(1:len_trim(modif)) .eq. '...') elseif ...
-	
-       enddo ! of do ! infinite loop on liste of changes
-
- 999  continue
-
- 
-c=======================================================================
-c   Correct pressure on the new grid (menu 0)
-c=======================================================================
-
-      if (choix_1.eq.0) then
-        r = 1000.*8.31/mugaz
-
-        do j=1,jjp1
-          do i=1,iip1
-             ps(i,j) = ps(i,j) * 
-     .            exp((phisold_newgrid(i,j)-phis(i,j)) /
-     .                                  (t(i,j,1) * r))
-          end do
-        end do
-  
-c periodicity of surface ps in longitude
-        do j=1,jjp1
-          ps(1,j) = ps(iip1,j)
-        end do
-      end if
-
-c=======================================================================
-c=======================================================================
-
-c=======================================================================
-c    Initialisation de la physique / ecriture de newstartfi :
-c=======================================================================
-
-
-      CALL inifilr 
-      CALL pression(ip1jmp1, ap, bp, ps, p3d)
-
-c-----------------------------------------------------------------------
-c   Initialisation  pks:
-c-----------------------------------------------------------------------
-
-      CALL exner_hyb(ip1jmp1, ps, p3d, beta, pks, pk, pkf)
-! Calcul de la temperature potentielle teta
-
-      if (flagtset) then
-          DO l=1,llm
-             DO j=1,jjp1
-                DO i=1,iim
-                   teta(i,j,l) = Tset(i,j,l) * cpp/pk(i,j,l)
-                ENDDO
-                teta (iip1,j,l)= teta (1,j,l)
-             ENDDO
-          ENDDO
-      else if (choix_1.eq.0) then
-         DO l=1,llm
-            DO j=1,jjp1
-               DO i=1,iim
-                  teta(i,j,l) = t(i,j,l) * cpp/pk(i,j,l)
-               ENDDO
-               teta (iip1,j,l)= teta (1,j,l)
-            ENDDO
-         ENDDO
-      endif
-
-C Calcul intermediaire
-c
-      if (choix_1.eq.0) then
-         CALL massdair( p3d, masse  )
-c
-         print *,' ALPHAX ',alphax
-
-         DO  l = 1, llm
-           DO  i    = 1, iim
-             xppn(i) = aire( i, 1   ) * masse(  i     ,  1   , l )
-             xpps(i) = aire( i,jjp1 ) * masse(  i     , jjp1 , l )
-           ENDDO
-             xpn      = SUM(xppn)/apoln
-             xps      = SUM(xpps)/apols
-           DO i   = 1, iip1
-             masse(   i   ,   1     ,  l )   = xpn
-             masse(   i   ,   jjp1  ,  l )   = xps
-           ENDDO
-         ENDDO
-      endif
-      phis(iip1,:) = phis(1,:)
-
-      CALL inidissip ( lstardis, nitergdiv, nitergrot, niterh,
-     *                tetagdiv, tetagrot , tetatemp  )
-      itau=0
-      if (choix_1.eq.0) then
-         day_ini=int(date)
-      endif
-c
-      CALL geopot  ( ip1jmp1, teta  , pk , pks,  phis  , phi   )
-
-      CALL caldyn0( itau,ucov,vcov,teta,ps,masse,pk,phis ,
-     *                phi,w, pbaru,pbarv,day_ini+time )
-c     CALL caldyn
-c    $  ( itau,ucov,vcov,teta,ps,masse,pk,pkf,phis ,
-c    $    phi,conser,du,dv,dteta,dp,w, pbaru,pbarv, day_ini )
-
-      CALL dynredem0("restart.nc",day_ini,anneeref,phis,nqmx)
-      CALL dynredem1("restart.nc",0.0,vcov,ucov,teta,q,nqmx,masse,ps) 
-C
-C Ecriture etat initial physique
-C
-
-      call physdem1("restartfi.nc",lonfi,latfi,nsoilmx,nqmx,
-     .              dtphys,float(day_ini),
-     .              time,tsurf,tsoil,emis,q2,qsurf,
-     .              airefi,albfi,ithfi,zmea,zstd,zsig,zgam,zthe)
-
-c=======================================================================
-c	Formats 
-c=======================================================================
-
-   1  FORMAT(//10x,'la valeur de im =',i4,2x,'lue sur le fichier de dema
-     *rrage est differente de la valeur parametree iim =',i4//)
-   2  FORMAT(//10x,'la valeur de jm =',i4,2x,'lue sur le fichier de dema
-     *rrage est differente de la valeur parametree jjm =',i4//)
-   3  FORMAT(//10x,'la valeur de lllm =',i4,2x,'lue sur le fichier demar
-     *rage est differente de la valeur parametree llm =',i4//)
-
-      end
-
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-      subroutine load_MONS_data(MONS_Hdn,MONS_d21)
-      implicit none
-      ! routine to load Benedicte Diez MONS dataset, fill in date in southern
-      ! polar region, and interpolate the result onto the GCM grid
-#include"dimensions.h"
-#include"paramet.h"
-#include"datafile.h"
-#include"comgeom.h"
-      ! arguments:
-      real,intent(out) :: MONS_Hdn(iip1,jjp1) ! Hdn: %WEH=Mass fraction of H2O
-      real,intent(out) :: MONS_d21(iip1,jjp1) ! ice table "depth" (in kg/m2)
-      ! N.B MONS datasets should be of dimension (iip1,jjp1)
-      ! local variables:
-      character(len=88) :: filename="results_MONS_lat_lon_H_depth.txt"
-      character(len=88) :: txt ! to store some text
-      integer :: ierr,i,j
-      integer,parameter :: nblon=180 ! number of longitudes of MONS datasets
-      integer,parameter :: nblat=90 ! number of latitudes of MONS datasets
-      real :: pi
-      real :: longitudes(nblon) ! MONS dataset longitudes
-      real :: latitudes(nblat)  ! MONS dataset latitudes
-      ! MONS dataset: mass fraction of H2O where H is assumed to be in H2O
-      real :: Hdn(nblon,nblat)
-      real :: d21(nblon,nblat)! MONS dataset "depth" (g/cm2)
-
-      ! Extended MONS dataset (for interp_horiz)
-      real :: Hdnx(nblon+1,nblat)
-      real :: d21x(nblon+1,nblat)
-      real :: lon_bound(nblon+1) ! longitude boundaries
-      real :: lat_bound(nblat-1) ! latitude boundaries
-
-      ! 1. Initializations:
-
-      write(*,*) "Loading MONS data"
-
-      ! Open MONS datafile:
-      open(42,file=trim(datafile)//"/"//trim(filename),
-     &     status="old",iostat=ierr)
-      if (ierr/=0) then
-        write(*,*) "Error in load_MONS_data:"
-        write(*,*) "Failed opening file ",
-     &             trim(datafile)//"/"//trim(filename)
-        write(*,*)'1) You can change the path to the file in '
-        write(*,*)'   file phymars/datafile.h'
-        write(*,*)'2) If necessary ',trim(filename),
-     &                 ' (and other datafiles)'
-        write(*,*)'   can be obtained online at:'
-        write(*,*)' http://www.lmd.jussieu.fr/~forget/datagcm/datafile'
-        CALL ABORT
-      else ! skip first line of file (dummy read)
-         read(42,*) txt
-      endif
-
-      pi=2.*asin(1.)
-      
-      !2. Load MONS data (on MONS grid)
-      do j=1,nblat
-        do i=1,nblon
-        ! swap latitude index so latitudes go from north pole to south pole:
-          read(42,*) latitudes(nblat-j+1),longitudes(i),
-     &               Hdn(i,nblat-j+1),d21(i,nblat-j+1)
-        ! multiply d21 by 10 to convert from g/cm2 to kg/m2
-          d21(i,nblat-j+1)=d21(i,nblat-j+1)*10.0
-        enddo
-      enddo
-      close(42)
-      
-      ! there is unfortunately no d21 data for latitudes -77 to -90
-      ! so we build some by linear interpolation between values at -75
-      ! and assuming d21=0 at the pole
-      do j=84,90 ! latitudes(84)=-77 ; latitudes(83)=-75
-        do i=1,nblon
-          d21(i,j)=d21(i,83)*((latitudes(j)+90)/15.0)
-        enddo
-      enddo
-
-      ! 3. Build extended MONS dataset & boundaries (for interp_horiz)
-      ! longitude boundaries (in radians):
-      do i=1,nblon
-        ! NB: MONS data is every 2 degrees in longitude
-        lon_bound(i)=(longitudes(i)+1.0)*pi/180.0
-      enddo
-      ! extra 'modulo' value
-      lon_bound(nblon+1)=lon_bound(1)+2.0*pi
-      
-      ! latitude boundaries (in radians):
-      do j=1,nblat-1
-        ! NB: Mons data is every 2 degrees in latitude
-        lat_bound(j)=(latitudes(j)-1.0)*pi/180.0
-      enddo
-      
-      ! MONS datasets:
-      do j=1,nblat
-        Hdnx(1:nblon,j)=Hdn(1:nblon,j)
-        Hdnx(nblon+1,j)=Hdnx(1,j)
-        d21x(1:nblon,j)=d21(1:nblon,j)
-        d21x(nblon+1,j)=d21x(1,j)
-      enddo
-      
-      ! Interpolate onto GCM grid
-      call interp_horiz(Hdnx,MONS_Hdn,nblon,nblat-1,iim,jjm,1,
-     &                  lon_bound,lat_bound,rlonu,rlatv)
-      call interp_horiz(d21x,MONS_d21,nblon,nblat-1,iim,jjm,1,
-     &                  lon_bound,lat_bound,rlonu,rlatv)
-      
-      end subroutine
Index: unk/LMDZ.GENERIC/libf/dyn3d/newstart.old2
===================================================================
--- /trunk/LMDZ.GENERIC/libf/dyn3d/newstart.old2	(revision 252)
+++ 	(revision )
@@ -1,1569 +1,0 @@
-C======================================================================
-      PROGRAM newstart
-c=======================================================================
-c
-c
-c   Auteur:   Christophe Hourdin/Francois Forget/Yann Wanherdrick
-c   ------
-c             Derniere modif : 12/03
-c
-c
-c   Objet:  Create or modify the initial state for the LMD Mars GCM
-c   -----           (fichiers NetCDF start et startfi)
-c
-c
-c=======================================================================
-
-      implicit none
-
-#include "dimensions.h"
-#include "dimphys.h"
-#include "surfdat.h"
-#include "comsoil.h"
-#include "planete.h"
-#include "paramet.h"
-#include "comconst.h"
-#include "comvert.h"
-#include "comgeom2.h"
-#include "control.h"
-#include "logic.h"
-#include "description.h"
-#include "ener.h"
-#include "temps.h"
-#include "lmdstd.h"
-#include "comdissnew.h"
-#include "clesph0.h"
-#include "serre.h"
-#include "netcdf.inc"
-#include "advtrac.h"
-#include "tracer.h"
-c=======================================================================
-c   Declarations
-c=======================================================================
-
-c Variables dimension du fichier "start_archive"
-c------------------------------------
-      CHARACTER	relief*3
-
-
-c Variables pour les lectures NetCDF des fichiers "start_archive" 
-c--------------------------------------------------
-      INTEGER nid_dyn, nid_fi,nid,nvarid
-      INTEGER length
-      parameter (length = 100)
-      INTEGER tab0
-      INTEGER   NB_ETATMAX
-      parameter (NB_ETATMAX = 100)
-
-      REAL  date
-      REAL p_rad,p_omeg,p_g,p_mugaz,p_daysec
-
-c Variable histoire 
-c------------------
-      REAL vcov(iip1,jjm,llm),ucov(iip1,jjp1,llm) ! vents covariants
-      REAL phis(iip1,jjp1)
-      REAL q(iip1,jjp1,llm,nqmx)               ! champs advectes
-
-c autre variables dynamique nouvelle grille
-c------------------------------------------
-      REAL pks(iip1,jjp1)
-      REAL w(iip1,jjp1,llm+1)
-      REAL pbaru(ip1jmp1,llm),pbarv(ip1jm,llm)
-!      REAL dv(ip1jm,llm),du(ip1jmp1,llm)
-!      REAL dh(ip1jmp1,llm),dp(ip1jmp1)
-      REAL phi(iip1,jjp1,llm)
-
-      integer klatdat,klongdat
-      PARAMETER (klatdat=180,klongdat=360)
-
-c Physique sur grille scalaire 
-c----------------------------
-      real zmeaS(iip1,jjp1),zstdS(iip1,jjp1)
-      real zsigS(iip1,jjp1),zgamS(iip1,jjp1),ztheS(iip1,jjp1)
-
-c variable physique
-c------------------
-      REAL tsurf(ngridmx)	! surface temperature
-      REAL tsoil(ngridmx,nsoilmx) ! soil temperature
-!      REAL co2ice(ngridmx)	! CO2 ice layer
-      REAL emis(ngridmx)	! surface emissivity
-      REAL qsurf(ngridmx,nqmx)
-      REAL q2(ngridmx,nlayermx+1)
-!      REAL rnaturfi(ngridmx)
-      real alb(iip1,jjp1),albfi(ngridmx) ! albedos
-      real ith(iip1,jjp1,nsoilmx),ithfi(ngridmx,nsoilmx) ! thermal inertia (3D)
-      real surfith(iip1,jjp1),surfithfi(ngridmx) ! surface thermal inertia (2D)
-      REAL latfi(ngridmx),lonfi(ngridmx),airefi(ngridmx)
-
-      INTEGER i,j,l,isoil,ig,idum
-      real mugaz ! molar mass of the atmosphere
-
-      integer ierr 
-
-c Variables on the new grid along scalar points 
-c------------------------------------------------------
-!      REAL p(iip1,jjp1)
-      REAL t(iip1,jjp1,llm)
-      REAL tset(iip1,jjp1,llm)
-      real phisold_newgrid(iip1,jjp1)
-      REAL :: teta(iip1, jjp1, llm)
-      REAL :: pk(iip1,jjp1,llm)
-      REAL :: pkf(iip1,jjp1,llm)
-      REAL :: ps(iip1, jjp1)
-      REAL :: masse(iip1,jjp1,llm)
-      REAL :: xpn,xps,xppn(iim),xpps(iim)
-      REAL :: p3d(iip1, jjp1, llm+1)
-      REAL :: beta(iip1,jjp1,llm)
-!      REAL dteta(ip1jmp1,llm)
-
-c Variable de l'ancienne grille 
-c------------------------------
-      real time
-      real tab_cntrl(100)
-      real tab_cntrl_bis(100)
-
-c variables diverses
-c-------------------
-      real choix_1,pp
-      character*80      fichnom
-      integer Lmodif,iq,thermo
-      character modif*20
-      real z_reel(iip1,jjp1)
-      real tsud,albsud,alb_bb,ith_bb,Tiso,Tabove
-      real ptoto,pcap,patm,airetot,ptotn,patmn
-!      real ssum
-      character*1 yes
-      logical :: flagtset=.false. ,  flagps0=.false.
-      real val, val2, val3 ! to store temporary variables
-      real :: iceith=2000 ! thermal inertia of subterranean ice
-      integer iref,jref
-
-      INTEGER :: itau
-      
-      INTEGER :: nq,numvanle
-      character(len=20) :: txt ! to store some text
-      integer :: count
-
-! MONS data:
-      real :: MONS_Hdn(iip1,jjp1) ! Hdn: %WEH=Mass fraction of H2O
-      real :: MONS_d21(iip1,jjp1) ! ice table "depth" (in kg/m2)
-      ! coefficient to apply to convert d21 to 'true' depth (m)
-      real :: MONS_coeff
-      real :: MONS_coeffS ! coeff for southern hemisphere
-      real :: MONS_coeffN ! coeff for northern hemisphere
-!      real,parameter :: icedepthmin=1.e-3 ! Ice begins at most at that depth
-
-c sortie visu pour les champs dynamiques
-c---------------------------------------
-!      INTEGER :: visuid
-!      real :: time_step,t_ops,t_wrt
-!      CHARACTER*80 :: visu_file
-
-      cpp    = 744.499 ! for Mars, instead of 1004.70885 (Earth)
-
-
-      preff  = 610.    ! for Mars, instead of 101325. (Earth)
-      pa= 20           ! for Mars, instead of 500 (Earth)
-
-c=======================================================================
-c   Choice of the start file(s) to use
-c=======================================================================
-
-      write(*,*) 'From which kind of files do you want to create new',
-     .  'start and startfi files'
-      write(*,*) '    0 - from a file start_archive'
-      write(*,*) '    1 - from files start and startfi'
- 
-c-----------------------------------------------------------------------
-c   Open file(s) to modify (start or start_archive)
-c-----------------------------------------------------------------------
-
-      DO
-         read(*,*,iostat=ierr) choix_1
-         if ((choix_1 /= 0).OR.(choix_1 /=1)) EXIT
-      ENDDO
-
-c     Open start_archive
-c     ~~~~~~~~~~~~~~~~~~~~~~~~~~
-      if (choix_1.eq.0) then
-
-        write(*,*) 'Creating start files from:'
-        write(*,*) './start_archive.nc'
-        write(*,*)
-        fichnom = 'start_archive.nc'
-        ierr = NF_OPEN (fichnom, NF_NOWRITE,nid)
-        IF (ierr.NE.NF_NOERR) THEN
-          write(6,*)' Problem opening file:',fichnom
-          write(6,*)' ierr = ', ierr
-          CALL ABORT
-        ENDIF
-        tab0 = 50 
-        Lmodif = 1
-
-c     OR open start and startfi files
-c     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-      else
-        write(*,*) 'Creating start files from:'
-        write(*,*) './start.nc and ./startfi.nc'
-        write(*,*)
-        fichnom = 'start.nc'
-        ierr = NF_OPEN (fichnom, NF_NOWRITE,nid_dyn)
-        IF (ierr.NE.NF_NOERR) THEN
-          write(6,*)' Problem opening file:',fichnom
-          write(6,*)' ierr = ', ierr
-          CALL ABORT
-        ENDIF
- 
-        fichnom = 'startfi.nc'
-        ierr = NF_OPEN (fichnom, NF_NOWRITE,nid_fi)
-        IF (ierr.NE.NF_NOERR) THEN
-          write(6,*)' Problem opening file:',fichnom
-          write(6,*)' ierr = ', ierr
-          CALL ABORT
-        ENDIF
-
-        tab0 = 0 
-        Lmodif = 0
-
-      endif
-
-c-----------------------------------------------------------------------
-c Lecture du tableau des parametres du run (pour la dynamique)
-c-----------------------------------------------------------------------
-
-      if (choix_1.eq.0) then
-
-        write(*,*) 'reading tab_cntrl START_ARCHIVE'
-c
-        ierr = NF_INQ_VARID (nid, "controle", nvarid)
-#ifdef NC_DOUBLE
-        ierr = NF_GET_VAR_DOUBLE(nid, nvarid, tab_cntrl)
-#else
-        ierr = NF_GET_VAR_REAL(nid, nvarid, tab_cntrl)
-#endif
-c
-      else if (choix_1.eq.1) then
-
-        write(*,*) 'reading tab_cntrl START'
-c
-        ierr = NF_INQ_VARID (nid_dyn, "controle", nvarid)
-#ifdef NC_DOUBLE
-        ierr = NF_GET_VAR_DOUBLE(nid_dyn, nvarid, tab_cntrl)
-#else
-        ierr = NF_GET_VAR_REAL(nid_dyn, nvarid, tab_cntrl)
-#endif
-c
-        write(*,*) 'reading tab_cntrl STARTFI'
-c
-        ierr = NF_INQ_VARID (nid_fi, "controle", nvarid)
-#ifdef NC_DOUBLE
-        ierr = NF_GET_VAR_DOUBLE(nid_fi, nvarid, tab_cntrl_bis)
-#else
-        ierr = NF_GET_VAR_REAL(nid_fi, nvarid, tab_cntrl_bis)
-#endif
-c
-        do i=1,50
-          tab_cntrl(i+50)=tab_cntrl_bis(i)
-        enddo
-      write(*,*) 'printing tab_cntrl', tab_cntrl
-      do i=1,100
-        write(*,*) i,tab_cntrl(i)
-      enddo
-      
-      endif
-c-----------------------------------------------------------------------
-c		Initialisation des constantes dynamique
-c-----------------------------------------------------------------------
-
-      kappa = tab_cntrl(9) 
-      etot0 = tab_cntrl(12)
-      ptot0 = tab_cntrl(13)
-      ztot0 = tab_cntrl(14)
-      stot0 = tab_cntrl(15)
-      ang0 = tab_cntrl(16)
-      write(*,*) "Newstart: kappa,etot0,ptot0,ztot0,stot0,ang0"
-      write(*,*) kappa,etot0,ptot0,ztot0,stot0,ang0
-
-      ! for vertical coordinate
-      preff=tab_cntrl(18) ! reference surface pressure
-      pa=tab_cntrl(17)  ! reference pressure at which coord is purely pressure
-      !NB: in start_archive files tab_cntrl(17)=tab_cntrl(18)=0
-      if (preff.eq.0) then
-        preff=610
-        pa=20
-      endif
-      write(*,*) "Newstart: preff=",preff," pa=",pa
-      yes=' '
-      do while ((yes.ne.'y').and.(yes.ne.'n'))
-        write(*,*) "Change the values of preff and pa? (y/n)"
-        read(*,fmt='(a)') yes
-      end do
-      if (yes.eq.'y') then
-        write(*,*)"New value of reference surface pressure preff?"
-        write(*,*)"   (for Mars, typically preff=610)"
-        read(*,*) preff
-        write(*,*)"New value of reference pressure pa for purely"
-        write(*,*)"pressure levels (for hybrid coordinates)?"
-        write(*,*)"   (for Mars, typically pa=20)"
-        read(*,*) pa
-      endif
-c-----------------------------------------------------------------------
-c   Lecture du tab_cntrl et initialisation des constantes physiques
-c  - pour start:  Lmodif = 0 => pas de modifications possibles
-c                  (modif dans le tabfi de readfi + loin)
-c  - pour start_archive:  Lmodif = 1 => modifications possibles
-c-----------------------------------------------------------------------
-      if (choix_1.eq.0) then
-         call tabfi (nid,Lmodif,tab0,day_ini,lllm,p_rad,
-     .            p_omeg,p_g,p_mugaz,p_daysec,time)
-      else if (choix_1.eq.1) then
-         call tabfi (nid_fi,Lmodif,tab0,day_ini,lllm,p_rad,
-     .            p_omeg,p_g,p_mugaz,p_daysec,time)
-      endif
-
-      rad = p_rad
-      omeg = p_omeg
-      g = p_g
-      mugaz = p_mugaz
-      daysec = p_daysec
-
-!      print*,'daysec=',p_daysec
-!      stop
-
-!      write(*,*) 'aire',aire
-
-
-c=======================================================================
-c  INITIALISATIONS DIVERSES
-c=======================================================================
-! Load tracer names:
-      call iniadvtrac(nq,numvanle)
-      ! tnom(:) now contains tracer names
-! Initialize global tracer indexes (stored in tracer.h)
-      call initracer()
-! Load parameters from run.def file
-      CALL defrun_new( 99, .TRUE. )
-      CALL iniconst 
-      CALL inigeom
-      idum=-1
-      idum=0
-
-c Initialisation coordonnees /aires
-c -------------------------------
-! Note: rlatu(:) and rlonv(:) are commons defined in "comgeom.h"
-!       rlatu() and rlonv() are given in radians
-      latfi(1)=rlatu(1)
-      lonfi(1)=0.
-      DO j=2,jjm
-         DO i=1,iim
-            latfi((j-2)*iim+1+i)=rlatu(j)
-            lonfi((j-2)*iim+1+i)=rlonv(i)
-         ENDDO
-      ENDDO
-      latfi(ngridmx)=rlatu(jjp1)
-      lonfi(ngridmx)=0.
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,aire,airefi)
-
-c=======================================================================
-c   lecture topographie, albedo, inertie thermique, relief sous-maille
-c=======================================================================
-
-      if (choix_1.ne.1) then  ! pour ne pas avoir besoin du fichier 
-                              ! surface.dat dans le cas des start
-
-c do while((relief(1:3).ne.'mol').AND.(relief(1:3).ne.'pla'))
-c       write(*,*)
-c       write(*,*) 'choix du relief (mola,pla)'
-c       write(*,*) '(Topographie MGS MOLA, plat)'
-c       read(*,fmt='(a3)') relief
-        relief="mola"
-c     enddo
-
-      CALL datareadnc(relief,phis,alb,surfith,zmeaS,zstdS,zsigS,zgamS,
-     .          ztheS)
-
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,phis,phisfi)
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,surfith,surfithfi)
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,alb,albfi)
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,zmeaS,zmea)
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,zstdS,zstd)
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,zsigS,zsig)
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,zgamS,zgam)
-      CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,ztheS,zthe)
-
-      endif ! of if (choix_1.ne.1)
-
-
-c=======================================================================
-c  Lecture des fichiers (start ou start_archive)
-c=======================================================================
-
-      if (choix_1.eq.0) then
-
-        write(*,*) 'Reading file START_ARCHIVE'
-        CALL lect_start_archive(date,tsurf,tsoil,emis,q2,
-     .   t,ucov,vcov,ps,teta,phisold_newgrid,q,qsurf,
-     &   surfith,nid)
-        write(*,*) "OK, read start_archive file"
-	! copy soil thermal inertia
-	ithfi(:,:)=inertiedat(:,:)
-	
-        ierr= NF_CLOSE(nid)
-
-      else if (choix_1.eq.1) then !  c'est l'appel a tabfi de phyeta0 qui
-                                  !  permet de changer les valeurs du 
-                                  !  tab_cntrl Lmodif=1
-        tab0=0
-        Lmodif=1 ! Lmodif set to 1 to allow modifications in phyeta0                           
-        write(*,*) 'Reading file START'
-        fichnom = 'start.nc'
-        CALL dynetat0(fichnom,nqmx,vcov,ucov,teta,q,masse,
-     .       ps,phis,time)
-
-        write(*,*) 'Reading file STARTFI'
-        fichnom = 'startfi.nc'
-        CALL phyetat0 (fichnom,tab0,Lmodif,nsoilmx,nqmx,
-     .        day_ini,time,
-     .        tsurf,tsoil,emis,q2,qsurf)
-        
-        ! copy albedo and soil thermal inertia
-        do i=1,ngridmx
-          albfi(i) = albedodat(i)
-	  do j=1,nsoilmx
-           ithfi(i,j) = inertiedat(i,j)
-	  enddo
-        ! build a surfithfi(:) using 1st layer of ithfi(:), which might
-        ! be neede later on if reinitializing soil thermal inertia
-          surfithfi(i)=ithfi(i,1)
-        enddo
-
-      else 
-        CALL exit(1)
-      endif
-
-      dtvr   = daysec/FLOAT(day_step)
-      dtphys   = dtvr * FLOAT(iphysiq)
-
-c=======================================================================
-c 
-c=======================================================================
-
-      do ! infinite loop on list of changes
-
-      write(*,*)
-      write(*,*)
-      write(*,*) 'List of possible changes :'
-      write(*,*) '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
-      write(*,*)
-      write(*,*) 'flat : no topography ("aquaplanet")'
-      write(*,*) 'bilball : uniform albedo and thermal inertia'
-      write(*,*) 'coldspole : cold subsurface and high albedo at S.pole'
-      write(*,*) 'qname : change tracer name'
-      write(*,*) 'q=0 : ALL tracer =zero'
-      write(*,*) 'q=x : give a specific uniform value to one tracer'
-      write(*,*) 'ini_q : tracers initialisation for chemistry, water an
-     $d ice   '
-      write(*,*) 'ini_q-H2O : tracers initialisation for chemistry and 
-     $ice '
-      write(*,*) 'ini_q-iceH2O : tracers initialisation for chemistry on
-     $ly '
-      write(*,*) 'noglacier : Remove tropical H2O ice if |lat|<45'
-      write(*,*) 'watercapn : H20 ice on permanent N polar cap '
-      write(*,*) 'watercaps : H20 ice on permanent S polar cap '
-      write(*,*) 'wetstart  : start with a wet atmosphere'
-      write(*,*) 'isotherm : Isothermal Temperatures, wind set to zero'
-      write(*,*) 'coldstart : Start X K above the CO2 frost point and 
-     $set wind to zero (assumes 100% CO2)'
-      write(*,*) 'co2ice=0 : remove CO2 polar cap'
-      write(*,*) 'ptot : change total pressure'
-      write(*,*) 'therm_ini_s: Set soil thermal inertia to reference sur
-     &face values'
-      write(*,*) 'subsoilice_n: Put deep underground ice layer in northe
-     &rn hemisphere'
-      write(*,*) 'subsoilice_s: Put deep underground ice layer in southe
-     &rn hemisphere'
-      write(*,*) 'mons_ice: Put underground ice layer according to MONS-
-     &derived data'
-
-        write(*,*)
-        write(*,*) 'Change to perform ?'
-        write(*,*) '   (enter keyword or return to end)'
-        write(*,*)
-
-        read(*,fmt='(a20)') modif
-        if (modif(1:1) .eq. ' ') exit ! exit loop on changes
-
-        write(*,*)
-        write(*,*) trim(modif) , ' : '
-
-c       'flat : no topography ("aquaplanet")'
-c       -------------------------------------
-        if (modif(1:len_trim(modif)) .eq. 'flat') then
-c         set topo to zero 
-          CALL initial0(ip1jmp1,z_reel)
-          CALL multscal(ip1jmp1,z_reel,g,phis)
-          CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,phis,phisfi)
-          write(*,*) 'topography set to zero.'
-          write(*,*) 'WARNING : the subgrid topography parameters',
-     &    ' were not set to zero ! => set calllott to F'                    
-
-c        Choice for surface pressure
-         yes=' '
-         do while ((yes.ne.'y').and.(yes.ne.'n'))
-            write(*,*) 'Do you wish to choose homogeneous surface',
-     &                 'pressure (y) or let newstart interpolate ',
-     &                 ' the previous field  (n)?'
-             read(*,fmt='(a)') yes
-         end do
-         if (yes.eq.'y') then
-           flagps0=.true.
-           write(*,*) 'New value for ps (Pa) ?'
- 201       read(*,*,iostat=ierr) patm
-            if(ierr.ne.0) goto 201
-             write(*,*)
-             write(*,*) ' new ps everywhere (Pa) = ', patm
-             write(*,*)
-             do j=1,jjp1
-               do i=1,iip1
-                 ps(i,j)=patm
-               enddo
-             enddo
-         end if
-
-c       bilball : albedo, inertie thermique uniforme
-c       --------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'bilball') then
-          write(*,*) 'constante albedo and iner.therm:'
-          write(*,*) 'New value for albedo (ex: 0.25) ?'
- 101      read(*,*,iostat=ierr) alb_bb
-          if(ierr.ne.0) goto 101
-          write(*,*)
-          write(*,*) ' uniform albedo (new value):',alb_bb
-          write(*,*)
-
-          write(*,*) 'New value for thermal inertia (eg: 247) ?'
- 102      read(*,*,iostat=ierr) ith_bb
-          if(ierr.ne.0) goto 102
-          write(*,*) 'uniform thermal inertia (new value):',ith_bb
-          DO j=1,jjp1
-             DO i=1,iip1
-                alb(i,j) = alb_bb	! albedo
-		do isoil=1,nsoilmx
-                  ith(i,j,isoil) = ith_bb	! thermal inertia
-		enddo
-             END DO
-          END DO
-!          CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,ith,ithfi)
-          CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
-          CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,alb,albfi)
-
-c       coldspole : sous-sol de la calotte sud toujours froid
-c       -----------------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'coldspole') then
-          write(*,*)'new value for the subsurface temperature',
-     &   ' beneath the permanent southern polar cap ? (eg: 141 K)'
- 103      read(*,*,iostat=ierr) tsud
-          if(ierr.ne.0) goto 103
-          write(*,*)
-          write(*,*) ' new value of the subsurface temperature:',tsud
-c         nouvelle temperature sous la calotte permanente
-          do l=2,nsoilmx
-               tsoil(ngridmx,l) =  tsud
-          end do
-
-
-          write(*,*)'new value for the albedo',
-     &   'of the permanent southern polar cap ? (eg: 0.75)'
- 104      read(*,*,iostat=ierr) albsud
-          if(ierr.ne.0) goto 104
-          write(*,*)
-
-c         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-c         Option 1:  only the albedo of the pole is modified :    
-          albfi(ngridmx)=albsud
-          write(*,*) 'ig=',ngridmx,'   albedo perennial cap ',
-     &    albfi(ngridmx)
-
-c         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
-c          Option 2 A haute resolution : coordonnee de la vrai calotte ~    
-c           DO j=1,jjp1
-c             DO i=1,iip1
-c                ig=1+(j-2)*iim +i
-c                if(j.eq.1) ig=1
-c                if(j.eq.jjp1) ig=ngridmx
-c                if ((rlatu(j)*180./pi.lt.-84.).and.
-c     &            (rlatu(j)*180./pi.gt.-91.).and.
-c     &            (rlonv(i)*180./pi.gt.-91.).and.
-c     &            (rlonv(i)*180./pi.lt.0.))         then
-cc    albedo de la calotte permanente fixe a albsud
-c                   alb(i,j)=albsud
-c                   write(*,*) 'lat=',rlatu(j)*180./pi,
-c     &                      ' lon=',rlonv(i)*180./pi
-cc     fin de la condition sur les limites de la calotte permanente
-c                end if
-c             ENDDO
-c          ENDDO
-c      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-c         CALL gr_dyn_fi(1,iip1,jjp1,ngridmx,alb,albfi)
-
-
-c       ptot : Modification of the total pressure: ice + current atmosphere 
-c       -------------------------------------------------------------------
-        else if (modif(1:len_trim(modif)).eq.'ptot') then
-
-          ! check if we have a co2_ice surface tracer:
-          if (igcm_co2_ice.eq.0) then
-            write(*,*) " No surface CO2 ice !"
-            write(*,*) " only atmospheric pressure will be considered!"
-          endif
-c         calcul de la pression totale glace + atm actuelle
-          patm=0.
-          airetot=0.
-          pcap=0.
-          DO j=1,jjp1
-             DO i=1,iim
-                ig=1+(j-2)*iim +i
-                if(j.eq.1) ig=1
-                if(j.eq.jjp1) ig=ngridmx
-                patm = patm + ps(i,j)*aire(i,j)
-                airetot= airetot + aire(i,j)
-                if (igcm_co2_ice.ne.0) then
-                  !pcap = pcap + aire(i,j)*co2ice(ig)*g
-                  pcap = pcap + aire(i,j)*qsurf(ig,igcm_co2_ice)*g
-                endif
-             ENDDO
-          ENDDO
-          ptoto = pcap + patm
-
-          print*,'Current total pressure at surface (co2 ice + atm) ',
-     &       ptoto/airetot
-
-          print*,'new value?'
-          read(*,*) ptotn
-          ptotn=ptotn*airetot
-          patmn=ptotn-pcap
-          print*,'ptoto,patm,ptotn,patmn'
-          print*,ptoto,patm,ptotn,patmn
-          print*,'Mult. factor for pressure (atm only)', patmn/patm
-          do j=1,jjp1
-             do i=1,iip1
-                ps(i,j)=ps(i,j)*patmn/patm
-             enddo
-          enddo
-
-c        Correction pour la conservation des traceurs
-         yes=' '
-         do while ((yes.ne.'y').and.(yes.ne.'n'))
-            write(*,*) 'Do you wish to conserve tracer total mass (y)',
-     &              ' or tracer mixing ratio (n) ?'
-             read(*,fmt='(a)') yes
-         end do
-
-         if (yes.eq.'y') then
-           write(*,*) 'OK : conservation of tracer total mass'
-           DO iq =1, nqmx
-             DO l=1,llm
-               DO j=1,jjp1
-                  DO i=1,iip1
-                    q(i,j,l,iq)=q(i,j,l,iq)*patm/patmn
-                  ENDDO
-               ENDDO
-             ENDDO
-           ENDDO
-          else
-            write(*,*) 'OK : conservation of tracer mixing ratio'
-          end if
-
-c       qname : change tracer name
-c       --------------------------
-        else if (trim(modif).eq.'qname') then
-         yes='y'
-         do while (yes.eq.'y')
-          write(*,*) 'Which tracer name do you want to change ?'
-          do iq=1,nqmx
-            write(*,'(i3,a3,a20)')iq,' : ',trim(tnom(iq))
-          enddo
-          write(*,'(a35,i3)')
-     &            '(enter tracer number; between 1 and ',nqmx
-          write(*,*)' or any other value to quit this option)'
-          read(*,*) iq
-          if ((iq.ge.1).and.(iq.le.nqmx)) then
-            write(*,*)'Change tracer name ',trim(tnom(iq)),' to ?'
-            read(*,*) txt
-            tnom(iq)=txt
-            write(*,*)'Do you want to change another tracer name (y/n)?'
-            read(*,'(a)') yes 
-          else
-! inapropiate value of iq; quit this option
-            yes='n'
-          endif ! of if ((iq.ge.1).and.(iq.le.nqmx))
-         enddo ! of do while (yes.ne.'y')
-
-c       q=0 : set tracers to zero
-c       -------------------------
-        else if (modif(1:len_trim(modif)).eq.'q=0') then
-c          mise a 0 des q (traceurs)
-          write(*,*) 'Tracers set to 0 (1.E-30 in fact)'
-           DO iq =1, nqmx
-             DO l=1,llm
-               DO j=1,jjp1
-                  DO i=1,iip1
-                    q(i,j,l,iq)=1.e-30
-                  ENDDO
-               ENDDO
-             ENDDO
-           ENDDO
-
-c          set surface tracers to zero
-           DO iq =1, nqmx
-             DO ig=1,ngridmx
-                 qsurf(ig,iq)=0.
-             ENDDO
-           ENDDO
-
-c       q=x : initialise tracer manually 
-c       --------------------------------
-        else if (modif(1:len_trim(modif)).eq.'q=x') then
-             write(*,*) 'Which tracer do you want to modify ?'
-             do iq=1,nqmx
-               write(*,*)iq,' : ',trim(tnom(iq))
-             enddo
-             write(*,*) '(choose between 1 and ',nqmx,')'
-             read(*,*) iq 
-             write(*,*)'mixing ratio of tracer ',trim(tnom(iq)),
-     &                 ' ? (kg/kg)'
-             read(*,*) val
-             DO l=1,llm
-               DO j=1,jjp1
-                  DO i=1,iip1
-                    q(i,j,l,iq)=val
-                  ENDDO
-               ENDDO
-             ENDDO
-             write(*,*) 'SURFACE value of tracer ',trim(tnom(iq)),
-     &                   ' ? (kg/m2)'
-             read(*,*) val
-             DO ig=1,ngridmx
-                 qsurf(ig,iq)=val
-             ENDDO
-
-c       ini_q : Initialize tracers for chemistry
-c       -----------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'ini_q') then
-c         For more than 32 layers, possible to initiate thermosphere only     
-          thermo=0
-          yes=' '
-          if (llm.gt.32) then 
-            do while ((yes.ne.'y').and.(yes.ne.'n'))
-            write(*,*)'',
-     &     'initialisation for thermosphere only? (y/n)'
-            read(*,fmt='(a)') yes
-            if (yes.eq.'y') then
-            thermo=1 
-            else
-            thermo=0
-            endif
-            enddo  
-          endif
-          
-c             call inichim_newstart(q,ps,sig,nqmx,latfi,lonfi,airefi,
-c    $   thermo,qsurf)
-          write(*,*) 'Chemical species initialized'
-
-        if (thermo.eq.0) then 
-c          mise a 0 des qsurf (traceurs a la surface)
-           DO iq =1, nqmx
-             DO ig=1,ngridmx
-                 qsurf(ig,iq)=0.
-             ENDDO
-           ENDDO
-        endif   
-
-c       ini_q-H2O : as above exept for the water vapour tracer 
-c       ------------------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'ini_q-H2O') then
-          ! for more than 32 layers, possible to initiate thermosphere only     
-          thermo=0
-          yes=' '
-          if(llm.gt.32) then
-            do while ((yes.ne.'y').and.(yes.ne.'n'))
-            write(*,*)'',
-     &      'initialisation for thermosphere only? (y/n)'
-            read(*,fmt='(a)') yes
-            if (yes.eq.'y') then 
-            thermo=1 
-            else
-            thermo=0
-            endif
-            enddo
-          endif
-c             call inichim_newstart(q,ps,sig,nqmx-1,latfi,lonfi,airefi,
-c    $   thermo,qsurf)
-c         write(*,*) 'Initialized chem. species exept last (H2O)'
-
-        if (thermo.eq.0) then 
-c          set surface tracers to zero, except water ice
-           DO iq =1, nqmx
-            if (iq.ne.igcm_h2o_ice) then
-             DO ig=1,ngridmx
-                 qsurf(ig,iq)=0.
-             ENDDO
-            endif
-           ENDDO
-        endif
-
-c       ini_q-iceH2O : as above exept for ice et H2O
-c       -----------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'ini_q-iceH2O') then
-c         For more than 32 layers, possible to initiate thermosphere only     
-          thermo=0
-          yes=' '
-          if(llm.gt.32) then
-            do while ((yes.ne.'y').and.(yes.ne.'n'))
-            write(*,*)'',
-     &      'initialisation for thermosphere only? (y/n)'
-            read(*,fmt='(a)') yes
-            if (yes.eq.'y') then 
-            thermo=1 
-            else
-            thermo=0
-            endif
-            enddo
-          endif
-     
-c        call inichim_newstart(q,ps,sig,nqmx-2,latfi,lonfi,airefi,
-c    $   thermo,qsurf)
-c         write(*,*) 'Initialized chem. species exept ice and H2O'
-
-        if (thermo.eq.0) then 
-c          set surface tracers to zero, except water ice
-           DO iq =1, nqmx
-            if (iq.ne.igcm_h2o_ice) then
-             DO ig=1,ngridmx
-                 qsurf(ig,iq)=0.
-             ENDDO 
-            endif
-           ENDDO
-        endif
-
-c      wetstart : wet atmosphere with a north to south gradient
-c      --------------------------------------------------------
-       else if (modif(1:len_trim(modif)) .eq. 'wetstart') then
-        ! check that there is indeed a water vapor tracer
-        if (igcm_h2o_vap.eq.0) then
-          write(*,*) "No water vapour tracer! Can't use this option"
-          stop
-        endif
-          DO l=1,llm
-            DO j=1,jjp1
-              DO i=1,iip1
-                q(i,j,l,igcm_h2o_vap)=150.e-6 * (rlatu(j)+pi/2.) / pi
-              ENDDO
-            ENDDO
-          ENDDO
-
-         write(*,*) 'Water mass mixing ratio at north pole='
-     *               ,q(1,1,1,igcm_h2o_vap)
-         write(*,*) '---------------------------south pole='
-     *               ,q(1,jjp1,1,igcm_h2o_vap)
-
-c      noglacier : remove tropical water ice (to initialize high res sim)
-c      --------------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'noglacier') then
-           do ig=1,ngridmx
-             j=(ig-2)/iim +2
-              if(ig.eq.1) j=1
-              write(*,*) 'OK: remove surface ice for |lat|<45'
-              if (abs(rlatu(j)*180./pi).lt.45.) then
-                   qsurf(ig,igcm_h2o_ice)=0.
-              end if
-           end do
-
-
-c      watercapn : H20 ice on permanent northern cap
-c      --------------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'watercapn') then
-           do ig=1,ngridmx
-             j=(ig-2)/iim +2
-              if(ig.eq.1) j=1
-              if (rlatu(j)*180./pi.gt.80.) then
-                   qsurf(ig,igcm_h2o_ice)=1.e5
-                   write(*,*) 'ig=',ig,'    H2O ice mass (kg/m2)= ',
-     &              qsurf(ig,igcm_h2o_ice)
-                   write(*,*)'     ==> Ice mesh South boundary (deg)= ',
-     &              rlatv(j)*180./pi
-                end if
-           enddo
-
-c      watercaps : H20 ice on permanent southern cap
-c      -------------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'watercaps') then
-           do ig=1,ngridmx
-               j=(ig-2)/iim +2
-               if(ig.eq.1) j=1
-               if (rlatu(j)*180./pi.lt.-80.) then
-                   qsurf(ig,igcm_h2o_ice)=1.e5
-                   write(*,*) 'ig=',ig,'   H2O ice mass (kg/m2)= ',
-     &              qsurf(ig,igcm_h2o_ice)
-                   write(*,*)'     ==> Ice mesh North boundary (deg)= ',
-     &              rlatv(j-1)*180./pi
-               end if
-           enddo
-
-
-!       northsea goes here !
-
-
-
-           
-c       isotherm : Isothermal temperatures and no winds
-c       ------------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'isotherm') then
-
-          write(*,*)'Isothermal temperature of the atmosphere, 
-     &           surface and subsurface'
-          write(*,*) 'Value of this temperature ? :'
- 203      read(*,*,iostat=ierr) Tiso
-          if(ierr.ne.0) goto 203
-
-          do ig=1, ngridmx
-            tsurf(ig) = Tiso
-          end do
-          do l=2,nsoilmx
-            do ig=1, ngridmx
-              tsoil(ig,l) = Tiso
-            end do
-          end do
-          DO j=1,jjp1
-           DO i=1,iim
-            Do l=1,llm
-               Tset(i,j,l)=Tiso
-            end do
-           end do
-          end do
-          flagtset=.true.
-          call initial0(llm*ip1jmp1,ucov)
-          call initial0(llm*ip1jm,vcov)
-          call initial0(ngridmx*(llm+1),q2)
-
-
-c       coldstart : T set 1K above CO2 frost point and no winds
-c       ------------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'coldstart') then
-
-          write(*,*)'set temperature of the atmosphere,' 
-     &,'surface and subsurface how many degrees above CO2 frost point?'
- 204      read(*,*,iostat=ierr) Tabove
-          if(ierr.ne.0) goto 204
-
-            DO j=1,jjp1
-             DO i=1,iim
-                ig=1+(j-2)*iim +i
-                if(j.eq.1) ig=1
-                if(j.eq.jjp1) ig=ngridmx
-            tsurf(ig) = (-3167.8)/(log(.01*ps(i,j))-23.23)+Tabove
-             END DO
-            END DO
-          do l=1,nsoilmx
-            do ig=1, ngridmx
-              tsoil(ig,l) = tsurf(ig)
-            end do
-          end do
-          DO j=1,jjp1
-           DO i=1,iim
-            Do l=1,llm
-               pp = aps(l) +bps(l)*ps(i,j) 
-               Tset(i,j,l)=(-3167.8)/(log(.01*pp)-23.23)+Tabove
-            end do
-           end do
-          end do
-
-          flagtset=.true.
-          call initial0(llm*ip1jmp1,ucov)
-          call initial0(llm*ip1jm,vcov)
-          call initial0(ngridmx*(llm+1),q2)
-
-
-c       co2ice=0 : remove CO2 polar ice caps'
-c       ------------------------------------------------
-        else if (modif(1:len_trim(modif)) .eq. 'co2ice=0') then
-         ! check that there is indeed a co2_ice tracer ...
-          if (igcm_co2_ice.ne.0) then
-           do ig=1,ngridmx
-              !co2ice(ig)=0
-              qsurf(ig,igcm_co2_ice)=0
-              emis(ig)=emis(ngridmx/2)
-           end do
-          else
-            write(*,*) "Can't remove CO2 ice!! (no co2_ice tracer)"
-          endif
-        
-!       therm_ini_s: (re)-set soil thermal inertia to reference surface values
-!       ----------------------------------------------------------------------
-
-	else if (modif(1:len_trim(modif)).eq.'therm_ini_s') then
-!          write(*,*)"surfithfi(1):",surfithfi(1)
-	  do isoil=1,nsoilmx
-	    inertiedat(1:ngridmx,isoil)=surfithfi(1:ngridmx)
-	  enddo
-          write(*,*)'OK: Soil thermal inertia has been reset to referenc
-     &e surface values'
-!	  write(*,*)"inertiedat(1,1):",inertiedat(1,1)
-	  ithfi(:,:)=inertiedat(:,:)
-	 ! recast ithfi() onto ith()
-	 call gr_fi_dyn(nsoilmx,ngridmx,iip1,jjp1,ithfi,ith)
-! Check:
-!         do i=1,iip1
-!           do j=1,jjp1
-!             do isoil=1,nsoilmx
-!               write(77,*) i,j,isoil,"  ",ith(i,j,isoil)
-!             enddo
-!           enddo
-!	 enddo
-
-!       subsoilice_n: Put deep ice layer in northern hemisphere soil
-!       ------------------------------------------------------------
-
-	else if (modif(1:len_trim(modif)).eq.'subsoilice_n') then
-
-         write(*,*)'From which latitude (in deg.), up to the north pole,
-     &should we put subterranean ice?'
-	 ierr=1
-	 do while (ierr.ne.0)
-	  read(*,*,iostat=ierr) val
-	  if (ierr.eq.0) then ! got a value
-	    ! do a sanity check
-	    if((val.lt.0.).or.(val.gt.90)) then
-	      write(*,*)'Latitude should be between 0 and 90 deg. !!!'
-	      ierr=1
-	    else ! find corresponding jref (nearest latitude)
-	      ! note: rlatu(:) contains decreasing values of latitude
-	      !       starting from PI/2 to -PI/2
-	      do j=1,jjp1
-	        if ((rlatu(j)*180./pi.ge.val).and.
-     &              (rlatu(j+1)*180./pi.le.val)) then
-		  ! find which grid point is nearest to val:
-		  if (abs(rlatu(j)*180./pi-val).le.
-     &                abs((rlatu(j+1)*180./pi-val))) then
-		   jref=j
-		  else
-		   jref=j+1
-		  endif
-		 
-		 write(*,*)'Will use nearest grid latitude which is:',
-     &                     rlatu(jref)*180./pi
-		endif
-	      enddo ! of do j=1,jjp1
-	    endif ! of if((val.lt.0.).or.(val.gt.90))
-	  endif !of if (ierr.eq.0)
-	 enddo ! of do while
-
-         ! Build layers() (as in soil_settings.F)
-	 val2=sqrt(mlayer(0)*mlayer(1))
-	 val3=mlayer(1)/mlayer(0)
-	 do isoil=1,nsoilmx
-	   layer(isoil)=val2*(val3**(isoil-1))
-	 enddo
-
-         write(*,*)'At which depth (in m.) does the ice layer begin?'
-         write(*,*)'(currently, the deepest soil layer extends down to:'
-     &              ,layer(nsoilmx),')'
-	 ierr=1
-	 do while (ierr.ne.0)
-	  read(*,*,iostat=ierr) val2
-!	  write(*,*)'val2:',val2,'ierr=',ierr
-	  if (ierr.eq.0) then ! got a value, but do a sanity check
-	    if(val2.gt.layer(nsoilmx)) then
-	      write(*,*)'Depth should be less than ',layer(nsoilmx)
-	      ierr=1
-	    endif
-	    if(val2.lt.layer(1)) then
-	      write(*,*)'Depth should be more than ',layer(1)
-	      ierr=1
-	    endif
-	  endif
-         enddo ! of do while
-	 
-	 ! find the reference index iref the depth corresponds to
-!	 if (val2.lt.layer(1)) then
-!	  iref=1
-!	 else
-	  do isoil=1,nsoilmx-1
-	   if((val2.gt.layer(isoil)).and.(val2.lt.layer(isoil+1)))
-     &       then
-	     iref=isoil
-	     exit
-	   endif
-	  enddo
-!	 endif
-	 
-!	 write(*,*)'iref:',iref,'  jref:',jref
-!	 write(*,*)'layer',layer
-!	 write(*,*)'mlayer',mlayer
-         
-	 ! thermal inertia of the ice:
-	 ierr=1
-	 do while (ierr.ne.0)
-          write(*,*)'What is the value of subterranean ice thermal inert
-     &ia? (e.g.: 2000)'
-          read(*,*,iostat=ierr)iceith
-	 enddo ! of do while
-	 
-	 ! recast ithfi() onto ith()
-	 call gr_fi_dyn(nsoilmx,ngridmx,iip1,jjp1,ithfi,ith)
-	 
-	 do j=1,jref
-!	    write(*,*)'j:',j,'rlatu(j)*180./pi:',rlatu(j)*180./pi
-	    do i=1,iip1 ! loop on longitudes
-	     ! Build "equivalent" thermal inertia for the mixed layer
-	     ith(i,j,iref+1)=sqrt((layer(iref+1)-layer(iref))/
-     &                     (((val2-layer(iref))/(ith(i,j,iref)**2))+
-     &                      ((layer(iref+1)-val2)/(iceith)**2)))
-	     ! Set thermal inertia of lower layers
-	     do isoil=iref+2,nsoilmx
-	      ith(i,j,isoil)=iceith ! ice
-	     enddo
-	    enddo ! of do i=1,iip1 
-	 enddo ! of do j=1,jjp1
-	 
-
-	 CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
-
-!         do i=1,nsoilmx
-!	  write(*,*)'i:',i,'ithfi(1,i):',ithfi(1,i)
-!	 enddo
-
-	
-!       subsoilice_s: Put deep ice layer in southern hemisphere soil
-!       ------------------------------------------------------------
-
-	else if (modif(1:len_trim(modif)).eq.'subsoilice_s') then
-
-         write(*,*)'From which latitude (in deg.), down to the south pol
-     &e, should we put subterranean ice?'
-	 ierr=1
-	 do while (ierr.ne.0)
-	  read(*,*,iostat=ierr) val
-	  if (ierr.eq.0) then ! got a value
-	    ! do a sanity check
-	    if((val.gt.0.).or.(val.lt.-90)) then
-	      write(*,*)'Latitude should be between 0 and -90 deg. !!!'
-	      ierr=1
-	    else ! find corresponding jref (nearest latitude)
-	      ! note: rlatu(:) contains decreasing values of latitude
-	      !       starting from PI/2 to -PI/2
-	      do j=1,jjp1
-	        if ((rlatu(j)*180./pi.ge.val).and.
-     &              (rlatu(j+1)*180./pi.le.val)) then
-		  ! find which grid point is nearest to val:
-		  if (abs(rlatu(j)*180./pi-val).le.
-     &                abs((rlatu(j+1)*180./pi-val))) then
-		   jref=j
-		  else
-		   jref=j+1
-		  endif
-		 
-		 write(*,*)'Will use nearest grid latitude which is:',
-     &                     rlatu(jref)*180./pi
-		endif
-	      enddo ! of do j=1,jjp1
-	    endif ! of if((val.lt.0.).or.(val.gt.90))
-	  endif !of if (ierr.eq.0)
-	 enddo ! of do while
-
-         ! Build layers() (as in soil_settings.F)
-	 val2=sqrt(mlayer(0)*mlayer(1))
-	 val3=mlayer(1)/mlayer(0)
-	 do isoil=1,nsoilmx
-	   layer(isoil)=val2*(val3**(isoil-1))
-	 enddo
-
-         write(*,*)'At which depth (in m.) does the ice layer begin?'
-         write(*,*)'(currently, the deepest soil layer extends down to:'
-     &              ,layer(nsoilmx),')'
-	 ierr=1
-	 do while (ierr.ne.0)
-	  read(*,*,iostat=ierr) val2
-!	  write(*,*)'val2:',val2,'ierr=',ierr
-	  if (ierr.eq.0) then ! got a value, but do a sanity check
-	    if(val2.gt.layer(nsoilmx)) then
-	      write(*,*)'Depth should be less than ',layer(nsoilmx)
-	      ierr=1
-	    endif
-	    if(val2.lt.layer(1)) then
-	      write(*,*)'Depth should be more than ',layer(1)
-	      ierr=1
-	    endif
-	  endif
-         enddo ! of do while
-	 
-	 ! find the reference index iref the depth corresponds to
-	  do isoil=1,nsoilmx-1
-	   if((val2.gt.layer(isoil)).and.(val2.lt.layer(isoil+1)))
-     &       then
-	     iref=isoil
-	     exit
-	   endif
-	  enddo
-	 
-!	 write(*,*)'iref:',iref,'  jref:',jref
-         
-	 ! thermal inertia of the ice:
-	 ierr=1
-	 do while (ierr.ne.0)
-          write(*,*)'What is the value of subterranean ice thermal inert
-     &ia? (e.g.: 2000)'
-          read(*,*,iostat=ierr)iceith
-	 enddo ! of do while
-	 
-	 ! recast ithfi() onto ith()
-	 call gr_fi_dyn(nsoilmx,ngridmx,iip1,jjp1,ithfi,ith)
-	 
-	 do j=jref,jjp1
-!	    write(*,*)'j:',j,'rlatu(j)*180./pi:',rlatu(j)*180./pi
-	    do i=1,iip1 ! loop on longitudes
-	     ! Build "equivalent" thermal inertia for the mixed layer
-	     ith(i,j,iref+1)=sqrt((layer(iref+1)-layer(iref))/
-     &                     (((val2-layer(iref))/(ith(i,j,iref)**2))+
-     &                      ((layer(iref+1)-val2)/(iceith)**2)))
-	     ! Set thermal inertia of lower layers
-	     do isoil=iref+2,nsoilmx
-	      ith(i,j,isoil)=iceith ! ice
-	     enddo
-	    enddo ! of do i=1,iip1 
-	 enddo ! of do j=jref,jjp1
-	 
-
-	 CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
-
-c       'mons_ice' : use MONS data to build subsurface ice table
-c       --------------------------------------------------------
-        else if (modif(1:len_trim(modif)).eq.'mons_ice') then
-        
-       ! 1. Load MONS data
-        call load_MONS_data(MONS_Hdn,MONS_d21)
-        
-        ! 2. Get parameters from user
-        ierr=1
-	do while (ierr.ne.0)
-          write(*,*) "Coefficient to apply to MONS 'depth' in Northern",
-     &               " Hemisphere?"
-          write(*,*) " (should be somewhere between 3.2e-4 and 1.3e-3)"
-          read(*,*,iostat=ierr) MONS_coeffN
-        enddo
-        ierr=1
-	do while (ierr.ne.0)
-          write(*,*) "Coefficient to apply to MONS 'depth' in Southern",
-     &               " Hemisphere?"
-          write(*,*) " (should be somewhere between 3.2e-4 and 1.3e-3)"
-          read(*,*,iostat=ierr) MONS_coeffS
-        enddo
-        ierr=1
-        do while (ierr.ne.0)
-          write(*,*) "Value of subterranean ice thermal inertia?"
-          write(*,*) " (e.g.: 2000, or perhaps 2290)"
-          read(*,*,iostat=ierr) iceith
-        enddo
-        
-        ! 3. Build subterranean thermal inertia
-        
-        ! initialise subsurface inertia with reference surface values
-        do isoil=1,nsoilmx
-          ithfi(1:ngridmx,isoil)=surfithfi(1:ngridmx)
-        enddo
-        ! recast ithfi() onto ith()
-	call gr_fi_dyn(nsoilmx,ngridmx,iip1,jjp1,ithfi,ith)
-        
-        do i=1,iip1 ! loop on longitudes
-          do j=1,jjp1 ! loop on latitudes
-            ! set MONS_coeff
-            if (rlatu(j).ge.0) then ! northern hemisphere
-              ! N.B: rlatu(:) contains decreasing values of latitude
-	      !       starting from PI/2 to -PI/2
-              MONS_coeff=MONS_coeffN
-            else ! southern hemisphere
-              MONS_coeff=MONS_coeffS
-            endif
-            ! check if we should put subterranean ice
-            if (MONS_Hdn(i,j).ge.14.0) then ! no ice if Hdn<14%
-              ! compute depth at which ice lies:
-              val=MONS_d21(i,j)*MONS_coeff
-              ! compute val2= the diurnal skin depth of surface inertia
-              ! assuming a volumetric heat cap. of C=1.e6 J.m-3.K-1
-              val2=ith(i,j,1)*1.e-6*sqrt(88775./3.14159)
-              if (val.lt.val2) then
-                ! ice must be below the (surface inertia) diurnal skin depth
-                val=val2
-              endif
-              if (val.lt.layer(nsoilmx)) then ! subterranean ice
-                ! find the reference index iref that depth corresponds to
-                iref=0
-                do isoil=1,nsoilmx-1
-                 if ((val.ge.layer(isoil)).and.(val.lt.layer(isoil+1)))
-     &             then
-	           iref=isoil
-	           exit
-	         endif
-                enddo
-                ! Build "equivalent" thermal inertia for the mixed layer
-                ith(i,j,iref+1)=sqrt((layer(iref+1)-layer(iref))/
-     &                     (((val-layer(iref))/(ith(i,j,iref+1)**2))+
-     &                      ((layer(iref+1)-val)/(iceith)**2)))
-	        ! Set thermal inertia of lower layers
-                do isoil=iref+2,nsoilmx
-                  ith(i,j,isoil)=iceith 
-                enddo
-              endif ! of if (val.lt.layer(nsoilmx))
-            endif ! of if (MONS_Hdn(i,j).lt.14.0)
-          enddo ! do j=1,jjp1
-        enddo ! do i=1,iip1
-        
-! Check:
-!         do i=1,iip1
-!           do j=1,jjp1
-!             do isoil=1,nsoilmx
-!               write(77,*) i,j,isoil,"  ",ith(i,j,isoil)
-!             enddo
-!           enddo
-!	 enddo
-
-        ! recast ith() into ithfi()
-        CALL gr_dyn_fi(nsoilmx,iip1,jjp1,ngridmx,ith,ithfi)
-        
-	else
-          write(*,*) '       Unknown (misspelled?) option!!!'
-        end if ! of if (modif(1:len_trim(modif)) .eq. '...') elseif ...
-	
-       enddo ! of do ! infinite loop on liste of changes
-
- 999  continue
-
- 
-c=======================================================================
-c   Correct pressure on the new grid (menu 0)
-c=======================================================================
-
-      if ((choix_1.eq.0).and.(.not.flagps0)) then
-        r = 1000.*8.31/mugaz
-
-        do j=1,jjp1
-          do i=1,iip1
-             ps(i,j) = ps(i,j) * 
-     .            exp((phisold_newgrid(i,j)-phis(i,j)) /
-     .                                  (t(i,j,1) * r))
-          end do
-        end do
-  
-c periodicity of surface ps in longitude
-        do j=1,jjp1
-          ps(1,j) = ps(iip1,j)
-        end do
-      end if
-
-c=======================================================================
-c=======================================================================
-
-c=======================================================================
-c    Initialisation de la physique / ecriture de newstartfi :
-c=======================================================================
-
-
-      CALL inifilr 
-      CALL pression(ip1jmp1, ap, bp, ps, p3d)
-
-c-----------------------------------------------------------------------
-c   Initialisation  pks:
-c-----------------------------------------------------------------------
-
-      CALL exner_hyb(ip1jmp1, ps, p3d, beta, pks, pk, pkf)
-! Calcul de la temperature potentielle teta
-
-      if (flagtset) then
-          DO l=1,llm
-             DO j=1,jjp1
-                DO i=1,iim
-                   teta(i,j,l) = Tset(i,j,l) * cpp/pk(i,j,l)
-                ENDDO
-                teta (iip1,j,l)= teta (1,j,l)
-             ENDDO
-          ENDDO
-      else if (choix_1.eq.0) then
-         DO l=1,llm
-            DO j=1,jjp1
-               DO i=1,iim
-                  teta(i,j,l) = t(i,j,l) * cpp/pk(i,j,l)
-               ENDDO
-               teta (iip1,j,l)= teta (1,j,l)
-            ENDDO
-         ENDDO
-      endif
-
-C Calcul intermediaire
-c
-      if (choix_1.eq.0) then
-         CALL massdair( p3d, masse  )
-c
-         print *,' ALPHAX ',alphax
-
-         DO  l = 1, llm
-           DO  i    = 1, iim
-             xppn(i) = aire( i, 1   ) * masse(  i     ,  1   , l )
-             xpps(i) = aire( i,jjp1 ) * masse(  i     , jjp1 , l )
-           ENDDO
-             xpn      = SUM(xppn)/apoln
-             xps      = SUM(xpps)/apols
-           DO i   = 1, iip1
-             masse(   i   ,   1     ,  l )   = xpn
-             masse(   i   ,   jjp1  ,  l )   = xps
-           ENDDO
-         ENDDO
-      endif
-      phis(iip1,:) = phis(1,:)
-
-      CALL inidissip ( lstardis, nitergdiv, nitergrot, niterh,
-     *                tetagdiv, tetagrot , tetatemp  )
-      itau=0
-      if (choix_1.eq.0) then
-         day_ini=int(date)
-      endif
-c
-      CALL geopot  ( ip1jmp1, teta  , pk , pks,  phis  , phi   )
-
-      CALL caldyn0( itau,ucov,vcov,teta,ps,masse,pk,phis ,
-     *                phi,w, pbaru,pbarv,day_ini+time )
-c     CALL caldyn
-c    $  ( itau,ucov,vcov,teta,ps,masse,pk,pkf,phis ,
-c    $    phi,conser,du,dv,dteta,dp,w, pbaru,pbarv, day_ini )
-
-      CALL dynredem0("restart.nc",day_ini,anneeref,phis,nqmx)
-      CALL dynredem1("restart.nc",0.0,vcov,ucov,teta,q,nqmx,masse,ps) 
-C
-C Ecriture etat initial physique
-C
-
-      call physdem1("restartfi.nc",lonfi,latfi,nsoilmx,nqmx,
-     .              dtphys,float(day_ini),
-     .              time,tsurf,tsoil,emis,q2,qsurf,
-     .              airefi,albfi,ithfi,zmea,zstd,zsig,zgam,zthe)
-
-c=======================================================================
-c	Formats 
-c=======================================================================
-
-   1  FORMAT(//10x,'la valeur de im =',i4,2x,'lue sur le fichier de dema
-     *rrage est differente de la valeur parametree iim =',i4//)
-   2  FORMAT(//10x,'la valeur de jm =',i4,2x,'lue sur le fichier de dema
-     *rrage est differente de la valeur parametree jjm =',i4//)
-   3  FORMAT(//10x,'la valeur de lllm =',i4,2x,'lue sur le fichier demar
-     *rage est differente de la valeur parametree llm =',i4//)
-
-      end
-
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-      subroutine load_MONS_data(MONS_Hdn,MONS_d21)
-      implicit none
-      ! routine to load Benedicte Diez MONS dataset, fill in date in southern
-      ! polar region, and interpolate the result onto the GCM grid
-#include"dimensions.h"
-#include"paramet.h"
-#include"datafile.h"
-#include"comgeom.h"
-      ! arguments:
-      real,intent(out) :: MONS_Hdn(iip1,jjp1) ! Hdn: %WEH=Mass fraction of H2O
-      real,intent(out) :: MONS_d21(iip1,jjp1) ! ice table "depth" (in kg/m2)
-      ! N.B MONS datasets should be of dimension (iip1,jjp1)
-      ! local variables:
-      character(len=88) :: filename="results_MONS_lat_lon_H_depth.txt"
-      character(len=88) :: txt ! to store some text
-      integer :: ierr,i,j
-      integer,parameter :: nblon=180 ! number of longitudes of MONS datasets
-      integer,parameter :: nblat=90 ! number of latitudes of MONS datasets
-      real :: pi
-      real :: longitudes(nblon) ! MONS dataset longitudes
-      real :: latitudes(nblat)  ! MONS dataset latitudes
-      ! MONS dataset: mass fraction of H2O where H is assumed to be in H2O
-      real :: Hdn(nblon,nblat)
-      real :: d21(nblon,nblat)! MONS dataset "depth" (g/cm2)
-
-      ! Extended MONS dataset (for interp_horiz)
-      real :: Hdnx(nblon+1,nblat)
-      real :: d21x(nblon+1,nblat)
-      real :: lon_bound(nblon+1) ! longitude boundaries
-      real :: lat_bound(nblat-1) ! latitude boundaries
-
-      ! 1. Initializations:
-
-      write(*,*) "Loading MONS data"
-
-      ! Open MONS datafile:
-      open(42,file=trim(datafile)//"/"//trim(filename),
-     &     status="old",iostat=ierr)
-      if (ierr/=0) then
-        write(*,*) "Error in load_MONS_data:"
-        write(*,*) "Failed opening file ",
-     &             trim(datafile)//"/"//trim(filename)
-        write(*,*)'1) You can change the path to the file in '
-        write(*,*)'   file phymars/datafile.h'
-        write(*,*)'2) If necessary ',trim(filename),
-     &                 ' (and other datafiles)'
-        write(*,*)'   can be obtained online at:'
-        write(*,*)' http://www.lmd.jussieu.fr/~forget/datagcm/datafile'
-        CALL ABORT
-      else ! skip first line of file (dummy read)
-         read(42,*) txt
-      endif
-
-      pi=2.*asin(1.)
-      
-      !2. Load MONS data (on MONS grid)
-      do j=1,nblat
-        do i=1,nblon
-        ! swap latitude index so latitudes go from north pole to south pole:
-          read(42,*) latitudes(nblat-j+1),longitudes(i),
-     &               Hdn(i,nblat-j+1),d21(i,nblat-j+1)
-        ! multiply d21 by 10 to convert from g/cm2 to kg/m2
-          d21(i,nblat-j+1)=d21(i,nblat-j+1)*10.0
-        enddo
-      enddo
-      close(42)
-      
-      ! there is unfortunately no d21 data for latitudes -77 to -90
-      ! so we build some by linear interpolation between values at -75
-      ! and assuming d21=0 at the pole
-      do j=84,90 ! latitudes(84)=-77 ; latitudes(83)=-75
-        do i=1,nblon
-          d21(i,j)=d21(i,83)*((latitudes(j)+90)/15.0)
-        enddo
-      enddo
-
-      ! 3. Build extended MONS dataset & boundaries (for interp_horiz)
-      ! longitude boundaries (in radians):
-      do i=1,nblon
-        ! NB: MONS data is every 2 degrees in longitude
-        lon_bound(i)=(longitudes(i)+1.0)*pi/180.0
-      enddo
-      ! extra 'modulo' value
-      lon_bound(nblon+1)=lon_bound(1)+2.0*pi
-      
-      ! latitude boundaries (in radians):
-      do j=1,nblat-1
-        ! NB: Mons data is every 2 degrees in latitude
-        lat_bound(j)=(latitudes(j)-1.0)*pi/180.0
-      enddo
-      
-      ! MONS datasets:
-      do j=1,nblat
-        Hdnx(1:nblon,j)=Hdn(1:nblon,j)
-        Hdnx(nblon+1,j)=Hdnx(1,j)
-        d21x(1:nblon,j)=d21(1:nblon,j)
-        d21x(nblon+1,j)=d21x(1,j)
-      enddo
-      
-      ! Interpolate onto GCM grid
-      call interp_horiz(Hdnx,MONS_Hdn,nblon,nblat-1,iim,jjm,1,
-     &                  lon_bound,lat_bound,rlonu,rlatv)
-      call interp_horiz(d21x,MONS_d21,nblon,nblat-1,iim,jjm,1,
-     &                  lon_bound,lat_bound,rlonu,rlatv)
-      
-      end subroutine
Index: /trunk/LMDZ.GENERIC/libf/dyn3d/start2archive.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/dyn3d/start2archive.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/dyn3d/start2archive.F	(revision 253)
@@ -68,4 +68,9 @@
       INTEGER*4 day_ini_fi
 
+!     added by FF for cloud fraction setup
+      REAL hice(ngridmx)
+      REAL cloudfrac(ngridmx,nlayermx),totalcloudfrac(ngridmx)
+
+
 c Variable naturelle / grille scalaire
 c ------------------------------------
@@ -78,4 +83,8 @@
       REAL emisS(ip1jmp1)
 
+!     added by FF for cloud fraction setup
+      REAL hiceS(ip1jmp1)
+      REAL cloudfracS(ip1jmp1,llm),totalcloudfracS(ip1jmp1)
+
 c Variables intermediaires : vent naturel, mais pas coord scalaire
 c----------------------------------------------------------------
@@ -127,5 +136,9 @@
 
       CALL phyetat0 (fichnom,0,Lmodif,nsoilmx,nqmx,day_ini_fi,timefi,
-     .      tsurf,tsoil,emis,q2,qsurf)
+     .      tsurf,tsoil,emis,q2,qsurf,
+!       change FF 05/2011
+     .       cloudfrac,totalcloudfrac,hice)
+
+
 
        ierr = NF_OPEN (fichnom, NF_NOWRITE,nid1)
@@ -233,4 +246,7 @@
       call gr_fi_dyn(llm+1,ngridmx,iip1,jjp1,q2,q2S)
       call gr_fi_dyn(nqmx,ngridmx,iip1,jjp1,qsurf,qsurfS)
+      call gr_fi_dyn(llm,ngridmx,iip1,jjp1,cloudfrac,cloudfracS)
+      call gr_fi_dyn(1,ngridmx,iip1,jjp1,hice,hiceS)
+      call gr_fi_dyn(1,ngridmx,iip1,jjp1,totalcloudfrac,totalcloudfracS)
 
 c=======================================================================
@@ -376,8 +392,17 @@
 ! Note: no need to write volcapa, it is stored in "controle" table
 
+c-----------------------------------------------------------------------
+c Ecriture du champs  cloudfrac,hice,totalcloudfrac
+c-----------------------------------------------------------------------
+      call write_archive(nid,ntime,'hice',
+     &         'Height of oceanic ice','m',2,hiceS)
+      call write_archive(nid,ntime,'totalcloudfrac',
+     &        'Total cloud Fraction','',2,totalcloudfracS)
+      call write_archive(nid,ntime,'cloudfrac'
+     &        ,'Cloud fraction','',3,cloudfracS)
+c-----------------------------------------------------------------------
+c Fin 
+c-----------------------------------------------------------------------
       ierr=NF_CLOSE(nid)
-c-----------------------------------------------------------------------
-c Fin 
-c-----------------------------------------------------------------------
 
       end 
Index: /trunk/LMDZ.GENERIC/libf/dyn3d/tracvl.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/dyn3d/tracvl.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/dyn3d/tracvl.F	(revision 253)
@@ -72,4 +72,7 @@
 c   Test pour savoir si on advecte a ce pas de temps
       IF ( iadvtr.EQ.iapp_tracvl ) THEN
+!      print*,'WARNING: ALL TRACER ADVECTION HALTED IN TRACVL.F'
+!         if(2.eq.1)then
+
 
 cc   ..  Modif P.Le Van  ( 20/12/97 )  ....
Index: /trunk/LMDZ.GENERIC/libf/filtrez/parafilt.h
===================================================================
--- /trunk/LMDZ.GENERIC/libf/filtrez/parafilt.h	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/filtrez/parafilt.h	(revision 253)
@@ -21,5 +21,10 @@
 c      PARAMETER (nfilun=18, nfilus=17, nfilvn=17, nfilvs=17) !!NO fxyhyper
 !!        PARAMETER (nfilun=9,nfilus=8,nfilvn=8,nfilvs=8)
-        PARAMETER (nfilun=9,nfilus=9,nfilvn=9,nfilvs=9)
+!        PARAMETER (nfilun=9,nfilus=9,nfilvn=9,nfilvs=9)
+
+        PARAMETER (nfilun=11,nfilus=11,nfilvn=11,nfilvs=11)
+!        PARAMETER (nfilun=12,nfilus=12,nfilvn=12,nfilvs=12)
+
+
 c 96 72 19 non-zoom:
 ccc      PARAMETER (nfilun=12, nfilus=11, nfilvn=12, nfilvs=12)
Index: /trunk/LMDZ.GENERIC/libf/phystd/N2broadprof_fn.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/N2broadprof_fn.F90	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/N2broadprof_fn.F90	(revision 253)
@@ -0,0 +1,110 @@
+      subroutine N2broadprof_fn(tsurf,temp,popsk,play,plev,qvap)
+      implicit none
+
+!     creates a temperature profile for an N2-CO2 atmosphere
+!     a fine resolution grid is used for accuracy
+
+#include "dimensions.h"
+#include "dimphys.h"
+#include "comcstfi.h"
+#include "callkeys.h"
+
+      REAL play(nlayermx)   ! Pressure at the middle of the layers (Pa)
+      REAL plev(nlayermx+1) ! Intermediate pressure levels (pa)
+      REAL psurf,tsurf      
+!      REAL tcond(nlayermx)
+      REAL qvap(nlayermx)
+      REAL temp(nlayermx)   ! temperature at the middle of the layers
+
+      real, parameter :: Rstar   = 8.314
+      real, parameter :: ptriple = 518000.0
+      real, parameter :: latcond = 5.9e5     ! as in condense_co2
+      real, parameter :: mn      = 0.02801   ! molar mass of background gas (N2)
+      real, parameter :: mv      = 0.04401   ! molar mass of background gas (CO2)
+
+      real popsk(nlayermx)  ! this is dodgy as in rest of code, zpopsk(ngridmx,nlayermx)
+                            ! but kastprof requires 1D, so its ok I guess
+
+      real gamma,dqdlnT,dlnqdlnT,dlnpdlnT,dpdT,dln_p
+
+      integer l,iter
+
+      real sigma_loc,q_loc,vmr_loc,ppvar_loc,T_loc,p_loc
+      real Tcond
+      real Told,qold,pold
+
+      integer, parameter :: Niter = 2000
+
+      if(ngridmx.gt.1)then
+         print*,'DO NOT RUN KASTPROF IN 3D!!!'
+         call abort
+      end if
+
+      l=1
+
+      vmr_loc = 0.05 ! value at ground
+      q_loc   = vmr_loc*mv/mn
+      T_loc   = Tsurf
+
+      dln_p = log(pceil/plev(1))/Niter ! please check
+      do iter=1,Niter
+
+         sigma_loc = (pceil/plev(1))**(real(iter)/real(Niter))
+         p_loc     = plev(1)*sigma_loc
+
+         ppvar_loc = vmr_loc*p_loc
+         if(ppvar_loc.lt.ptriple)then
+            Tcond = (-3167.8)/(log(.01*ppvar_loc)-23.23)         ! Fanale's formula
+         else
+            Tcond = 684.2-92.3*log(ppvar_loc)+4.32*log(ppvar_loc)**2 ! liquid-vapour (CRC handbook 2003 data)
+         endif
+
+            if (T_loc.le.Tstrat)then
+               T_loc     = Tstrat            ! isothermal stratosphere
+            elseif(T_loc.le.Tcond)then
+
+               gamma     = cpp - q_loc*latcond/T_loc
+               dqdlnT    = (mv*latcond/(mn*T_loc) - gamma) & 
+                            / (latcond/T_loc + Rstar/(mn*q_loc))
+               dlnqdlnT  = (1./q_loc)*dqdlnT
+               dlnpdlnT  = mv*latcond/(Rstar*T_loc) - dlnqdlnT/(1. + q_loc*mn/mv)
+               dpdT      = (p_loc/T_loc)*dlnpdlnT
+               q_loc     = q_loc  + dqdlnT*dln_p/dlnpdlnT
+               vmr_loc   = q_loc*mn/mv ! needed for Tcond calc.
+               T_loc     = T_loc*(1 + dln_p/dlnpdlnT)
+               print*,T_loc
+            else
+               ! nothing doing; so dry convection
+               T_loc     = tsurf*(p_loc/plev(1))**rcp
+            endif
+
+            ! update true gridpoints when we reach them
+            if((p_loc.le.play(l)) .and. (l.le.nlayermx))then
+               temp(l)=T_loc
+               qvap(l)=q_loc
+               ! do an avg you lazy bastard
+!               temp(l)=T_loc*(p_loc-play(l))/(p_loc-pold)+Told*(play(l)-pold)/(p_loc-pold)
+!               qvap(l)=q_loc*(p_loc-play(l))/(p_loc-pold)+qold*(play(l)-pold)/(p_loc-pold)
+
+!               f=fA*(y2-y)/(y2-y1)+fB*(y-y1)/(y2-y1)
+
+!               print*,'l=',l
+!               print*,'temp(l)=',temp(l)
+!               print*,'qvap(l)=',qvap(l)
+
+
+               qvap(l)=0.05*mv/mn ! suface amount everywhere to test
+
+               l=l+1
+            endif
+
+            Told=T_loc
+            qold=q_loc
+            pold=p_loc
+
+      enddo ! vertical loop
+
+      print*,'---fin---'
+
+      return
+    end subroutine N2broadprof_fn
Index: /trunk/LMDZ.GENERIC/libf/phystd/aeropacity.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/aeropacity.F90	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/aeropacity.F90	(revision 253)
@@ -1,6 +1,6 @@
-      subroutine aeropacity(ngrid,nlayer,nq,pplev,pq, &
-         aerosol,reffrad,QREFvis3d,QREFir3d,tau_col)
-
-       use radinc_h, only : naerkind
+      Subroutine aeropacity(ngrid,nlayer,nq,pplay,pplev,pq, &
+         aerosol,reffrad,QREFvis3d,QREFir3d,tau_col,cloudfrac,totcloudfrac,clearsky)
+
+       use radinc_h, only : naerkind, L_TAUMAX
                   
        implicit none
@@ -46,4 +46,5 @@
       INTEGER ngrid,nlayer,nq
 
+      REAL pplay(ngrid,nlayer)
       REAL pplev(ngrid,nlayer+1)
       REAL pq(ngrid,nlayer,nq)
@@ -53,5 +54,9 @@
       REAL QREFir3d(ngridmx,nlayermx,naerkind)
 
-      REAL tauref(ngrid), tau_col(ngrid)
+      REAL tau_col(ngrid)
+!      REAL tauref(ngrid), tau_col(ngrid)
+
+      real cloudfrac(ngridmx,nlayermx)
+      real aerosol0
 
       INTEGER l,ig,iq,iaer
@@ -68,9 +73,17 @@
       CHARACTER(LEN=20) :: tracername ! to temporarily store text
 
-
-! identify tracers
+      ! for fixed dust profiles
+      real topdust, expfactor, zp
+      REAL taudusttmp(ngridmx) ! Temporary dust opacity used before scaling
+
+      ! BENJAMIN MODIFS
+      real CLFtot,CLF1,CLF2
+      real totcloudfrac(ngridmx)
+      logical clearsky
+
+      ! identify tracers
       IF (firstcall) THEN
 
-         ! are these tests of any real use?
+         ! are these tests of any real use ?
         IF(ngrid.NE.ngridmx) THEN
             PRINT*,'STOP in aeropacity!'
@@ -86,5 +99,4 @@
            stop
         endif
-
 
         do iq=1,nqmx
@@ -101,8 +113,17 @@
         write(*,*) "            i_h2oice=",i_h2oice
         
-        !if((i_h2oice.lt.1) .and. (naerkind.gt.1))then
-        !   print*,'naerkind > 1 but no h2o ice, this will not work.'
-        !   stop
-        !endif
+      if(watercond.and.(.not.aerofixed))then
+         if(naerkind.lt.2)then
+            print*,'Cannot have active H2O clouds with naerkind less than 2!'
+            call abort
+         endif
+      endif
+
+      if(dusttau.gt.0.0)then
+         if(naerkind.lt.3)then
+            print*,'Cannot have active dust with naerkind less than 3!'
+            call abort
+         endif
+      endif
 
         firstcall=.false.
@@ -110,71 +131,117 @@
 
 
-      aerosol(:,:,:)=0.0
-
       DO iaer = 1, naerkind ! Loop on aerosol kind (NOT tracer)
 !     ---------------------------------------------------------
-        aerkind: SELECT CASE (iaer)
-!==================================================================
-        CASE(1) aerkind                          ! CO2 ice (iaer=1)
+         aerkind: SELECT CASE (iaer)
+!==================================================================
+         CASE(1) aerkind                         ! CO2 ice (iaer=1)
 !==================================================================
 
 !       1. Initialization
-        CALL zerophys(ngrid*nlayer,aerosol(1,1,iaer))
+            aerosol(:,:,iaer)=0.0
 
 !       2. Opacity calculation
-        if (aerofixed.or.(i_co2ice.eq.0)) then !  CO2 ice cloud prescribed
-           do ig=1, ngrid
-              do l=1,nlayer
-                 aerosol(ig,l,iaer) =1.e-9
-              end do
-              aerosol(ig,14,iaer)=1.e-9 ! single cloud layer option
-           end do
-        else
-           DO ig=1, ngrid
-              DO l=1,nlayer
-                 aerosol(ig,l,iaer) =                   &
-                      (  0.75 * QREFvis3d(ig,l,iaer) /  &
-                      ( rho_co2 * reffrad(ig,l,iaer) )  ) * &
-                      ( pq(ig,l,i_co2ice) + 1.E-9 ) *   &
-                      ( pplev(ig,l) - pplev(ig,l+1) ) / g
-              ENDDO
-           ENDDO
-        end if
-
-!==================================================================
-        CASE(2) aerkind               ! Water ice crystals (iaer=2)
-!==================================================================
-
+            if (aerofixed.or.(i_co2ice.eq.0)) then !  CO2 ice cloud prescribed
+               do ig=1, ngrid
+                  do l=1,nlayer
+                     aerosol(ig,l,iaer)=1.e-9
+                  end do
+                  !aerosol(ig,12,iaer)=4.0 ! single cloud layer option
+               end do
+            else
+               DO ig=1, ngrid
+                  DO l=1,nlayer-1 ! to stop the rad tran bug
+
+                     aerosol0 =                         &
+                          (  0.75 * QREFvis3d(ig,l,iaer) /        &
+                          ( rho_co2 * reffrad(ig,l,iaer) )  ) *   &
+                          ( pq(ig,l,i_co2ice) + 1.E-9 ) *         &
+                          ( pplev(ig,l) - pplev(ig,l+1) ) / g
+                     aerosol0           = max(aerosol0,1.e-9)
+                     aerosol0           = min(aerosol0,L_TAUMAX)
+                     aerosol(ig,l,iaer) = aerosol0
+!                     aerosol(ig,l,iaer) = 0.0
+
+!        using cloud fraction
+!                     aerosol(ig,l,iaer) = -log(1 - CLF + CLF*exp(-aerosol0/CLF))
+!                     aerosol(ig,l,iaer) = min(aerosol(ig,l,iaer),L_TAUMAX)
+
+
+                  ENDDO
+               ENDDO
+            end if
+            
+!==================================================================
+         CASE(2) aerkind              ! Water ice / liquid (iaer=2)
+!==================================================================
 
 !       1. Initialization
-        CALL zerophys(ngrid*nlayer,aerosol(1,1,iaer))
+            aerosol(:,:,iaer)=0.0
 
 !       2. Opacity calculation
-!     if (1.eq.1) then
-     if (aerofixed.or.(i_h2oice.eq.0)) then
-!        print*,'No H2O clouds in the radiative transfer!'
-        do ig=1, ngrid
-           do l=1,nlayer
-              aerosol(ig,l,iaer) =1.e-9
-           end do
-           aerosol(ig,5,iaer)=1.e-9 ! single cloud layer option
-        end do
-     else
-        DO ig=1, ngrid
-          DO l=1,nlayer
-             aerosol(ig,l,iaer) =                   &
-            (  0.75 * QREFvis3d(ig,l,iaer) /        &
-              ( rho_ice * reffrad(ig,l,iaer) )  ) * &
-              ( pq(ig,l,i_h2oice) + 1.E-9 ) *   &
-              ( pplev(ig,l) - pplev(ig,l+1) ) / g
-          ENDDO
-        ENDDO
-
-     end if
-
-
-!==================================================================
-        END SELECT aerkind
-
+            if (aerofixed.or.(i_h2oice.eq.0).or.clearsky) then
+               do ig=1, ngrid ! to stop the rad tran bug
+                  do l=1,nlayer
+                     aerosol(ig,l,iaer) =1.e-9
+                  end do
+               end do
+            else
+               do ig=1, ngrid
+                  do l=1,nlayer-1 ! to stop the rad tran bug
+
+                     if(CLFvarying)then
+                        CLF1    = max(cloudfrac(ig,l),0.01)
+                        CLFtot  = max(totcloudfrac(ig),0.01)
+                        CLF2    = CLF1/CLFtot 
+                        CLF2    = min(1.,CLF2)
+                     else
+                        CLF1=1.0
+                        CLF2=CLFfixval
+                     endif
+                     
+                     aerosol0 =                                   &
+                          (  0.75 * QREFvis3d(ig,l,iaer) /        &
+                          ( rho_ice * reffrad(ig,l,iaer) )  ) *   &
+                          ( pq(ig,l,i_h2oice) + 1.E-9 ) *         &
+                          ( pplev(ig,l) - pplev(ig,l+1) ) / g /   &
+                            CLF1
+
+                     aerosol(ig,l,iaer) = -log(1 - CLF2 + CLF2*exp(-aerosol0)) 
+                     ! why no division in exponential?
+                     ! because its already done in aerosol0
+                     
+                     aerosol(ig,l,iaer) = max(aerosol(ig,l,iaer),1.e-9)
+                     aerosol(ig,l,iaer) = min(aerosol(ig,l,iaer),aerosol0)                     
+                     
+                  enddo
+               enddo
+            end if
+
+
+!==================================================================
+         CASE(3) aerkind                            ! Dust (iaer=3)
+!==================================================================
+
+!       1. Initialization
+            aerosol(:,:,iaer)=0.0
+
+            topdust=10.0 ! km
+
+            print*,'WARNING, dust is experimental for Early Mars'
+
+!       2. Opacity calculation
+
+            do l=1,nlayer
+               do ig=1,ngrid-1 ! to stop the rad tran bug
+                  zp=700./pplay(ig,l)
+                  aerosol(ig,l,1)=(dusttau/700.)*(pplev(ig,l)-pplev(ig,l+1)) &
+                       *max( exp(.03*(1.-max(zp,1.))) , 1.E-3 ) &
+                       *QREFvis3d(ig,l,iaer) / QREFvis3d(ig,1,iaer) 
+                  ! takes into account particle variation
+              enddo
+            enddo
+
+!==================================================================
+         END SELECT aerkind
       ENDDO ! iaer (loop on aerosol kind)
 
@@ -183,5 +250,5 @@
 ! Column integrated visible optical depth in each point (used for diagnostic)
 
-      call zerophys(ngrid,tau_col)
+      tau_col(:)=0.0
       do iaer = 1, naerkind
          do l=1,nlayer
@@ -192,4 +259,27 @@
       end do
 
+      do ig=1, ngrid
+         do l=1,nlayer
+            do iaer = 1, naerkind
+               if(aerosol(ig,l,iaer).gt.1.e3)then
+                  print*,'WARNING: aerosol=',aerosol(ig,l,iaer)
+                  print*,'at ig=',ig,',  l=',l,', iaer=',iaer
+                  print*,'QREFvis3d=',QREFvis3d(ig,l,iaer)
+                  print*,'reffrad=',reffrad(ig,l,iaer)
+               endif
+            end do
+         end do
+      end do
+
+      do ig=1, ngrid
+         if(tau_col(ig).gt.1.e3)then
+            print*,'WARNING: tau_col=',tau_col(ig)
+            print*,'at ig=',ig
+            print*,'aerosol=',aerosol(ig,:,:)
+            print*,'QREFvis3d=',QREFvis3d(ig,:,:)
+            print*,'reffrad=',reffrad(ig,:,:)
+         endif
+      end do
+
       return
     end subroutine aeropacity
Index: /trunk/LMDZ.GENERIC/libf/phystd/aeroptproperties.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/aeroptproperties.F90	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/aeroptproperties.F90	(revision 253)
@@ -1,35 +1,34 @@
-      subroutine aeroptproperties(ngrid,nlayer,reffrad,nueffrad, &
-                                 QVISsQREF3d,omegaVIS3d,gVIS3d, &
-                                 QIRsQREF3d,omegaIR3d,gIR3d,    &
-                                 QREFvis3d,QREFir3d)
+      SUBROUTINE aeroptproperties(ngrid,nlayer,reffrad,nueffrad,   &
+                                  QVISsQREF3d,omegaVIS3d,gVIS3d,   &
+                                  QIRsQREF3d,omegaIR3d,gIR3d,      &
+                                  QREFvis3d,QREFir3d)!,		   &
+!                                  omegaREFvis3d,omegaREFir3d)
 
       use radinc_h,    only: L_NSPECTI,L_NSPECTV,naerkind,nsizemax
       use radcommon_h, only: QVISsQREF,omegavis,gvis,QIRsQREF,omegair,gir
-      use radcommon_h, only: radiustab,nsize,qrefvis,qrefir
+      use radcommon_h, only: qrefvis,qrefir,omegarefvis,omegarefir
+      use radcommon_h, only: radiustab,nsize
 
       implicit none
 
-!==================================================================
-!     
-!     Purpose
-!     -------
-!     Compute the scattering parameters in each grid
-!     box, depending on aerosol grain sizes.
+!     =============================================================
+!     Aerosol Optical Properties
 !
-!     Notes
-!     -----
-!     Don't forget to set the value of varyingnueff below; If
-!     the effective variance of the distribution for the given
-!     aerosol is considered homogeneous in the atmosphere, please
-!     set varyingnueff(iaer) to .false. Resulting computational
-!     time will be much better.
-!
-!     Authors
-!     ------- 
-!     J.-B. Madeleine, F. Montmessin
+!     Description:
+!       Compute the scattering parameters in each grid
+!       box, depending on aerosol grain sizes. Log-normal size
+!       distribution and Gauss-Legendre integration are used.
+
+!     Parameters:
+!       Don't forget to set the value of varyingnueff below; If
+!       the effective variance of the distribution for the given
+!       aerosol is considered homogeneous in the atmosphere, please
+!       set varyingnueff(iaer) to .false. Resulting computational
+!       time will be much better.
+
+!     Authors: J.-B. Madeleine, F. Forget, F. Montmessin
 !     Slightly modified and converted to F90 by R. Wordsworth (2009)
 !     Varying nueff section removed by R. Wordsworth for simplicity
-!     
-!==================================================================
+!     ==============================================================
 
 #include "dimensions.h"
@@ -40,38 +39,52 @@
 !     ---------------
 
+
+
 !     =============================================================
       LOGICAL, PARAMETER :: varyingnueff(naerkind) = .false.
 !     =============================================================
 
-!     Radius axis used for integration 
-      DOUBLE PRECISION :: radiusint(nsizemax+1)
-!     Min. and max radii of the interpolation grid (in METERS)
-      REAL, PARAMETER :: refftabmin = 2e-8
+!     Min. and max radius of the interpolation grid (in METERS)
+      REAL, PARAMETER :: refftabmin = 2e-8 !2e-8
 !      REAL, PARAMETER :: refftabmax = 35e-6
-      REAL, PARAMETER :: refftabmax = 1e-3 ! CHANGED BY RDW
+      REAL, PARAMETER :: refftabmax = 1e-3
 !     Log of the min and max variance of the interpolation grid
       REAL, PARAMETER :: nuefftabmin = -4.6
       REAL, PARAMETER :: nuefftabmax = 0.
-!     Number of effective radii of the interpolation grid
+!     Number of effective radius of the interpolation grid
       INTEGER, PARAMETER :: refftabsize = 200
 !     Number of effective variances of the interpolation grid
 !      INTEGER, PARAMETER :: nuefftabsize = 100
-      INTEGER, PARAMETER :: nuefftabsize = 1  ! CHANGED BY RDW
+      INTEGER, PARAMETER :: nuefftabsize = 1
 !     Interpolation grid indices (reff,nueff)
       INTEGER :: grid_i,grid_j
-!     Volume ratio of the look-up table (different in VIS and IR)
-      DOUBLE PRECISION :: vrat
-!     r_g and sigma_g for the log-normal distribution
-!       as defined by [hansen_1974]
-      REAL :: r_g,sigma_g
-!     Error function used for integration
-      DOUBLE PRECISION :: derf
-!     Density function f(x)dx of the log-normal distribution
-      REAL :: dfi
-      DOUBLE PRECISION :: dfi_tmp(nsizemax+1)
 !     Intermediate variable
       REAL :: var_tmp,var3d_tmp(ngridmx,nlayermx)
 !     Bilinear interpolation factors
       REAL :: kx,ky,k1,k2,k3,k4
+!     Size distribution parameters
+      REAL :: sizedistk1,sizedistk2
+!     Pi!
+      REAL,SAVE :: pi
+!     Variables used by the Gauss-Legendre integration:
+      INTEGER radius_id,gausind
+      REAL kint
+      REAL drad
+      INTEGER, PARAMETER :: ngau = 10
+      REAL weightgaus(ngau),radgaus(ngau)
+      SAVE weightgaus,radgaus
+!      DATA weightgaus/.2955242247,.2692667193,.2190863625,.1494513491,.0666713443/
+!      DATA radgaus/.1488743389,.4333953941,.6794095682,.8650633666,.9739065285/
+      DATA    radgaus/0.07652652113350,0.22778585114165, &
+                      0.37370608871528,0.51086700195146, &
+                      0.63605368072468,0.74633190646476, &
+                      0.83911697181213,0.91223442826796, &
+                      0.96397192726078,0.99312859919241/
+
+      DATA weightgaus/0.15275338723120,0.14917298659407, &
+                      0.14209610937519,0.13168863843930, &
+                      0.11819453196154,0.10193011980823, &
+                      0.08327674160932,0.06267204829828, &
+                      0.04060142982019,0.01761400714091/
 !     Indices
       INTEGER :: i,j,k,l,m,iaer,idomain
@@ -82,25 +95,64 @@
 
 !     Radius axis of the interpolation grid
-      DOUBLE PRECISION,SAVE :: refftab(refftabsize)
+      REAL,SAVE :: refftab(refftabsize)
 !     Variance axis of the interpolation grid
-      DOUBLE PRECISION,SAVE :: nuefftab(nuefftabsize)
+      REAL,SAVE :: nuefftab(nuefftabsize)
 !     Volume ratio of the grid
-      DOUBLE PRECISION,SAVE :: logvratgrid,vratgrid
+      REAL,SAVE :: logvratgrid,vratgrid
 !     Grid used to remember which calculation is done
-      LOGICAL,SAVE :: checkgrid(refftabsize,nuefftabsize,naerkind,2) &
-                     = .false.
+      LOGICAL,SAVE :: checkgrid(refftabsize,nuefftabsize,naerkind,2) = .false.
 !     Optical properties of the grid (VISIBLE)
-      REAL,SAVE :: epVISgrid(refftabsize,nuefftabsize,L_NSPECTV,naerkind)
+      REAL,SAVE :: qsqrefVISgrid(refftabsize,nuefftabsize,L_NSPECTV,naerkind)
+      REAL,SAVE :: qextVISgrid(refftabsize,nuefftabsize,L_NSPECTV,naerkind)
+      REAL,SAVE :: qscatVISgrid(refftabsize,nuefftabsize,L_NSPECTV,naerkind)
       REAL,SAVE :: omegVISgrid(refftabsize,nuefftabsize,L_NSPECTV,naerkind)
       REAL,SAVE :: gVISgrid(refftabsize,nuefftabsize,L_NSPECTV,naerkind)
 !     Optical properties of the grid (INFRARED)
-      REAL,SAVE :: epIRgrid(refftabsize,nuefftabsize,L_NSPECTI,naerkind)
+      REAL,SAVE :: qsqrefIRgrid(refftabsize,nuefftabsize,L_NSPECTI,naerkind)
+      REAL,SAVE :: qextIRgrid(refftabsize,nuefftabsize,L_NSPECTI,naerkind)
+      REAL,SAVE :: qscatIRgrid(refftabsize,nuefftabsize,L_NSPECTI,naerkind)
       REAL,SAVE :: omegIRgrid(refftabsize,nuefftabsize,L_NSPECTI,naerkind)
       REAL,SAVE :: gIRgrid(refftabsize,nuefftabsize,L_NSPECTI,naerkind)
 !     Optical properties of the grid (REFERENCE WAVELENGTHS)
-      REAL,SAVE :: eprefVISgrid(refftabsize,nuefftabsize,naerkind)
-      REAL,SAVE :: eprefIRgrid(refftabsize,nuefftabsize,naerkind)
+      REAL,SAVE :: qrefVISgrid(refftabsize,nuefftabsize,naerkind)
+      REAL,SAVE :: qscatrefVISgrid(refftabsize,nuefftabsize,naerkind)
+      REAL,SAVE :: qrefIRgrid(refftabsize,nuefftabsize,naerkind)
+      REAL,SAVE :: qscatrefIRgrid(refftabsize,nuefftabsize,naerkind)
+      REAL,SAVE :: omegrefVISgrid(refftabsize,nuefftabsize,naerkind)
+      REAL,SAVE :: omegrefIRgrid(refftabsize,nuefftabsize,naerkind)
 !     Firstcall
       LOGICAL,SAVE :: firstcall = .true.
+!     Variables used by the Gauss-Legendre integration:
+      REAL,SAVE :: normd(refftabsize,nuefftabsize,naerkind,2)
+      REAL,SAVE :: dista(refftabsize,nuefftabsize,naerkind,2,ngau)
+      REAL,SAVE :: distb(refftabsize,nuefftabsize,naerkind,2,ngau)
+
+      REAL,SAVE :: radGAUSa(ngau,naerkind,2)
+      REAL,SAVE :: radGAUSb(ngau,naerkind,2)
+
+      REAL,SAVE :: qsqrefVISa(L_NSPECTV,ngau,naerkind)
+      REAL,SAVE :: qrefVISa(ngau,naerkind)
+      REAL,SAVE :: qsqrefVISb(L_NSPECTV,ngau,naerkind)
+      REAL,SAVE :: qrefVISb(ngau,naerkind)
+      REAL,SAVE :: omegVISa(L_NSPECTV,ngau,naerkind)
+      REAL,SAVE :: omegrefVISa(ngau,naerkind)
+      REAL,SAVE :: omegVISb(L_NSPECTV,ngau,naerkind)
+      REAL,SAVE :: omegrefVISb(ngau,naerkind)
+      REAL,SAVE :: gVISa(L_NSPECTV,ngau,naerkind)
+      REAL,SAVE :: gVISb(L_NSPECTV,ngau,naerkind)
+
+      REAL,SAVE :: qsqrefIRa(L_NSPECTI,ngau,naerkind)
+      REAL,SAVE :: qrefIRa(ngau,naerkind)
+      REAL,SAVE :: qsqrefIRb(L_NSPECTI,ngau,naerkind)
+      REAL,SAVE :: qrefIRb(ngau,naerkind)
+      REAL,SAVE :: omegIRa(L_NSPECTI,ngau,naerkind)
+      REAL,SAVE :: omegrefIRa(ngau,naerkind)
+      REAL,SAVE :: omegIRb(L_NSPECTI,ngau,naerkind)
+      REAL,SAVE :: omegrefIRb(ngau,naerkind)
+      REAL,SAVE :: gIRa(L_NSPECTI,ngau,naerkind)
+      REAL,SAVE :: gIRb(L_NSPECTI,ngau,naerkind)
+
+      REAL :: radiusm
+      REAL :: radiusr
 
 !     Inputs
@@ -127,8 +179,9 @@
       REAL :: QREFir3d(ngridmx,nlayermx,naerkind)
 
+      REAL :: omegaREFvis3d(ngridmx,nlayermx,naerkind)
+      REAL :: omegaREFir3d(ngridmx,nlayermx,naerkind)
+
       DO iaer = 1, naerkind ! Loop on aerosol kind
-
         IF ( (nsize(iaer,1).EQ.1).AND.(nsize(iaer,2).EQ.1) ) THEN
-
 !==================================================================
 !       If there is one single particle size, optical
@@ -148,6 +201,9 @@
               QREFvis3d(ig,lg,iaer)=QREFvis(iaer,1)
               QREFir3d(ig,lg,iaer)=QREFir(iaer,1)
+              omegaREFvis3d(ig,lg,iaer)=omegaREFvis(iaer,1)
+              omegaREFir3d(ig,lg,iaer)=omegaREFir(iaer,1)
             ENDDO
           ENDDO
+
 
           if (firstcall) then
@@ -162,10 +218,13 @@
 !     --------------------------------------------------
       IF (firstcall) THEN
-!       1.1 Effective radius
+
+!       1.1 Pi!
+        pi = 2. * asin(1.e0)
+
+!       1.2 Effective radius
         refftab(1)    = refftabmin
         refftab(refftabsize) = refftabmax
 
-        logvratgrid = log(refftabmax/refftabmin) / &
-                     float(refftabsize-1)*3.
+        logvratgrid = log(refftabmax/refftabmin) / float(refftabsize-1)*3.
         vratgrid = exp(logvratgrid)
 
@@ -174,31 +233,149 @@
         enddo
 
-!       1.2 Effective variance
-        do i = 0, nuefftabsize-1
-          nuefftab(i+1) = exp( nuefftabmin + &
-                  i*(nuefftabmax-nuefftabmin)/(nuefftabsize-1) )
-        enddo
+!       1.3 Effective variance
+        if(nuefftabsize.eq.1)then ! addded by RDW
+           print*,'Warning: no variance range in aeroptproperties'
+           nuefftab(1)=0.2
+        else
+           do i = 0, nuefftabsize-1
+              nuefftab(i+1) = exp( nuefftabmin + i*(nuefftabmax-nuefftabmin)/(nuefftabsize-1) )
+           enddo
+        endif
+
         firstcall = .false.
       ENDIF
 
-
+!       1.4 Radius middle point and range for Gauss integration
+        radiusm=0.5*(radiustab(iaer,idomain,nsize(iaer,idomain)) + radiustab(iaer,idomain,1))
+        radiusr=0.5*(radiustab(iaer,idomain,nsize(iaer,idomain)) - radiustab(iaer,idomain,1))
+
+!       1.5 Interpolating data at the Gauss quadrature points:
+        DO gausind=1,ngau
+          drad=radiusr*radgaus(gausind)
+          radGAUSa(gausind,iaer,idomain)=radiusm-drad
+
+          radius_id=minloc(abs(radiustab(iaer,idomain,:) - (radiusm-drad)),DIM=1)
+          IF ((radiustab(iaer,idomain,radius_id) - (radiusm-drad)).GT.0) THEN
+            radius_id=radius_id-1
+          ENDIF
+          IF (radius_id.GE.nsize(iaer,idomain)) THEN
+            radius_id=nsize(iaer,idomain)-1
+            kint = 1.
+          ELSEIF (radius_id.LT.1) THEN
+            radius_id=1
+            kint = 0.
+          ELSE
+          kint = ( (radiusm-drad) -				&
+                   radiustab(iaer,idomain,radius_id) ) /	&
+                 ( radiustab(iaer,idomain,radius_id+1) -	&
+                   radiustab(iaer,idomain,radius_id) )
+          ENDIF
+          IF (idomain.EQ.1) THEN ! VISIBLE DOMAIN -----------------
+            DO m=1,L_NSPECTV
+               qsqrefVISa(m,gausind,iaer)=                      &
+                    (1-kint)*QVISsQREF(m,iaer,radius_id) +      &
+                    kint*QVISsQREF(m,iaer,radius_id+1)
+            omegVISa(m,gausind,iaer)=                           &
+                    (1-kint)*omegaVIS(m,iaer,radius_id) +       &
+                    kint*omegaVIS(m,iaer,radius_id+1)
+            gVISa(m,gausind,iaer)=                              &
+                    (1-kint)*gVIS(m,iaer,radius_id) +           &
+                    kint*gVIS(m,iaer,radius_id+1)
+            ENDDO
+            qrefVISa(gausind,iaer)=                             &
+                    (1-kint)*QREFvis(iaer,radius_id) +          &
+                    kint*QREFvis(iaer,radius_id+1)
+            omegrefVISa(gausind,iaer)=                          &
+                    (1-kint)*omegaREFvis(iaer,radius_id) +      &
+                    kint*omegaREFvis(iaer,radius_id+1)
+          ELSE ! INFRARED DOMAIN ----------------------------------
+            DO m=1,L_NSPECTI
+            qsqrefIRa(m,gausind,iaer)=                          &
+                    (1-kint)*QIRsQREF(m,iaer,radius_id) +       &
+                    kint*QIRsQREF(m,iaer,radius_id+1)
+            omegIRa(m,gausind,iaer)=                            &
+                    (1-kint)*omegaIR(m,iaer,radius_id) +        &
+                    kint*omegaIR(m,iaer,radius_id+1)
+            gIRa(m,gausind,iaer)=                               &
+                    (1-kint)*gIR(m,iaer,radius_id) +            &
+                    kint*gIR(m,iaer,radius_id+1)
+            ENDDO
+            qrefIRa(gausind,iaer)=                              &
+                    (1-kint)*QREFir(iaer,radius_id) +           &
+                    kint*QREFir(iaer,radius_id+1)
+            omegrefIRa(gausind,iaer)=                           &
+                    (1-kint)*omegaREFir(iaer,radius_id) +       &
+                    kint*omegaREFir(iaer,radius_id+1)
+          ENDIF
+        ENDDO
+
+        DO gausind=1,ngau
+          drad=radiusr*radgaus(gausind)
+          radGAUSb(gausind,iaer,idomain)=radiusm+drad
+
+          radius_id=minloc(abs(radiustab(iaer,idomain,:) -      &
+                               (radiusm+drad)),DIM=1)
+          IF ((radiustab(iaer,idomain,radius_id) -              &
+               (radiusm+drad)).GT.0) THEN
+            radius_id=radius_id-1
+          ENDIF
+          IF (radius_id.GE.nsize(iaer,idomain)) THEN
+            radius_id=nsize(iaer,idomain)-1
+            kint = 1.
+          ELSEIF (radius_id.LT.1) THEN
+            radius_id=1
+            kint = 0.
+          ELSE
+            kint = ( (radiusm+drad) -                           &
+                     radiustab(iaer,idomain,radius_id) ) /      &
+                   ( radiustab(iaer,idomain,radius_id+1) -      &
+                     radiustab(iaer,idomain,radius_id) )
+          ENDIF
+          IF (idomain.EQ.1) THEN ! VISIBLE DOMAIN -----------------
+            DO m=1,L_NSPECTV
+            qsqrefVISb(m,gausind,iaer)=                         &
+                    (1-kint)*QVISsQREF(m,iaer,radius_id) +      &
+                    kint*QVISsQREF(m,iaer,radius_id+1)    
+            omegVISb(m,gausind,iaer)=                           &
+                    (1-kint)*omegaVIS(m,iaer,radius_id) +       &
+                    kint*omegaVIS(m,iaer,radius_id+1)
+            gVISb(m,gausind,iaer)=                              &
+                    (1-kint)*gVIS(m,iaer,radius_id) +           &
+                    kint*gVIS(m,iaer,radius_id+1)
+            ENDDO
+            qrefVISb(gausind,iaer)=                             &
+                    (1-kint)*QREFvis(iaer,radius_id) +          &
+                    kint*QREFvis(iaer,radius_id+1)
+            omegrefVISb(gausind,iaer)=                          &
+                    (1-kint)*omegaREFvis(iaer,radius_id) +      &
+                    kint*omegaREFvis(iaer,radius_id+1)
+          ELSE ! INFRARED DOMAIN ----------------------------------
+            DO m=1,L_NSPECTI
+            qsqrefIRb(m,gausind,iaer)=                          &
+                    (1-kint)*QIRsQREF(m,iaer,radius_id) +       &
+                    kint*QIRsQREF(m,iaer,radius_id+1)
+            omegIRb(m,gausind,iaer)=                            &
+                    (1-kint)*omegaIR(m,iaer,radius_id) +        &
+                    kint*omegaIR(m,iaer,radius_id+1)
+            gIRb(m,gausind,iaer)=                               &
+                    (1-kint)*gIR(m,iaer,radius_id) +            &
+                    kint*gIR(m,iaer,radius_id+1)
+            ENDDO
+            qrefIRb(gausind,iaer)=                              &
+                    (1-kint)*QREFir(iaer,radius_id) +           &
+                    kint*QREFir(iaer,radius_id+1)
+            omegrefIRb(gausind,iaer)=                           &
+                    (1-kint)*omegaREFir(iaer,radius_id) +       &
+                    kint*omegaREFir(iaer,radius_id+1)
+          ENDIF
+        ENDDO
+
+!==================================================================
+! CONSTANT NUEFF FROM HERE
+!==================================================================
 
 !     2. Compute the scattering parameters using linear
 !       interpolation over grain sizes and constant nueff
 !     ---------------------------------------------------
-
-!     2.1 Initialization
-
-      vrat = log(radiustab(iaer,idomain,nsize(iaer,idomain)) / &
-              radiustab(iaer,idomain,1)) / &
-              float(nsize(iaer,idomain)-1)*3.
-      vrat = exp(vrat)
-
-      radiusint(1) = 1.e-9
-      DO i = 2,nsize(iaer,idomain)
-        radiusint(i) = ( (2.*vrat) / (vrat+1.) )**(1./3.) * &
-                      radiustab(iaer,idomain,i-1)
-      ENDDO
-      radiusint(nsize(iaer,idomain)+1) = 1.e-2
 
       DO lg = 1,nlayer
@@ -210,92 +387,297 @@
           grid_i=floor(var_tmp)
           IF (grid_i.GE.refftabsize) THEN
-           WRITE(*,*) 'Warning: Aerosol particle size in grid box #'
-           WRITE(*,*) ig,' is too large to be used by the '
-           WRITE(*,*) 'radiative transfer; please extend the '
-           WRITE(*,*) 'interpolation grid to larger sizes.'
-
+!           WRITE(*,*) 'Warning: particle size in grid box #'
+!           WRITE(*,*) ig,' is too large to be used by the '
+!           WRITE(*,*) 'radiative transfer; please extend the '
+!           WRITE(*,*) 'interpolation grid to larger grain sizes.'
             grid_i=refftabsize-1
             kx = 1.
           ELSEIF (grid_i.LT.1) THEN
-           WRITE(*,*) 'Warning: Aerosol particle size in grid box #'
-           WRITE(*,*) ig,' is too small to be used by the '
-           WRITE(*,*) 'radiative transfer; please extend the '
-           WRITE(*,*) 'interpolation grid to smaller sizes.'
+!           WRITE(*,*) 'Warning: particle size in grid box #'
+!           WRITE(*,*) ig,' is too small to be used by the '
+!           WRITE(*,*) 'radiative transfer; please extend the '
+!           WRITE(*,*) 'interpolation grid to smaller grain sizes.'
             grid_i=1
             kx = 0.
           ELSE
-            kx = ( reffrad(ig,lg,iaer)-refftab(grid_i) ) / &
-                ( refftab(grid_i+1)-refftab(grid_i) )
+            kx = ( reffrad(ig,lg,iaer)-refftab(grid_i) ) /            &
+                 ( refftab(grid_i+1)-refftab(grid_i) )
           ENDIF
 !         2.3 Integration
           DO j=grid_i,grid_i+1
-!             2.3.1 Check if the calculation has been completed
+!             2.3.1 Check if the calculation has been done
               IF (.NOT.checkgrid(j,1,iaer,idomain)) THEN
-!               2.3.2 Compute r_g and sigma_g for the log-normal
-!                 distribution as defined by [hansen_1974], "Light
-!                 scattering in planetary atmospheres", Space
-!                 Science Reviews 16 527-610, p558
-                sigma_g = log(1.+nueffrad(1,1,iaer))
-                r_g = exp(2.5*sigma_g)
-                sigma_g = sqrt(sigma_g)
-                r_g = refftab(j) / r_g
+!               2.3.2 Log-normal dist., r_g and sigma_g are defined
+!                 in [hansen_1974], "Light scattering in planetary
+!                 atmospheres", Space Science Reviews 16 527-610.
+!                 Here, sizedistk1=r_g and sizedistk2=sigma_g^2
+                sizedistk2 = log(1.+nueffrad(1,1,iaer))
+                sizedistk1 = exp(2.5*sizedistk2)
+                sizedistk1 = refftab(j) / sizedistk1
+
+                normd(j,1,iaer,idomain) = 1e-30
+                DO gausind=1,ngau
+                  drad=radiusr*radgaus(gausind)
+                  dista(j,1,iaer,idomain,gausind) = LOG((radiusm-drad)/sizedistk1)
+                  dista(j,1,iaer,idomain,gausind) =                   &
+                    EXP(-dista(j,1,iaer,idomain,gausind) *            &
+                    dista(j,1,iaer,idomain,gausind) *                 &
+                    0.5e0/sizedistk2)/(radiusm-drad)                  
+                  dista(j,1,iaer,idomain,gausind) =                   &
+                    dista(j,1,iaer,idomain,gausind) /                 &
+                    (sqrt(2e0*pi*sizedistk2))
+
+                  distb(j,1,iaer,idomain,gausind) = LOG((radiusm+drad)/sizedistk1)
+                  distb(j,1,iaer,idomain,gausind) =                   &
+                    EXP(-distb(j,1,iaer,idomain,gausind) *            &
+                    distb(j,1,iaer,idomain,gausind) *                 &
+                    0.5e0/sizedistk2)/(radiusm+drad)
+                  distb(j,1,iaer,idomain,gausind) =                   &
+                    distb(j,1,iaer,idomain,gausind) /                 &
+                    (sqrt(2e0*pi*sizedistk2))
+
+                  normd(j,1,iaer,idomain)=normd(j,1,iaer,idomain) +   &
+                    weightgaus(gausind) *                             &
+                    (                                                 &
+                    distb(j,1,iaer,idomain,gausind) * pi *            &
+                    radGAUSb(gausind,iaer,idomain) *                  &
+                    radGAUSb(gausind,iaer,idomain) +                  &
+                    dista(j,1,iaer,idomain,gausind) * pi *            &
+                    radGAUSa(gausind,iaer,idomain) *                  &
+                    radGAUSa(gausind,iaer,idomain)                    &
+                    )
+                ENDDO
                 IF (idomain.EQ.1) THEN ! VISIBLE DOMAIN -----------
 !                 2.3.3.vis Initialization
-                  epVISgrid(j,1,:,iaer)=0.
+                  qsqrefVISgrid(j,1,:,iaer)=0.
+                  qextVISgrid(j,1,:,iaer)=0.
+                  qscatVISgrid(j,1,:,iaer)=0.
                   omegVISgrid(j,1,:,iaer)=0.
                   gVISgrid(j,1,:,iaer)=0.
-                  eprefVISgrid(j,1,iaer)=0.
-!                 2.3.4.vis Log-normal distribution
-                  DO l=1,nsize(iaer,idomain)+1
-                    dfi_tmp(l) = log(radiusint(l)/r_g) /  &
-                                sqrt(2.)/sigma_g
+                  qrefVISgrid(j,1,iaer)=0.
+                  qscatrefVISgrid(j,1,iaer)=0.
+                  omegrefVISgrid(j,1,iaer)=0.
+
+                  DO gausind=1,ngau
+                    DO m=1,L_NSPECTV
+!                     Convolution:
+                      qextVISgrid(j,1,m,iaer) =              &
+                        qextVISgrid(j,1,m,iaer) +            & 
+                        weightgaus(gausind) *                &
+                        (                                    &
+                        qsqrefVISb(m,gausind,iaer) *         &
+                        qrefVISb(gausind,iaer) *             &
+                        pi*radGAUSb(gausind,iaer,idomain) *  &
+                        radGAUSb(gausind,iaer,idomain) *     &
+                        distb(j,1,iaer,idomain,gausind) +    &
+                        qsqrefVISa(m,gausind,iaer) *         &
+                        qrefVISa(gausind,iaer) *             &
+                        pi*radGAUSa(gausind,iaer,idomain) *  &
+                        radGAUSa(gausind,iaer,idomain) *     &
+                        dista(j,1,iaer,idomain,gausind)      &
+                        )
+                      qscatVISgrid(j,1,m,iaer) =             &
+                        qscatVISgrid(j,1,m,iaer) +           &
+                        weightgaus(gausind) *                &
+                        (                                    &
+                        omegVISb(m,gausind,iaer) *           &
+                        qsqrefVISb(m,gausind,iaer) *         &
+                        qrefVISb(gausind,iaer) *             &
+                        pi*radGAUSb(gausind,iaer,idomain) *  &
+                        radGAUSb(gausind,iaer,idomain) *     &
+                        distb(j,1,iaer,idomain,gausind) +    &
+                        omegVISa(m,gausind,iaer) *           &
+                        qsqrefVISa(m,gausind,iaer) *         &
+                        qrefVISa(gausind,iaer) *             &
+                        pi*radGAUSa(gausind,iaer,idomain) *  &
+                        radGAUSa(gausind,iaer,idomain) *     &
+                        dista(j,1,iaer,idomain,gausind)      &
+                        )
+                      gVISgrid(j,1,m,iaer) =                 &
+                        gVISgrid(j,1,m,iaer) +               &
+                        weightgaus(gausind) *                &
+                        (                                    &
+                        omegVISb(m,gausind,iaer) *           &
+                        qsqrefVISb(m,gausind,iaer) *         &
+                        qrefVISb(gausind,iaer) *             &
+                        gVISb(m,gausind,iaer) *              &
+                        pi*radGAUSb(gausind,iaer,idomain) *  &
+                        radGAUSb(gausind,iaer,idomain) *     &
+                        distb(j,1,iaer,idomain,gausind) +    &
+                        omegVISa(m,gausind,iaer) *           &
+                        qsqrefVISa(m,gausind,iaer) *         &
+                        qrefVISa(gausind,iaer) *             &
+                        gVISa(m,gausind,iaer) *              &
+                        pi*radGAUSa(gausind,iaer,idomain) *  &
+                        radGAUSa(gausind,iaer,idomain) *     &
+                        dista(j,1,iaer,idomain,gausind)      &
+                        )
+                    ENDDO
+                    qrefVISgrid(j,1,iaer) =                  &
+                      qrefVISgrid(j,1,iaer) +                &
+                      weightgaus(gausind) *                  &
+                      (                                      &
+                      qrefVISb(gausind,iaer) *               &
+                      pi*radGAUSb(gausind,iaer,idomain) *    &
+                      radGAUSb(gausind,iaer,idomain) *       &
+                      distb(j,1,iaer,idomain,gausind) +      &
+                      qrefVISa(gausind,iaer) *               &
+                      pi*radGAUSa(gausind,iaer,idomain) *    &
+                      radGAUSa(gausind,iaer,idomain) *       &
+                      dista(j,1,iaer,idomain,gausind)        &
+                      )
+                    qscatrefVISgrid(j,1,iaer) =              &
+                      qscatrefVISgrid(j,1,iaer) +            &
+                      weightgaus(gausind) *                  &
+                      (                                      &
+                      omegrefVISb(gausind,iaer) *            &
+                      qrefVISb(gausind,iaer) *               & 
+                      pi*radGAUSb(gausind,iaer,idomain) *    &
+                      radGAUSb(gausind,iaer,idomain) *       &
+                      distb(j,1,iaer,idomain,gausind) +      &
+                      omegrefVISa(gausind,iaer) *            &
+                      qrefVISa(gausind,iaer) *               &
+                      pi*radGAUSa(gausind,iaer,idomain) *    &
+                      radGAUSa(gausind,iaer,idomain) *       &
+                      dista(j,1,iaer,idomain,gausind)        &
+                      )
                   ENDDO
-                  DO l=1,nsize(iaer,idomain)
-                    dfi = 0.5*( derf(dfi_tmp(l+1)) -  &
-                               derf(dfi_tmp(l)) )
-                    DO m=1,L_NSPECTV
-                      epVISgrid(j,1,m,iaer) = &
-                               epVISgrid(j,1,m,iaer) &
-                               + QVISsQREF(m,iaer,l)*dfi
-                      omegVISgrid(j,1,m,iaer) = &
-                               omegVISgrid(j,1,m,iaer) &
-                               + omegaVIS(m,iaer,l)*dfi
-                      gVISgrid(j,1,m,iaer) = &
-                               gVISgrid(j,1,m,iaer)  &
-                               + gVIS(m,iaer,l)*dfi
-                    ENDDO !L_NSPECTV
-                    eprefVISgrid(j,1,iaer) =  &
-                               eprefVISgrid(j,1,iaer)  &
-                               + QREFvis(iaer,l)*dfi
-                  ENDDO !nsize
+
+                  qrefVISgrid(j,1,iaer)=qrefVISgrid(j,1,iaer) /          &
+                                normd(j,1,iaer,idomain)       
+                  qscatrefVISgrid(j,1,iaer)=qscatrefVISgrid(j,1,iaer) /  &
+                                normd(j,1,iaer,idomain)
+                  omegrefVISgrid(j,1,iaer)=qscatrefVISgrid(j,1,iaer) /   &
+                               qrefVISgrid(j,1,iaer)
+                  DO m=1,L_NSPECTV
+                    qextVISgrid(j,1,m,iaer)=qextVISgrid(j,1,m,iaer) /    &
+                                normd(j,1,iaer,idomain)
+                    qscatVISgrid(j,1,m,iaer)=qscatVISgrid(j,1,m,iaer) /  &
+                                normd(j,1,iaer,idomain)
+                    gVISgrid(j,1,m,iaer)=gVISgrid(j,1,m,iaer) /          &
+                                qscatVISgrid(j,1,m,iaer) /               &
+                                normd(j,1,iaer,idomain)
+
+                    qsqrefVISgrid(j,1,m,iaer)=qextVISgrid(j,1,m,iaer) /  &
+                                qrefVISgrid(j,1,iaer)
+                    omegVISgrid(j,1,m,iaer)=qscatVISgrid(j,1,m,iaer) /   &
+                                qextVISgrid(j,1,m,iaer)
+                  ENDDO
                 ELSE                   ! INFRARED DOMAIN ----------
 !                 2.3.3.ir Initialization
-                  epIRgrid(j,1,:,iaer)=0.
+                  qsqrefIRgrid(j,1,:,iaer)=0.
+                  qextIRgrid(j,1,:,iaer)=0.
+                  qscatIRgrid(j,1,:,iaer)=0.
                   omegIRgrid(j,1,:,iaer)=0.
                   gIRgrid(j,1,:,iaer)=0.
-                  eprefIRgrid(j,1,iaer)=0.
-!                 2.3.4.ir Log-normal distribution
-                  DO l=1,nsize(iaer,idomain)+1
-                    dfi_tmp(l) = log(radiusint(l)/r_g) / &
-                                sqrt(2.)/sigma_g
+                  qrefIRgrid(j,1,iaer)=0.
+                  qscatrefIRgrid(j,1,iaer)=0.
+                  omegrefIRgrid(j,1,iaer)=0.
+
+                  DO gausind=1,ngau
+                    DO m=1,L_NSPECTI
+!                     Convolution:
+                      qextIRgrid(j,1,m,iaer) =                  &
+                        qextIRgrid(j,1,m,iaer) +                &
+                        weightgaus(gausind) *                   &
+                        (                                       &
+                        qsqrefIRb(m,gausind,iaer) *             &
+                        qrefVISb(gausind,iaer) *                &
+                        pi*radGAUSb(gausind,iaer,idomain) *     &
+                        radGAUSb(gausind,iaer,idomain) *        &
+                        distb(j,1,iaer,idomain,gausind) +       &
+                        qsqrefIRa(m,gausind,iaer) *             &
+                        qrefVISa(gausind,iaer) *                &
+                        pi*radGAUSa(gausind,iaer,idomain) *     &
+                        radGAUSa(gausind,iaer,idomain) *        &
+                        dista(j,1,iaer,idomain,gausind)         &
+                        )
+                      qscatIRgrid(j,1,m,iaer) =                 &
+                        qscatIRgrid(j,1,m,iaer) +               &
+                        weightgaus(gausind) *                   &
+                        (                                       &
+                        omegIRb(m,gausind,iaer) *               &
+                        qsqrefIRb(m,gausind,iaer) *             &
+                        qrefVISb(gausind,iaer) *                &
+                        pi*radGAUSb(gausind,iaer,idomain) *     &
+                        radGAUSb(gausind,iaer,idomain) *        &
+                        distb(j,1,iaer,idomain,gausind) +       &
+                        omegIRa(m,gausind,iaer) *               &
+                        qsqrefIRa(m,gausind,iaer) *             &
+                        qrefVISa(gausind,iaer) *                &
+                        pi*radGAUSa(gausind,iaer,idomain) *     &
+                        radGAUSa(gausind,iaer,idomain) *        &
+                        dista(j,1,iaer,idomain,gausind)         &
+                        )
+                      gIRgrid(j,1,m,iaer) =                     &
+                        gIRgrid(j,1,m,iaer) +                   &
+                        weightgaus(gausind) *                   &
+                        (                                       &
+                        omegIRb(m,gausind,iaer) *               &
+                        qsqrefIRb(m,gausind,iaer) *             &
+                        qrefVISb(gausind,iaer) *                &
+                        gIRb(m,gausind,iaer) *                  &
+                        pi*radGAUSb(gausind,iaer,idomain) *     &
+                        radGAUSb(gausind,iaer,idomain) *        &
+                        distb(j,1,iaer,idomain,gausind) +       &
+                        omegIRa(m,gausind,iaer) *               &
+                        qsqrefIRa(m,gausind,iaer) *             &
+                        qrefVISa(gausind,iaer) *                &
+                        gIRa(m,gausind,iaer) *                  &
+                        pi*radGAUSa(gausind,iaer,idomain) *     &
+                        radGAUSa(gausind,iaer,idomain) *        &
+                        dista(j,1,iaer,idomain,gausind)         &
+                        )
+                    ENDDO
+                    qrefIRgrid(j,1,iaer) =                      &
+                      qrefIRgrid(j,1,iaer) +                    &
+                      weightgaus(gausind) *                     &
+                      (                                         &
+                      qrefIRb(gausind,iaer) *                   &
+                      pi*radGAUSb(gausind,iaer,idomain) *       &
+                      radGAUSb(gausind,iaer,idomain) *          &
+                      distb(j,1,iaer,idomain,gausind) +         &
+                      qrefIRa(gausind,iaer) *                   &
+                      pi*radGAUSa(gausind,iaer,idomain) *       &
+                      radGAUSa(gausind,iaer,idomain) *          &
+                      dista(j,1,iaer,idomain,gausind)           &
+                      )
+                    qscatrefIRgrid(j,1,iaer) =                  &
+                      qscatrefIRgrid(j,1,iaer) +                &
+                      weightgaus(gausind) *                     &
+                      (                                         &
+                      omegrefIRb(gausind,iaer) *                &
+                      qrefIRb(gausind,iaer) *                   &
+                      pi*radGAUSb(gausind,iaer,idomain) *       &
+                      radGAUSb(gausind,iaer,idomain) *          &
+                      distb(j,1,iaer,idomain,gausind) +         &
+                      omegrefIRa(gausind,iaer) *                &
+                      qrefIRa(gausind,iaer) *                   &
+                      pi*radGAUSa(gausind,iaer,idomain) *       &
+                      radGAUSa(gausind,iaer,idomain) *          &
+                      dista(j,1,iaer,idomain,gausind)           &
+                      )
                   ENDDO
-                  DO l=1,nsize(iaer,idomain)
-                    dfi = 0.5*( derf(dfi_tmp(l+1)) - &
-                               derf(dfi_tmp(l)) )
-                    DO m=1,L_NSPECTI
-                      epIRgrid(j,1,m,iaer) = &
-                               epIRgrid(j,1,m,iaer) &
-                               + QIRsQREF(m,iaer,l)*dfi
-                      omegIRgrid(j,1,m,iaer) = &
-                               omegIRgrid(j,1,m,iaer) &
-                               + omegaIR(m,iaer,l)*dfi
-                      gIRgrid(j,1,m,iaer) = &
-                               gIRgrid(j,1,m,iaer) &
-                               + gIR(m,iaer,l)*dfi
-                    ENDDO !L_NSPECTI
-                    eprefIRgrid(j,1,iaer) = &
-                               eprefIRgrid(j,1,iaer) &
-                               + QREFir(iaer,l)*dfi
-                  ENDDO !nsize
+ 
+                  qrefIRgrid(j,1,iaer)=qrefIRgrid(j,1,iaer) /          &
+                                normd(j,1,iaer,idomain)
+                  qscatrefIRgrid(j,1,iaer)=qscatrefIRgrid(j,1,iaer) /  &
+                                normd(j,1,iaer,idomain)
+                  omegrefIRgrid(j,1,iaer)=qscatrefIRgrid(j,1,iaer) /   &
+                               qrefIRgrid(j,1,iaer)
+                  DO m=1,L_NSPECTI
+                    qextIRgrid(j,1,m,iaer)=qextIRgrid(j,1,m,iaer) /    &
+                                normd(j,1,iaer,idomain)
+                    qscatIRgrid(j,1,m,iaer)=qscatIRgrid(j,1,m,iaer) /  &
+                                normd(j,1,iaer,idomain)
+                    gIRgrid(j,1,m,iaer)=gIRgrid(j,1,m,iaer) /          &
+                                qscatIRgrid(j,1,m,iaer) /              &
+                                normd(j,1,iaer,idomain)
+
+                    qsqrefIRgrid(j,1,m,iaer)=qextIRgrid(j,1,m,iaer) /  &
+                                qrefVISgrid(j,1,iaer)
+                    omegIRgrid(j,1,m,iaer)=qscatIRgrid(j,1,m,iaer) /   &
+                                qextIRgrid(j,1,m,iaer)
+                  ENDDO
                 ENDIF                  ! --------------------------
                 checkgrid(j,1,iaer,idomain) = .true.
@@ -307,53 +689,56 @@
           IF (idomain.EQ.1) THEN ! VISIBLE ------------------------
           DO m=1,L_NSPECTV
-            QVISsQREF3d(ig,lg,m,iaer) = &
-                       k1*epVISgrid(grid_i,1,m,iaer) + &
-                       k2*epVISgrid(grid_i+1,1,m,iaer)
-            omegaVIS3d(ig,lg,m,iaer) = &
-                       k1*omegVISgrid(grid_i,1,m,iaer) + &
-                       k2*omegVISgrid(grid_i+1,1,m,iaer)
-            gVIS3d(ig,lg,m,iaer) = &
-                       k1*gVISgrid(grid_i,1,m,iaer) + &
-                       k2*gVISgrid(grid_i+1,1,m,iaer)
+             QVISsQREF3d(ig,lg,m,iaer) =                           &
+                        k1*qsqrefVISgrid(grid_i,1,m,iaer) +        &
+                        k2*qsqrefVISgrid(grid_i+1,1,m,iaer)
+            omegaVIS3d(ig,lg,m,iaer) =                             &
+                        k1*omegVISgrid(grid_i,1,m,iaer) +          &
+                        k2*omegVISgrid(grid_i+1,1,m,iaer)
+            gVIS3d(ig,lg,m,iaer) =                                 &
+                        k1*gVISgrid(grid_i,1,m,iaer) +             &
+                        k2*gVISgrid(grid_i+1,1,m,iaer)
           ENDDO !L_NSPECTV
-          QREFvis3d(ig,lg,iaer) = &
-                       k1*eprefVISgrid(grid_i,1,iaer) + &
-                       k2*eprefVISgrid(grid_i+1,1,iaer)
+          QREFvis3d(ig,lg,iaer) =                                  &
+                        k1*qrefVISgrid(grid_i,1,iaer) +            &
+                        k2*qrefVISgrid(grid_i+1,1,iaer)
+          omegaREFvis3d(ig,lg,iaer) =                              &
+                        k1*omegrefVISgrid(grid_i,1,iaer) +         &
+                        k2*omegrefVISgrid(grid_i+1,1,iaer)
           ELSE                   ! INFRARED -----------------------
           DO m=1,L_NSPECTI
-            QIRsQREF3d(ig,lg,m,iaer) = &
-                       k1*epIRgrid(grid_i,1,m,iaer) + &
-                       k2*epIRgrid(grid_i+1,1,m,iaer)
-            omegaIR3d(ig,lg,m,iaer) = &
-                       k1*omegIRgrid(grid_i,1,m,iaer) + &
-                       k2*omegIRgrid(grid_i+1,1,m,iaer)
-            gIR3d(ig,lg,m,iaer) = &
-                       k1*gIRgrid(grid_i,1,m,iaer) + &
-                       k2*gIRgrid(grid_i+1,1,m,iaer)
+            QIRsQREF3d(ig,lg,m,iaer) =                             &
+                        k1*qsqrefIRgrid(grid_i,1,m,iaer) +         &
+                        k2*qsqrefIRgrid(grid_i+1,1,m,iaer)
+            omegaIR3d(ig,lg,m,iaer) =                              &
+                        k1*omegIRgrid(grid_i,1,m,iaer) +           &
+                        k2*omegIRgrid(grid_i+1,1,m,iaer) 
+            gIR3d(ig,lg,m,iaer) =                                  & 
+                        k1*gIRgrid(grid_i,1,m,iaer) +              &
+                        k2*gIRgrid(grid_i+1,1,m,iaer)
           ENDDO !L_NSPECTI
-          QREFir3d(ig,lg,iaer) = &
-                       k1*eprefIRgrid(grid_i,1,iaer) + &
-                       k2*eprefIRgrid(grid_i+1,1,iaer)
+          QREFir3d(ig,lg,iaer) =                                   &
+                        k1*qrefIRgrid(grid_i,1,iaer) +             &
+                        k2*qrefIRgrid(grid_i+1,1,iaer)
+          omegaREFir3d(ig,lg,iaer) =                               &
+                        k1*omegrefIRgrid(grid_i,1,iaer) +          &
+                        k2*omegrefIRgrid(grid_i+1,1,iaer)
           ENDIF                  ! --------------------------------
         ENDDO !nlayermx
       ENDDO !ngridmx
 
+!==================================================================
+
+
+
       ENDDO ! idomain
 
-
-        ENDIF ! nsize = 1
+      ENDIF ! nsize = 1
+
       ENDDO ! iaer (loop on aerosol kind)
 
-!      open(116,file='QIRsQREF3dO.dat')
-!      write(116,*) QIRsQREF3d
-!      close(116)
-!      open(117,file='omegaIR3dO.dat')
-!      write(117,*) omegaIR3d
-!      close(117)
-!      open(118,file='gIR3dO.dat')
-!      write(118,*) gIR3d
-!      close(118)
-!      stop
-
       RETURN
-    END subroutine aeroptproperties
+    END SUBROUTINE aeroptproperties
+
+
+
+      
Index: unk/LMDZ.GENERIC/libf/phystd/aeroptpropertiesJBnew.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/aeroptpropertiesJBnew.F90	(revision 252)
+++ 	(revision )
@@ -1,729 +1,0 @@
-      SUBROUTINE aeroptpropertiesJBnew(ngrid,nlayer,reffrad,nueffrad,   &
-                                  QVISsQREF3d,omegaVIS3d,gVIS3d,   &
-                                  QIRsQREF3d,omegaIR3d,gIR3d,      &
-                                  QREFvis3d,QREFir3d)!,		   &
-!                                  omegaREFvis3d,omegaREFir3d)
-
-      use radinc_h,    only: L_NSPECTI,L_NSPECTV,naerkind,nsizemax
-      use radcommon_h, only: QVISsQREF,omegavis,gvis,QIRsQREF,omegair,gir
-      use radcommon_h, only: qrefvis,qrefir,omegarefvis,omegarefir
-      use radcommon_h, only: radiustab,nsize
-
-      implicit none
-
-!     =============================================================
-!     Aerosol Optical Properties
-!
-!     Description:
-!       Compute the scattering parameters in each grid
-!       box, depending on aerosol grain sizes. Log-normal size
-!       distribution and Gauss-Legendre integration are used.
-
-!     Parameters:
-!       Don't forget to set the value of varyingnueff below; If
-!       the effective variance of the distribution for the given
-!       aerosol is considered homogeneous in the atmosphere, please
-!       set varyingnueff(iaer) to .false. Resulting computational
-!       time will be much better.
-
-!     Authors: J.-B. Madeleine, F. Forget, F. Montmessin
-!     Slightly modified and converted to F90 by R. Wordsworth (2009)
-!     Varying nueff section removed by R. Wordsworth for simplicity
-!     ==============================================================
-
-#include "dimensions.h"
-#include "dimphys.h"
-#include "callkeys.h"
-
-!     Local variables 
-!     ---------------
-
-
-
-!     =============================================================
-      LOGICAL, PARAMETER :: varyingnueff(naerkind) = .false.
-!     =============================================================
-
-!     Min. and max radius of the interpolation grid (in METERS)
-      REAL, PARAMETER :: refftabmin = 2e-8 !2e-8
-!      REAL, PARAMETER :: refftabmax = 35e-6
-      REAL, PARAMETER :: refftabmax = 1e-3
-!     Log of the min and max variance of the interpolation grid
-      REAL, PARAMETER :: nuefftabmin = -4.6
-      REAL, PARAMETER :: nuefftabmax = 0.
-!     Number of effective radius of the interpolation grid
-      INTEGER, PARAMETER :: refftabsize = 200
-!     Number of effective variances of the interpolation grid
-!      INTEGER, PARAMETER :: nuefftabsize = 100
-      INTEGER, PARAMETER :: nuefftabsize = 1
-!     Interpolation grid indices (reff,nueff)
-      INTEGER :: grid_i,grid_j
-!     Intermediate variable
-      REAL :: var_tmp,var3d_tmp(ngridmx,nlayermx)
-!     Bilinear interpolation factors
-      REAL :: kx,ky,k1,k2,k3,k4
-!     Size distribution parameters
-      REAL :: sizedistk1,sizedistk2
-!     Pi!
-      REAL,SAVE :: pi
-!     Variables used by the Gauss-Legendre integration:
-      INTEGER radius_id,gausind
-      REAL kint
-      REAL drad
-      REAL weightgaus(5),radgaus(5)
-      SAVE weightgaus,radgaus
-      DATA weightgaus/.2955242247,.2692667193,.2190863625,.1494513491,.0666713443/
-      DATA radgaus/.1488743389,.4333953941,.6794095682,.8650633666,.9739065285/
-
-!     Indices
-      INTEGER :: i,j,k,l,m,iaer,idomain
-      INTEGER :: ig,lg,chg
-
-!     Local saved variables
-!     ---------------------
-
-!     Radius axis of the interpolation grid
-      REAL,SAVE :: refftab(refftabsize)
-!     Variance axis of the interpolation grid
-      REAL,SAVE :: nuefftab(nuefftabsize)
-!     Volume ratio of the grid
-      REAL,SAVE :: logvratgrid,vratgrid
-!     Grid used to remember which calculation is done
-      LOGICAL,SAVE :: checkgrid(refftabsize,nuefftabsize,naerkind,2) = .false.
-!     Optical properties of the grid (VISIBLE)
-      REAL,SAVE :: qsqrefVISgrid(refftabsize,nuefftabsize,L_NSPECTV,naerkind)
-      REAL,SAVE :: qextVISgrid(refftabsize,nuefftabsize,L_NSPECTV,naerkind)
-      REAL,SAVE :: qscatVISgrid(refftabsize,nuefftabsize,L_NSPECTV,naerkind)
-      REAL,SAVE :: omegVISgrid(refftabsize,nuefftabsize,L_NSPECTV,naerkind)
-      REAL,SAVE :: gVISgrid(refftabsize,nuefftabsize,L_NSPECTV,naerkind)
-!     Optical properties of the grid (INFRARED)
-      REAL,SAVE :: qsqrefIRgrid(refftabsize,nuefftabsize,L_NSPECTI,naerkind)
-      REAL,SAVE :: qextIRgrid(refftabsize,nuefftabsize,L_NSPECTI,naerkind)
-      REAL,SAVE :: qscatIRgrid(refftabsize,nuefftabsize,L_NSPECTI,naerkind)
-      REAL,SAVE :: omegIRgrid(refftabsize,nuefftabsize,L_NSPECTI,naerkind)
-      REAL,SAVE :: gIRgrid(refftabsize,nuefftabsize,L_NSPECTI,naerkind)
-!     Optical properties of the grid (REFERENCE WAVELENGTHS)
-      REAL,SAVE :: qrefVISgrid(refftabsize,nuefftabsize,naerkind)
-      REAL,SAVE :: qscatrefVISgrid(refftabsize,nuefftabsize,naerkind)
-      REAL,SAVE :: qrefIRgrid(refftabsize,nuefftabsize,naerkind)
-      REAL,SAVE :: qscatrefIRgrid(refftabsize,nuefftabsize,naerkind)
-      REAL,SAVE :: omegrefVISgrid(refftabsize,nuefftabsize,naerkind)
-      REAL,SAVE :: omegrefIRgrid(refftabsize,nuefftabsize,naerkind)
-!     Firstcall
-      LOGICAL,SAVE :: firstcall = .true.
-!     Variables used by the Gauss-Legendre integration:
-      REAL,SAVE :: normd(refftabsize,nuefftabsize,naerkind,2)
-      REAL,SAVE :: dista(refftabsize,nuefftabsize,naerkind,2,5)
-      REAL,SAVE :: distb(refftabsize,nuefftabsize,naerkind,2,5)
-
-      REAL,SAVE :: radGAUSa(5,naerkind,2)
-      REAL,SAVE :: radGAUSb(5,naerkind,2)
-
-      REAL,SAVE :: qsqrefVISa(L_NSPECTV,5,naerkind)
-      REAL,SAVE :: qrefVISa(5,naerkind)
-      REAL,SAVE :: qsqrefVISb(L_NSPECTV,5,naerkind)
-      REAL,SAVE :: qrefVISb(5,naerkind)
-      REAL,SAVE :: omegVISa(L_NSPECTV,5,naerkind)
-      REAL,SAVE :: omegrefVISa(5,naerkind)
-      REAL,SAVE :: omegVISb(L_NSPECTV,5,naerkind)
-      REAL,SAVE :: omegrefVISb(5,naerkind)
-      REAL,SAVE :: gVISa(L_NSPECTV,5,naerkind)
-      REAL,SAVE :: gVISb(L_NSPECTV,5,naerkind)
-
-      REAL,SAVE :: qsqrefIRa(L_NSPECTI,5,naerkind)
-      REAL,SAVE :: qrefIRa(5,naerkind)
-      REAL,SAVE :: qsqrefIRb(L_NSPECTI,5,naerkind)
-      REAL,SAVE :: qrefIRb(5,naerkind)
-      REAL,SAVE :: omegIRa(L_NSPECTI,5,naerkind)
-      REAL,SAVE :: omegrefIRa(5,naerkind)
-      REAL,SAVE :: omegIRb(L_NSPECTI,5,naerkind)
-      REAL,SAVE :: omegrefIRb(5,naerkind)
-      REAL,SAVE :: gIRa(L_NSPECTI,5,naerkind)
-      REAL,SAVE :: gIRb(L_NSPECTI,5,naerkind)
-
-      REAL :: radiusm
-      REAL :: radiusr
-
-!     Inputs
-!     ------
-
-      INTEGER :: ngrid,nlayer
-!     Aerosol effective radius used for radiative transfer (meter)
-      REAL :: reffrad(ngridmx,nlayermx,naerkind)
-!     Aerosol effective variance used for radiative transfer (n.u.)
-      REAL :: nueffrad(ngridmx,nlayermx,naerkind)
-
-!     Outputs
-!     -------
-
-      REAL :: QVISsQREF3d(ngridmx,nlayermx,L_NSPECTV,naerkind)
-      REAL :: omegaVIS3d(ngridmx,nlayermx,L_NSPECTV,naerkind)
-      REAL :: gVIS3d(ngridmx,nlayermx,L_NSPECTV,naerkind)
-
-      REAL :: QIRsQREF3d(ngridmx,nlayermx,L_NSPECTI,naerkind)
-      REAL :: omegaIR3d(ngridmx,nlayermx,L_NSPECTI,naerkind)
-      REAL :: gIR3d(ngridmx,nlayermx,L_NSPECTI,naerkind)
-
-      REAL :: QREFvis3d(ngridmx,nlayermx,naerkind)
-      REAL :: QREFir3d(ngridmx,nlayermx,naerkind)
-
-      REAL :: omegaREFvis3d(ngridmx,nlayermx,naerkind)
-      REAL :: omegaREFir3d(ngridmx,nlayermx,naerkind)
-
-      DO iaer = 1, naerkind ! Loop on aerosol kind
-        IF ( (nsize(iaer,1).EQ.1).AND.(nsize(iaer,2).EQ.1) ) THEN
-!        IF (1.eq.1) THEN
-
-!==================================================================
-!       If there is one single particle size, optical
-!         properties of the considered aerosol are homogeneous
-          DO lg = 1, nlayer
-            DO ig = 1, ngrid
-              DO chg = 1, L_NSPECTV
-                QVISsQREF3d(ig,lg,chg,iaer)=QVISsQREF(chg,iaer,1)
-                omegaVIS3d(ig,lg,chg,iaer)=omegaVIS(chg,iaer,1)
-                gVIS3d(ig,lg,chg,iaer)=gVIS(chg,iaer,1)
-              ENDDO
-              DO chg = 1, L_NSPECTI
-                QIRsQREF3d(ig,lg,chg,iaer)=QIRsQREF(chg,iaer,1)
-                omegaIR3d(ig,lg,chg,iaer)=omegaIR(chg,iaer,1)
-                gIR3d(ig,lg,chg,iaer)=gIR(chg,iaer,1)
-              ENDDO
-              QREFvis3d(ig,lg,iaer)=QREFvis(iaer,1)
-              QREFir3d(ig,lg,iaer)=QREFir(iaer,1)
-              omegaREFvis3d(ig,lg,iaer)=omegaREFvis(iaer,1)
-              omegaREFir3d(ig,lg,iaer)=omegaREFir(iaer,1)
-            ENDDO
-          ENDDO
-
-
-          if (firstcall) then
-             print*,'Optical properties of the aerosol are homogenous for:'
-             print*,'iaer = ',iaer
-          endif
-
-        ELSE ! Varying effective radius and variance
-      DO idomain = 1, 2 ! Loop on visible or infrared channel
-!==================================================================
-!     1. Creating the effective radius and variance grid
-!     --------------------------------------------------
-      IF (firstcall) THEN
-
-!       1.1 Pi!
-        pi = 2. * asin(1.e0)
-
-!       1.2 Effective radius
-        refftab(1)    = refftabmin
-        refftab(refftabsize) = refftabmax
-
-        logvratgrid = log(refftabmax/refftabmin) / float(refftabsize-1)*3.
-        vratgrid = exp(logvratgrid)
-
-        do i = 2, refftabsize-1
-          refftab(i) = refftab(i-1)*vratgrid**(1./3.)
-        enddo
-
-!       1.3 Effective variance
-        do i = 0, nuefftabsize-1
-          nuefftab(i+1) = exp( nuefftabmin + i*(nuefftabmax-nuefftabmin)/(nuefftabsize-1) )
-        enddo
-        firstcall = .false.
-      ENDIF
-
-!       1.4 Radius middle point and range for Gauss integration
-        radiusm=0.5*(radiustab(iaer,idomain,nsize(iaer,idomain)) + radiustab(iaer,idomain,1))
-        radiusr=0.5*(radiustab(iaer,idomain,nsize(iaer,idomain)) - radiustab(iaer,idomain,1))
-
-!       1.5 Interpolating data at the Gauss quadrature points:
-        DO gausind=1,5
-          drad=radiusr*radgaus(gausind)
-          radGAUSa(gausind,iaer,idomain)=radiusm-drad
-
-          radius_id=minloc(abs(radiustab(iaer,idomain,:) - (radiusm-drad)),DIM=1)
-          IF ((radiustab(iaer,idomain,radius_id) - (radiusm-drad)).GT.0) THEN
-            radius_id=radius_id-1
-          ENDIF
-          IF (radius_id.GE.nsize(iaer,idomain)) THEN
-            radius_id=nsize(iaer,idomain)-1
-            kint = 1.
-          ELSEIF (radius_id.LT.1) THEN
-            radius_id=1
-            kint = 0.
-          ELSE
-          kint = ( (radiusm-drad) -				&
-                   radiustab(iaer,idomain,radius_id) ) /	&
-                 ( radiustab(iaer,idomain,radius_id+1) -	&
-                   radiustab(iaer,idomain,radius_id) )
-          ENDIF
-          IF (idomain.EQ.1) THEN ! VISIBLE DOMAIN -----------------
-            DO m=1,L_NSPECTV
-               qsqrefVISa(m,gausind,iaer)=                      &
-                    (1-kint)*QVISsQREF(m,iaer,radius_id) +      &
-                    kint*QVISsQREF(m,iaer,radius_id+1)
-            omegVISa(m,gausind,iaer)=                           &
-                    (1-kint)*omegaVIS(m,iaer,radius_id) +       &
-                    kint*omegaVIS(m,iaer,radius_id+1)
-            gVISa(m,gausind,iaer)=                              &
-                    (1-kint)*gVIS(m,iaer,radius_id) +           &
-                    kint*gVIS(m,iaer,radius_id+1)
-            ENDDO
-            qrefVISa(gausind,iaer)=                             &
-                    (1-kint)*QREFvis(iaer,radius_id) +          &
-                    kint*QREFvis(iaer,radius_id+1)
-            omegrefVISa(gausind,iaer)=                          &
-                    (1-kint)*omegaREFvis(iaer,radius_id) +      &
-                    kint*omegaREFvis(iaer,radius_id+1)
-          ELSE ! INFRARED DOMAIN ----------------------------------
-            DO m=1,L_NSPECTI
-            qsqrefIRa(m,gausind,iaer)=                          &
-                    (1-kint)*QIRsQREF(m,iaer,radius_id) +       &
-                    kint*QIRsQREF(m,iaer,radius_id+1)
-            omegIRa(m,gausind,iaer)=                            &
-                    (1-kint)*omegaIR(m,iaer,radius_id) +        &
-                    kint*omegaIR(m,iaer,radius_id+1)
-            gIRa(m,gausind,iaer)=                               &
-                    (1-kint)*gIR(m,iaer,radius_id) +            &
-                    kint*gIR(m,iaer,radius_id+1)
-            ENDDO
-            qrefIRa(gausind,iaer)=                              &
-                    (1-kint)*QREFir(iaer,radius_id) +           &
-                    kint*QREFir(iaer,radius_id+1)
-            omegrefIRa(gausind,iaer)=                           &
-                    (1-kint)*omegaREFir(iaer,radius_id) +       &
-                    kint*omegaREFir(iaer,radius_id+1)
-          ENDIF
-        ENDDO
-
-        DO gausind=1,5
-          drad=radiusr*radgaus(gausind)
-          radGAUSb(gausind,iaer,idomain)=radiusm+drad
-
-          radius_id=minloc(abs(radiustab(iaer,idomain,:) -      &
-                               (radiusm+drad)),DIM=1)
-          IF ((radiustab(iaer,idomain,radius_id) -              &
-               (radiusm+drad)).GT.0) THEN
-            radius_id=radius_id-1
-          ENDIF
-          IF (radius_id.GE.nsize(iaer,idomain)) THEN
-            radius_id=nsize(iaer,idomain)-1
-            kint = 1.
-          ELSEIF (radius_id.LT.1) THEN
-            radius_id=1
-            kint = 0.
-          ELSE
-            kint = ( (radiusm+drad) -                           &
-                     radiustab(iaer,idomain,radius_id) ) /      &
-                   ( radiustab(iaer,idomain,radius_id+1) -      &
-                     radiustab(iaer,idomain,radius_id) )
-          ENDIF
-          IF (idomain.EQ.1) THEN ! VISIBLE DOMAIN -----------------
-            DO m=1,L_NSPECTV
-            qsqrefVISb(m,gausind,iaer)=                         &
-                    (1-kint)*QVISsQREF(m,iaer,radius_id) +      &
-                    kint*QVISsQREF(m,iaer,radius_id+1)    
-            omegVISb(m,gausind,iaer)=                           &
-                    (1-kint)*omegaVIS(m,iaer,radius_id) +       &
-                    kint*omegaVIS(m,iaer,radius_id+1)
-            gVISb(m,gausind,iaer)=                              &
-                    (1-kint)*gVIS(m,iaer,radius_id) +           &
-                    kint*gVIS(m,iaer,radius_id+1)
-            ENDDO
-            qrefVISb(gausind,iaer)=                             &
-                    (1-kint)*QREFvis(iaer,radius_id) +          &
-                    kint*QREFvis(iaer,radius_id+1)
-            omegrefVISb(gausind,iaer)=                          &
-                    (1-kint)*omegaREFvis(iaer,radius_id) +      &
-                    kint*omegaREFvis(iaer,radius_id+1)
-          ELSE ! INFRARED DOMAIN ----------------------------------
-            DO m=1,L_NSPECTI
-            qsqrefIRb(m,gausind,iaer)=                          &
-                    (1-kint)*QIRsQREF(m,iaer,radius_id) +       &
-                    kint*QIRsQREF(m,iaer,radius_id+1)
-            omegIRb(m,gausind,iaer)=                            &
-                    (1-kint)*omegaIR(m,iaer,radius_id) +        &
-                    kint*omegaIR(m,iaer,radius_id+1)
-            gIRb(m,gausind,iaer)=                               &
-                    (1-kint)*gIR(m,iaer,radius_id) +            &
-                    kint*gIR(m,iaer,radius_id+1)
-            ENDDO
-            qrefIRb(gausind,iaer)=                              &
-                    (1-kint)*QREFir(iaer,radius_id) +           &
-                    kint*QREFir(iaer,radius_id+1)
-            omegrefIRb(gausind,iaer)=                           &
-                    (1-kint)*omegaREFir(iaer,radius_id) +       &
-                    kint*omegaREFir(iaer,radius_id+1)
-          ENDIF
-        ENDDO
-
-!==================================================================
-! CONSTANT NUEFF FROM HERE
-!==================================================================
-
-!     2. Compute the scattering parameters using linear
-!       interpolation over grain sizes and constant nueff
-!     ---------------------------------------------------
-
-      DO lg = 1,nlayer
-        DO ig = 1,ngrid
-!         2.1 Effective radius index and kx calculation
-          var_tmp=reffrad(ig,lg,iaer)/refftabmin
-          var_tmp=log(var_tmp)*3.
-          var_tmp=var_tmp/logvratgrid+1.
-          grid_i=floor(var_tmp)
-          IF (grid_i.GE.refftabsize) THEN
-!           WRITE(*,*) 'Warning: particle size in grid box #'
-!           WRITE(*,*) ig,' is too large to be used by the '
-!           WRITE(*,*) 'radiative transfer; please extend the '
-!           WRITE(*,*) 'interpolation grid to larger grain sizes.'
-            grid_i=refftabsize-1
-            kx = 1.
-          ELSEIF (grid_i.LT.1) THEN
-!           WRITE(*,*) 'Warning: particle size in grid box #'
-!           WRITE(*,*) ig,' is too small to be used by the '
-!           WRITE(*,*) 'radiative transfer; please extend the '
-!           WRITE(*,*) 'interpolation grid to smaller grain sizes.'
-            grid_i=1
-            kx = 0.
-          ELSE
-            kx = ( reffrad(ig,lg,iaer)-refftab(grid_i) ) /            &
-                 ( refftab(grid_i+1)-refftab(grid_i) )
-          ENDIF
-!         2.3 Integration
-          DO j=grid_i,grid_i+1
-!             2.3.1 Check if the calculation has been done
-              IF (.NOT.checkgrid(j,1,iaer,idomain)) THEN
-!               2.3.2 Log-normal dist., r_g and sigma_g are defined
-!                 in [hansen_1974], "Light scattering in planetary
-!                 atmospheres", Space Science Reviews 16 527-610.
-!                 Here, sizedistk1=r_g and sizedistk2=sigma_g^2
-                sizedistk2 = log(1.+nueffrad(1,1,iaer))
-                sizedistk1 = exp(2.5*sizedistk2)
-                sizedistk1 = refftab(j) / sizedistk1
-
-                normd(j,1,iaer,idomain) = 1e-30
-                DO gausind=1,5
-                  drad=radiusr*radgaus(gausind)
-                  dista(j,1,iaer,idomain,gausind) = LOG((radiusm-drad)/sizedistk1)
-                  dista(j,1,iaer,idomain,gausind) =                   &
-                    EXP(-dista(j,1,iaer,idomain,gausind) *            &
-                    dista(j,1,iaer,idomain,gausind) *                 &
-                    0.5e0/sizedistk2)/(radiusm-drad)                  
-                  dista(j,1,iaer,idomain,gausind) =                   &
-                    dista(j,1,iaer,idomain,gausind) /                 &
-                    (sqrt(2e0*pi*sizedistk2))
-
-                  distb(j,1,iaer,idomain,gausind) = LOG((radiusm+drad)/sizedistk1)
-                  distb(j,1,iaer,idomain,gausind) =                   &
-                    EXP(-distb(j,1,iaer,idomain,gausind) *            &
-                    distb(j,1,iaer,idomain,gausind) *                 &
-                    0.5e0/sizedistk2)/(radiusm+drad)
-                  distb(j,1,iaer,idomain,gausind) =                   &
-                    distb(j,1,iaer,idomain,gausind) /                 &
-                    (sqrt(2e0*pi*sizedistk2))
-
-                  normd(j,1,iaer,idomain)=normd(j,1,iaer,idomain) +   &
-                    weightgaus(gausind) *                             &
-                    (                                                 &
-                    distb(j,1,iaer,idomain,gausind) * pi *            &
-                    radGAUSb(gausind,iaer,idomain) *                  &
-                    radGAUSb(gausind,iaer,idomain) +                  &
-                    dista(j,1,iaer,idomain,gausind) * pi *            &
-                    radGAUSa(gausind,iaer,idomain) *                  &
-                    radGAUSa(gausind,iaer,idomain)                    &
-                    )
-                ENDDO
-                IF (idomain.EQ.1) THEN ! VISIBLE DOMAIN -----------
-!                 2.3.3.vis Initialization
-                  qsqrefVISgrid(j,1,:,iaer)=0.
-                  qextVISgrid(j,1,:,iaer)=0.
-                  qscatVISgrid(j,1,:,iaer)=0.
-                  omegVISgrid(j,1,:,iaer)=0.
-                  gVISgrid(j,1,:,iaer)=0.
-                  qrefVISgrid(j,1,iaer)=0.
-                  qscatrefVISgrid(j,1,iaer)=0.
-                  omegrefVISgrid(j,1,iaer)=0.
-
-                  DO gausind=1,5
-                    DO m=1,L_NSPECTV
-!                     Convolution:
-                      qextVISgrid(j,1,m,iaer) =              &
-                        qextVISgrid(j,1,m,iaer) +            & 
-                        weightgaus(gausind) *                &
-                        (                                    &
-                        qsqrefVISb(m,gausind,iaer) *         &
-                        qrefVISb(gausind,iaer) *             &
-                        pi*radGAUSb(gausind,iaer,idomain) *  &
-                        radGAUSb(gausind,iaer,idomain) *     &
-                        distb(j,1,iaer,idomain,gausind) +    &
-                        qsqrefVISa(m,gausind,iaer) *         &
-                        qrefVISa(gausind,iaer) *             &
-                        pi*radGAUSa(gausind,iaer,idomain) *  &
-                        radGAUSa(gausind,iaer,idomain) *     &
-                        dista(j,1,iaer,idomain,gausind)      &
-                        )
-                      qscatVISgrid(j,1,m,iaer) =             &
-                        qscatVISgrid(j,1,m,iaer) +           &
-                        weightgaus(gausind) *                &
-                        (                                    &
-                        omegVISb(m,gausind,iaer) *           &
-                        qsqrefVISb(m,gausind,iaer) *         &
-                        qrefVISb(gausind,iaer) *             &
-                        pi*radGAUSb(gausind,iaer,idomain) *  &
-                        radGAUSb(gausind,iaer,idomain) *     &
-                        distb(j,1,iaer,idomain,gausind) +    &
-                        omegVISa(m,gausind,iaer) *           &
-                        qsqrefVISa(m,gausind,iaer) *         &
-                        qrefVISa(gausind,iaer) *             &
-                        pi*radGAUSa(gausind,iaer,idomain) *  &
-                        radGAUSa(gausind,iaer,idomain) *     &
-                        dista(j,1,iaer,idomain,gausind)      &
-                        )
-                      gVISgrid(j,1,m,iaer) =                 &
-                        gVISgrid(j,1,m,iaer) +               &
-                        weightgaus(gausind) *                &
-                        (                                    &
-                        omegVISb(m,gausind,iaer) *           &
-                        qsqrefVISb(m,gausind,iaer) *         &
-                        qrefVISb(gausind,iaer) *             &
-                        gVISb(m,gausind,iaer) *              &
-                        pi*radGAUSb(gausind,iaer,idomain) *  &
-                        radGAUSb(gausind,iaer,idomain) *     &
-                        distb(j,1,iaer,idomain,gausind) +    &
-                        omegVISa(m,gausind,iaer) *           &
-                        qsqrefVISa(m,gausind,iaer) *         &
-                        qrefVISa(gausind,iaer) *             &
-                        gVISa(m,gausind,iaer) *              &
-                        pi*radGAUSa(gausind,iaer,idomain) *  &
-                        radGAUSa(gausind,iaer,idomain) *     &
-                        dista(j,1,iaer,idomain,gausind)      &
-                        )
-                    ENDDO
-                    qrefVISgrid(j,1,iaer) =                  &
-                      qrefVISgrid(j,1,iaer) +                &
-                      weightgaus(gausind) *                  &
-                      (                                      &
-                      qrefVISb(gausind,iaer) *               &
-                      pi*radGAUSb(gausind,iaer,idomain) *    &
-                      radGAUSb(gausind,iaer,idomain) *       &
-                      distb(j,1,iaer,idomain,gausind) +      &
-                      qrefVISa(gausind,iaer) *               &
-                      pi*radGAUSa(gausind,iaer,idomain) *    &
-                      radGAUSa(gausind,iaer,idomain) *       &
-                      dista(j,1,iaer,idomain,gausind)        &
-                      )
-                    qscatrefVISgrid(j,1,iaer) =              &
-                      qscatrefVISgrid(j,1,iaer) +            &
-                      weightgaus(gausind) *                  &
-                      (                                      &
-                      omegrefVISb(gausind,iaer) *            &
-                      qrefVISb(gausind,iaer) *               & 
-                      pi*radGAUSb(gausind,iaer,idomain) *    &
-                      radGAUSb(gausind,iaer,idomain) *       &
-                      distb(j,1,iaer,idomain,gausind) +      &
-                      omegrefVISa(gausind,iaer) *            &
-                      qrefVISa(gausind,iaer) *               &
-                      pi*radGAUSa(gausind,iaer,idomain) *    &
-                      radGAUSa(gausind,iaer,idomain) *       &
-                      dista(j,1,iaer,idomain,gausind)        &
-                      )
-                  ENDDO
-
-                  qrefVISgrid(j,1,iaer)=qrefVISgrid(j,1,iaer) /          &
-                                normd(j,1,iaer,idomain)       
-                  qscatrefVISgrid(j,1,iaer)=qscatrefVISgrid(j,1,iaer) /  &
-                                normd(j,1,iaer,idomain)
-                  omegrefVISgrid(j,1,iaer)=qscatrefVISgrid(j,1,iaer) /   &
-                               qrefVISgrid(j,1,iaer)
-                  DO m=1,L_NSPECTV
-                    qextVISgrid(j,1,m,iaer)=qextVISgrid(j,1,m,iaer) /    &
-                                normd(j,1,iaer,idomain)
-                    qscatVISgrid(j,1,m,iaer)=qscatVISgrid(j,1,m,iaer) /  &
-                                normd(j,1,iaer,idomain)
-                    gVISgrid(j,1,m,iaer)=gVISgrid(j,1,m,iaer) /          &
-                                qscatVISgrid(j,1,m,iaer) /               &
-                                normd(j,1,iaer,idomain)
-
-                    qsqrefVISgrid(j,1,m,iaer)=qextVISgrid(j,1,m,iaer) /  &
-                                qrefVISgrid(j,1,iaer)
-                    omegVISgrid(j,1,m,iaer)=qscatVISgrid(j,1,m,iaer) /   &
-                                qextVISgrid(j,1,m,iaer)
-                  ENDDO
-                ELSE                   ! INFRARED DOMAIN ----------
-!                 2.3.3.ir Initialization
-                  qsqrefIRgrid(j,1,:,iaer)=0.
-                  qextIRgrid(j,1,:,iaer)=0.
-                  qscatIRgrid(j,1,:,iaer)=0.
-                  omegIRgrid(j,1,:,iaer)=0.
-                  gIRgrid(j,1,:,iaer)=0.
-                  qrefIRgrid(j,1,iaer)=0.
-                  qscatrefIRgrid(j,1,iaer)=0.
-                  omegrefIRgrid(j,1,iaer)=0.
-
-                  DO gausind=1,5
-                    DO m=1,L_NSPECTI
-!                     Convolution:
-                      qextIRgrid(j,1,m,iaer) =                  &
-                        qextIRgrid(j,1,m,iaer) +                &
-                        weightgaus(gausind) *                   &
-                        (                                       &
-                        qsqrefIRb(m,gausind,iaer) *             &
-                        qrefVISb(gausind,iaer) *                &
-                        pi*radGAUSb(gausind,iaer,idomain) *     &
-                        radGAUSb(gausind,iaer,idomain) *        &
-                        distb(j,1,iaer,idomain,gausind) +       &
-                        qsqrefIRa(m,gausind,iaer) *             &
-                        qrefVISa(gausind,iaer) *                &
-                        pi*radGAUSa(gausind,iaer,idomain) *     &
-                        radGAUSa(gausind,iaer,idomain) *        &
-                        dista(j,1,iaer,idomain,gausind)         &
-                        )
-                      qscatIRgrid(j,1,m,iaer) =                 &
-                        qscatIRgrid(j,1,m,iaer) +               &
-                        weightgaus(gausind) *                   &
-                        (                                       &
-                        omegIRb(m,gausind,iaer) *               &
-                        qsqrefIRb(m,gausind,iaer) *             &
-                        qrefVISb(gausind,iaer) *                &
-                        pi*radGAUSb(gausind,iaer,idomain) *     &
-                        radGAUSb(gausind,iaer,idomain) *        &
-                        distb(j,1,iaer,idomain,gausind) +       &
-                        omegIRa(m,gausind,iaer) *               &
-                        qsqrefIRa(m,gausind,iaer) *             &
-                        qrefVISa(gausind,iaer) *                &
-                        pi*radGAUSa(gausind,iaer,idomain) *     &
-                        radGAUSa(gausind,iaer,idomain) *        &
-                        dista(j,1,iaer,idomain,gausind)         &
-                        )
-                      gIRgrid(j,1,m,iaer) =                     &
-                        gIRgrid(j,1,m,iaer) +                   &
-                        weightgaus(gausind) *                   &
-                        (                                       &
-                        omegIRb(m,gausind,iaer) *               &
-                        qsqrefIRb(m,gausind,iaer) *             &
-                        qrefVISb(gausind,iaer) *                &
-                        gIRb(m,gausind,iaer) *                  &
-                        pi*radGAUSb(gausind,iaer,idomain) *     &
-                        radGAUSb(gausind,iaer,idomain) *        &
-                        distb(j,1,iaer,idomain,gausind) +       &
-                        omegIRa(m,gausind,iaer) *               &
-                        qsqrefIRa(m,gausind,iaer) *             &
-                        qrefVISa(gausind,iaer) *                &
-                        gIRa(m,gausind,iaer) *                  &
-                        pi*radGAUSa(gausind,iaer,idomain) *     &
-                        radGAUSa(gausind,iaer,idomain) *        &
-                        dista(j,1,iaer,idomain,gausind)         &
-                        )
-                    ENDDO
-                    qrefIRgrid(j,1,iaer) =                      &
-                      qrefIRgrid(j,1,iaer) +                    &
-                      weightgaus(gausind) *                     &
-                      (                                         &
-                      qrefIRb(gausind,iaer) *                   &
-                      pi*radGAUSb(gausind,iaer,idomain) *       &
-                      radGAUSb(gausind,iaer,idomain) *          &
-                      distb(j,1,iaer,idomain,gausind) +         &
-                      qrefIRa(gausind,iaer) *                   &
-                      pi*radGAUSa(gausind,iaer,idomain) *       &
-                      radGAUSa(gausind,iaer,idomain) *          &
-                      dista(j,1,iaer,idomain,gausind)           &
-                      )
-                    qscatrefIRgrid(j,1,iaer) =                  &
-                      qscatrefIRgrid(j,1,iaer) +                &
-                      weightgaus(gausind) *                     &
-                      (                                         &
-                      omegrefIRb(gausind,iaer) *                &
-                      qrefIRb(gausind,iaer) *                   &
-                      pi*radGAUSb(gausind,iaer,idomain) *       &
-                      radGAUSb(gausind,iaer,idomain) *          &
-                      distb(j,1,iaer,idomain,gausind) +         &
-                      omegrefIRa(gausind,iaer) *                &
-                      qrefIRa(gausind,iaer) *                   &
-                      pi*radGAUSa(gausind,iaer,idomain) *       &
-                      radGAUSa(gausind,iaer,idomain) *          &
-                      dista(j,1,iaer,idomain,gausind)           &
-                      )
-                  ENDDO
- 
-                  qrefIRgrid(j,1,iaer)=qrefIRgrid(j,1,iaer) /          &
-                                normd(j,1,iaer,idomain)
-                  qscatrefIRgrid(j,1,iaer)=qscatrefIRgrid(j,1,iaer) /  &
-                                normd(j,1,iaer,idomain)
-                  omegrefIRgrid(j,1,iaer)=qscatrefIRgrid(j,1,iaer) /   &
-                               qrefIRgrid(j,1,iaer)
-                  DO m=1,L_NSPECTI
-                    qextIRgrid(j,1,m,iaer)=qextIRgrid(j,1,m,iaer) /    &
-                                normd(j,1,iaer,idomain)
-                    qscatIRgrid(j,1,m,iaer)=qscatIRgrid(j,1,m,iaer) /  &
-                                normd(j,1,iaer,idomain)
-                    gIRgrid(j,1,m,iaer)=gIRgrid(j,1,m,iaer) /          &
-                                qscatIRgrid(j,1,m,iaer) /              &
-                                normd(j,1,iaer,idomain)
-
-                    qsqrefIRgrid(j,1,m,iaer)=qextIRgrid(j,1,m,iaer) /  &
-                                qrefVISgrid(j,1,iaer)
-                    omegIRgrid(j,1,m,iaer)=qscatIRgrid(j,1,m,iaer) /   &
-                                qextIRgrid(j,1,m,iaer)
-                  ENDDO
-                ENDIF                  ! --------------------------
-                checkgrid(j,1,iaer,idomain) = .true.
-              ENDIF !checkgrid
-          ENDDO !grid_i
-!         2.4 Linear interpolation
-          k1 = (1-kx)
-          k2 = kx
-          IF (idomain.EQ.1) THEN ! VISIBLE ------------------------
-          DO m=1,L_NSPECTV
-             QVISsQREF3d(ig,lg,m,iaer) =                           &
-                        k1*qsqrefVISgrid(grid_i,1,m,iaer) +        &
-                        k2*qsqrefVISgrid(grid_i+1,1,m,iaer)
-            omegaVIS3d(ig,lg,m,iaer) =                             &
-                        k1*omegVISgrid(grid_i,1,m,iaer) +          &
-                        k2*omegVISgrid(grid_i+1,1,m,iaer)
-            gVIS3d(ig,lg,m,iaer) =                                 &
-                        k1*gVISgrid(grid_i,1,m,iaer) +             &
-                        k2*gVISgrid(grid_i+1,1,m,iaer)
-          ENDDO !L_NSPECTV
-          QREFvis3d(ig,lg,iaer) =                                  &
-                        k1*qrefVISgrid(grid_i,1,iaer) +            &
-                        k2*qrefVISgrid(grid_i+1,1,iaer)
-          omegaREFvis3d(ig,lg,iaer) =                              &
-                        k1*omegrefVISgrid(grid_i,1,iaer) +         &
-                        k2*omegrefVISgrid(grid_i+1,1,iaer)
-          ELSE                   ! INFRARED -----------------------
-          DO m=1,L_NSPECTI
-            QIRsQREF3d(ig,lg,m,iaer) =                             &
-                        k1*qsqrefIRgrid(grid_i,1,m,iaer) +         &
-                        k2*qsqrefIRgrid(grid_i+1,1,m,iaer)
-            omegaIR3d(ig,lg,m,iaer) =                              &
-                        k1*omegIRgrid(grid_i,1,m,iaer) +           &
-                        k2*omegIRgrid(grid_i+1,1,m,iaer) 
-            gIR3d(ig,lg,m,iaer) =                                  & 
-                        k1*gIRgrid(grid_i,1,m,iaer) +              &
-                        k2*gIRgrid(grid_i+1,1,m,iaer)
-          ENDDO !L_NSPECTI
-          QREFir3d(ig,lg,iaer) =                                   &
-                        k1*qrefIRgrid(grid_i,1,iaer) +             &
-                        k2*qrefIRgrid(grid_i+1,1,iaer)
-          omegaREFir3d(ig,lg,iaer) =                               &
-                        k1*omegrefIRgrid(grid_i,1,iaer) +          &
-                        k2*omegrefIRgrid(grid_i+1,1,iaer)
-          ENDIF                  ! --------------------------------
-        ENDDO !nlayermx
-      ENDDO !ngridmx
-
-!==================================================================
-
-
-
-      ENDDO ! idomain
-
-      ENDIF ! nsize = 1
-
-      ENDDO ! iaer (loop on aerosol kind)
-
-      RETURN
-    END SUBROUTINE aeroptpropertiesJBnew
-
-
-
-      
Index: /trunk/LMDZ.GENERIC/libf/phystd/ave_stelspec.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/ave_stelspec.F90	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/ave_stelspec.F90	(revision 253)
@@ -1,3 +1,3 @@
-      subroutine ave_stelspec(startype,STELLAR)
+      subroutine ave_stelspec(STELLAR)
 
 !==================================================================
@@ -28,7 +28,8 @@
 
 #include "datafile.h"
+#include "callkeys.h"
 
       real*8 STELLAR(L_NSPECTV)
-      integer startype 
+!      integer startype 
 
       integer Nfine
@@ -43,4 +44,7 @@
       character(len=50)  :: file_id
       character(len=100) :: file_path
+
+      real lam_temp
+      double precision stel_temp
 
       STELLAR(:)=0.0
@@ -58,33 +62,44 @@
       dl=lam(2)-lam(1)
 
-      ! load high resolution stellar data
-      if(startype.eq.1)then
-         file_id='/stellar_spectra/sol.txt'
-         tstellar=5800.
-      elseif(startype.eq.2)then
-         file_id='/stellar_spectra/gl581.txt'
-         tstellar=3200.
-      elseif(startype.eq.3)then
-         file_id='/stellar_spectra/adleo.txt'
-         tstellar=3200.
-      elseif(startype.eq.4)then
-         file_id='/stellar_spectra/gj644.txt'
-         print*,'Find out tstellar before using this star!'
-         call abort
-      elseif(startype.eq.5)then
-         file_id='/stellar_spectra/hd128167.txt'
-         tstellar=6700. ! Segura et al. (2003)
+
+      if(stelbbody)then
+         tstellar=stelTbb
+         do ifine=1,Nfine
+            lam_temp=lam(ifine)
+            call blackl(dble(lam_temp*1e-6),dble(tstellar),stel_temp)
+            stel_f(ifine)=stel_temp
+         enddo
       else
-         print*,'Error: unknown star type chosen'
-         call abort
+         ! load high resolution stellar data
+         if(startype.eq.1)then
+            file_id='/stellar_spectra/sol.txt'
+            tstellar=5800.
+         elseif(startype.eq.2)then
+            file_id='/stellar_spectra/gl581.txt'
+            tstellar=3200.
+         elseif(startype.eq.3)then
+            file_id='/stellar_spectra/adleo.txt'
+            tstellar=3200.
+         elseif(startype.eq.4)then
+            file_id='/stellar_spectra/gj644.txt'
+            print*,'Find out tstellar before using this star!'
+            call abort
+         elseif(startype.eq.5)then
+            file_id='/stellar_spectra/hd128167.txt'
+            tstellar=6700. ! Segura et al. (2003)
+         else
+            print*,'Error: unknown star type chosen'
+            call abort
+         endif
+         file_path=datafile(1:LEN_TRIM(datafile))//file_id(1:LEN_TRIM(file_id))
+
+         open(111,file=file_path,form='formatted')
+         do ifine=1,Nfine
+            read(111,*) stel_f(ifine)
+         enddo
+         close(111)
       endif
-      file_path=datafile(1:LEN_TRIM(datafile))//file_id(1:LEN_TRIM(file_id))
 
-      open(111,file=file_path,form='formatted')
-      do ifine=1,Nfine
-         read(111,*) stel_f(ifine)
-      enddo
-      close(111)
-      
+
       ! sum data by band
       band=1
@@ -104,3 +119,4 @@
       STELLAR=STELLAR/sum(STELLAR)
 
+
       end subroutine ave_stelspec
Index: /trunk/LMDZ.GENERIC/libf/phystd/blackl.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/blackl.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/blackl.F	(revision 253)
@@ -1,7 +1,7 @@
       subroutine blackl(blalong,blat,blae)
-c.......................................................................
+
       implicit double precision (a-h,o-z)
-c.......................................................................
-c.....donnees de fond
+
+      ! physical constants
       sigma=5.6693d-08
       pi=datan(1.d0)*4.d0
@@ -13,8 +13,9 @@
       c1=h*(c**2)
       c2=h*c/cbol
-c.....fin de donnees de fond
-c.......................................................................
+
+
       blae=2.d0*pi*c1/blalong**5/(dexp(c2/blalong/blat)-1.d0)
-c.......................................................................
+
+
       return
       end
Index: /trunk/LMDZ.GENERIC/libf/phystd/calc_cpp3d.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/calc_cpp3d.F90	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/calc_cpp3d.F90	(revision 253)
@@ -13,26 +13,19 @@
 !==================================================================
 
-        ! you still need to validate this equation vs something....
-
       implicit none
 
 #include "comcstfi.h"
+#include "callkeys.h"
+#include "cpdet.h"
 
-      real cp0, dB2dT2
+      !real cp0, dB2dT2
       real cppNI      ! specific heat capacity at const. pressure
       real rcpNI      ! R / specific heat capacity
       real t
       real p
-      real calmol
-      real bar
 
-      calmol = 94.9784 ! 4.18/(mco2/1000)
-      bar    = 100000
+      ! dummy function until I decide what to do!
 
-      cp0    = (7.70+5.3e-3*t - 8.3e-7*t**2)*calmol
-      dB2dT2 = 2.69e-5*t - 0.0098
-      cppNI  = cp0 - t*(p/bar)*dB2dT2
-      !cppNI  = 1000*(t/460)**0.35 ! Sebastian's version
-
+      cppNI  = cpp
       rcpNI  = R/cppNI
 
Index: /trunk/LMDZ.GENERIC/libf/phystd/calc_cpp_mugaz.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/calc_cpp_mugaz.F90	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/calc_cpp_mugaz.F90	(revision 253)
@@ -0,0 +1,68 @@
+      subroutine calc_cpp_mugaz
+
+!==================================================================
+!     Purpose
+!     -------
+!     Compute the atmospheric specific heat capacity.
+!     Compute the atmospheric mean molar mass.
+!
+!     Authors
+!     ------- 
+!     Robin Wordsworth (2009)
+!
+!==================================================================
+
+      implicit none
+
+#include "comcstfi.h"
+!#include "callkeys.h"
+#include "gases.h"
+
+      integer igas
+
+      cpp=0.0
+      mugaz=0.0
+
+      do igas=1,ngasmx
+
+         if(igas.eq.vgas)then
+            ! ignore variable gas in cpp calculation
+         else
+            ! all values at 300 K from Engineering Toolbox
+            if(gnom(igas).eq.'CO2')then
+               cpp   = cpp   + 0.846*gfrac(igas)
+               mugaz = mugaz + 44.01*gfrac(igas)
+            elseif(gnom(igas).eq.'N2_')then
+               cpp   = cpp   + 1.040*gfrac(igas)
+               mugaz = mugaz + 28.01*gfrac(igas)
+            elseif(gnom(igas).eq.'H2_')then
+               cpp   = cpp   + 14.31*gfrac(igas)
+               mugaz = mugaz + 2.01*gfrac(igas)
+            elseif(gnom(igas).eq.'H2O')then
+               cpp   = cpp   + 1.864*gfrac(igas)
+               mugaz = mugaz + 18.02*gfrac(igas)
+            elseif(gnom(igas).eq.'CH4')then
+               cpp   = cpp   + 2.226*gfrac(igas)
+               mugaz = mugaz + 16.04*gfrac(igas)
+            elseif(gnom(igas).eq.'NH3')then
+               cpp   = cpp   + 2.175*gfrac(igas)
+               mugaz = mugaz + 17.03*gfrac(igas)
+               print*,'WARNING, cpp for NH3 may be for liquid' 
+            else
+               print*,'Error in calc_cpp_mugaz: Gas species not recognised!'
+               call abort
+            endif
+         endif
+
+      enddo
+
+      cpp=1000.0*cpp
+
+      print*,'Cp in calc_cpp_mugaz is ',cpp,'J kg^-1 K^-1'
+      print*,'Mg in calc_cpp_mugaz is ',mugaz,'amu'
+
+      R = 8.314511E+0 *1000.E+0/mugaz
+      rcp = R/cpp
+
+      return
+    end subroutine calc_cpp_mugaz
Index: /trunk/LMDZ.GENERIC/libf/phystd/calc_rayleigh.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/calc_rayleigh.F90	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/calc_rayleigh.F90	(revision 253)
@@ -7,9 +7,10 @@
 !     Average the Rayleigh scattering in each band, weighting the 
 !     average by the blackbody function at temperature tstellar.
+!     Works for an arbitrary mix of gases (currently CO2, N2 and 
+!     H2 are possible).
 !     
 !     Authors
 !     ------- 
 !     Robin Wordsworth (2010)
-!     Benjamin Charnay (2010)
 !
 !     Called by
@@ -24,75 +25,121 @@
 
       use radinc_h, only: L_NSPECTV
-      use radcommon_h, only: WAVEV, BWNV, DWNV, tstellar, gastype, tauray, scalep
+      use radcommon_h, only: WAVEV, BWNV, DWNV, tstellar, tauray, scalep
 
       implicit none
 
 #include "comcstfi.h"
+#include "callkeys.h"
+#include "gases.h"
 
       real*8 wl
-      integer N,Nfine,ifine
+      integer N,Nfine,ifine,igas
       parameter(Nfine=500.0)
       real*8 :: P0 = 9.423D+6   ! Rayleigh scattering reference pressure in pascals.    
 
-      logical waverage
-      real*8 tauconst,tauvar,tausum,tauwei,bwidth,bstart
+      logical typeknown
+      real*8 tauvar,tausum,tauwei,bwidth,bstart
       double precision df
 
-      waverage=.true. ! do we perform a blackbody weighted average by band?
+      real*8 tauconsti(ngasmx)
+      real*8 tauvari(ngasmx)
 
-      if(waverage)then
-         if(gastype(1).eq.'CO2')then
-            print*,'Rayleigh scattering is for a CO2 atmosphere.'
-            tauconst = (8.7/g)*1.527*scalep/P0
-         elseif(gastype(1).eq.'AIR')then ! AIR = Earth air
-            print*,'Rayleigh scattering is for an Earth-like atmosphere.'
-            tauconst = (9.81/g)*8.569E-3*scalep/(P0/93.0)
+      ! tau0/p0=tau/p (Hansen 1974)
+      ! Then calculate tau0 = (8*pi^3*p_1atm)/(3*N0)  *  4*delta^2/(g*mugaz*lambda^4)
+      ! Then calculate tau0 = 1.16e-20 * 4*delta^2/(g*mugaz*lambda^4 [in um])
+      ! where delta=n-1
+
+      typeknown=.false.
+      do igas=1,ngasmx
+         !if((igas.eq.vgas).or.(gfrac(igas).lt.1.e-4))then
+         if(igas.eq.vgas)then
+            print*,'Ignoring ',gnom(igas),' in Rayleigh scattering '// &
+            'as it is variable.'
+         elseif(gfrac(igas).lt.5.e-2)then
+            print*,'Ignoring ',gnom(igas),' in Rayleigh scattering '// &
+            'as its mixing ratio is less than 0.05.' 
+            ! ignore variable gas in Rayleigh calculation
+            ! ignore gases of mixing ratio < 1e-4 in Rayleigh calculation
+            tauconsti(igas) = 0.0
          else
-            print*,'Rayleigh scattering not defined for gas type ',gastype(n)
-            print*,'exiting.'
-            call abort
+            if(gnom(igas).eq.'CO2')then
+               tauconsti(igas) = (8.7/g)*1.527*scalep/P0
+            elseif(gnom(igas).eq.'N2_')then
+               tauconsti(igas) = (9.81/g)*8.569E-3*scalep/(P0/93.0)
+            elseif(gnom(igas).eq.'H2_')then
+               tauconsti(igas) = (10.0/g)*0.0487*scalep/(101325.0)
+               ! uses n=1.000132 from Optics, Fourth Edition.
+               ! around four times more opaque than CO2
+               ! around 5.5 times more opaque than air
+            elseif(gnom(igas).eq.'He_')then
+               print*,'Helium not ready yet!'
+            else
+               print*,'Error in calc_rayleigh: Gas species not recognised!'
+               call abort
+            endif
+
+            if(gfrac(igas).eq.1.0)then
+               print*,'Rayleigh scattering is for a pure ',gnom(igas),' atmosphere.'
+               typeknown=.true.
+            endif
+
          endif
+      enddo
+
+      if(.not.typeknown)then
+         print*,'Rayleigh scattering is for a mixed gas atmosphere.'
+         typeknown=.true.
       endif
+
  
       do N=1,L_NSPECTV
          
-         if(waverage)then
-            tausum = 0.0
-            tauwei = 0.0
-            bstart = 10000.0/BWNV(N+1)
-            bwidth = (10000.0/BWNV(N)) - (10000.0/BWNV(N+1))
-            do ifine=1,Nfine
-                wl=bstart+dble(ifine)*bwidth/Nfine
+         tausum = 0.0
+         tauwei = 0.0
+         bstart = 10000.0/BWNV(N+1)
+         bwidth = (10000.0/BWNV(N)) - (10000.0/BWNV(N+1))
+         do ifine=1,Nfine
+            wl=bstart+dble(ifine)*bwidth/Nfine
 
-                if(gastype(1).eq.'CO2')then
-                   tauvar = (1.0+0.013/wl**2)/wl**4
-                elseif(gastype(1).eq.'AIR')then
-                   tauvar = (1.0+0.0113/wl**2+0.00013/wl**4)/wl**4
-                endif
+            tauvar=0.0
+            do igas=1,ngasmx
+               !if((igas.eq.vgas).or.(gfrac(igas).lt.1.e-4))then
+               if((igas.eq.vgas).or.(gfrac(igas).lt.5.e-2))then
+                  ! ignore variable gas in Rayleigh calculation
+                  ! ignore gases of mixing ratio < 1e-4 in Rayleigh calculation
+                  tauvari(igas)   = 0.0
+               else
+                  if(gnom(igas).eq.'CO2')then
+                     tauvari(igas) = (1.0+0.013/wl**2)/wl**4
+                  elseif(gnom(igas).eq.'N2_')then
+                     tauvari(igas) = (1.0+0.0113/wl**2+0.00013/wl**4)/wl**4
+                  elseif(gnom(igas).eq.'H2_')then
+                     tauvari(igas) = 1.0/wl**4 ! no wvl dependence of ref. index here - improve?
+                  else
+                     print*,'Error in calc_rayleigh: Gas species not recognised!'
+                     call abort
+                  endif
+               endif
 
-                call blackl(dble(wl*1e-6),dble(tstellar),df)
-                df=df*bwidth/Nfine
-                tauwei=tauwei+df
-                tausum=tausum+tauvar*df
+               tauvar=tauvar+tauconsti(igas)*tauvari(igas)*gfrac(igas)
+
             enddo
-            TAURAY(N)=tauconst*tausum/tauwei
-         else
-            wl = WAVEV(N)
-            if(gastype(1).eq.'CO2')then
-               if(N.eq.1) print*,'Rayleigh scattering is for a CO2 atmosphere.'
-               TAURAY(N) = (8.7/g)*(1.527*(1.0+0.013/wl**2)/wl**4)*scalep/P0
-            elseif(gastype(1).eq.'AIR')then ! AIR = Earth air
-               if(N.eq.1) print*,'Rayleigh scattering is for an Earth-like atmosphere.'
-               TAURAY(N) = (9.81/g)*(8.569E-3*(1.0+0.0113/wl**2+0.00013/wl**4)/wl**4)*scalep/(P0/93.0)
-            else
-               print*,'Rayleigh scattering not defined for gas type ',gastype(n)
-               print*,'exiting.'
-               call abort
-            endif
-         endif       
 
+            call blackl(dble(wl*1e-6),dble(tstellar),df)
+            df=df*bwidth/Nfine
+            tauwei=tauwei+df
+            tausum=tausum+tauvar*df
+         
+         enddo
+         TAURAY(N)=tausum/tauwei
          ! we multiply by scalep here (100) because plev, which is used in optcv,
          ! is in units of mBar, so we need to convert.
+
       end do
 
+      print*,'At 1 atm and lambda = ',WAVEV(L_NSPECTV-5), &
+           ' um, tau_R = ',TAURAY(L_NSPECTV-5)*1013.25
+      print*,'At 1 atm and lambda = ',WAVEV(L_NSPECTV-6), &
+           ' um, tau_R = ',TAURAY(L_NSPECTV-6)*1013.25
+
     end subroutine calc_rayleigh
Index: unk/LMDZ.GENERIC/libf/phystd/callcorrk.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/callcorrk.F	(revision 252)
+++ 	(revision )
@@ -1,739 +1,0 @@
-           subroutine callcorrk(icount,ngrid,nlayer,pq,nq,qsurf,
-     &     albedo,emis,mu0,pplev,pplay,pt,
-     &     tsurf,fract,dist_star,igout,aerosol,cpp3D,
-     &     dtlw,dtsw,fluxsurf_lw,
-     &     fluxsurf_sw,fluxtop_lw,fluxtop_sw,fluxtop_dn,
-     &     reffrad,tau_col,ptime,pday,firstcall,lastcall)
-         
-      use radinc_h
-      use radcommon_h
-      use ioipsl_getincom 
-
-      implicit none
-
-!==================================================================
-!
-!     Purpose
-!     -------
-!     Solve the radiative transfer using the correlated-k method for
-!     the gaseous absorption and the Toon et al. (1989) method for
-!     scatttering due to aerosols.
-!
-!     Authors
-!     ------- 
-!     Emmanuel 01/2001, Forget 09/2001
-!     Robin Wordsworth (2009)
-!
-!==================================================================
-
-#include "dimphys.h"
-#include "datafile.h"
-#include "comcstfi.h"
-#include "callkeys.h"
-#include "tracer.h"
-
-!-----------------------------------------------------------------------
-!     Declaration of the arguments (INPUT - OUTPUT) on the LMD GCM grid
-!     Layer #1 is the layer near the ground. 
-!     Layer #nlayermx is the layer at the top.
-
-!     INPUT
-      INTEGER icount
-      INTEGER ngrid,nlayer
-      INTEGER igout
-      REAL aerosol(ngrid,nlayermx,naerkind) ! aerosol tau (kg/kg)
-      REAL albedo(ngrid)                    ! SW albedo
-      REAL emis(ngrid)                      ! LW emissivity
-      REAL pplay(ngrid,nlayermx)            ! pres. level in GCM mid of layer
-      REAL pplev(ngrid,nlayermx+1)          ! pres. level at GCM layer boundaries
-
-      REAL pt(ngrid,nlayermx)               ! air temperature (K)
-      REAL tsurf(ngrid)                     ! surface temperature (K)
-      REAL dist_star,mu0(ngrid)             ! distance star-planet (AU)
-      REAL fract(ngrid)                     ! fraction of day
-
-!     Globally varying aerosol optical properties on GCM grid
-!     Not needed everywhere so not in radcommon_h
-      REAL :: QVISsQREF3d(ngridmx,nlayermx,L_NSPECTV,naerkind)
-      REAL :: omegaVIS3d(ngridmx,nlayermx,L_NSPECTV,naerkind)
-      REAL :: gVIS3d(ngridmx,nlayermx,L_NSPECTV,naerkind)
-
-      REAL :: QIRsQREF3d(ngridmx,nlayermx,L_NSPECTI,naerkind)
-      REAL :: omegaIR3d(ngridmx,nlayermx,L_NSPECTI,naerkind)
-      REAL :: gIR3d(ngridmx,nlayermx,L_NSPECTI,naerkind)
-
-      REAL :: QREFvis3d(ngridmx,nlayermx,naerkind)
-      REAL :: QREFir3d(ngridmx,nlayermx,naerkind)
-
-!      REAL :: omegaREFvis3d(ngridmx,nlayermx,naerkind)
-!      REAL :: omegaREFir3d(ngridmx,nlayermx,naerkind) ! not sure of the point of these...
-
-      REAL reffrad(ngrid,nlayer,naerkind)
-      REAL nueffrad(ngrid,nlayer,naerkind)
-
-!     OUTPUT
-      REAL dtsw(ngridmx,nlayermx) ! heating rate (K/s) due to SW
-      REAL dtlw(ngridmx,nlayermx) ! heating rate (K/s) due to LW
-      REAL fluxsurf_lw(ngridmx)   ! incident LW flux to surf (W/m2)
-      REAL fluxtop_lw(ngridmx)    ! outgoing LW flux to space (W/m2)
-      REAL fluxsurf_sw(ngridmx)   ! incident SW flux to surf (W/m2)
-      REAL fluxtop_sw(ngridmx)    ! outgoing LW flux to space (W/m2)
-      REAL fluxtop_dn(ngridmx)    ! incident top of atmosphere SW flux (W/m2)
-
-!-----------------------------------------------------------------------
-!     Declaration of the variables required by correlated-k subroutines
-!     Numbered from top to bottom unlike in the GCM!
-
-      REAL*8 tmid(L_LEVELS),pmid(L_LEVELS)
-      REAL*8 tlevrad(L_LEVELS),plevrad(L_LEVELS)
-
-!     Optical values for the optci/cv subroutines
-      REAL*8 stel(L_NSPECTV),stel_fract(L_NSPECTV)
-      REAL*8 dtaui(L_NLAYRAD,L_NSPECTI,L_NGAUSS)
-      REAL*8 dtauv(L_NLAYRAD,L_NSPECTV,L_NGAUSS)
-      REAL*8 cosbv(L_NLAYRAD,L_NSPECTV,L_NGAUSS)
-      REAL*8 cosbi(L_NLAYRAD,L_NSPECTI,L_NGAUSS)
-      REAL*8 wbari(L_NLAYRAD,L_NSPECTI,L_NGAUSS)
-      REAL*8 wbarv(L_NLAYRAD,L_NSPECTV,L_NGAUSS)
-      REAL*8 tauv(L_NLEVRAD,L_NSPECTV,L_NGAUSS)
-      REAL*8 taucumv(L_LEVELS,L_NSPECTV,L_NGAUSS)
-      REAL*8 taucumi(L_LEVELS,L_NSPECTI,L_NGAUSS)
-
-      REAL*8 tauaero(L_LEVELS+1,naerkind)
-      REAL*8 nfluxtopv,nfluxtopi,nfluxtop
-      real*8 NFLUXTOPV_nu(L_NSPECTV)
-      real*8 NFLUXTOPI_nu(L_NSPECTI)
-      real*8 fluxupi_nu(L_NLAYRAD,L_NSPECTI) ! for 1D diagnostic
-      REAL*8 fmneti(L_NLAYRAD),fmnetv(L_NLAYRAD)
-      REAL*8 fluxupv(L_NLAYRAD),fluxupi(L_NLAYRAD)
-      REAL*8 fluxdnv(L_NLAYRAD),fluxdni(L_NLAYRAD)
-      REAL*8 albi,albv,acosz
-
-      INTEGER ig,l,k,nw,iaer,irad
-
-      real fluxtoplanet
-      real*8 taugsurf(L_NSPECTV,L_NGAUSS-1)
-      real*8 taugsurfi(L_NSPECTI,L_NGAUSS-1)
-
-      real*8 qvar(L_LEVELS)          ! mixing ratio of variable component
-      REAL pq(ngridmx,nlayer,nq)
-      REAL qsurf(ngridmx,nqmx)       ! tracer on surface (e.g. kg.m-2)
-      integer nq
-
-!     Local aerosol optical properties for each column on RADIATIVE grid
-      real*8  QXVAER(L_LEVELS+1,L_NSPECTV,naerkind)
-      real*8  QSVAER(L_LEVELS+1,L_NSPECTV,naerkind)
-      real*8  GVAER(L_LEVELS+1,L_NSPECTV,naerkind)
-      real*8  QXIAER(L_LEVELS+1,L_NSPECTI,naerkind)
-      real*8  QSIAER(L_LEVELS+1,L_NSPECTI,naerkind)
-      real*8  GIAER(L_LEVELS+1,L_NSPECTI,naerkind)
-
-      save qxvaer, qsvaer, gvaer
-      save qxiaer, qsiaer, giaer
-      save QREFvis3d, QREFir3d 
-
-      REAL tau_col(ngrid) ! diagnostic from aeropacity
-
-!     Misc.
-      logical firstcall, lastcall, nantest
-      real*8  tempv(L_NSPECTV)
-      real*8  tempi(L_NSPECTI)
-      real*8  temp,temp1,temp2,pweight
-      character(len=10) :: tmp1
-      character(len=10) :: tmp2
-
-!     for fixed water vapour profiles
-      integer i_var
-      real RH
-      real*8 pq_temp(nlayer)
-      real ptemp, Ttemp, qsat
-
-!      real(KIND=r8) :: pq_temp(nlayer) ! better F90 way.. DOESNT PORT TO F77!!!
-
-!     for OLR spec
-      integer OLRcount
-      save OLRcount
-      integer OLRcount2
-      save OLRcount2
-      character(len=2)  :: tempOLR
-      character(len=30) :: filenomOLR
-      real ptime, pday
-      logical OLRz
-      real OLR_nu(ngrid,L_NSPECTI)
-
-!     Allow variations in cp with location
-      REAL cpp3D(ngridmx,nlayermx)   ! specific heat capacity at const. pressure
-
-!     for Dave Crisp LBL data comparison
-      logical crisp
-      crisp=.false.
-
-
-!=======================================================================
-!     Initialization on first call
-
-      CALL zerophys((L_LEVELS+1)*L_NSPECTV*naerkind,qxvaer)
-      CALL zerophys((L_LEVELS+1)*L_NSPECTV*naerkind,qsvaer)
-      CALL zerophys((L_LEVELS+1)*L_NSPECTV*naerkind,gvaer)
-
-      CALL zerophys((L_LEVELS+1)*L_NSPECTI*naerkind,qxiaer)
-      CALL zerophys((L_LEVELS+1)*L_NSPECTI*naerkind,qsiaer)
-      CALL zerophys((L_LEVELS+1)*L_NSPECTI*naerkind,giaer)
-
-      if(firstcall) then
-
-
-!--------------------------------------------------
-!     Effective radius and variance of the aerosols
-
-!     CO2 ice:
-         DO l=1,nlayer
-            DO ig=1,ngrid
-               reffrad(ig,l,1)  = 1.e-4
-               nueffrad(ig,l,1) = 0.1 
-!     these values will change once the microphysics gets to work
-!     UNLESS tracer=.false., in which case we should be working with
-!     a fixed aerosol layer, and be able to define reffrad in a 
-!     .def file. To be improved!
-            ENDDO
-         ENDDO
-
-!     H2O ice:
-         if(naerkind.eq.2)then
-            DO l=1,nlayer
-               DO ig=1,ngrid
-                  reffrad(ig,l,naerkind)  = 1.e-5
-                  nueffrad(ig,l,naerkind) = 0.1
-               ENDDO  
-            ENDDO
-         endif
-
-         print*, "Correlated-k data base folder:",datafile
-         call getin("corrkdir",corrkdir)
-         print*, "corrkdir = ",corrkdir
-         write( tmp1, '(i3)' ) L_NSPECTI
-         write( tmp2, '(i3)' ) L_NSPECTV
-         banddir=trim(adjustl(tmp1))//'x'//trim(adjustl(tmp2))
-         banddir=trim(adjustl(corrkdir))//'/'//trim(adjustl(banddir))
-
-         print*,'starting sugas'
-         call sugas_corrk       ! set up gaseous absorption properties
-         print*,'starting setspi'
-         call setspi            ! basic infrared properties
-         print*,'starting setspv'
-         call setspv            ! basic visible properties
-         print*,'starting suaer_corrk'
-         call suaer_corrk       ! set up aerosol optical properties
-
-         Cmk= 0.01 * 1.0 / (g * mugaz * 1.672621e-27) ! q_main=1.0 assumed
-
-         if((igcm_h2o_vap.eq.0) .and. varactive)then
-            print*,'varactive in callcorrk but no h2o_vap tracer.'
-            stop
-         endif
-
-         firstcall=.false.   
-
-      end if
-
-!=======================================================================
-!     Initialization on every call    
-
-      do l=1,nlayer
-         do ig=1,ngrid
-            do iaer=1,naerkind
-               nueffrad(ig,l,iaer) = 0.1 ! this little bastard stays at 0.1 forever
-            enddo
-         enddo
-      enddo
-
-    !  if(aerofixed)then ! fixed particle radii if aerofixed=.true.
-         do l=1,nlayer
-            do ig=1,ngrid
-               reffrad(ig,l,1)  = 3.5e-5
-            enddo
-         enddo
-         if(naerkind.eq.2)then
-            do l=1,nlayer
-               do ig=1,ngrid
-                  reffrad(ig,l,2)  = 5.e-6
-               enddo
-            enddo
-         endif
-    !  endif
-
-!     how much light we get
-      fluxtoplanet=0
-      DO nw=1,L_NSPECTV
-         stel(nw)=stellarf(nw)/(dist_star**2)
-         fluxtoplanet=fluxtoplanet + stel(nw)
-      END DO
-
-!      print*,'nueffrad',nueffrad
-!      print*,'reffrad before',reffrad
-!      print*,'nueffrad before',nueffrad
-!      CALL aeroptproperties(ngrid,nlayer,reffrad,nueffrad,
-!     &     QVISsQREF3d,omegaVIS3d,gVIS3d,
-!     &     QIRsQREF3d,omegaIR3d,gIR3d,
-!     &     QREFvis3d,QREFir3d)                  ! get 3D aerosol optical properties
-
-      CALL aeroptpropertiesJBnew(ngrid,nlayer,reffrad,nueffrad,
-     &     QVISsQREF3d,omegaVIS3d,gVIS3d,
-     &     QIRsQREF3d,omegaIR3d,gIR3d,
-     &     QREFvis3d,QREFir3d)
-
-!      print*,'QVISsQREF3d=',QVISsQREF3d
-!      print*,'QIRsQREF3d=',QIRsQREF3d
-!      print*,'omegaVIS3d=',omegaVIS3d
-!      print*,'omegaIR3d=',omegaIR3d
-!      print*,'gVIS3d=',gVIS3d
-!      print*,'gIR3d=',gIR3d
-!      print*,'reffrad after',reffrad
-!      print*,'nueffrad after',nueffrad
-!      print*,'QREFvis3d=',QREFvis3d
-!      print*,'QREFir3d=',QREFir3d
-!      stop
-
-      call aeropacity(ngrid,nlayer,nq,pplev,pq,aerosol,
-     &     reffrad,QREFvis3d,QREFir3d,tau_col)  ! get aerosol optical depths
-
-
-!-----------------------------------------------------------------------
-!     Starting Big Loop over every GCM column
-      do ig=1,ngridmx
-
-!=======================================================================
-!     Transformation of the GCM variables
-
-!-----------------------------------------------------------------------
-!     Aerosol optical properties Qext, Qscat and g
-!     The transformation in the vertical is the same as for temperature
-           
-!     shortwave
-            do iaer=1,naerkind
-               DO nw=1,L_NSPECTV 
-                  do l=1,nlayermx
-
-                     temp1=QVISsQREF3d(ig,nlayermx+1-l,nw,iaer) 
-     $                    *QREFvis3d(ig,nlayermx+1-l,iaer)
-
-                     temp2=QVISsQREF3d(ig,max(nlayermx-l,1),nw,iaer) 
-     $                    *QREFvis3d(ig,max(nlayermx-l,1),iaer)
-
-                     qxvaer(2*l,nw,iaer)  = temp1
-                     qxvaer(2*l+1,nw,iaer)=(temp1+temp2)/2
-
-                    temp1=temp1*omegavis3d(ig,nlayermx+1-l,nw,iaer)
-                    temp2=temp2*omegavis3d(ig,max(nlayermx-l,1),nw,iaer)
-
-                     qsvaer(2*l,nw,iaer)  = temp1
-                     qsvaer(2*l+1,nw,iaer)=(temp1+temp2)/2
-
-                     temp1=gvis3d(ig,nlayermx+1-l,nw,iaer)
-                     temp2=gvis3d(ig,max(nlayermx-l,1),nw,iaer)
-
-                     gvaer(2*l,nw,iaer)  = temp1
-                     gvaer(2*l+1,nw,iaer)=(temp1+temp2)/2
-
-                  end do
-                  qxvaer(1,nw,iaer)=qxvaer(2,nw,iaer)
-                  qxvaer(2*nlayermx+1,nw,iaer)=0.
-
-                  qsvaer(1,nw,iaer)=qsvaer(2,nw,iaer)
-                  qsvaer(2*nlayermx+1,nw,iaer)=0.
-
-                  gvaer(1,nw,iaer)=gvaer(2,nw,iaer)
-                  gvaer(2*nlayermx+1,nw,iaer)=0.
-               end do
-
-!     longwave
-               DO nw=1,L_NSPECTI 
-                  do l=1,nlayermx
-
-                     temp1=QIRsQREF3d(ig,nlayermx+1-l,nw,iaer) 
-     $                    *QREFir3d(ig,nlayermx+1-l,iaer)
-
-                     temp2=QIRsQREF3d(ig,max(nlayermx-l,1),nw,iaer) 
-     $                    *QREFir3d(ig,max(nlayermx-l,1),iaer)
-
-                     qxiaer(2*l,nw,iaer)  = temp1
-                     qxiaer(2*l+1,nw,iaer)=(temp1+temp2)/2
-
-                     temp1=temp1*omegair3d(ig,nlayermx+1-l,nw,iaer)
-                     temp2=temp2*omegair3d(ig,max(nlayermx-l,1),nw,iaer)
-
-                     qsiaer(2*l,nw,iaer)  = temp1
-                     qsiaer(2*l+1,nw,iaer)=(temp1+temp2)/2
-
-                     temp1=gir3d(ig,nlayermx+1-l,nw,iaer)
-                     temp2=gir3d(ig,max(nlayermx-l,1),nw,iaer)
-
-                     giaer(2*l,nw,iaer)  = temp1
-                     giaer(2*l+1,nw,iaer)=(temp1+temp2)/2
-
-                  end do
-
-                  qxiaer(1,nw,iaer)=qxiaer(2,nw,iaer)
-                  qxiaer(2*nlayermx+1,nw,iaer)=0.
-
-                  qsiaer(1,nw,iaer)=qsiaer(2,nw,iaer)
-                  qsiaer(2*nlayermx+1,nw,iaer)=0.
-
-                  giaer(1,nw,iaer)=giaer(2,nw,iaer)
-                  giaer(2*nlayermx+1,nw,iaer)=0.
-               end do
-            end do
-
-!-----------------------------------------------------------------------
-!     Aerosol optical depths
-            
-         do iaer=1,naerkind     ! a bug was here           
-            do k=0,nlayer-1
-               
-               pweight=
-     $              (pplay(ig,L_NLAYRAD-k)-pplev(ig,L_NLAYRAD-k+1))/
-     $              (pplev(ig,L_NLAYRAD-k)-pplev(ig,L_NLAYRAD-k+1))
-
-               temp=aerosol(ig,L_NLAYRAD-k,iaer)/
-     $              QREFvis3d(ig,L_NLAYRAD-k,iaer)
-
-            tauaero(2*k+2,iaer)=max(temp*pweight,0.0)
-            tauaero(2*k+3,iaer)=max(temp-tauaero(2*k+2,iaer),0.0)
-!               tauaero(2*k+2,iaer)=
-!     &              real(max(temp*pweight,0.0),8)
-!               tauaero(2*k+3,iaer)=
-!     &              real(max(temp-tauaero(2*k+2,iaer),0.0),8)
-
-            end do
-            tauaero(1,iaer)=0.
-         end do
-
-!     Albedo and emissivity
-         albi=1-emis(ig)        ! longwave
-         albv=albedo(ig)        ! shortwave 
-
-      if(ngrid.eq.1) then       ! fixed zenith angle in 1D
-         acosz     = 0.5
-         print*,'Solar zenith angle fixed at 60 deg in 1D (callcorrk.F)'
-      else
-         acosz=mu0(ig)          ! cosine of sun incident angle
-      endif
-
-
-!-----------------------------------------------------------------------
-!     Water vapour (to be generalised / ignored for other planets)
-
-      if(varactive) then
-         i_var=igcm_h2o_vap
-
-         do l=1,nlayer
-            qvar(2*l)   = pq(ig,nlayer+1-l,i_var)
-            qvar(2*l+1) = (pq(ig,nlayer+1-l,i_var)+pq(ig,
-     $           max(nlayer-l,1),i_var))/2    ! Average approximation as for temperature...
-         end do
-         qvar(1)=qvar(2)
-         qvar(2*nlayermx+1)=qsurf(ig,i_var)
-
-      elseif(varfixed)then
-
-         do l=1,nlayermx        ! here we will assign fixed water vapour profiles globally
-            RH = satval * ((pplay(ig,l)/pplev(ig,1) - 0.02) / 0.98)
-            if(RH.lt.0.0) RH=0.0
-            
-            ptemp=pplay(ig,l)
-            Ttemp=pt(ig,l)
-            call watersat_2(Ttemp,ptemp,qsat)
-
-            !pq_temp(l) = qsat      ! fully saturated everywhere
-            pq_temp(l) = RH * qsat ! ~realistic profile (80% saturation at ground)
-         end do
-         
-         do l=1,nlayer
-            qvar(2*l)   = pq_temp(nlayer+1-l)
-            qvar(2*l+1) = (pq_temp(nlayer+1-l)+pq_temp(
-     $           max(nlayer-l,1)))/2
-         end do
-         qvar(1)=qvar(2)
-
-         ! Lowest layer of atmosphere
-         RH = satval * (1 - 0.02) / 0.98
-         if(RH.lt.0.0) RH=0.0
-
-         ptemp = pplev(ig,1)
-         Ttemp = tsurf(ig)
-         call watersat_2(Ttemp,ptemp,qsat)
-
-         !qvar(2*nlayermx+1)=qsat      ! fully saturated everywhere
-         qvar(2*nlayermx+1)= RH * qsat ! ~realistic profile (80% saturation at ground)
-
-      else
-         do k=1,L_LEVELS
-            qvar(k) = 1.0D-7
-         end do
-      end if
-
-      ! Keep values inside limits for which we have radiative transfer coefficients
-      if(L_REFVAR.gt.1)then ! there was a bug here!
-         do k=1,L_LEVELS
-            if(qvar(k).lt.wrefvar(1))then
-               qvar(k)=wrefvar(1)+1.0e-8
-            elseif(qvar(k).gt.wrefvar(L_REFVAR))then
-               qvar(k)=wrefvar(L_REFVAR)-1.0e-8
-            endif
-         end do
-      endif
-
-!-----------------------------------------------------------------------
-!     Pressure and temperature
-
-      DO l=1,nlayer
-         plevrad(2*l)   = pplay(ig,nlayer+1-l)/scalep
-         plevrad(2*l+1) = pplev(ig,nlayer+1-l)/scalep
-         tlevrad(2*l)   = pt(ig,nlayer+1-l)
-         tlevrad(2*l+1) = (pt(ig,nlayer+1-l)+pt(ig,
-     $        max(nlayer-l,1)))/2
-      END DO
-      
-      plevrad(1) = 0
-      plevrad(2) = max(pgasmin,0.0001*plevrad(3))
-
-      tlevrad(1) = tlevrad(2)
-      tlevrad(2*nlayermx+1)=tsurf(ig)
-      
-
-      if(crisp)then
-         open(111,file='/u/rwlmd/CrispLBL/p.dat')
-         open(112,file='/u/rwlmd/CrispLBL/T.dat')
-         do k=1,L_LEVELS
-            read(111,*) plevrad(k)
-            read(112,*) tlevrad(k)
-            plevrad(k)=plevrad(k)*1000.0
-         enddo
-         close(111)
-         close(112)
-      endif
-
-      tmid(1) = tlevrad(2)
-      tmid(2) = tlevrad(2)
-      pmid(1) = plevrad(2)
-      pmid(2) = plevrad(2)
-      
-      DO l=1,L_NLAYRAD-1
-         tmid(2*l+1) = tlevrad(2*l+1)
-         tmid(2*l+2) = tlevrad(2*l+1)
-         pmid(2*l+1) = plevrad(2*l+1)
-         pmid(2*l+2) = plevrad(2*l+1)
-      END DO
-      pmid(L_LEVELS) = plevrad(L_LEVELS)
-      tmid(L_LEVELS) = tlevrad(L_LEVELS)
-      
-      ! test for out-of-bounds pressure
-      if(plevrad(3).lt.pgasmin)then
-         print*,'Minimum pressure is outside the radiative'
-         print*,'transfer kmatrix bounds, exiting.'
-         call abort
-      elseif(plevrad(L_LEVELS).gt.pgasmax)then
-         print*,'Maximum pressure is outside the radiative'
-         print*,'transfer kmatrix bounds, exiting.'
-         call abort
-      endif
-
-      ! test for out-of-bounds temperature
-      do k=1,L_LEVELS
-         if(tlevrad(k).lt.tgasmin)then
-            print*,'Minimum temperature is outside the radiative'
-            print*,'transfer kmatrix bounds, exiting.'
-            call abort
-         elseif(tlevrad(k).gt.tgasmax)then
-            print*,'Maximum temperature is outside the radiative'
-            print*,'transfer kmatrix bounds, exiting.'
-            call abort
-         endif
-      enddo
-
-!=======================================================================
-!     Calling the main radiative transfer subroutines
-
-
-
-!-----------------------------------------------------------------------
-!     Shortwave
-
-         IF(fract(ig) .GE. 1.0e-4) THEN ! only during daylight!
-
-            fluxtoplanet=0.
-            DO nw=1,L_NSPECTV
-               stel_fract(nw)= stel(nw) * fract(ig)
-               fluxtoplanet=fluxtoplanet + stel_fract(nw)
-            END DO
-            
-            call optcv(dtauv,tauv,taucumv,plevrad,
-     $           qxvaer,qsvaer,gvaer,wbarv,cosbv,tauray,tauaero,
-     $           tmid,pmid,taugsurf,qvar)
-
-            call sfluxv(dtauv,tauv,taucumv,albv,dwnv,wbarv,cosbv,
-     $           acosz,stel_fract,gweight,nfluxtopv,nfluxtopv_nu,
-     $           fmnetv,fluxupv,fluxdnv,fzerov,taugsurf)
-
-         ELSE                          ! during the night, fluxes = 0
-            nfluxtopv=0.0
-            DO l=1,L_NLAYRAD
-               fmnetv(l)=0.0
-               fluxupv(l)=0.0
-               fluxdnv(l)=0.0
-            END DO
-         END IF
-
-!-----------------------------------------------------------------------
-!     Longwave
-
-         call optci(plevrad,tlevrad,dtaui,taucumi,
-     $        qxiaer,qsiaer,giaer,cosbi,wbari,tauaero,tmid,pmid,
-     $        taugsurfi,qvar)
-
-         call sfluxi(plevrad,tlevrad,dtaui,taucumi,ubari,albi,
-     $        wnoi,dwni,cosbi,wbari,gweight,nfluxtopi,nfluxtopi_nu,
-     $        fmneti,fluxupi,fluxdni,fluxupi_nu,fzeroi,taugsurfi)
-
-!-----------------------------------------------------------------------
-!     Transformation of the correlated-k code outputs
-!     (into dtlw, dtsw, fluxsurf_lw, fluxsurf_sw, fluxtop_lw, fluxtop_sw)
-
-         fluxtop_lw(ig)  = fluxupi(1)
-         fluxsurf_lw(ig) = fluxdni(L_NLAYRAD)
-         fluxtop_sw(ig)  = fluxupv(1)
-         fluxsurf_sw(ig) = fluxdnv(L_NLAYRAD)
-
-!     Flux incident at the top of the atmosphere
-         fluxtop_dn(ig)=fluxdnv(1)  
-
-         !if(lastcall)then 
-         !print*,'albv=',albv
-         !print*,'albi=',albi
-         !print*,'fluxupi',fluxupi
-         !print*,'fluxirnet',fluxdni-fluxupi
-         !print*,'fmneti',fmneti
-         !print*,'fluxdnv',fluxdnv
-         !print*,'fluxtop_sw=',fluxtop_sw
-         !print*,'fluxsurf_sw=',fluxsurf_sw
-         !print*,'fluxtop_lw=',fluxtop_lw
-         !print*,'fluxsurf_lw=',fluxsurf_lw
-         !endif
-
-         if(crisp)then
-            open(111,file='/u/rwlmd/CrispLBL/GCMfluxdn.dat')
-            open(112,file='/u/rwlmd/CrispLBL/GCMfluxup.dat')
-            do k=1,L_NLAYRAD
-               write(111,*) fluxdni(k)
-               write(112,*) fluxupi(k)
-            enddo
-            close(111)
-            close(112)
-            print*,'fluxdni',fluxdni
-            print*,'fluxupi',fluxupi
-            call abort
-         endif
-
-!     IR spectral output, for exoplanet observational comparison
-         if(specOLR)then
-            do nw=1,L_NSPECTI 
-               OLR_nu(ig,nw)=nfluxtopi_nu(nw)
-            end do
-         endif
-
-!     Finally, the heating rates
-
-         if(nonideal)then
-
-            DO l=2,L_NLAYRAD
-               dtsw(ig,L_NLAYRAD+1-l)=(fmnetv(l)-fmnetv(l-1))
-     $              *g/(cpp3D(ig,L_NLAYRAD+1-l)
-     $              *scalep*(plevrad(2*l+1)-plevrad(2*l-1)))
-               dtlw(ig,L_NLAYRAD+1-l)=(fmneti(l)-fmneti(l-1))
-     $              *g/(cpp3D(ig,L_NLAYRAD+1-l)
-     $              *scalep*(plevrad(2*l+1)-plevrad(2*l-1)))           
-            END DO      
-
-!     These are values at top of atmosphere
-            dtsw(ig,L_NLAYRAD)=(fmnetv(1)-nfluxtopv)
-     $           *g/(cpp3D(ig,L_NLAYRAD)*scalep*(plevrad(3)-plevrad(1)))
-            dtlw(ig,L_NLAYRAD)=(fmneti(1)-nfluxtopi)
-     $           *g/(cpp3D(ig,L_NLAYRAD)*scalep*(plevrad(3)-plevrad(1)))
-
-         else
-
-            DO l=2,L_NLAYRAD
-               dtsw(ig,L_NLAYRAD+1-l)=(fmnetv(l)-fmnetv(l-1))
-     $              *g/(cpp*scalep*(plevrad(2*l+1)-plevrad(2*l-1)))
-               dtlw(ig,L_NLAYRAD+1-l)=(fmneti(l)-fmneti(l-1))
-     $              *g/(cpp*scalep*(plevrad(2*l+1)-plevrad(2*l-1)))
-            END DO      
-
-!     These are values at top of atmosphere
-            dtsw(ig,L_NLAYRAD)=(fmnetv(1)-nfluxtopv)
-     $           *g/(cpp*scalep*(plevrad(3)-plevrad(1)))
-            dtlw(ig,L_NLAYRAD)=(fmneti(1)-nfluxtopi)
-     $           *g/(cpp*scalep*(plevrad(3)-plevrad(1)))
-
-         endif
-
-        !if(lastcall)then
-        !  ! print*,'tlevrad=',tlevrad
-        !   print*,'tsurf=',tsurf
-        !   print*,'pt=',pt
-        !   print*,'fmnetv',shape(fmnetv)
-        !   print*,'fmneti',shape(fmneti)
-        !!endif
-
-!     ---------------------------------------------------------------
-      end do                    ! end of big loop over every GCM column (ig = 1:ngrid)
-
-
-!-----------------------------------------------------------------------
-!     Additional diagnostics
-
-!     IR spectral output, for exoplanet observational comparison
-      if(specOLR)then
-        if(ngrid.ne.1)then
-          call writediagspec(ngrid,"OLR3D",
-     &        "OLR(lon,lat,band)","W m^-2",3,OLR_nu)
-        endif
-      endif
-
-      if(lastcall)then ! for kasthop
-
-        if(ngrid.eq.1)then
-
-           print*,'Saving tsurf,psurf in surf_vals.out...'
-           open(116,file='surf_vals.out')
-           write(116,*) tsurf(1),pplev(1,1),
-     &          fluxtop_dn(1) - fluxtop_sw(1),fluxtop_lw(1) 
-           close(116)
-
-           if(specOLR)then
-               open(117,file='OLRnu.out')
-               do nw=1,L_NSPECTI
-                   write(117,*) OLR_nu(1,nw)
-               enddo   
-               close(117)
-           endif
-!     OLR vs altitude: do it as a .txt file
-           OLRz=.false.
-           if(OLRz)then
-              print*,'saving IR vertical flux for OLRz...'
-              open(118,file='OLRz_plevs.out')
-              open(119,file='OLRz.out')
-              do l=1,L_NLAYRAD
-                 write(118,*) plevrad(2*l)
-                 do nw=1,L_NSPECTI
-                     write(119,*) fluxupi_nu(l,nw) 
-                  enddo
-              enddo 
-              close(118)
-              close(119)
-           endif
-        endif
-
-      endif
-
-      end
Index: /trunk/LMDZ.GENERIC/libf/phystd/callcorrk.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/callcorrk.F90	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/callcorrk.F90	(revision 253)
@@ -0,0 +1,884 @@
+      subroutine callcorrk(icount,ngrid,nlayer,pq,nq,qsurf,    &
+          albedo,emis,mu0,pplev,pplay,pt,                      & 
+          tsurf,fract,dist_star,aerosol,cpp3D,                 &
+          dtlw,dtsw,fluxsurf_lw,                               &
+          fluxsurf_sw,fluxtop_lw,fluxabs_sw,fluxtop_dn,        &
+          reffrad,tau_col,ptime,pday,cloudfrac,totcloudfrac,   &
+          clearsky,firstcall,lastcall)
+
+      use radinc_h
+      use radcommon_h
+      use watercommon_h
+      use ioipsl_getincom 
+
+      implicit none
+
+!==================================================================
+!
+!     Purpose
+!     -------
+!     Solve the radiative transfer using the correlated-k method for
+!     the gaseous absorption and the Toon et al. (1989) method for
+!     scatttering due to aerosols.
+!
+!     Authors
+!     ------- 
+!     Emmanuel 01/2001, Forget 09/2001
+!     Robin Wordsworth (2009)
+!
+!==================================================================
+
+#include "dimphys.h"
+#include "datafile.h"
+#include "comcstfi.h"
+#include "callkeys.h"
+#include "tracer.h"
+
+!-----------------------------------------------------------------------
+!     Declaration of the arguments (INPUT - OUTPUT) on the LMD GCM grid
+!     Layer #1 is the layer near the ground. 
+!     Layer #nlayermx is the layer at the top.
+
+!     INPUT
+      INTEGER icount
+      INTEGER ngrid,nlayer
+      REAL aerosol(ngrid,nlayermx,naerkind) ! aerosol tau (kg/kg)
+      REAL albedo(ngrid)                    ! SW albedo
+      REAL emis(ngrid)                      ! LW emissivity
+      REAL pplay(ngrid,nlayermx)            ! pres. level in GCM mid of layer
+      REAL pplev(ngrid,nlayermx+1)          ! pres. level at GCM layer boundaries
+
+      REAL pt(ngrid,nlayermx)               ! air temperature (K)
+      REAL tsurf(ngrid)                     ! surface temperature (K)
+      REAL dist_star,mu0(ngrid)             ! distance star-planet (AU)
+      REAL fract(ngrid)                     ! fraction of day
+
+!     Globally varying aerosol optical properties on GCM grid
+!     Not needed everywhere so not in radcommon_h
+      REAL :: QVISsQREF3d(ngridmx,nlayermx,L_NSPECTV,naerkind)
+      REAL :: omegaVIS3d(ngridmx,nlayermx,L_NSPECTV,naerkind)
+      REAL :: gVIS3d(ngridmx,nlayermx,L_NSPECTV,naerkind)
+
+      REAL :: QIRsQREF3d(ngridmx,nlayermx,L_NSPECTI,naerkind)
+      REAL :: omegaIR3d(ngridmx,nlayermx,L_NSPECTI,naerkind)
+      REAL :: gIR3d(ngridmx,nlayermx,L_NSPECTI,naerkind)
+
+      REAL :: QREFvis3d(ngridmx,nlayermx,naerkind)
+      REAL :: QREFir3d(ngridmx,nlayermx,naerkind)
+
+!      REAL :: omegaREFvis3d(ngridmx,nlayermx,naerkind)
+!      REAL :: omegaREFir3d(ngridmx,nlayermx,naerkind) ! not sure of the point of these...
+
+      REAL reffrad(ngrid,nlayer,naerkind)
+      REAL nueffrad(ngrid,nlayer,naerkind)
+
+!     OUTPUT
+      REAL dtsw(ngridmx,nlayermx) ! heating rate (K/s) due to SW
+      REAL dtlw(ngridmx,nlayermx) ! heating rate (K/s) due to LW
+      REAL fluxsurf_lw(ngridmx)   ! incident LW flux to surf (W/m2)
+      REAL fluxtop_lw(ngridmx)    ! outgoing LW flux to space (W/m2)
+      REAL fluxsurf_sw(ngridmx)   ! incident SW flux to surf (W/m2)
+      REAL fluxabs_sw(ngridmx)    ! SW flux absorbed by planet (W/m2)
+      REAL fluxtop_dn(ngridmx)    ! incident top of atmosphere SW flux (W/m2)
+
+!-----------------------------------------------------------------------
+!     Declaration of the variables required by correlated-k subroutines
+!     Numbered from top to bottom unlike in the GCM!
+
+      REAL*8 tmid(L_LEVELS),pmid(L_LEVELS)
+      REAL*8 tlevrad(L_LEVELS),plevrad(L_LEVELS)
+
+!     Optical values for the optci/cv subroutines
+      REAL*8 stel(L_NSPECTV),stel_fract(L_NSPECTV)
+      REAL*8 dtaui(L_NLAYRAD,L_NSPECTI,L_NGAUSS)
+      REAL*8 dtauv(L_NLAYRAD,L_NSPECTV,L_NGAUSS)
+      REAL*8 cosbv(L_NLAYRAD,L_NSPECTV,L_NGAUSS)
+      REAL*8 cosbi(L_NLAYRAD,L_NSPECTI,L_NGAUSS)
+      REAL*8 wbari(L_NLAYRAD,L_NSPECTI,L_NGAUSS)
+      REAL*8 wbarv(L_NLAYRAD,L_NSPECTV,L_NGAUSS)
+      REAL*8 tauv(L_NLEVRAD,L_NSPECTV,L_NGAUSS)
+      REAL*8 taucumv(L_LEVELS,L_NSPECTV,L_NGAUSS)
+      REAL*8 taucumi(L_LEVELS,L_NSPECTI,L_NGAUSS)
+
+      REAL*8 tauaero(L_LEVELS+1,naerkind)
+      REAL*8 nfluxtopv,nfluxtopi,nfluxtop
+      real*8 NFLUXTOPV_nu(L_NSPECTV)
+      real*8 NFLUXTOPI_nu(L_NSPECTI)
+      real*8 fluxupi_nu(L_NLAYRAD,L_NSPECTI) ! for 1D diagnostic
+      REAL*8 fmneti(L_NLAYRAD),fmnetv(L_NLAYRAD)
+      REAL*8 fluxupv(L_NLAYRAD),fluxupi(L_NLAYRAD)
+      REAL*8 fluxdnv(L_NLAYRAD),fluxdni(L_NLAYRAD)
+      REAL*8 albi,albv,acosz
+
+      INTEGER ig,l,k,nw,iaer,irad
+
+      real fluxtoplanet
+      real*8 taugsurf(L_NSPECTV,L_NGAUSS-1)
+      real*8 taugsurfi(L_NSPECTI,L_NGAUSS-1)
+
+      real*8 qvar(L_LEVELS)          ! mixing ratio of variable component
+      REAL pq(ngridmx,nlayer,nq)
+      REAL qsurf(ngridmx,nqmx)       ! tracer on surface (e.g. kg.m-2)
+      integer nq
+
+!     Local aerosol optical properties for each column on RADIATIVE grid
+      real*8  QXVAER(L_LEVELS+1,L_NSPECTV,naerkind)
+      real*8  QSVAER(L_LEVELS+1,L_NSPECTV,naerkind)
+      real*8  GVAER(L_LEVELS+1,L_NSPECTV,naerkind)
+      real*8  QXIAER(L_LEVELS+1,L_NSPECTI,naerkind)
+      real*8  QSIAER(L_LEVELS+1,L_NSPECTI,naerkind)
+      real*8  GIAER(L_LEVELS+1,L_NSPECTI,naerkind)
+
+      save qxvaer, qsvaer, gvaer
+      save qxiaer, qsiaer, giaer
+      save QREFvis3d, QREFir3d 
+
+      REAL tau_col(ngrid) ! diagnostic from aeropacity
+
+!     Misc.
+      logical firstcall, lastcall, nantest
+      real*8  tempv(L_NSPECTV)
+      real*8  tempi(L_NSPECTI)
+      real*8  temp,temp1,temp2,pweight
+      character(len=10) :: tmp1
+      character(len=10) :: tmp2
+
+!     for fixed water vapour profiles
+      integer i_var
+      real RH
+      real*8 pq_temp(nlayer)
+      real ptemp, Ttemp, qsat
+
+!      real(KIND=r8) :: pq_temp(nlayer) ! better F90 way.. DOESNT PORT TO F77!!!
+
+!     for OLR spec
+      integer OLRcount
+      save OLRcount
+      integer OLRcount2
+      save OLRcount2
+      character(len=2)  :: tempOLR
+      character(len=30) :: filenomOLR
+      real ptime, pday
+      logical OLRz
+      real OLR_nu(ngrid,L_NSPECTI)
+
+      real GSR_nu(ngrid,L_NSPECTV)
+      real*8 NFLUXGNDV_nu(L_NSPECTV)
+
+!     for H2O cloud fraction in aeropacity
+      real cloudfrac(ngridmx,nlayermx)
+      real totcloudfrac(ngridmx)
+      logical clearsky
+
+!     Allow variations in cp with location
+      real cpp3D(ngridmx,nlayermx)   ! specific heat capacity at const. pressure
+
+      ! for weird cloud test
+      real pqtest(ngridmx,nlayer,nq)
+
+!     for Dave Crisp LBL data comparison
+      logical crisp
+
+!     are particle radii fixed?
+      logical radfixed
+      real maxrad, minrad
+
+      real CBRT
+      external CBRT
+
+      crisp=.false.
+      radfixed=.false.
+
+!=======================================================================
+!     Initialization on first call
+
+      qxvaer(:,:,:)=0.0
+      qsvaer(:,:,:)=0.0
+      gvaer(:,:,:) =0.0
+
+      qxiaer(:,:,:)=0.0
+      qsiaer(:,:,:)=0.0
+      giaer(:,:,:) =0.0
+
+      if(firstcall) then
+
+         call system('rm -f surf_vals_long.out')
+
+!--------------------------------------------------
+!     Effective radius and variance of the aerosols
+
+!     CO2 ice:
+         DO l=1,nlayer
+            DO ig=1,ngrid
+               reffrad(ig,l,1)  = 1.e-4
+               nueffrad(ig,l,1) = 0.1 
+!     these values will change once the microphysics gets to work
+!     UNLESS tracer=.false., in which case we should be working with
+!     a fixed aerosol layer, and be able to define reffrad in a 
+!     .def file. To be improved!
+            ENDDO
+         ENDDO
+
+!     H2O ice:
+         if(naerkind.eq.2)then
+            DO l=1,nlayer
+               DO ig=1,ngrid
+                  reffrad(ig,l,naerkind)  = 1.e-5
+                  nueffrad(ig,l,naerkind) = 0.1
+               ENDDO  
+            ENDDO
+         endif
+
+         print*, "Correlated-k data base folder:",datafile
+         call getin("corrkdir",corrkdir)
+         print*, "corrkdir = ",corrkdir
+         write( tmp1, '(i3)' ) L_NSPECTI
+         write( tmp2, '(i3)' ) L_NSPECTV
+         banddir=trim(adjustl(tmp1))//'x'//trim(adjustl(tmp2))
+         banddir=trim(adjustl(corrkdir))//'/'//trim(adjustl(banddir))
+
+         call sugas_corrk       ! set up gaseous absorption properties
+         call setspi            ! basic infrared properties
+         call setspv            ! basic visible properties
+         call suaer_corrk       ! set up aerosol optical properties
+
+         Cmk= 0.01 * 1.0 / (g * mugaz * 1.672621e-27) ! q_main=1.0 assumed
+
+         if((igcm_h2o_vap.eq.0) .and. varactive)then
+            print*,'varactive in callcorrk but no h2o_vap tracer.'
+            stop
+         endif
+
+         firstcall=.false.   
+
+      end if
+
+!=======================================================================
+!     Initialization on every call    
+
+      do l=1,nlayer
+         do ig=1,ngrid
+            do iaer=1,naerkind
+               nueffrad(ig,l,iaer) = 0.1 ! stays at 0.1
+            enddo
+         enddo
+      enddo
+
+
+      if(radfixed)then
+         do l=1,nlayer
+            do ig=1,ngrid
+               reffrad(ig,l,1)    = 5.e-5 ! CO2 ice
+            enddo
+         enddo
+         print*,'CO2 ice particle size = ',reffrad(1,1,1)/1.e-6,' um'
+         if(naerkind.ge.2)then
+            do l=1,nlayer
+               do ig=1,ngrid
+                  reffrad(ig,l,2) = 2.e-5 ! H2O ice
+               enddo
+            enddo
+            print*,'H2O ice particle size = ',reffrad(1,1,2)/1.e-6,' um'
+         endif
+         if(naerkind.eq.3)then
+            do l=1,nlayer
+               do ig=1,ngrid
+                  reffrad(ig,l,naerkind) = 2.e-6 ! dust
+               enddo
+            enddo
+            print*,'Dust particle size = ',reffrad(1,1,naerkind)/1.e-6,' um'
+         endif
+         if(naerkind.gt.3)then
+            print*,'Code not general enough to deal with naerkind > 3 yet.'
+            call abort
+         endif
+
+      else
+
+         maxrad=0.0
+         minrad=1.0
+         do l=1,nlayer
+            do ig=1,ngrid
+
+               if(tracer)then
+                  reffrad(ig,l,1) = CBRT( 3*pq(ig,l,igcm_co2_ice)/ &
+                       (4*Nmix_co2*pi*rho_co2) )
+               endif
+               reffrad(ig,l,1) = max(reffrad(ig,l,1),1.e-6)
+               reffrad(ig,l,1) = min(reffrad(ig,l,1),500.e-6)
+
+               maxrad = max(reffrad(ig,l,1),maxrad)
+               minrad = min(reffrad(ig,l,1),minrad)
+            enddo
+         enddo
+         if(igcm_co2_ice.gt.0)then
+            print*,'Max. CO2 ice particle size = ',maxrad/1.e-6,' um'
+            print*,'Min. CO2 ice particle size = ',minrad/1.e-6,' um'
+         endif
+
+         if((naerkind.ge.2).and.water)then
+            maxrad=0.0
+            minrad=1.0
+            do l=1,nlayer
+               do ig=1,ngrid
+                  reffrad(ig,l,2) = CBRT( 3*pq(ig,l,igcm_h2o_ice)/ &
+                       (4*Nmix_h2o*pi*rho_ice) )
+                  reffrad(ig,l,2) = max(reffrad(ig,l,2),1.e-6)
+                  reffrad(ig,l,2) = min(reffrad(ig,l,2),100.e-6)
+
+                  maxrad = max(reffrad(ig,l,2),maxrad)
+                  minrad = min(reffrad(ig,l,2),minrad)
+               enddo
+            enddo
+            print*,'Max. H2O ice particle size = ',maxrad/1.e-6,' um'
+            print*,'Min. H2O ice particle size = ',minrad/1.e-6,' um'
+         endif
+
+         if(naerkind.eq.3)then
+            do l=1,nlayer
+               do ig=1,ngrid
+                  reffrad(ig,l,naerkind) = 2.e-6 ! dust
+               enddo
+            enddo
+         endif
+
+      endif
+
+!     how much light we get
+      fluxtoplanet=0
+      do nw=1,L_NSPECTV
+         stel(nw)=stellarf(nw)/(dist_star**2)
+         fluxtoplanet=fluxtoplanet + stel(nw)
+      end do
+
+      call aeroptproperties(ngrid,nlayer,reffrad,nueffrad,         &
+           QVISsQREF3d,omegaVIS3d,gVIS3d,                          &
+           QIRsQREF3d,omegaIR3d,gIR3d,                             &
+           QREFvis3d,QREFir3d)                                     ! get 3D aerosol optical properties
+
+      call aeropacity(ngrid,nlayer,nq,pplay,pplev,pq,aerosol,      &
+           reffrad,QREFvis3d,QREFir3d,                             & 
+           tau_col,cloudfrac,totcloudfrac,clearsky)                ! get aerosol optical depths
+
+!-----------------------------------------------------------------------
+!     Starting Big Loop over every GCM column
+      do ig=1,ngridmx
+
+!=======================================================================
+!     Transformation of the GCM variables
+
+!-----------------------------------------------------------------------
+!     Aerosol optical properties Qext, Qscat and g
+!     The transformation in the vertical is the same as for temperature
+           
+!     shortwave
+            do iaer=1,naerkind
+               DO nw=1,L_NSPECTV 
+                  do l=1,nlayermx
+
+                     temp1=QVISsQREF3d(ig,nlayermx+1-l,nw,iaer)         &
+                         *QREFvis3d(ig,nlayermx+1-l,iaer)
+
+                     temp2=QVISsQREF3d(ig,max(nlayermx-l,1),nw,iaer)    &
+                         *QREFvis3d(ig,max(nlayermx-l,1),iaer)
+
+                     qxvaer(2*l,nw,iaer)  = temp1
+                     qxvaer(2*l+1,nw,iaer)=(temp1+temp2)/2
+
+                     temp1=temp1*omegavis3d(ig,nlayermx+1-l,nw,iaer)
+                     temp2=temp2*omegavis3d(ig,max(nlayermx-l,1),nw,iaer)
+
+                     qsvaer(2*l,nw,iaer)  = temp1
+                     qsvaer(2*l+1,nw,iaer)=(temp1+temp2)/2
+
+                     temp1=gvis3d(ig,nlayermx+1-l,nw,iaer)
+                     temp2=gvis3d(ig,max(nlayermx-l,1),nw,iaer)
+
+                     gvaer(2*l,nw,iaer)  = temp1
+                     gvaer(2*l+1,nw,iaer)=(temp1+temp2)/2
+
+                  end do
+
+                  qxvaer(1,nw,iaer)=qxvaer(2,nw,iaer)
+                  qxvaer(2*nlayermx+1,nw,iaer)=0.
+
+                  qsvaer(1,nw,iaer)=qsvaer(2,nw,iaer)
+                  qsvaer(2*nlayermx+1,nw,iaer)=0.
+
+                  gvaer(1,nw,iaer)=gvaer(2,nw,iaer)
+                  gvaer(2*nlayermx+1,nw,iaer)=0.
+
+               end do
+
+
+!     longwave
+               DO nw=1,L_NSPECTI 
+                  do l=1,nlayermx
+
+                     temp1=QIRsQREF3d(ig,nlayermx+1-l,nw,iaer)         &
+                          *QREFir3d(ig,nlayermx+1-l,iaer)
+
+                     temp2=QIRsQREF3d(ig,max(nlayermx-l,1),nw,iaer)    &
+                          *QREFir3d(ig,max(nlayermx-l,1),iaer)
+
+                     qxiaer(2*l,nw,iaer)  = temp1
+                     qxiaer(2*l+1,nw,iaer)=(temp1+temp2)/2
+
+                     temp1=temp1*omegair3d(ig,nlayermx+1-l,nw,iaer)
+                     temp2=temp2*omegair3d(ig,max(nlayermx-l,1),nw,iaer)
+
+                     qsiaer(2*l,nw,iaer)  = temp1
+                     qsiaer(2*l+1,nw,iaer)=(temp1+temp2)/2
+
+                     temp1=gir3d(ig,nlayermx+1-l,nw,iaer)
+                     temp2=gir3d(ig,max(nlayermx-l,1),nw,iaer)
+
+                     giaer(2*l,nw,iaer)  = temp1
+                     giaer(2*l+1,nw,iaer)=(temp1+temp2)/2
+
+                  end do
+
+                  qxiaer(1,nw,iaer)=qxiaer(2,nw,iaer)
+                  qxiaer(2*nlayermx+1,nw,iaer)=0.
+
+                  qsiaer(1,nw,iaer)=qsiaer(2,nw,iaer)
+                  qsiaer(2*nlayermx+1,nw,iaer)=0.
+
+                  giaer(1,nw,iaer)=giaer(2,nw,iaer)
+                  giaer(2*nlayermx+1,nw,iaer)=0.
+
+               end do
+            end do
+
+
+            ! test / correct for freaky s. s. albedo values
+            do iaer=1,naerkind
+               do k=1,L_LEVELS+1
+
+                  do nw=1,L_NSPECTV
+                     if(qsvaer(k,nw,iaer).gt.1.05*qxvaer(k,nw,iaer))then
+                        print*,'Serious problems with qsvaer values in callcorrk'
+                        call abort
+                     endif
+                     if(qsvaer(k,nw,iaer).gt.qxvaer(k,nw,iaer))then
+                        qsvaer(k,nw,iaer)=qxvaer(k,nw,iaer)
+                     endif
+                  end do
+
+                  do nw=1,L_NSPECTI 
+                     if(qsiaer(k,nw,iaer).gt.1.05*qxiaer(k,nw,iaer))then
+                        print*,'Serious problems with qsiaer values in callcorrk'
+                        call abort
+                     endif
+                     if(qsiaer(k,nw,iaer).gt.qxiaer(k,nw,iaer))then
+                        qsiaer(k,nw,iaer)=qxiaer(k,nw,iaer)
+                     endif
+                  end do
+
+               end do
+            end do
+
+!-----------------------------------------------------------------------
+!     Aerosol optical depths
+            
+         do iaer=1,naerkind     ! a bug was here           
+            do k=0,nlayer-1
+               
+               pweight=(pplay(ig,L_NLAYRAD-k)-pplev(ig,L_NLAYRAD-k+1))/   &
+                        (pplev(ig,L_NLAYRAD-k)-pplev(ig,L_NLAYRAD-k+1))
+
+               temp=aerosol(ig,L_NLAYRAD-k,iaer)/QREFvis3d(ig,L_NLAYRAD-k,iaer)
+
+               tauaero(2*k+2,iaer)=max(temp*pweight,0.0)
+               tauaero(2*k+3,iaer)=max(temp-tauaero(2*k+2,iaer),0.0)
+!
+            end do
+            ! boundary conditions
+            tauaero(1,iaer)          = tauaero(2,iaer)
+            tauaero(L_LEVELS+1,iaer) = tauaero(L_LEVELS,iaer)
+            !tauaero(1,iaer)          = 0.
+            !tauaero(L_LEVELS+1,iaer) = 0.
+         end do
+         !print*,'Note changed tauaero BCs in callcorrk!'
+
+!     Albedo and emissivity
+         albi=1-emis(ig)        ! longwave
+         albv=albedo(ig)        ! shortwave 
+
+      if(noradsurf.and.(albv.gt.0.0))then
+         print*,'For open lower boundary in callcorrk must'
+         print*,'have surface albedo set to zero!'
+         call abort
+      endif
+
+      if(ngridmx.eq.1) then       ! fixed zenith angle in 1D
+         acosz = cos(pi*szangle/180.0)
+         !acosz=mu0(ig)
+         !print*,'oned SZ angle OVERRIDE in callcorrk'
+         print*,'acosz=',acosz,', szangle=',szangle
+      else
+         acosz=mu0(ig)          ! cosine of sun incident angle
+      endif
+
+!-----------------------------------------------------------------------
+!     Water vapour (to be generalised / ignored for other planets)
+      
+      if(varactive) then
+
+         i_var=igcm_h2o_vap
+
+         do l=1,nlayer
+
+            qvar(2*l)   = pq(ig,nlayer+1-l,i_var)
+            qvar(2*l+1) = (pq(ig,nlayer+1-l,i_var)+pq(ig,max(nlayer-l,1),i_var))/2    
+            ! Average approximation as for temperature...
+
+         end do
+         qvar(1)=qvar(2)
+         qvar(2*nlayermx+1)=qsurf(ig,i_var)
+
+      elseif(varfixed)then
+
+         do l=1,nlayermx        ! here we will assign fixed water vapour profiles globally
+            RH = satval * ((pplay(ig,l)/pplev(ig,1) - 0.02) / 0.98)
+            if(RH.lt.0.0) RH=0.0
+            
+            ptemp=pplay(ig,l)
+            Ttemp=pt(ig,l)
+            call watersat(Ttemp,ptemp,qsat)
+
+            !pq_temp(l) = qsat      ! fully saturated everywhere
+            pq_temp(l) = RH * qsat ! ~realistic profile (e.g. 80% saturation at ground)
+         end do
+         
+         do l=1,nlayer
+            qvar(2*l)   = pq_temp(nlayer+1-l)
+            qvar(2*l+1) = (pq_temp(nlayer+1-l)+pq_temp(max(nlayer-l,1)))/2
+         end do
+         qvar(1)=qvar(2)
+
+         ! Lowest layer of atmosphere
+         RH = satval * (1 - 0.02) / 0.98
+         if(RH.lt.0.0) RH=0.0
+
+         ptemp = pplev(ig,1)
+         Ttemp = tsurf(ig)
+         call watersat(Ttemp,ptemp,qsat)
+
+         !qvar(2*nlayermx+1)=qsat      ! fully saturated everywhere
+         qvar(2*nlayermx+1)= RH * qsat ! ~realistic profile (e.g. 80% saturation at ground)
+
+      else
+         do k=1,L_LEVELS
+            qvar(k) = 1.0D-7
+         end do
+      end if
+
+      ! Now convert from kg/kg to mol/mol
+      do k=1,L_LEVELS
+         qvar(k) = qvar(k)/epsi
+      end do
+
+      ! Keep values inside limits for which we have radiative transfer coefficients
+      if(L_REFVAR.gt.1)then ! there was a bug here!
+         do k=1,L_LEVELS
+            if(qvar(k).lt.wrefvar(1))then
+               qvar(k)=wrefvar(1)+1.0e-8
+            elseif(qvar(k).gt.wrefvar(L_REFVAR))then
+               qvar(k)=wrefvar(L_REFVAR)-1.0e-8
+            endif
+         end do
+      endif
+
+!-----------------------------------------------------------------------
+!     Pressure and temperature
+
+      DO l=1,nlayer
+         plevrad(2*l)   = pplay(ig,nlayer+1-l)/scalep
+         plevrad(2*l+1) = pplev(ig,nlayer+1-l)/scalep
+         tlevrad(2*l)   = pt(ig,nlayer+1-l)
+         tlevrad(2*l+1) = (pt(ig,nlayer+1-l)+pt(ig,max(nlayer-l,1)))/2
+      END DO
+      
+      plevrad(1) = 0
+      plevrad(2) = max(pgasmin,0.0001*plevrad(3))
+
+      tlevrad(1) = tlevrad(2)
+      tlevrad(2*nlayermx+1)=tsurf(ig)
+      
+
+      if(crisp)then
+         open(111,file='/u/rwlmd/CrispLBL/p.dat')
+         open(112,file='/u/rwlmd/CrispLBL/T.dat')
+         do k=1,L_LEVELS
+            read(111,*) plevrad(k)
+            read(112,*) tlevrad(k)
+            plevrad(k)=plevrad(k)*1000.0
+         enddo
+         close(111)
+         close(112)
+      endif
+
+      tmid(1) = tlevrad(2)
+      tmid(2) = tlevrad(2)
+      pmid(1) = plevrad(2)
+      pmid(2) = plevrad(2)
+      
+      DO l=1,L_NLAYRAD-1
+         tmid(2*l+1) = tlevrad(2*l+1)
+         tmid(2*l+2) = tlevrad(2*l+1)
+         pmid(2*l+1) = plevrad(2*l+1)
+         pmid(2*l+2) = plevrad(2*l+1)
+      END DO
+      pmid(L_LEVELS) = plevrad(L_LEVELS)
+      tmid(L_LEVELS) = tlevrad(L_LEVELS)
+
+
+      ! test for out-of-bounds pressure
+      if(plevrad(3).lt.pgasmin)then
+         print*,'Minimum pressure is outside the radiative'
+         print*,'transfer kmatrix bounds, exiting.'
+         call abort
+      elseif(plevrad(L_LEVELS).gt.pgasmax)then
+         print*,'Maximum pressure is outside the radiative'
+         print*,'transfer kmatrix bounds, exiting.'
+         call abort
+      endif
+
+      ! test for out-of-bounds temperature
+      do k=1,L_LEVELS
+         if(tlevrad(k).lt.tgasmin)then
+            print*,'Minimum temperature is outside the radiative'
+            print*,'transfer kmatrix bounds, exiting.'
+            !print*,'WARNING, OVERRIDING FOR TEST'
+            call abort
+         elseif(tlevrad(k).gt.tgasmax)then
+            print*,'Maximum temperature is outside the radiative'
+            print*,'transfer kmatrix bounds, exiting.'
+            !print*,'WARNING, OVERRIDING FOR TEST'
+            call abort
+         endif
+      enddo
+
+!=======================================================================
+!     Calling the main radiative transfer subroutines
+
+
+!-----------------------------------------------------------------------
+!     Shortwave
+
+         if(fract(ig) .ge. 1.0e-4) then ! only during daylight!
+
+            fluxtoplanet=0.
+
+            if((ngridmx.eq.1).and.(.not.(diurnal.or.tlocked)))then
+               do nw=1,L_NSPECTV
+                  stel_fract(nw)= stel(nw) * 0.25 / acosz
+                  fluxtoplanet=fluxtoplanet + stel_fract(nw)
+                                ! globally averaged = divide by 4
+                                ! but we correct for solar zenith angle
+               end do
+            else
+               do nw=1,L_NSPECTV
+                  stel_fract(nw)= stel(nw) * fract(ig)
+                  fluxtoplanet=fluxtoplanet + stel_fract(nw)
+               end do
+            endif
+
+            call optcv(dtauv,tauv,taucumv,plevrad,                 &
+                 qxvaer,qsvaer,gvaer,wbarv,cosbv,tauray,tauaero,   &
+                 tmid,pmid,taugsurf,qvar)
+
+
+            call sfluxv(dtauv,tauv,taucumv,albv,dwnv,wbarv,cosbv,  &
+                 acosz,stel_fract,gweight,nfluxtopv,nfluxgndv_nu,  &
+                 fmnetv,fluxupv,fluxdnv,fzerov,taugsurf)
+
+         else                          ! during the night, fluxes = 0
+            nfluxtopv=0.0
+            do l=1,L_NLAYRAD
+               fmnetv(l)=0.0
+               fluxupv(l)=0.0
+               fluxdnv(l)=0.0
+            end do
+         end if
+
+	!print*,'taugsurf=',taugsurf(:,L_NGAUSS-1)
+
+
+!-----------------------------------------------------------------------
+!     Longwave
+
+         call optci(plevrad,tlevrad,dtaui,taucumi,                  &
+              qxiaer,qsiaer,giaer,cosbi,wbari,tauaero,tmid,pmid,    &
+              taugsurfi,qvar)
+
+         call sfluxi(plevrad,tlevrad,dtaui,taucumi,ubari,albi,      &
+              wnoi,dwni,cosbi,wbari,gweight,nfluxtopi,nfluxtopi_nu, & 
+              fmneti,fluxupi,fluxdni,fluxupi_nu,fzeroi,taugsurfi)
+
+!-----------------------------------------------------------------------
+!     Transformation of the correlated-k code outputs
+!     (into dtlw, dtsw, fluxsurf_lw, fluxsurf_sw, fluxtop_lw, fluxtop_sw)
+
+!     Flux incident at the top of the atmosphere
+         fluxtop_dn(ig)=fluxdnv(1)
+
+         fluxtop_lw(ig)  = real(nfluxtopi)
+         fluxabs_sw(ig)  = real(-nfluxtopv)
+         fluxsurf_lw(ig) = real(fluxdni(L_NLAYRAD))
+         fluxsurf_sw(ig) = real(fluxdnv(L_NLAYRAD))
+
+         if(fluxtop_dn(ig).lt.0.0)then
+            print*,'Achtung! fluxtop_dn has lost the plot!'
+            print*,'fluxtop_dn=',fluxtop_dn(ig)
+            print*,'acosz=',acosz
+            print*,'aerosol=',aerosol(ig,:,:)
+            print*,'temp=   ',pt(ig,:)
+            print*,'pplay=  ',pplay(ig,:)
+            call abort
+         endif
+
+         if(crisp)then
+            open(111,file='/u/rwlmd/CrispLBL/GCMfluxdn.dat')
+            open(112,file='/u/rwlmd/CrispLBL/GCMfluxup.dat')
+            do k=1,L_NLAYRAD
+               write(111,*) fluxdni(k)
+               write(112,*) fluxupi(k)
+            enddo
+            close(111)
+            close(112)
+            print*,'fluxdni',fluxdni
+            print*,'fluxupi',fluxupi
+            call abort
+         endif
+
+!     Spectral output, for exoplanet observational comparison
+         if(specOLR)then
+            do nw=1,L_NSPECTI 
+               OLR_nu(ig,nw)=nfluxtopi_nu(nw)
+            end do
+            do nw=1,L_NSPECTV 
+               GSR_nu(ig,nw)=nfluxgndv_nu(nw)
+            end do
+         endif
+
+!     Finally, the heating rates
+         if(nonideal)then
+
+            DO l=2,L_NLAYRAD
+               dtsw(ig,L_NLAYRAD+1-l)=(fmnetv(l)-fmnetv(l-1))  &
+                    *g/(cpp3D(ig,L_NLAYRAD+1-l)                &
+                    *scalep*(plevrad(2*l+1)-plevrad(2*l-1)))
+               dtlw(ig,L_NLAYRAD+1-l)=(fmneti(l)-fmneti(l-1))  &
+                    *g/(cpp3D(ig,L_NLAYRAD+1-l)                &
+                    *scalep*(plevrad(2*l+1)-plevrad(2*l-1)))           
+            END DO      
+
+!     These are values at top of atmosphere
+            dtsw(ig,L_NLAYRAD)=(fmnetv(1)-nfluxtopv)           &
+                 *g/(cpp3D(ig,L_NLAYRAD)*scalep*(plevrad(3)-plevrad(1)))
+            dtlw(ig,L_NLAYRAD)=(fmneti(1)-nfluxtopi)           &
+                 *g/(cpp3D(ig,L_NLAYRAD)*scalep*(plevrad(3)-plevrad(1)))
+
+         else
+
+            DO l=2,L_NLAYRAD
+               dtsw(ig,L_NLAYRAD+1-l)=(fmnetv(l)-fmnetv(l-1))  &
+                   *g/(cpp*scalep*(plevrad(2*l+1)-plevrad(2*l-1)))
+               dtlw(ig,L_NLAYRAD+1-l)=(fmneti(l)-fmneti(l-1))  &
+                   *g/(cpp*scalep*(plevrad(2*l+1)-plevrad(2*l-1)))
+            END DO      
+
+!     These are values at top of atmosphere
+            dtsw(ig,L_NLAYRAD)=(fmnetv(1)-nfluxtopv)           &
+                *g/(cpp*scalep*(plevrad(3)-plevrad(1)))
+            dtlw(ig,L_NLAYRAD)=(fmneti(1)-nfluxtopi)           &
+                *g/(cpp*scalep*(plevrad(3)-plevrad(1)))
+
+         endif
+
+!     ---------------------------------------------------------------
+      end do                    ! end of big loop over every GCM column (ig = 1:ngrid)
+
+
+!-----------------------------------------------------------------------
+!     Additional diagnostics
+
+!     IR spectral output, for exoplanet observational comparison
+      if(specOLR)then
+        if(ngrid.ne.1)then
+          call writediagspec(ngrid,"OLR3D","OLR(lon,lat,band)","W m^-2",3,OLR_nu)
+!          call writediagspec(ngrid,"OSR3D","OSR(lon,lat,band)","W m^-2",3,OSR_nu)
+        endif
+      endif
+
+      if(ngrid.eq.1)then
+         open(113,file='surf_vals_long.out',ACCESS='append')
+         write(113,*) tsurf(1),fluxtop_dn(1),         &
+              real(-nfluxtopv),real(nfluxtopi) 
+         close(113)
+      endif
+
+      !if(kastprof)then ! for kasthop only
+
+        if(ngrid.eq.1)then
+
+           print*,'Saving tsurf,psurf in surf_vals.out...'
+           open(116,file='surf_vals.out')
+           write(116,*) tsurf(1),pplev(1,1),fluxtop_dn(1),         &
+                real(-nfluxtopv),real(nfluxtopi) 
+           close(116)
+
+           if(specOLR)then
+               open(117,file='OLRnu.out')
+               do nw=1,L_NSPECTI
+                  write(117,*) OLR_nu(1,nw)
+               enddo
+               close(117)
+
+               open(127,file='GSRnu.out')
+               do nw=1,L_NSPECTV
+                  write(127,*) GSR_nu(1,nw)
+               enddo
+               close(127)
+           endif
+
+!     mixing ratio: CO2 ice particles
+           if(igcm_co2_ice.ne.0)then
+              open(122,file='qCO2ice.out')
+              do l=1,L_NLAYRAD
+                 write(122,*) pq(1,l,igcm_co2_ice)
+              enddo
+              close(122)
+           endif
+
+!     mixing ratio: H2O vapour
+           if(igcm_h2o_vap.ne.0)then
+              open(123,file='qH2Ovap.out')
+              do l=1,L_NLAYRAD
+                 write(123,*) pq(1,l,igcm_h2o_vap)
+              enddo
+              close(123)
+           endif
+
+!     OLR vs altitude: do it as a .txt file
+           OLRz=.false.
+           if(OLRz)then
+              print*,'saving IR vertical flux for OLRz...'
+              open(118,file='OLRz_plevs.out')
+              open(119,file='OLRz.out')
+              do l=1,L_NLAYRAD
+                 write(118,*) plevrad(2*l)
+                 do nw=1,L_NSPECTI
+                     write(119,*) fluxupi_nu(l,nw) 
+                  enddo
+              enddo 
+              close(118)
+              close(119)
+           endif
+        endif
+
+      !endif
+
+    end subroutine callcorrk
Index: /trunk/LMDZ.GENERIC/libf/phystd/callkeys.h
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/callkeys.h	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/callkeys.h	(revision 253)
@@ -3,26 +3,25 @@
 ! symbols '&' in columns 73 and 6
 !
-      COMMON/callkeys/callrad,corrk,calldifv,calladj,                   &
-     &   co2cond,callsoil,                                              &
-     &   season,diurnal,tlocked,iradia,lwrite,calllott                  &
-     &   ,iaervar,iddist,topdustref,callstats,calleofdump               &
-     &   ,enertest                                                      &
-     &   ,callgasvis,callnlte,callthermos,callconduct,                  &
-     &        calleuv,callmolvis,callmoldiff,thermochem                 &
-     &   , solarcondate, Nmix_co2, Nmix_h2o, thermoswater               &
-     &   , semi                                                         &
-     &   , callemis                                                     &
-     &   , callg2d                                                      &
-     &   , linear                                                       &
-     &   , ilwd                                                         &
-     &   , ilwb                                                         &
-     &   , ilwn                                                         &
-     &   , ncouche                                                      &
-     &   , alphan                                                       &
+      COMMON/callkeys/callrad,corrk,calldifv,calladj                    &
+     &   , co2cond,callsoil                                             &
+     &   , season,diurnal,tlocked,iradia,lwrite                         &
+     &   , iaervar,iddist,topdustref,callstats,calleofdump              &
+     &   , enertest                                                     &
+     &   , callgasvis                                                   &
+     &   , Nmix_co2, Nmix_h2o                                           &
+     &   , dusttau                                                      &
      &   , nonideal                                                     &
      &   , meanOLR                                                      &
      &   , specOLR                                                      &
+     &   , kastprof                                                     &
+     &   , noradsurf                                                    &
+     &   , Tsurfk                                                       &
+     &   , Tstrat                                                       &
+     &   , newtonian                                                    &
+     &   , tau_relax                                                    &
+     &   , testradtimes                                                 &
      &   , rayleigh                                                     &
-     &   , ozone                                                        &
+     &   , stelbbody                                                    &
+     &   , stelTbb                                                      &
      &   , tplanet                                                      &
      &   , startype                                                     &
@@ -36,20 +35,30 @@
      &   , rainthreshold                                                &
      &   , aerofixed                                                    &
-     &   , photochem,nqchem_min                                         
+     &   , szangle                                                      &
+     &   , hydrology                                                    &
+     &   , sourceevol                                                   &
+     &   , albedosnow                                                   &
+     &   , maxicethick                                                  &
+     &   , Tsaldiff                                                     &
+     &   , CLFfixval                                                    &
+     &   , CLFvarying                                                   &
+     &   , n2mixratio                                                   &
+     &   , co2supsat                                                    &
+     &   , pceil                                                    
 
-      logical callrad,corrk,calldifv,calladj,co2cond,callsoil,          &
-     &   season,diurnal,tlocked,lwrite,calllott                         &
-     &   ,callstats,calleofdump                                         &
-     &   ,callgasvis,callnlte,callthermos,callconduct,                  &
-     &    calleuv,callmolvis,callmoldiff,thermochem,thermoswater
+      logical callrad,corrk,calldifv,calladj,co2cond,callsoil           &
+     &   , season,diurnal,tlocked,lwrite                                &
+     &   , callstats,calleofdump                                        &
+     &   , callgasvis
 
       logical enertest
-      logical callemis
-      logical callg2d
-      logical linear
       logical nonideal
       logical meanOLR
       logical specOLR
+      logical kastprof
+      logical newtonian
+      logical testradtimes
       logical rayleigh
+      logical stelbbody
       logical ozone
       logical nearco2cond
@@ -60,25 +69,32 @@
       logical water,watercond,waterrain
       logical aerofixed
-      logical photochem
+      logical hydrology
+      logical sourceevol
+      logical CLFvarying
+      logical noradsurf
 
       integer iddist
       integer iaervar
       integer iradia
-      integer ilwd
-      integer ilwb
-      integer ilwn
-      integer ncouche
-      integer dustbin
       integer startype
-      integer nqchem_min
 
       real topdustref
-      real semi
-      real alphan
-      real solarcondate
       real Nmix_co2
       real Nmix_h2o
+      real dusttau
       real Fat1AU
+      real stelTbb
+      real Tstrat
       real tplanet
       real satval
       real rainthreshold
+      real szangle
+      real CLFfixval
+      real n2mixratio
+      real co2supsat
+      real pceil
+      real albedosnow
+      real maxicethick
+      real Tsaldiff
+      real Tsurfk
+      real tau_relax
Index: /trunk/LMDZ.GENERIC/libf/phystd/callsedim.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/callsedim.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/callsedim.F	(revision 253)
@@ -1,5 +1,5 @@
       SUBROUTINE callsedim(ngrid,nlay, ptimestep,
      $                pplev,zlev, pt,
-     &                pq, pdqfi, pdqsed,pdqs_sed,nq)
+     &                pq, pdqfi, pdqsed,pdqs_sed,nq,rfall)
       IMPLICIT NONE
 
@@ -29,5 +29,5 @@
 
 #include "fisice.h"
-c
+
 c   arguments:
 c   ----------
@@ -84,5 +84,4 @@
 !     (mass (kg.m-2), thickness (m), etc.
 
-
       do  l=1,nlay
         do ig=1, ngrid
@@ -92,6 +91,5 @@
       end do
 
-      do iq=1,nq
-        if(radius(iq).gt.1.e-9) then   ! no sedimentation for gases (defined by radius=0)
+      iq=igcm_h2o_ice
 
 !     The value of q is updated after the other parameterisations
@@ -101,27 +99,14 @@
               ! store locally updated tracers
               zqi(ig,l)=pq(ig,l,iq)+pdqfi(ig,l,iq)*ptimestep
-!              if (iceparty.and.(iq.eq.igcm_h2o_ice)) then
-              if (iq.eq.igcm_h2o_ice) then
-c               On affecte un rayon moyen aux poussieres a chaque altitude du type :
-c               r(z)=r0*exp(-z/H) avec r0=0.8 micron et H=18 km.
-c               ''''''''''''''''''''''''''''''''''''''''''''''''
-                rfall(ig,l)=max( rice(ig,l)*1.5,rdust(ig,l) )
-c modif FranckMM pour ameliorer cycle H2O: rfall= 20 microns
-                rfall(ig,l)=min(rfall(ig,l),1.e-4)
-              endif
             enddo
           enddo ! of do l=1,nlay
+
+
 
 !=======================================================================
 !     Calculate the transport due to sedimentation for each tracer
 
-          if (iq.eq.igcm_h2o_ice) then
-          !if (iceparty.and.(iq.eq.igcm_h2o_ice)) then
-            call newsedim(ngrid,nlay,ngrid*nlay,ptimestep,
-     &      pplev,masse,epaisseur,pt,rfall,rho_q(iq),zqi,wq)
-          else
-            call newsedim(ngrid,nlay,1,ptimestep,
-     &      pplev,masse,epaisseur,pt,radius(iq),rho_q(iq),zqi,wq)
-          endif
+          call newsedim(ngrid,nlay,ngrid*nlay,ptimestep,
+     &         pplev,masse,epaisseur,pt,rfall,rho_q(iq),zqi,wq)
 
 !=======================================================================
@@ -140,8 +125,5 @@
           ENDDO
 
-        endif ! of if(radius(iq).gt.1.e-9)
-      enddo ! of do iq=1,nq
- 
-      RETURN
-      END
+      return
+      end
 
Index: unk/LMDZ.GENERIC/libf/phystd/co2snow.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/co2snow.F	(revision 252)
+++ 	(revision )
@@ -1,140 +1,0 @@
-      SUBROUTINE co2snow (ngrid,nlayer,ptimestep,emisref,condsub,pplev,
-     &        pcondicea,pcondices,pfallice,pemisurf)
-
-       IMPLICIT NONE
-
-c=======================================================================
-c     Program for simulate the impact of the CO2 snow fall on
-c     the surface infrared emission (emissivity)  and on 
-c     the airborne dust
-c     F.Forget 1996
-c=======================================================================
-
-c Declarations
-c ------------
-
-#include "dimensions.h"
-#include "dimphys.h"
-#include "comcstfi.h"
-#include "surfdat.h"
-#include "callkeys.h"
-
-c     input
-c     -----
-
-      INTEGER ngrid,nlayer
-      REAL ptimestep , emisref(ngrid) ! grd or ice  emissivity without snow
-      logical condsub(ngrid)
-
-      REAL pplev(ngrid,nlayer+1)
-      REAL pcondicea(ngrid,nlayer), pcondices(ngrid)
-      REAL pfallice(ngrid,nlayer+1)
-
-c     output
-c     ------
-
-      REAL pemisurf(ngrid)
-
-c     local
-c     -----
-      integer ig , l , icap
-
-      REAL zdemisurf ,dtemis
-      REAL sumdaer
-
-c     saved
-c     -----
-      REAL Kscat(2), scaveng
-      LOGICAL firstcall
-      SAVE firstcall
-      save Kscat , scaveng
-      DATA firstcall/.true./
-
-c --------------
-c Initialisation
-c --------------
-
-      if (firstcall) then
-
-c   Kscat : coefficient for decreasing the surface emissivity
-c           =(0.001/3.)*alpha/iceradius ,
-c           with 0.3< alpha < 0.6, set to 0.45 (coeff from emis = f (tau))
-c           and iceradius the mean radius of the
-c           scaterring particles  (200.e-6<iceradius<10.e-6)
-
-            Kscat(1)=(0.001/3.)*0.45/iceradius(1)
-            Kscat(2)=(0.001/3.)*0.45/iceradius(2)
-
-c          Scavenging Ratio (dust concentration in the air / in the snow)
-           scaveng = 100.0
-           
-c          Collision Scavenging coefficient  (m2.kg-1)
-c          Csca  = 2.3  ! not used yet !!!!!!!!!!!
-           firstcall = .false.
-
-      end if
-
-
-c     LOOP on grid points
-c     -------------------
-      do ig=1,ngrid 
-         if (condsub(ig)) then
-
-c         IF (scavenging) then
-c          Airborne Dust 
-c          -------------
-c          sumdaer=0.
-c          do l=nlayer, 1, -1
-c             pdaerosol(ig,l)= -paerosol(ig,l,1)*
-c    &              (1-exp(-scaveng*pcondicea(ig,l)*ptimestep*g/
-c    &               (pplev(ig,l)-pplev(ig,l+1))))/ptimestep  
-
-c    &           - Csca*paerosol(ig,l,1) ! Scavenging by collision
-c    &           * 0.5*(pfallice(ig,l)) ! not included
-
-c             test to avoid releasing to much dust when subliming:
-c             if(pdaerosol(ig,l).gt.-sumdaer)pdaerosol(ig,l)=-sumdaer 
-c             sumdaer=sumdaer + pdaerosol(ig,l)
-
-c            if (-pdaerosol(ig,l)*ptimestep.gt.paerosol(ig,l,1)) then
-c                write(*,*) 'ds co2snow: aerosol < 0.0 !!!'
-c                write(*,*) 'ig =' , ig
-c            end if
-c          end do
-c         END IF
-
-c          Surface emissivity
-c          ------------------
-c   dtemis: Time scale for increasing the ice emissivity
-
-           IF(ig.GT.ngrid/2+1) THEN
-              icap=2
-           ELSE
-              icap=1
-           ENDIF
-
-           zdemisurf = 
-     &    (emisref(ig)-pemisurf(ig))/(dtemisice(icap)*daysec) 
-c Using directly the diferential equation:
-c    &       -Kscat(icap)*emisref(ig)*
-c    &      (pemisurf(ig)/emisref(ig))**4 *pfallice(ig,1) 
-c Using an integrated form for numerical safety instead
-     & +(emisref(ig)* ((pemisurf(ig)/emisref(ig))**(-3)+3.*Kscat(icap)*
-     & pfallice(ig,1)*ptimestep)**(-1/3.) -pemisurf(ig))/ptimestep   
-
-
-           pemisurf(ig) = pemisurf(ig) + zdemisurf*ptimestep 
-
-           if (pemisurf(ig).lt.0.1) then
-                 write(*,*) 'ds co2snow: emis < 0.1 !!!'
-                 write(*,*) 'ig =' , ig
-                 write(*,*)'pemisurf(ig)',pemisurf(ig)
-                 write(*,*) 'zdemisurf*ptimestep',zdemisurf*ptimestep
-           end if
-         else
-           pemisurf(ig) = emisref(ig)
-         end if
-      end do
-
-      return
-      end 
Index: /trunk/LMDZ.GENERIC/libf/phystd/comcstfi.h
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/comcstfi.h	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/comcstfi.h	(revision 253)
@@ -3,7 +3,7 @@
 
       common/comcstfi/pi,rad,g,r,cpp,rcp,dtphys,daysec,mugaz,omeg
-      common/comcstfi/avocado,molrad,visc
+      common/comcstfi/avocado!,molrad,visc
 
       real pi,rad,g,r,cpp,rcp,dtphys,daysec,mugaz,omeg
-      real avocado,molrad,visc
+      real avocado!,molrad,visc
 
Index: /trunk/LMDZ.GENERIC/libf/phystd/comdiurn.h
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/comdiurn.h	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/comdiurn.h	(revision 253)
@@ -1,5 +1,6 @@
-      COMMON/comdiurn/ldiurn,
-     s     sinlon(ngridmx),coslon(ngridmx),
-     s     sinlat(ngridmx),coslat(ngridmx)
-      REAL sinlon,coslon,sinlat,coslat
-      LOGICAL ldiurn
+      COMMON/comdiurn/ldiurn,                                           &
+     &     sinlon(ngridmx),coslon(ngridmx),                             &
+     &     sinlat(ngridmx),coslat(ngridmx)
+      
+      real sinlon,coslon,sinlat,coslat
+      logical ldiurn
Index: /trunk/LMDZ.GENERIC/libf/phystd/comg1d.h
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/comg1d.h	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/comg1d.h	(revision 253)
@@ -1,27 +1,27 @@
-c.......................................................................
-c  le COMMON pour GRADS-1D
-c  (Utilise pour les sorties format Grads dans la version 1D du modele)
-c
-c  on peut se dire : "on ne sauvera pas plus de 1000 variables ... hein ?"
-c
+!.......................................................................
+!  le COMMON pour GRADS-1D
+!  (Utilise pour les sorties format Grads dans la version 1D du modele)
+!
+!  on peut se dire : "on ne sauvera pas plus de 1000 variables ... hein ?"
+!
       INTEGER g1d_nvarmx
       PARAMETER(g1d_nvarmx=1000)
-c
-c         * g1d_nlayer     ---> nombre de couches verticales
-c         * g1d_nomfich    ---> nom du fichier grads
-c         * g1d_unitfich   ---> code du fichier grads
-c         * g1d_nomctl     ---> nom du fichier ctl
-c         * g1d_unitctl    ---> code du fichier ctl
-c         * g1d_premier    ---> variable logique pour dire si le fichier
-c                               est deja ouvert
-c         * g1d_irec       ---> indice de derniere ecriture
-c         * g1d_nvar       ---> nombre de variables deja definies a la
-c                               derniere ecriture
-c         * g1d_nomvar     ---> noms des vecteurs existants
-c         * g1d_dimvar     ---> taille des vecteurs
-c         * g1d_titrevar   ---> titres des vecteurs
-c         * g1d_tmp1       ---> caractere 
-c         * g1d_tmp2       ---> caractere 
-c
+
+!         * g1d_nlayer     ---> nombre de couches verticales
+!         * g1d_nomfich    ---> nom du fichier grads
+!         * g1d_unitfich   ---> code du fichier grads
+!         * g1d_nomctl     ---> nom du fichier ctl
+!         * g1d_unitctl    ---> code du fichier ctl
+!         * g1d_premier    ---> variable logique pour dire si le fichier
+!                               est deja ouvert
+!         * g1d_irec       ---> indice de derniere ecriture
+!         * g1d_nvar       ---> nombre de variables deja definies a la
+!                               derniere ecriture
+!         * g1d_nomvar     ---> noms des vecteurs existants
+!         * g1d_dimvar     ---> taille des vecteurs
+!         * g1d_titrevar   ---> titres des vecteurs
+!         * g1d_tmp1       ---> caractere 
+!         * g1d_tmp2       ---> caractere 
+
       INTEGER g1d_nlayer
       CHARACTER*100 g1d_nomfich
@@ -43,21 +43,21 @@
       integer saveG1D
 
-      COMMON/COMG1DI/g1d_nlayer
-     &             ,g1d_unitfich
-     &             ,g1d_unitctl
-     &             ,g1d_irec
-     &             ,g2d_irec
-     &             ,g2d_appel
-     &             ,g1d_nvar
+      COMMON/COMG1DI/g1d_nlayer                                         &
+     &             ,g1d_unitfich                                        &
+     &             ,g1d_unitctl                                         &
+     &             ,g1d_irec                                            &
+     &             ,g2d_irec                                            &
+     &             ,g2d_appel                                           &
+     &             ,g1d_nvar                                            &
      &             ,saveG1D
-      COMMON/COMG1DC/g1d_dimvar(0:g1d_nvarmx)
-     &             ,g1d_nomfich
-     &             ,g1d_nomctl
-     &             ,g1d_nomvar(0:g1d_nvarmx)
-     &             ,g1d_titrevar(0:g1d_nvarmx)
-     &             ,g1d_tmp1
-     &             ,g1d_tmp2
-      COMMON/COMG1DL/g1d_premier
+      COMMON/COMG1DC/g1d_dimvar(0:g1d_nvarmx)                           &
+     &             ,g1d_nomfich                                         &
+     &             ,g1d_nomctl                                          &
+     &             ,g1d_nomvar(0:g1d_nvarmx)                            &
+     &             ,g1d_titrevar(0:g1d_nvarmx)                          &
+     &             ,g1d_tmp1                                            &
+     &             ,g1d_tmp2                                            
+      COMMON/COMG1DL/g1d_premier                                        &
      &             ,g2d_premier
-c
-c.......................................................................
+!
+!.......................................................................
Index: /trunk/LMDZ.GENERIC/libf/phystd/comsaison.h
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/comsaison.h	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/comsaison.h	(revision 253)
@@ -1,11 +1,11 @@
-c-----------------------------------------------------------------------
-c   INCLUDE saison.h
+!-----------------------------------------------------------------------
+!   INCLUDE saison.h
 
-      COMMON/saison/callsais,isaison,dist_sol,declin,
-     $             mu0(ngridmx),fract(ngridmx)
+      COMMON/saison/callsais,isaison,dist_star,declin,                   &
+     &             mu0(ngridmx),fract(ngridmx)
 
-      INTEGER isaison
-      LOGICAL callsais
-      REAL dist_sol,declin,mu0,fract
+      integer isaison
+      logical callsais
+      real dist_star,declin,mu0,fract
 
-c-----------------------------------------------------------------------
+!-----------------------------------------------------------------------
Index: /trunk/LMDZ.GENERIC/libf/phystd/condens_co2cloud.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/condens_co2cloud.F90	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/condens_co2cloud.F90	(revision 253)
@@ -17,5 +17,5 @@
 !  
 !     Inputs
-!     ------ 
+!     ------
 !     ngrid                 Number of vertical columns
 !     nlayer                Number of layers
@@ -56,4 +56,5 @@
 #include "callkeys.h"
 #include "tracer.h"
+#include "gases.h"
 
 !-----------------------------------------------------------------------
@@ -142,5 +143,11 @@
       CHARACTER(LEN=20) :: tracername ! to temporarily store text
 
+      integer igas
+      integer,save :: igasco2=0
+      character(len=3) :: gasname
+
       real reffradmin, reffradmax
+
+      real ppco2
 
 !-----------------------------------------------------------------------
@@ -154,19 +161,30 @@
       !reffradmin=1.e-7
       !reffradmax=5.e-4
-      reffradmin=0.5e-7
-      reffradmax=0.1e-3 ! FF data
-      !reffradmin=0.1e-5
-      !reffradmax=0.5e-3 ! JB data
+      !reffradmin=0.5e-7
+      !reffradmax=0.1e-3 ! FF data
+      reffradmin=0.1e-5
+      reffradmax=0.1e-3 ! JB data
 !     improve this in the future...
 
 !     Initialisation
       IF (firstcall) THEN
-        do iq=1,nqmx
-          tracername=noms(iq)
-          if (tracername.eq."co2_ice") then
-            i_co2ice=iq
-          endif
-        enddo
-        
+
+         ! find CO2 ice tracer
+         do iq=1,nqmx
+            tracername=noms(iq)
+            if (tracername.eq."co2_ice") then
+               i_co2ice=iq
+            endif
+         enddo
+         
+         ! find CO2 gas
+         do igas=1,ngasmx
+            gasname=gnom(igas)
+!            gasname=noms(igas) ! was a bug
+            if (gasname.eq."CO2") then
+               igasco2=igas
+            endif
+         enddo
+
         write(*,*) "condense_co2cloud: i_co2ice=",i_co2ice       
 
@@ -179,5 +197,20 @@
          print*,'In condens_co2cloud: ccond=',ccond,' latcond=',latcond
 
-         firstcall=.false.
+!          Prepare special treatment if gas is not pure CO2
+             !if (addn2) then
+             !   m_co2   = 44.01E-3 ! CO2 molecular mass (kg/mol)   
+             !   m_noco2 = 28.02E-3 ! N2 molecular mass (kg/mol)  
+!               Compute A and B coefficient use to compute
+!               mean molecular mass Mair defined by
+!               1/Mair = q(ico2)/m_co2 + (1-q(ico2))/m_noco2
+!               1/Mair = A*q(ico2) + B
+             !   A = (1/m_co2 - 1/m_noco2)
+             !   B = 1/m_noco2
+             !endif
+
+!          Minimum CO2 mixing ratio below which mixing occurs with layer above: 
+           !qco2min =0.75  
+
+           firstcall=.false.
       ENDIF
       zcpi=1./cpp
@@ -217,8 +250,29 @@
 !     Atmospheric condensation
 
+
+!     Compute CO2 Volume mixing ratio
+!     -------------------------------
+!      if (addn2) then
+!         DO l=1,nlayer
+!            DO ig=1,ngrid
+!              qco2=pq(ig,l,ico2)+pdq(ig,l,ico2)*ptimestep
+!!             Mean air molecular mass = 1/(q(ico2)/m_co2 + (1-q(ico2))/m_noco2)
+!              mmean=1/(A*qco2 +B)
+!              vmr_co2(ig,l) = qco2*mmean/m_co2 
+!            ENDDO
+!         ENDDO
+!      else
+!         DO l=1,nlayer
+!            DO ig=1,ngrid
+!              vmr_co2(ig,l)=0.5
+!            ENDDO
+!         ENDDO
+!      end if
+
 !     Forecast the atmospheric frost temperature 'ztcond'
       DO l=1,nlayer
          DO ig=1,ngrid
-            call get_tcond_co2(pplay(ig,l),ztcond(ig,l),1,1)
+            ppco2=gfrac(igasco2)*pplay(ig,l)
+            call get_tcond_co2(ppco2,ztcond(ig,l))
          ENDDO
       ENDDO
@@ -234,6 +288,4 @@
                   print*,'Perhaps the atmosphere is collapsing on surface...?'
                endif
-               stop
-
             END IF
          ENDDO
@@ -275,5 +327,4 @@
                ! there should be a more elegant way of doing this...
                if(reff.lt.1.e-16) reff=1.e-16
-
 
                ! update reffrad for radiative transfer
@@ -290,6 +341,7 @@
                call stokes                      &
                    (pplev(ig,ilay),pt(ig,ilay), &
-                    reff,vstokes,rho_co2) 
-
+                    reff,vstokes,rho_co2)
+
+               !w(ig,ilay,i_co2ice) = 0.0
                w(ig,ilay,i_co2ice) = vstokes *  subptimestep * &
                    pplev(ig,ilay)/(r*pt(ig,ilay))
@@ -369,7 +421,7 @@
 !     forecast of ground temperature ztsrf and frost temperature ztcondsol
       DO ig=1,ngrid
-
-         call get_tcond_co2(pplev(ig,1),ztcondsol(ig))
-
+         ppco2=gfrac(igasco2)*pplay(ig,1)
+         call get_tcond_co2(ppco2,ztcondsol(ig))
+         
          ztsrf(ig) = ptsrf(ig)
 
@@ -466,6 +518,17 @@
       implicit none
 
-      real p, tcond
-      tcond = (-3167.8)/(log(.01*p)-23.23) ! Fanale's formula
+#include "callkeys.h"
+
+      real p, peff, tcond
+      real, parameter :: ptriple=518000.0
+
+      peff=p!/co2supsat
+
+      if(peff.lt.ptriple)then
+         tcond = (-3167.8)/(log(.01*peff)-23.23) ! Fanale's formula
+      else
+         tcond = 684.2-92.3*log(peff)+4.32*log(peff)**2 
+         ! liquid-vapour transition (based on CRC handbook 2003 data)
+      endif
       return
 
Index: /trunk/LMDZ.GENERIC/libf/phystd/convadj.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/convadj.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/convadj.F	(revision 253)
@@ -1,23 +1,29 @@
-      SUBROUTINE convadj(ngrid,nlay,nq,ptimestep,
-     S                   pplay,pplev,ppopsk,
-     $                   pu,pv,ph,pq,
-     $                   pdufi,pdvfi,pdhfi,pdqfi,
-     $                   pduadj,pdvadj,pdhadj,
-     $                   pdqadj)
-      IMPLICIT NONE
-
-c=======================================================================
-c
-c   ajustement convectif sec
-c   on ajoute les tendances pdhfi au profil pdh avant l'ajustement
-c   SPECIAL VERSION : if one tracer is CO2, take into account the
-c   Molecular mass variation (e.g. when CO2 condense) to trigger
-c   convection  F. Forget 01/2005
-c
-c=======================================================================
-
-c-----------------------------------------------------------------------
-c   declarations:
-c   -------------
+      subroutine convadj(ngrid,nlay,nq,ptimestep,
+     &                   pplay,pplev,ppopsk,
+     &                   pu,pv,ph,pq,
+     &                   pdufi,pdvfi,pdhfi,pdqfi,
+     &                   pduadj,pdvadj,pdhadj,
+     &                   pdqadj)
+
+      implicit none
+
+!==================================================================
+!     
+!     Purpose
+!     -------
+!     Calculates dry convective adjustment. If one tracer is CO2,
+!     we take into account the molecular mass variation (e.g. when
+!     CO2 condenses) to trigger convection (F. Forget 01/2005)
+!
+!     Authors
+!     -------
+!     Original author unknown.
+!     Modif. 2005 by F. Forget.
+!     
+!==================================================================
+
+!     ------------
+!     Declarations
+!     ------------
 
 #include "dimensions.h"
@@ -28,6 +34,6 @@
 
 
-c   arguments:
-c   ----------
+!     Arguments
+!     ---------
 
       INTEGER ngrid,nlay
@@ -38,5 +44,5 @@
       REAL pv(ngrid,nlay),pdvfi(ngrid,nlay),pdvadj(ngrid,nlay)
 
-c    Traceurs :
+!     Tracers
       integer nq
       real pq(ngrid,nlay,nq), pdqfi(ngrid,nlay,nq)
@@ -44,6 +50,6 @@
 
 
-c   local:
-c   ------
+!     Local
+!     -----
 
       INTEGER ig,i,l,l1,l2,jj
@@ -56,7 +62,6 @@
       REAL zh2(ngridmx,nlayermx), zhc(ngridmx,nlayermx)
       REAL zhm,zsm,zdsm,zum,zvm,zalpha,zhmc
-      
-
-c    Traceurs :
+
+!     Tracers
       INTEGER iq,ico2
       save ico2
@@ -65,6 +70,4 @@
       real m_co2, m_noco2, A , B
       save A, B
-c    Temporaire (for diagnostic)
-c      REAL diag_alpha(ngridmx)
 
       real mtot1, mtot2 , mm1, mm2
@@ -74,14 +77,17 @@
       data firstcall/.true./
 
+!     for conservation test
+      real masse,cadjncons
+
       EXTERNAL SCOPY
-c
-c-----------------------------------------------------------------------
-c   initialisation:
-c   ---------------
-c
+
+!     --------------
+!     Initialisation
+!     --------------
+
       IF (firstcall) THEN 
         IF(ngrid.NE.ngridmx) THEN
            PRINT*
-           PRINT*,'STOP dans convadj'
+           PRINT*,'STOP in convadj'
            PRINT*,'ngrid    =',ngrid
            PRINT*,'ngridmx  =',ngridmx
@@ -89,5 +95,5 @@
         ico2=0
         if (tracer) then
-c          Prepare Special treatment if one of the tracer is CO2 gas
+!     Prepare Special treatment if one of the tracers is CO2 gas
            do iq=1,nqmx
              if (noms(iq).eq."co2") then
@@ -97,8 +103,8 @@
                 m_co2 = 44.01E-3  ! CO2 molecular mass (kg/mol)   
                 m_noco2 = 33.37E-3  ! Non condensible mol mass (kg/mol)   
-c               Compute A and B coefficient use to compute
-c               mean molecular mass Mair defined by
-c               1/Mair = q(ico2)/m_co2 + (1-q(ico2))/m_noco2
-c               1/Mair = A*q(ico2) + B
+!               Compute A and B coefficient use to compute
+!               mean molecular mass Mair defined by
+!               1/Mair = q(ico2)/m_co2 + (1-q(ico2))/m_noco2
+!               1/Mair = A*q(ico2) + B
                 A =(1/m_co2 - 1/m_noco2)
                 B=1/m_noco2
@@ -108,17 +114,4 @@
         firstcall=.false.
       ENDIF ! of IF (firstcall)
-
-c
-c-----------------------------------------------------------------------
-c   detection des profils a modifier:
-c   ---------------------------------
-c   si le profil est a modifier
-c   (i.e. ph(niv_sup) < ph(niv_inf) )
-c   alors le tableau "vtest" est mis a .TRUE. ;
-c   sinon, il reste a sa valeur initiale (.FALSE.)
-c   cette operation est vectorisable
-c   On en profite pour copier la valeur initiale de "ph"
-c   dans le champ de travail "zh"
-
 
       DO l=1,nlay
@@ -140,5 +133,4 @@
       end if
 
-
       CALL scopy(ngrid*nlay,zh,1,zh2,1)
       CALL scopy(ngrid*nlay,zu,1,zu2,1)
@@ -146,10 +138,15 @@
       CALL scopy(ngrid*nlay*nq,zq,1,zq2,1)
 
+!     -----------------------------
+!     Detection of unstable columns
+!     -----------------------------
+!     If ph(above) < ph(below) we set vtest=.true.
+
       DO ig=1,ngrid
-        vtest(ig)=.FALSE.
-      ENDDO
-c
+        vtest(ig)=.false.
+      ENDDO
+
       if (ico2.ne.0) then
-c        Special case if one of the tracer is CO2 gas
+!     Special case if one of the tracers is CO2 gas
          DO l=1,nlay
            DO ig=1,ngrid
@@ -161,12 +158,12 @@
        end if
 
-       
-
+!     Find out which grid points are convectively unstable
       DO l=2,nlay
         DO ig=1,ngrid
-          IF(zhc(ig,l).LT.zhc(ig,l-1)) vtest(ig)=.TRUE.
+          IF(zhc(ig,l).LT.zhc(ig,l-1)) vtest(ig)=.true.
         ENDDO
       ENDDO
-c
+
+!     Make a list of them
       jcnt=0
       DO ig=1,ngrid
@@ -178,13 +175,13 @@
 
 
-c-----------------------------------------------------------------------
-c  Ajustement des "jcnt" profils instables indices par "jadrs":
-c  ------------------------------------------------------------
-c
+!     ---------------------------------------------------------------
+!     Adjustment of the "jcnt" unstable profiles indicated by "jadrs"
+!     ---------------------------------------------------------------
+
       DO jj = 1, jcnt   ! loop on every convective grid point
-c
+
           i = jadrs(jj)
  
-c   Calcul des niveaux sigma sur cette colonne
+!     Calculate sigma in this column
           DO l=1,nlay+1
             sig(l)=pplev(i,l)/pplev(i,1)
@@ -196,15 +193,13 @@
          ENDDO
           l2 = 1
-c
-c      -- boucle de sondage vers le haut
-c
-cins$     Loop  vers le haut sur l2
+
+!     Test loop upwards on l2
+
           DO
-c
             l2 = l2 + 1
             IF (l2 .GT. nlay) EXIT
             IF (zhc(i, l2) .LT. zhc(i, l2-1)) THEN
  
-c          -- l2 est le niveau le plus haut de la colonne instable
+!     l2 is the highest level of the unstable column
  
               l1 = l2 - 1
@@ -214,9 +209,8 @@
               zhm = zh2(i, l2)
               if(ico2.ne.0) zqco2m = zq2(i,l2,ico2)
-c
-c          -- boucle de sondage vers le bas
-c             Loop
+
+!     Test loop downwards
+
               DO
-c
                 zsm = zsm + sdsig(l)
                 zdsm = zdsm + dsig(l)
@@ -230,36 +224,38 @@
                 end if
  
-c            -- doit on etendre la colonne vers le bas ?
- 
-                down = .FALSE.
-                IF (l1 .NE. 1) THEN    !--  and then
-                  IF (zhmc .LT. zhc(i, l1-1)) THEN
-                    down = .TRUE.
+!     do we have to extend the column downwards?
+ 
+                down = .false.
+                IF (l1 .ne. 1) then    !--  and then
+                  IF (zhmc .lt. zhc(i, l1-1)) then
+                    down = .true.
                   END IF
                 END IF
  
-                IF (down) THEN
+                ! this could be a problem...
+
+                if (down) then
  
                   l1 = l1 - 1
                   l  = l1
  
-                ELSE
- 
-c              -- peut on etendre la colonne vers le haut ?
- 
-                  IF (l2 .EQ. nlay) EXIT
- 
-                  IF (zhc(i, l2+1) .GE. zhmc) EXIT
-c
+                else
+ 
+!     can we extend the column upwards?
+ 
+                  if (l2 .eq. nlay) exit
+ 
+                  if (zhc(i, l2+1) .ge. zhmc) exit
+
                   l2 = l2 + 1
                   l  = l2
-c
-                END IF
-c
-cins$         End Loop
-              ENDDO
-c
-c          -- nouveau profil : constant (valeur moyenne)
-c
+
+                end if
+
+              enddo
+
+!     New constant profile (average value)
+
+
               zalpha=0.
               zum=0.
@@ -276,8 +272,19 @@
                 endif
                 zh2(i, l) = zhm
-                zum=zum+dsig(l)*zu(i,l)
-                zvm=zvm+dsig(l)*zv(i,l)
+!     modifs by RDW !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+                zum=zum+dsig(l)*zu2(i,l)
+                zvm=zvm+dsig(l)*zv2(i,l)
+!                zum=zum+dsig(l)*zu(i,l)
+!                zvm=zvm+dsig(l)*zv(i,l)
                 do iq=1,nq
-                   zqm(iq) = zqm(iq)+dsig(l)*zq(i,l,iq)
+                   zqm(iq) = zqm(iq)+dsig(l)*zq2(i,l,iq)
+!                   zqm(iq) = zqm(iq)+dsig(l)*zq(i,l,iq)
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+!     to conserve tracers/ KE, we must calculate zum, zvm and zqm using 
+!     the up-to-date column values. If we do not do this, there are cases 
+!     where convection stops at one level and starts at the next where we
+!     can break conservation of stuff (particularly tracers) significantly.
+
                 end do
               ENDDO
@@ -292,5 +299,5 @@
                  zalpha=1.
               ELSE
-c                IF(zalpha.LT.0.) STOP
+!                IF(zalpha.LT.0.) STOP
                  IF(zalpha.LT.1.e-4) zalpha=1.e-4
               ENDIF
@@ -300,9 +307,8 @@
                  zv2(i,l)=zv2(i,l)+zalpha*(zvm-zv2(i,l))
                  do iq=1,nq
-c                  zq2(i,l,iq)=zq2(i,l,iq)+zalpha*(zqm(iq)-zq2(i,l,iq)) 
+!                  zq2(i,l,iq)=zq2(i,l,iq)+zalpha*(zqm(iq)-zq2(i,l,iq)) 
                    zq2(i,l,iq)=zqm(iq)
                  end do
               ENDDO
-c              diag_alpha(i)=zalpha  !temporaire
               if (ico2.ne.0) then
                 DO l=l1, l2
@@ -311,13 +317,77 @@
               end if
 
- 
+
               l2 = l2 + 1
-c
-            END IF   ! fin traitement instabilité entre l1 et l2. 
-c                      On repart pour test à partir du l2 au dessus...
-          ENDDO   ! End Loop sur l2 vers le haut 
-c
-      ENDDO
-c
+
+            END IF   ! End of l1 to l2 instability treatment
+                     ! We now continue to test from l2 upwards
+
+          ENDDO   ! End of upwards loop on l2
+
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!     check conservation
+         cadjncons=0.0
+         if(water)then
+         do l = 1, nlay
+            masse = (pplev(i,l) - pplev(i,l+1))/g
+            iq    = igcm_h2o_vap
+            cadjncons = cadjncons + 
+     &           masse*(zq2(i,l,iq)-zq(i,l,iq))/ptimestep 
+         end do
+         endif
+
+         if(cadjncons.lt.-1.e-6)then
+            print*,'convadj has just crashed...'
+            print*,'i  = ',i
+            print*,'l1 = ',l1
+            print*,'l2 = ',l2
+            print*,'cadjncons        = ',cadjncons
+         do l = 1, nlay
+            print*,'dsig         = ',dsig(l)
+         end do         
+         do l = 1, nlay
+            print*,'dsig         = ',dsig(l)
+         end do
+         do l = 1, nlay
+            print*,'sig         = ',sig(l)
+         end do
+         do l = 1, nlay
+            print*,'pplay(ig,:)         = ',pplay(i,l)
+         end do
+         do l = 1, nlay+1
+            print*,'pplev(ig,:)         = ',pplev(i,l)
+         end do
+         do l = 1, nlay
+            print*,'ph(ig,:)         = ',ph(i,l)
+         end do
+         do l = 1, nlay
+            print*,'ph(ig,:)         = ',ph(i,l)
+         end do
+         do l = 1, nlay
+            print*,'ph(ig,:)         = ',ph(i,l)
+         end do
+         do l = 1, nlay
+            print*,'zh(ig,:)         = ',zh(i,l)
+         end do
+         do l = 1, nlay
+            print*,'zh2(ig,:)        = ',zh2(i,l)
+         end do
+         do l = 1, nlay
+            print*,'zq(ig,:,vap)     = ',zq(i,l,igcm_h2o_vap)
+         end do
+         do l = 1, nlay
+            print*,'zq2(ig,:,vap)    = ',zq2(i,l,igcm_h2o_vap)
+         end do
+            print*,'zqm(vap)         = ',zqm(igcm_h2o_vap)
+            print*,'jadrs=',jadrs
+
+            call abort
+         endif
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+
+      ENDDO
+
       DO l=1,nlay
         DO ig=1,ngrid
@@ -338,5 +408,6 @@
       end if
 
-c     output
+
+!     output
 !      if (ngrid.eq.1) then
 !         ig=1
@@ -349,4 +420,4 @@
 
 
-      RETURN
-      END
+      return
+      end
Index: /trunk/LMDZ.GENERIC/libf/phystd/cpdet.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/cpdet.F	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/cpdet.F	(revision 253)
@@ -0,0 +1,123 @@
+! ADAPTATION GCM POUR CP(T)
+c======================================================================
+c S. Lebonnois, 10/2007:
+c
+c VENUS: Cp(T) = cpp*(T/T0)^nu 
+c avec T0=460. et nu=0.35
+c cpp=RCPD=cp0 = 1000.
+c R/RCPD = RKAPPA
+c
+c La fonction d'Exner reste pk = RCPD*(play/pref)**RKAPPA
+c 
+c T et teta (temperature potentielle) sont liees par:
+c 
+c   integrale[teta a T](cp/T dT) = integrale[pref a p](R/p dp)
+c
+c Dans le cas de l'expression pour Venus, ca donne:
+c
+c   teta**nu = T**nu - nu * T0**nu * ln[ (p/pref)**RKAPPA ]
+c ou
+c   teta**nu = T**nu - nu * T0**nu * ln[pk/RCPD]
+c
+c On passe de T a teta par t2tpot(t,teta,pk)
+c On passe de teta a T par tpot2t(teta,t,pk)
+c
+c Pour DT <-> Dteta, on utilise: dteta = dT *(T/teta)**(nu-1)
+c -> routine dt2dtpot(dt,dteta,t,teta) 
+c (utilisee seulement pour le contregradient)
+c
+c======================================================================
+
+      FUNCTION cpdet(t)
+      IMPLICIT none
+#include "cpdet.h"
+
+      real cpdet,t
+
+      cpdet = cp0*(t/t0)**nu
+
+      return
+      end
+      
+c======================================================================
+c======================================================================
+
+      SUBROUTINE t2tpot(npoints,yt, yteta, ypk)
+      IMPLICIT none
+c======================================================================
+c Arguments:
+c
+c yt   --------input-R- Temperature
+c yteta-------output-R- Temperature potentielle
+c ypk  --------input-R- Fonction d'Exner: RCPD*(pplay/pref)**RKAPPA
+c
+c======================================================================
+#include "cpdet.h"
+
+      integer npoints
+      REAL    yt(npoints), yteta(npoints), ypk(npoints)
+      
+      yteta = yt**nu - nu * t0**nu * log(ypk/cp0)
+      yteta = yteta**(1./nu)
+        
+
+      !yteta = yt/ypk
+
+
+      return
+      end
+
+c======================================================================
+c======================================================================
+
+      SUBROUTINE tpot2t(npoints,yteta, yt, ypk)
+      IMPLICIT none
+c======================================================================
+c Arguments:
+c
+c yteta--------input-R- Temperature potentielle
+c yt   -------output-R- Temperature
+c ypk  --------input-R- Fonction d'Exner: RCPD*(pplay/pref)**RKAPPA
+c
+c======================================================================
+#include "cpdet.h"
+
+      integer npoints
+      REAL yt(npoints), yteta(npoints), ypk(npoints)
+
+      yt = yteta**nu + nu * t0**nu * log(ypk/cp0)
+      yt = yt**(1./nu)
+
+      !yt = yteta*ypk
+
+      return
+      end
+
+c$$$c======================================================================
+c$$$c======================================================================
+c$$$
+c$$$      SUBROUTINE dt2dtpot(npoints,ydt, ydteta, yt, yteta, ypk, ydpk)
+c$$$      IMPLICIT none
+c$$$c======================================================================
+c$$$c Arguments:
+c$$$c
+c$$$c ydt  --------input-R- D Temperature
+c$$$c ydteta------output-R- D Temperature potentielle
+c$$$c yt   --------input-R- Temperature
+c$$$c yteta--------input-R- Temperature potentielle
+c$$$c ypk  --------input-R- Fonction d'Exner: RCPD*(pplay/pref)**RKAPPA
+c$$$c ydpk  -------input-R- D Fonction d'Exner
+c$$$c
+c$$$c======================================================================
+c$$$#include "cpdet.h"
+c$$$
+c$$$      integer npoints
+c$$$      REAL    ydt(npoints), ydteta(npoints), ydpk(npoints)
+c$$$      REAL    yt(npoints), yteta(npoints), ypk(npoints)
+c$$$      
+c$$$      ydteta =  yteta**(1.-nu)* (ydt * yt**(nu-1.) 
+c$$$     .                           - t0**nu * ydpk / ypk)
+c$$$        
+c$$$      return
+c$$$      end
+
Index: /trunk/LMDZ.GENERIC/libf/phystd/cpdet.h
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/cpdet.h	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/cpdet.h	(revision 253)
@@ -0,0 +1,12 @@
+!-----------------------------------------------------------------------
+! INCLUDE cpdet.h
+
+      real cp0,t0,nu
+!      parameter (cp0 = 1000.) !doit etre egal a cpp (dyn) et RCPD (phy)
+      parameter (cp0 = 800.) !doit etre egal a cpp (dyn) et RCPD (phy)
+!      parameter (t0  = 460.)
+      parameter (t0  = 480.)
+!      parameter (t0  = 300.)
+      parameter (nu  = 0.35)
+!      parameter (nu  = 1.0)
+!-----------------------------------------------------------------------
Index: /trunk/LMDZ.GENERIC/libf/phystd/datafile.h
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/datafile.h	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/datafile.h	(revision 253)
@@ -4,6 +4,7 @@
 !  Address of the directory containing tables of data needed by the UCM
 
-      character (len=100) :: datafile
-!      data datafile /'/san/home/rdword/gcm/datagcm'/  ! gnome iDataPlex
-      data datafile /'/u/rwlmd/datagcm'/  ! planetary cluster
+      character (len=300) :: datafile
+!      data datafile /'/home/rdword/gcm/datagcm_lite'/  ! laptop
+      data datafile /'/san/home/rdword/gcm/datagcm'/  ! gnome iDataPlex
+!      data datafile /'/u/rwlmd/datagcm'/  ! planetary cluster
 !-----------------------------------------------------------------------
Index: /trunk/LMDZ.GENERIC/libf/phystd/dimphys.h
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/dimphys.h	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/dimphys.h	(revision 253)
@@ -8,4 +8,5 @@
       integer, parameter :: nlayermx = llm 
 ! nsoilmx : number of subterranean layers
-       integer, parameter :: nsoilmx = 18 
+      !integer, parameter :: nsoilmx = 4 ! for a test 
+      integer, parameter :: nsoilmx = 18 ! for z1=0.02 cm, depth = 104.8 m 
 !-----------------------------------------------------------------------
Index: /trunk/LMDZ.GENERIC/libf/phystd/dsolver.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/dsolver.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/dsolver.F	(revision 253)
@@ -93,5 +93,7 @@
         IF(XK2(N) .EQ. 0.0) GO TO 28
 c        IF (ABS (XK2(N)/XK(2*N-1)) .LT. 1.E-30) XK2(N)=0.0
+
         IF (ABS (XK2(N)/(XK(2*N-1)+1.e-20)) .LT. 1.E-30) XK2(N)=0.0   ! For debug only (with -Ktrap=fp option)
+
 
    28 CONTINUE
Index: unk/LMDZ.GENERIC/libf/phystd/dump.out
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/dump.out	(revision 252)
+++ 	(revision )
@@ -1,7 +1,0 @@
- Warning, stokes.F constants are defined for pure CO2.
- Cannot find required file "run.def"
-   (which should contain some input parameters
-    along with the following line:
-    INCLUDEDEF=callphys.def
-    )
-  ... might as well stop here ...
Index: /trunk/LMDZ.GENERIC/libf/phystd/evap.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/evap.F	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/evap.F	(revision 253)
@@ -0,0 +1,78 @@
+      subroutine evap(dtime,pt, pq, pdq, pdt,  
+     $     dqevap,dtevap, qevap, tevap) 
+        
+      use watercommon_h 
+
+      implicit none
+
+#include "dimensions.h"
+#include "dimphys.h"
+#include "tracer.h"
+#include "comcstfi.h"
+
+!==================================================================
+!     
+!     Purpose
+!     -------
+!     Evaporation of all water in the atmopshere.
+!     
+!     Authors
+!     -------
+!     Adapted from the LMDTERRE code by B. Charnay (2010)
+!     Original author Z. X. Li (1993)
+!     
+!==================================================================
+
+! Arguments:
+      REAL pt(ngridmx,nlayermx) 
+      REAL pq(ngridmx,nlayermx,nqmx) 
+      REAL pdt(ngridmx,nlayermx) 
+      REAL pdq(ngridmx,nlayermx,nqmx) 
+      REAL dqevap(ngridmx,nlayermx)
+      REAL dtevap(ngridmx,nlayermx)
+      REAL qevap(ngridmx,nlayermx,nqmx)
+      REAL dtime
+ 
+! Local:
+      REAL tevap(ngridmx,nlayermx) 
+      REAL zlvdcp
+      REAL zlsdcp
+      REAL zdelta
+      INTEGER l,ig
+
+!
+! Re-evaporer l'eau liquide nuageuse
+!
+
+      DO l=1,nlayermx
+        DO ig=1,ngridmx
+         qevap(ig,l,igcm_h2o_vap)=pq(ig,l,igcm_h2o_vap)	
+     s          	          +pdq(ig,l,igcm_h2o_vap)*dtime
+         qevap(ig,l,igcm_h2o_ice)=pq(ig,l,igcm_h2o_ice)	
+     s                            +pdq(ig,l,igcm_h2o_ice)*dtime
+         tevap(ig,l)=pt(ig,l)+pdt(ig,l)*dtime
+	ENDDO
+      ENDDO
+
+      DO l = 1, nlayermx  
+      	DO ig = 1, ngridmx
+         zlvdcp=RLVTT/RCPD!/(1.0+RVTMP2*qevap(ig,l,igcm_h2o_vap))
+         zlsdcp=RLSTT/RCPD!/(1.0+RVTMP2*qevap(ig,l,igcm_h2o_vap))
+         ! ignoring qevap term creates huge difference when qevap large!!!
+
+         zdelta = MAX(0.,SIGN(1.,To-tevap(ig,l))) ! what is this?
+                                                  ! for division between water / liquid
+	 dqevap(ig,l) = MAX(0.0,qevap(ig,l,igcm_h2o_ice))/dtime
+         dtevap(ig,l) = - dqevap(ig,l)*RLVTT/RCPD ! exactly as in largescale.F
+!         dtevap(ig,l) = - dqevap(ig,l)	
+!     s                       * (zlvdcp*(1.-zdelta)+zlsdcp*zdelta)
+         qevap(ig,l,igcm_h2o_vap) = qevap(ig,l,igcm_h2o_vap)	
+     s     	                    +dqevap(ig,l)*dtime
+	 qevap(ig,l,igcm_h2o_ice) = 0.0
+         tevap(ig,l) = tevap(ig,l)+dtevap(ig,l)*dtime
+
+      	ENDDO
+      ENDDO
+
+      RETURN
+      END
Index: /trunk/LMDZ.GENERIC/libf/phystd/fisice.h
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/fisice.h	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/fisice.h	(revision 253)
@@ -1,4 +1,4 @@
-c-----------------------------------------------------------------------
-c INCLUDE fisice.h
+!-----------------------------------------------------------------------
+! INCLUDE fisice.h
 
       COMMON/fisice/dqsf,rice,nuice,rdust,zcondicea
@@ -10,5 +10,5 @@
                                    !   MODIF_JBM_08W45
       REAL rdust(ngridmx,nlayermx) ! Prescribed dust radius in each layer (m) 
-c Variables used to define water ice scavenging by atmos. CO2 condensing
+! Variables used to define water ice scavenging by atmos. CO2 condensing
       REAL zcondicea(ngridmx,nlayermx)
-c-----------------------------------------------------------------------
+!-----------------------------------------------------------------------
Index: /trunk/LMDZ.GENERIC/libf/phystd/forceWCfn.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/forceWCfn.F	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/forceWCfn.F	(revision 253)
@@ -0,0 +1,47 @@
+      subroutine forceWCfn(pplev,pt,dq,dqs)
+
+      implicit none
+
+!==================================================================
+!     
+!     Purpose
+!     -------
+!     Force tracer conservation in a column for a given pair of 
+!     delta q, delta q_s
+!
+!     Authors
+!     ------- 
+!     R. Wordsworth
+!     
+!==================================================================
+
+#include "dimensions.h"
+#include "dimphys.h"
+#include "comcstfi.h"
+#include "tracer.h"
+
+      real masse, Wtot, Wdiff
+
+      real pplev(ngridmx,nlayermx+1)
+      real pt(ngridmx)
+
+      real dqs(ngridmx,nqmx) 
+      real dq(ngridmx,nlayermx,nqmx)
+
+      integer iq, ig, ilay
+
+      do iq=1,nqmx 
+        do ig=1,ngridmx
+           Wtot = 0.0
+           do ilay=1,nlayermx
+              masse = (pplev(ig,ilay) - pplev(ig,ilay+1))/g
+              Wtot  = Wtot + masse*dq(ig,ilay,iq)
+           enddo
+           Wdiff = Wtot + dqs(ig,iq)
+         
+           dqs(ig,iq) = dqs(ig,iq) - Wdiff
+        enddo
+      enddo
+
+      end 
+
Index: /trunk/LMDZ.GENERIC/libf/phystd/gases.h
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/gases.h	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/gases.h	(revision 253)
@@ -0,0 +1,12 @@
+!-----------------------------------------------------------------------
+! INCLUDE 'gases.h'
+
+      integer, parameter :: ngasmx = 2 
+      integer vgas
+      character*3 :: gnom(ngasmx) ! name of the gas
+!      character(len=3) :: gnom(ngasmx) ! name of the gas
+      real gfrac(ngasmx)
+
+      COMMON/gases/gnom,gfrac,vgas 
+
+!-----------------------------------------------------------------------
Index: /trunk/LMDZ.GENERIC/libf/phystd/gfluxi.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/gfluxi.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/gfluxi.F	(revision 253)
@@ -70,6 +70,8 @@
         LAMDA(L) = ALPHA(L)*(1.0-W0(L)*COSBAR(L))/UBARI
 
-        NT2   = TLEV(2*L+2)*10.0D0-499
-        NT    = TLEV(2*L)*10.0D0-499
+        !NT2   = TLEV(2*L+2)*10.0D0-499
+        !NT    = TLEV(2*L)*10.0D0-499
+        NT    = int(TLEV(2*L)*10.0D0)   - NTstar+1
+        NT2   = int(TLEV(2*L+2)*10.0D0) - NTstar+1
 
         B1(L) = (PLANCKIR(NW,NT2)-PLANCKIR(NW,NT))/DTAU(L)
@@ -83,6 +85,8 @@
       LAMDA(L) = ALPHA(L)*(1.0-W0(L)*COSBAR(L))/UBARI
 
-      NT    = TLEV(2*L+1)*10.0D0-499
-      NT2   = TLEV(2*L)*10.0D0-499
+      !NT    = TLEV(2*L+1)*10.0D0-499
+      !NT2   = TLEV(2*L)*10.0D0-499
+      NT    = int(TLEV(2*L+1)*10.0D0) - NTstar+1
+      NT2   = int(TLEV(2*L)*10.0D0)   - NTstar+1
       B1(L) = (PLANCKIR(NW,NT)-PLANCKIR(NW,NT2))/DTAU(L)
       B0(L) = PLANCKIR(NW,NT2)
Index: /trunk/LMDZ.GENERIC/libf/phystd/gfluxv.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/gfluxv.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/gfluxv.F	(revision 253)
@@ -66,4 +66,5 @@
 
 
+
       NAYER  = L_NLAYRAD
       TAUMAX = L_TAUMAX    !Default is 35.0
@@ -84,4 +85,5 @@
         W0(L)       = WDEL(L)*(1.0D0-CDEL(L)**2)/FACTOR
         COSBAR(L)   = CDEL(L)/(1.0D0+CDEL(L))
+
         DTAU(L)     = DTDEL(L)*FACTOR
         TAU(L+1)    = TAU(L)+DTAU(L)
@@ -90,5 +92,4 @@
         TAUCUM(K+1) = TAUCUM(K) + (TAUCUMIN(K+1)-TAUCUMIN(K))*FACTOR
       END DO
-
 
 !  Bottom layer
@@ -102,5 +103,4 @@
       TAUCUM(2*L+1) = TAU(L+1)
 
-
       BSURF = RSF*UBAR0*F0PI*EXP(-MIN(TAU(L+1),TAUMAX)/UBAR0)
       ! new definition of BSURF
@@ -109,21 +109,34 @@
       ! of the radiation scattered in the forward direction
 
-
 C     WE GO WITH THE QUADRATURE APPROACH HERE.  THE "SQRT(3)" factors
 C     ARE THE UBARV TERM.
 
       DO L=1,L_NLAYRAD
-        
-        ALPHA(L)=SQRT( (1.0-W0(L))/(1.0-W0(L)*COSBAR(L)) )
-
+
+        ALPHA(L)=SQRT( (1.0-W0(L))/(1.0-W0(L)*COSBAR(L) ) )
 
 C       SET OF CONSTANTS DETERMINED BY DOM 
 
+!     Quadrature method
         G1(L)    = (SQRT(3.0)*0.5)*(2.0- W0(L)*(1.0+COSBAR(L)))
         G2(L)    = (SQRT(3.0)*W0(L)*0.5)*(1.0-COSBAR(L))
         G3(L)    = 0.5*(1.0-SQRT(3.0)*COSBAR(L)*UBAR0)
 
-
-c     this is Quadrature
+!     ----- some other methods... (RDW) ------
+
+!     Eddington method
+!        G1(L)    =  0.25*(7.0 - W0(L)*(4.0 - 3.0*COSBAR(L)))
+!        G2(L)    = -0.25*(1.0 - W0(L)*(4.0 - 3.0*COSBAR(L)))
+!        G3(L)    =  0.25*(2.0 - 3.0*COSBAR(L)*UBAR0)
+
+!     delta-Eddington method
+!        G1(L)    =  (7.0 - 3.0*g^2 - W0(L)*(4.0 + 3.0*g) + W0(L)*g^2*(4*beta0 + 3*g)) / &
+!                             (4* (1 - g^2*()   ))  0.25*(7.0 - W0(L)*(4.0 - 3.0*COSBAR(L)))
+
+!     Hybrid modified Eddington-delta function method
+
+!     ----------------------------------------
+
+c     So they use Quadrature
 c     but the scaling is Eddington?
 
@@ -255,5 +268,5 @@
 
       fluxdn = fluxdn+UBAR0*F0PI*EXP(-MIN(TAUCUM(1),TAUMAX)/UBAR0)
- 
+
 C     This is for the "special" bottom layer, where we take
 C     DTAU instead of DTAU/2.
@@ -269,5 +282,4 @@
 
 
-
 C     THERE IS A POTENTIAL PROBLEM HERE IF W0=0 AND UBARV=UBAR0
 C     THEN DENOM WILL VANISH. THIS ONLY HAPPENS PHYSICALLY WHEN 
@@ -304,8 +316,4 @@
 
 
-
-
       RETURN
-
-
       END
Index: /trunk/LMDZ.GENERIC/libf/phystd/hydrol.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/hydrol.F90	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/hydrol.F90	(revision 253)
@@ -0,0 +1,359 @@
+subroutine hydrol(ptimestep,rnat,tsurf,          &
+     qsurf,dqsurf,dqs_hyd,pcapcal,                &
+     albedo0,albedo,mu0,pdtsurf,pdtsurf_hyd,hice)
+
+  use watercommon_h, only: To, RLFTT, rhowater, mx_eau_sol
+
+  implicit none
+
+!==================================================================
+!     
+!     Purpose
+!     -------
+!     Calculate the surface hydrology and albedo changes.
+!     
+!     Authors
+!     ------- 
+!     Adapted from LMDTERRE by B. Charnay (2010). Further 
+!     modifications by R. Wordsworth (2010).
+!     
+!     Called by
+!     ---------
+!     physiq.F
+!     
+!     Calls
+!     -----
+!     none
+!
+!     Notes
+!     -----
+!     rnat is terrain type: 0-ocean; 1-continent
+!     
+!==================================================================
+
+#include "dimensions.h"
+#include "dimphys.h"
+#include "comcstfi.h"
+#include "callkeys.h"
+#include "tracer.h"
+#include "fisice.h"
+#include "comgeomfi.h"
+#include "comdiurn.h"
+#include "surfdat.h"
+
+!     Inputs
+!     ------
+      real albedoocean
+      parameter (albedoocean=0.07)
+!      parameter (albedoocean=0.2)
+      real albedoice
+      save albedoice
+
+      real snowlayer
+      parameter (snowlayer=33.0)        ! 33 kg/m^2 of snow, equal to a layer of 3.3 cm 
+      real oceantime
+      parameter (oceantime=1*3600)
+
+      logical oceanbulkavg ! relax ocean temperatures to a GLOBAL mean value?
+      logical activerunoff ! enable simple runoff scheme?
+      logical oceanalbvary ! ocean albedo varies with the diurnal cycle?
+
+!     Arguments
+!     ---------
+      integer rnat(ngridmx) ! I changed this to integer (RW)
+      real runoff(ngridmx)
+      save runoff
+      real totalrunoff, tsea, oceanarea
+      save oceanarea
+
+      real ptimestep
+      real mu0(ngridmx)
+      real qsurf(ngridmx,nqmx), tsurf(ngridmx)
+      real dqsurf(ngridmx,nqmx), pdtsurf(ngridmx)
+      real hice(ngridmx)
+      real albedo0(ngridmx), albedo(ngridmx)
+
+      real oceanarea2
+
+!     Output
+!     ------
+      real dqs_hyd(ngridmx,nqmx)
+      real pdtsurf_hyd(ngridmx)
+
+!     Local
+!     -----
+      real a,b,E
+      integer ig,iq, icap ! wld like to remove icap
+      real fsnoi, subli, fauxo
+      real twater(ngridmx)
+      real pcapcal(ngridmx)
+      real hicebis(ngridmx)
+      real zqsurf(ngridmx,nqmx)
+      real ztsurf(ngridmx)
+
+      integer ivap, iliq, iice
+      save ivap, iliq, iice
+
+      logical firstcall
+      save firstcall
+
+      data firstcall /.true./
+
+      oceanbulkavg=.false.
+      activerunoff=.false.
+      oceanalbvary=.false.
+
+      if(firstcall)then
+
+         ivap=igcm_h2o_vap
+         iliq=igcm_h2o_vap
+         iice=igcm_h2o_ice
+        
+         write(*,*) "hydrol: ivap=",ivap
+         write(*,*) "        iliq=",iliq
+         write(*,*) "        iice=",iice
+
+!     Here's the deal: iice is used in place of igcm_h2o_ice both on the 
+!                      surface and in the atmosphere. ivap is used in
+!                      place of igcm_h2o_vap ONLY in the atmosphere, while
+!                      iliq is used in place of igcm_h2o_vap ONLY on the 
+!                      surface.
+
+!                      Soon to be extended to the entire water cycle...
+
+!     Ice albedo = snow albedo for now
+         albedoice=albedosnow
+
+!     Total ocean surface area
+         oceanarea=0.
+         do ig=1,ngridmx
+            if(rnat(ig).eq.0)then
+               oceanarea=oceanarea+area(ig)
+            endif
+         enddo
+
+         if(oceanbulkavg.and.(oceanarea.le.0.))then
+            print*,'How are we supposed to average the ocean'
+            print*,'temperature, when there are no oceans?'
+            call abort
+         endif
+
+         if(activerunoff.and.(oceanarea.le.0.))then
+            print*,'You have enabled runoff, but you have no oceans.'
+            print*,'Where did you think the water was going to go?'
+            call abort
+         endif
+         
+         firstcall = .false.
+      endif
+
+!     add physical tendencies already calculated
+!     ------------------------------------------
+
+      do ig=1,ngridmx
+         ztsurf(ig) = tsurf(ig) + ptimestep*pdtsurf(ig)
+         pdtsurf_hyd(ig)=0.0
+         do iq=1,nqmx
+            zqsurf(ig,iq) = qsurf(ig,iq) + ptimestep*dqsurf(ig,iq)
+         enddo    
+      enddo
+ 
+      do ig=1,ngridmx
+         do iq=1,nqmx
+            dqs_hyd(ig,iq) = 0.0
+         enddo
+      enddo
+
+      do ig = 1, ngridmx
+
+!     Ocean
+!     -----
+         if(rnat(ig).eq.0)then
+
+!     re-calculate oceanic albedo
+            if(diurnal.and.oceanalbvary)then
+               fauxo      = ( 1.47 - ACOS( mu0(ig) ) )/0.15 ! where does this come from (Benjamin)?
+               albedo(ig) = 1.1*( .03 + .630/( 1. + fauxo*fauxo))
+               albedo(ig) = MAX(MIN(albedo(ig),0.60),0.04)
+            else
+               albedo(ig) = albedoocean ! modif Benjamin
+            end if
+
+!     calculate oceanic ice height including the latent heat of ice formation
+!     hice is the height of oceanic ice with a maximum of maxicethick.
+            hice(ig)    = zqsurf(ig,iice)/rhowater ! update hice to include recent snowfall
+
+!            twater(ig)  = tsurf(ig) + ptimestep*zdtsurf(ig) &
+            twater(ig)  = ztsurf(ig) - hice(ig)*RLFTT*rhowater/pcapcal(ig)
+            ! this is temperature water would have if we melted entire ocean ice layer
+            hicebis(ig) = hice(ig)
+            hice(ig)    = 0.
+
+            if(twater(ig) .lt. To)then
+               E=min((To+Tsaldiff-twater(ig))*pcapcal(ig),RLFTT*rhowater*maxicethick)
+               hice(ig)        = E/(RLFTT*rhowater)
+               hice(ig)        = max(hice(ig),0.0)
+               hice(ig)        = min(hice(ig),maxicethick)
+               pdtsurf_hyd(ig) = (hice(ig) - hicebis(ig))*RLFTT* &
+                   rhowater/pcapcal(ig)/ptimestep              
+               albedo(ig)      = albedoice
+
+!               if (zqsurf(ig,iice).ge.snowlayer) then
+!                  albedo(ig) = albedoice
+!               else
+!                  albedo(ig) = albedoocean &
+!                       + (albedosnow - albedoocean)*zqsurf(ig,iice)/snowlayer
+!               endif
+
+            else
+
+               pdtsurf_hyd(ig) = -hicebis(ig)*RLFTT*rhowater/pcapcal(ig)/ptimestep                
+               albedo(ig)      = albedoocean
+
+            endif
+
+            zqsurf(ig,iliq) = zqsurf(ig,iliq)-(hice(ig)*rhowater-zqsurf(ig,iice))
+            zqsurf(ig,iice) = hice(ig)*rhowater
+
+
+!     Continent
+!     ---------
+         elseif (rnat(ig).eq.1) then
+
+!     melt the snow
+            if(ztsurf(ig).gt.To)then
+               if(zqsurf(ig,iice).gt.1.0e-8)then
+
+                  a     = (ztsurf(ig)-To)*pcapcal(ig)/RLFTT
+                  b     = zqsurf(ig,iice)
+                  fsnoi = min(a,b)
+
+                  zqsurf(ig,iice) = zqsurf(ig,iice) - fsnoi
+                  zqsurf(ig,iliq) = zqsurf(ig,iliq) + fsnoi
+
+!                 thermal effects
+                  pdtsurf_hyd(ig) = -fsnoi*RLFTT/pcapcal(ig)/ptimestep  
+
+               endif
+            else
+
+!     freeze the water
+               if(zqsurf(ig,iliq).gt.1.0e-8)then
+
+                  a     = -(ztsurf(ig)-To)*pcapcal(ig)/RLFTT
+                  b     = zqsurf(ig,iliq)
+                  
+                  fsnoi = min(a,b)
+
+                  zqsurf(ig,iice) = zqsurf(ig,iice) + fsnoi
+                  zqsurf(ig,iliq) = zqsurf(ig,iliq) - fsnoi
+
+!                 thermal effects
+                  pdtsurf_hyd(ig) = +fsnoi*RLFTT/pcapcal(ig)/ptimestep  
+
+               endif
+            endif
+            
+!     deal with runoff
+            if(activerunoff)then
+
+               runoff(ig) = max(zqsurf(ig,iliq) - mx_eau_sol, 0.0)
+               if(ngridmx.gt.1)then ! runoff only exists in 3D
+                  if(runoff(ig).ne.0.0)then
+                     zqsurf(ig,iliq) = mx_eau_sol
+!                    runoff is added to ocean at end
+                  endif
+               end if
+
+            endif
+
+!     re-calculate continental albedo
+            albedo(ig) = albedo0(ig) ! albedo0 = base values
+            if (zqsurf(ig,iice).ge.snowlayer) then
+               albedo(ig) = albedosnow
+            else
+               albedo(ig) = albedo0(ig) &
+                    + (albedosnow - albedo0(ig))*zqsurf(ig,iice)/snowlayer
+            endif
+
+         else
+
+            print*,'Surface type not recognised in hydrol.F!'
+            print*,'Exiting...'
+            call abort
+
+         endif
+
+      end do ! ig=1,ngridmx
+
+!     perform crude bulk averaging of temperature in ocean
+!     ----------------------------------------------------
+      if(oceanbulkavg)then
+
+         oceanarea2=0.       
+         DO ig=1,ngridmx
+            if((rnat(ig).eq.0).and.(hice(ig).eq.0.))then
+               oceanarea2=oceanarea2+area(ig)*pcapcal(ig)
+            end if
+         END DO
+       
+         tsea=0.
+         DO ig=1,ngridmx
+            if((rnat(ig).eq.0).and.(hice(ig).eq.0.))then       
+               tsea=tsea+ztsurf(ig)*area(ig)*pcapcal(ig)/oceanarea2
+            end if
+         END DO
+
+         DO ig=1,ngridmx
+            if((rnat(ig).eq.0).and.(hice(ig).eq.0))then
+               pdtsurf_hyd(ig) = pdtsurf_hyd(ig) + (tsea-ztsurf(ig))/oceantime
+            end if
+         END DO
+
+         print*,'Mean ocean temperature = ',tsea
+
+      endif
+
+!     shove all the runoff water into the ocean
+!     -----------------------------------------
+      if(activerunoff)then
+
+         totalrunoff=0.
+         do ig=1,ngridmx
+            if (rnat(ig).eq.1) then
+               totalrunoff = totalrunoff + area(ig)*runoff(ig)
+            endif
+         enddo
+         
+         do ig=1,ngridmx
+            if (rnat(ig).eq.0) then
+               zqsurf(ig,iliq) = zqsurf(ig,iliq) + &
+                    totalrunoff/oceanarea
+            endif
+         enddo
+
+      endif
+
+!     Re-add the albedo effects of CO2 ice if necessary
+!     -------------------------------------------------
+      if(co2cond)then
+
+         icap=1
+         do ig=1,ngridmx
+            if (qsurf(ig,igcm_co2_ice).gt.0) then
+               albedo(ig) = albedice(icap)
+            endif
+         enddo
+         
+      endif
+
+
+      do ig=1,ngridmx
+         dqs_hyd(ig,iliq)=(zqsurf(ig,iliq) - qsurf(ig,iliq))/ptimestep
+         dqs_hyd(ig,iice)=(zqsurf(ig,iice) - qsurf(ig,iice))/ptimestep
+      enddo
+
+      call writediagfi(ngridmx,'runoff','Runoff amount',' ',2,runoff)
+
+      return
+    end subroutine hydrol
Index: /trunk/LMDZ.GENERIC/libf/phystd/inifis.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/inifis.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/inifis.F	(revision 253)
@@ -3,5 +3,8 @@
      $           plat,plon,parea,
      $           prad,pg,pr,pcpp)
-!
+
+      use radinc_h, only : naerkind
+
+
 !=======================================================================
 !
@@ -70,4 +73,6 @@
       logical :: parameter, doubleq=.false.
 
+      real psurf,pN2 ! added by RW for Gliese 581d N2+CO2
+
       rad=prad
       daysec=pdaysec
@@ -78,7 +83,5 @@
       rcp=r/cpp
 
-
       avocado = 6.02214179e23   ! added by RW
-
 
 ! --------------------------------------------------------
@@ -117,5 +120,4 @@
          PRINT*,'--------------------------------------------'
 
-
          write(*,*) "Run with or without tracer transport ?"
          tracer=.false. ! default value
@@ -168,29 +170,4 @@
          write(*,*) " enertest = ",enertest
 
-         write(*,*) "Save EOF profiles in file 'profiles' for ",
-     &              "Climate Database?"
-         calleofdump=.false. ! default value
-         call getin("calleofdump",calleofdump)
-         write(*,*) " calleofdump = ",calleofdump
-
-         write(*,*) "Dust scenario:"
-         iaervar=3 ! default value
-         call getin("iaervar",iaervar)
-         write(*,*) " iaervar = ",iaervar
-
-         write(*,*) "Dust vertical distribution:"
-         write(*,*) "(=1 Dust opt.deph read in startfi;",
-     & " =2 Viking scenario; =3 MGS scenario,",
-     & " =4 Mars Year 24 from TES assimilation)"
-         iddist=3 ! default value
-         call getin("iddist",iddist)
-         write(*,*) " iddist = ",iddist
-
-         write(*,*) "Dust top altitude (km). (Matters only if iddist=1)"
-         topdustref= 90.0 ! default value
-         call getin("topdustref",topdustref)
-         write(*,*) " topdustref = ",topdustref
-
-
          write(*,*) "call radiative transfer ?"
          callrad=.true. ! default value
@@ -203,10 +180,4 @@
          write(*,*) " corrk = ",corrk
 
-!         write(*,*) "call NLTE radiative schemes ?",
-!     &              "(matters only if callrad=T)"
-!         callnlte=.false. ! default value
-!         call getin("callnlte",callnlte)
-!         write(*,*) " callnlte = ",callnlte
-         
          write(*,*) "call gaseous absorption in the visible bands?",
      &              "(matters only if callrad=T)"
@@ -242,4 +213,15 @@
          write(*,*) " co2cond = ",co2cond
 
+         write(*,*) "CO2 supersaturation level ?"
+         co2supsat=1.0 ! default value
+         call getin("co2supsat",co2supsat)
+         write(*,*) " co2supsat = ",co2supsat
+
+         write(*,*) "Radiative timescale for Newtonian cooling ?"
+         tau_relax=30. ! default value
+         call getin("tau_relax",tau_relax)
+         write(*,*) " tau_relax = ",tau_relax
+         tau_relax=tau_relax*24*3600 ! convert Earth days --> seconds
+
          write(*,*)"call thermal conduction in the soil ?"
          callsoil=.true. ! default value
@@ -247,11 +229,5 @@
          write(*,*) " callsoil = ",callsoil
          
-!         write(*,*)"call Lott's gravity wave/subgrid topography ",
-!     &             "scheme ?"
-!         calllott=.true. ! default value
-!         call getin("calllott",calllott)
-!         write(*,*)" calllott = ",calllott
-
-         write(*,*)"rad.transfer is computed every iradia",
+         write(*,*)"Rad transfer is computed every iradia",
      &             " physical timestep"
          iradia=1 ! default value
@@ -264,8 +240,13 @@
          write(*,*)" rayleigh = ",rayleigh
 
-         write(*,*)"Parametrized Earth-like ozone absorption ?"
-         ozone=.false.      
-         call getin("ozone",ozone)
-         write(*,*) " ozone = ",ozone
+         write(*,*) "Use blackbody for stellar spectrum ?"
+         stelbbody=.false. ! default value
+         call getin("stelbbody",stelbbody)
+         write(*,*) " stelbbody = ",stelbbody
+
+         write(*,*) "Stellar blackbody temperature ?"
+         stelTbb=5800.0 ! default value
+         call getin("stelTbb",stelTbb)
+         write(*,*) " stelTbb = ",stelTbb
 
          write(*,*)"Output mean OLR in 1D?"
@@ -279,4 +260,73 @@
          write(*,*)" specOLR = ",specOLR
 
+         write(*,*)"Operate in kastprof mode?"
+         kastprof=.false.
+         call getin("kastprof",kastprof)
+         write(*,*)" kastprof = ",kastprof
+
+         write(*,*)"Surface temperature in kastprof mode?"
+         Tsurfk=273.15
+         call getin("Tsurfk",Tsurfk)
+         write(*,*)" Tsurfk = ",Tsurfk
+
+! Test of incompatibility:
+! if kastprof used, we must be in 1D
+         if (kastprof.and.(ngridmx.gt.1)) then
+           print*,'kastprof can only be used in 1D!'
+           call abort
+         endif
+
+         write(*,*)"Stratospheric temperature for kastprof mode?"
+         Tstrat=167.0
+         call getin("Tstrat",Tstrat)
+         write(*,*)" Tstrat = ",Tstrat
+
+         write(*,*)"Remove lower boundary?"
+         noradsurf=.false.
+         call getin("noradsurf",noradsurf)
+         write(*,*)" noradsurf = ",noradsurf
+
+! Tests of incompatibility:
+         if (noradsurf.and.callsoil) then
+           print*,'noradsurf not compatible with soil scheme!'
+           call abort
+         endif
+         if (noradsurf.and.calldifv) then
+           print*,'noradsurf not compatible with a boundary layer!'
+           call abort
+         endif
+
+
+         write(*,*)"Use Newtonian cooling for radiative transfer?"
+         newtonian=.false.
+         call getin("newtonian",newtonian)
+         write(*,*)" newtonian = ",newtonian
+
+! Tests of incompatibility:
+         if (newtonian.and.corrk) then
+           print*,'newtonian not compatible with correlated-k!'
+           call abort
+         endif
+         if (newtonian.and.calladj) then
+           print*,'newtonian not compatible with adjustment!'
+           call abort
+         endif
+         if (newtonian.and.calldifv) then
+           print*,'newtonian not compatible with a boundary layer!'
+           call abort
+         endif
+
+         write(*,*)"Test physics timescale in 1D?"
+         testradtimes=.false.
+         call getin("testradtimes",testradtimes)
+         write(*,*)" testradtimes = ",testradtimes
+
+! Test of incompatibility:
+! if testradtimes used, we must be in 1D
+         if (testradtimes.and.(ngridmx.gt.1)) then
+           print*,'testradtimes can only be used in 1D!'
+           call abort
+         endif
+
          write(*,*)"Default planetary temperature?"
          tplanet=215.0
@@ -299,15 +349,26 @@
          write(*,*)" nearco2cond = ",nearco2cond
 
+!     1D solar zenith angle
+         write(*,*)"Solar zenith angle in 1D?"
+         szangle=60.0
+         call getin("szangle",szangle)
+         write(*,*)" szangle = ",szangle
+
 ! TRACERS:
 
-         write(*,*)"Transported dust ? (if >0, use 'dustbin' dust bins)"
-         dustbin=0 ! default value
-         call getin("dustbin",dustbin)
-         write(*,*)" dustbin = ",dustbin
-
-         write(*,*)"Radiatively active aerosols?"
-         aerofixed=.true. ! default value
+         write(*,*)"Fixed / inactive aerosol distribution?"
+         aerofixed=.true.       ! default value
          call getin("aerofixed",aerofixed)
          write(*,*)" aerofixed = ",aerofixed
+
+         write(*,*)"Varying H2O cloud fraction?"
+         CLFvarying=.false.     ! default value
+         call getin("CLFvarying",CLFvarying)
+         write(*,*)" CLFvarying = ",CLFvarying
+
+         write(*,*)"Value of fixed H2O cloud fraction?"
+         CLFfixval=1.0                ! default value
+         call getin("CLFfixval",CLFfixval)
+         write(*,*)" CLFfixval = ",CLFfixval
 
          write(*,*)"Number mixing ratio of CO2 ice particles:"
@@ -321,4 +382,16 @@
          write(*,*)" Nmix_h2o = ",Nmix_h2o
 
+         write(*,*)"Opacity of dust (if used):"
+         dusttau=0. ! default value
+         call getin("dusttau",dusttau)
+         write(*,*)" dusttau = ",dusttau
+
+! Test of incompatibility:
+! if less than 3 aerosols, then dusttau should = 0
+         if ((naerkind.lt.3).and.dusttau.gt.0.) then
+           print*,'Need naer>2 for radiatively active dust!'
+           stop
+         endif
+
          write(*,*)"Is the variable gas species radiatively active?"
          varactive=.false.
@@ -336,9 +409,4 @@
          write(*,*)" satval = ",satval
 
-!         write(*,*)"Radiatively active dust ? (matters if dustbin>0)"
-!         active=.false. ! default value
-!         call getin("active",active)
-!         write(*,*)" active = ",active
-
 ! Test of incompatibility:
 ! if no tracers, then aerofixed should be true
@@ -356,65 +424,4 @@
 
 ! Test of incompatibility:
-! if active is used, then dustbin should be > 0
-
-!         if (active.and.(dustbin.lt.1)) then
-!           print*,'if active is used, then dustbin should > 0'
-!           stop
-!         endif
-
-!         write(*,*)"use mass and number mixing ratios to predict",
-!     &             " dust size ?"
-!         doubleq=.false. ! default value
-!         call getin("doubleq",doubleq)
-!         write(*,*)" doubleq = ",doubleq
-
-! Test of incompatibility:
-! if doubleq is used, then dustbin should be 1
-
-!         if (doubleq.and.(dustbin.ne.1)) then
-!           print*,'if doubleq is used, then dustbin should be 1'
-!           stop
-!         endif
-
-!         write(*,*)"dust lifted by GCM surface winds ?"
-!         lifting=.false. ! default value
-!         call getin("lifting",lifting)
-!         write(*,*)" lifting = ",lifting
-
-! Test of incompatibility:
-! if lifting is used, then dustbin should be > 0
-
-!         if (lifting.and.(dustbin.lt.1)) then
-!           print*,'if lifting is used, then dustbin should > 0'
-!           stop
-!         endif
-
-!         write(*,*)" dust lifted by dust devils ?"
-!         callddevil=.false. !default value
-!         call getin("callddevil",callddevil)
-!         write(*,*)" callddevil = ",callddevil
-         
-
-! Test of incompatibility:
-! if dustdevil is used, then dustbin should be > 0
-
-!         if (callddevil.and.(dustbin.lt.1)) then
-!           print*,'if dustdevil is used, then dustbin should > 0'
-!           stop
-!         endif
-
-!         write(*,*)"Dust scavenging by CO2 snowfall ?"
-!         scavenging=.false. ! default value
-!         call getin("scavenging",scavenging)
-!         write(*,*)" scavenging = ",scavenging
-         
-
-! Test of incompatibility:
-! if scavenging is used, then dustbin should be > 0
-
-!         if (scavenging.and.(dustbin.lt.1)) then
-!           print*,'if scavenging is used, then dustbin should > 0'
-!           stop
-!         endif
 
          write(*,*) "Gravitationnal sedimentation ?"
@@ -423,24 +430,6 @@
          write(*,*) " sedimentation = ",sedimentation
 
-!         write(*,*) "includes water ice",
-!     &              "(if true, 'water' must also be .true.)"
-!         iceparty=.false. ! default value
-!         call getin("iceparty",iceparty)
-!         write(*,*) " iceparty = ",iceparty
-
-!         write(*,*) "Radiatively active transported atmospheric ",
-!     &              "water ice ?"
-!         activice=.false. ! default value
-!         call getin("activice",activice)
-!         write(*,*) " activice = ",activice
-
-
-! Test of incompatibility:
-! if activice is used, then iceparty should be used too
-
-!         if (activice.and..not.iceparty) then
-!           print*,'if activice is used, iceparty should be used too'
-!           stop
-!         endif
+
+! Test of incompatibility:
 
          write(*,*) "Compute water cycle ?"
@@ -464,4 +453,29 @@
          write(*,*) " rainthreshold = ",rainthreshold
 
+         write(*,*) "Include surface hydrology ?"
+         hydrology=.false. ! default value
+         call getin("hydrology",hydrology)
+         write(*,*) " hydrology = ",hydrology
+
+         write(*,*) "Evolve surface water sources ?"
+         sourceevol=.false. ! default value
+         call getin("sourceevol",sourceevol)
+         write(*,*) " sourceevol = ",sourceevol
+
+         write(*,*) "Snow albedo ?"
+         albedosnow=0.5         ! default value
+         call getin("albedosnow",albedosnow)
+         write(*,*) " albedosnow = ",albedosnow
+
+         write(*,*) "Maximum ice thickness ?"
+         maxicethick=2.0         ! default value
+         call getin("maxicethick",maxicethick)
+         write(*,*) " maxicethick = ",maxicethick
+
+         write(*,*) "Freezing point of seawater ?"
+         Tsaldiff=-1.8          ! default value
+         call getin("Tsaldiff",Tsaldiff)
+         write(*,*) " Tsaldiff = ",Tsaldiff
+
 ! Test of incompatibility:
 ! if watercond is used, then water should be used too
@@ -472,106 +486,8 @@
          endif
 
-         write(*,*) "photochemistry: include chemical species"
-         photochem=.false. ! default value
-         call getin("photochem",photochem)
-         write(*,*) " photochem = ",photochem
-
-
-! THERMOSPHERE
-
-         write(*,*) "call thermosphere ?"
-         callthermos=.false. ! default value
-         call getin("callthermos",callthermos)
-         write(*,*) " callthermos = ",callthermos
-         
-         write(*,*) " water included without cycle ",
-     &              "(only if water=.false.)"
-         thermoswater=.false. ! default value
-         call getin("thermoswater",thermoswater)
-         write(*,*) " thermoswater = ",thermoswater
-
-         write(*,*) "call thermal conduction ?",
-     &    " (only if callthermos=.true.)"
-         callconduct=.false. ! default value
-         call getin("callconduct",callconduct)
-         write(*,*) " callconduct = ",callconduct
-
-         write(*,*) "call EUV heating ?",
-     &   " (only if callthermos=.true.)"
-         calleuv=.false.  ! default value
-         call getin("calleuv",calleuv)
-         write(*,*) " calleuv = ",calleuv
-
-         write(*,*) "call molecular viscosity ?",
-     &   " (only if callthermos=.true.)"
-         callmolvis=.false. ! default value
-         call getin("callmolvis",callmolvis)
-         write(*,*) " callmolvis = ",callmolvis
-
-         write(*,*) "call molecular diffusion ?",
-     &   " (only if callthermos=.true.)"
-         callmoldiff=.false. ! default value
-         call getin("callmoldiff",callmoldiff)
-         write(*,*) " callmoldiff = ",callmoldiff
-         
-         write(*,*) "call thermospheric photochemistry ?",
-     &   " (only if callthermos=.true.)"
-         thermochem=.false. ! default value
-         call getin("thermochem",thermochem)
-         write(*,*) " thermochem = ",thermochem
-
-         write(*,*) "date for solar flux calculation:",
-     &   " (1985 < date < 2002)"
-         write(*,*) "(Solar min=1996.4 ave=1993.4 max=1990.6)"
-         solarcondate=1993.4 ! default value
-         call getin("solarcondate",solarcondate)
-         write(*,*) " solarcondate = ",solarcondate
-         
-
-         if (.not.callthermos) then
-           if (thermoswater) then
-             print*,'if thermoswater is set, callthermos must be true'
-             stop
-           endif          
-           if (callconduct) then
-             print*,'if callconduct is set, callthermos must be true'
-             stop
-           endif        
-           if (calleuv) then
-             print*,'if calleuv is set, callthermos must be true'
-             stop
-           endif         
-           if (callmolvis) then
-             print*,'if callmolvis is set, callthermos must be true'
-             stop
-           endif        
-           if (callmoldiff) then
-             print*,'if callmoldiff is set, callthermos must be true'
-             stop
-           endif          
-           if (thermochem) then
-             print*,'if thermochem is set, callthermos must be true'
-             stop
-           endif          
-        endif
-
-! Test of incompatibility:
-! if photochem is used, then water should be used too
-
-         if (photochem.and..not.water) then
-           print*,'if photochem is used, water should be used too'
-           stop
-         endif
-
-! if callthermos is used, then thermoswater should be used too 
-! (if water not used already)
-
-         if (callthermos .and. .not.water) then
-           if (callthermos .and. .not.thermoswater) then
-             print*,'if callthermos is used, water or thermoswater 
-     &               should be used too'
-             stop
-           endif
-         endif
+         mugaz=0.
+         cpp=0.
+         call su_gases
+         call calc_cpp_mugaz
 
          PRINT*,'--------------------------------------------'
@@ -594,69 +510,5 @@
       PRINT*,'        or each ',iradia*dtphys,' seconds'
       PRINT*
-! --------------------------------------------------------------
-!  Managing the Longwave radiative transfer
-! --------------------------------------------------------------
-
-!     In most cases, the run just use the following values :
-!     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-      callemis=.true.     
-!     ilwd=10*int(daysec/dtphys) ! bug before 22/10/01       
-      ilwd=10*int(daysec/dtphys) 
-      ilwn=2               
-      linear=.true.        
-      ncouche=3
-      alphan=0.4
-      ilwb=2
-      semi=0
-
-c$$$!     BUT people working hard on the LW may want to read them in 'radia.def' 
-c$$$!     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-c$$$
-c$$$      OPEN(99,file='radia.def',status='old',form='formatted'
-c$$$     .     ,iostat=ierr)
-c$$$      IF(ierr.EQ.0) THEN
-c$$$         write(*,*) 'inifis: Reading radia.def !!!'
-c$$$         READ(99,fmt='(a)') ch1
-c$$$         READ(99,*) callemis
-c$$$         WRITE(*,8000) ch1,callemis
-c$$$
-c$$$         READ(99,fmt='(a)') ch1
-c$$$         READ(99,*) iradia
-c$$$         WRITE(*,8001) ch1,iradia
-c$$$
-c$$$         READ(99,fmt='(a)') ch1
-c$$$         READ(99,*) ilwd
-c$$$         WRITE(*,8001) ch1,ilwd
-c$$$
-c$$$         READ(99,fmt='(a)') ch1
-c$$$         READ(99,*) ilwn
-c$$$         WRITE(*,8001) ch1,ilwn
-c$$$
-c$$$         READ(99,fmt='(a)') ch1
-c$$$         READ(99,*) linear
-c$$$         WRITE(*,8000) ch1,linear
-c$$$
-c$$$         READ(99,fmt='(a)') ch1
-c$$$         READ(99,*) ncouche
-c$$$         WRITE(*,8001) ch1,ncouche
-c$$$
-c$$$         READ(99,fmt='(a)') ch1
-c$$$         READ(99,*) alphan
-c$$$         WRITE(*,*) ch1,alphan
-c$$$
-c$$$         READ(99,fmt='(a)') ch1
-c$$$         READ(99,*) ilwb
-c$$$         WRITE(*,8001) ch1,ilwb
-c$$$
-c$$$
-c$$$         READ(99,fmt='(a)') ch1
-c$$$         READ(99,'(l1)') callg2d
-c$$$         WRITE(*,8000) ch1,callg2d
-c$$$
-c$$$         READ(99,fmt='(a)') ch1
-c$$$         READ(99,*) semi
-c$$$         WRITE(*,*) ch1,semi
-c$$$      end if
-c$$$      CLOSE(99)
+
 
 !-----------------------------------------------------------------------
@@ -678,151 +530,4 @@
       pi=2.*asin(1.) ! NB: pi is a common in comcstfi.h
 
-!     managing the tracers, and tests:
-!     -------------------------------
-
-      if(tracer) then
-
-!          when photochem is used, nqchem_min is the rank
-!          of the first chemical species
-
-! Ehouarn: nqchem_min is now meaningless and no longer used
-!       nqchem_min = 1
-       if (photochem .or. callthermos) then
-         chem = .true.
-       end if
-
-       if (water .or. thermoswater)then
-          h2o = .true.
-       else
-          h2o = .false.
-       endif
-
-!          TESTS
-
-       print*,'inifis: TRACERS:'
-
-c$$$       if ((doubleq).and.(h2o).and.
-c$$$     $     (chem).and.(iceparty)) then
-c$$$         print*,' 2 dust tracers (doubleq)'
-c$$$         print*,' 1 water vapour tracer'
-c$$$         print*,' 1 water ice tracer'
-c$$$         print*,nqmx-4,' chemistry tracers'
-c$$$       endif
-c$$$
-c$$$       if ((doubleq).and.(h2o).and.
-c$$$     $     (chem).and..not.(iceparty)) then
-c$$$         print*,' 2 dust tracers (doubleq)'
-c$$$         print*,' 1 water vapour tracer'
-c$$$         print*,nqmx-3,' chemistry tracers'
-c$$$       endif
-c$$$
-c$$$       if ((doubleq).and.(h2o).and.
-c$$$     $     .not.(chem).and.(iceparty)) then
-c$$$         print*,' 2 dust tracers (doubleq)'
-c$$$         print*,' 1 water vapour tracer'
-c$$$         print*,' 1 water ice tracer'
-c$$$         if (nqmx.ne.4) then
-c$$$           print*,'nqmx should be 4 with these options.'
-c$$$		   print*,'(or check callphys.def)'
-c$$$           stop
-c$$$         endif
-c$$$       endif
-c$$$
-c$$$       if ((doubleq).and.(h2o).and.
-c$$$     $     .not.(chem).and..not.(iceparty)) then
-c$$$         print*,' 2 dust tracers (doubleq)'
-c$$$         print*,' 1 water vapour tracer'
-c$$$         if (nqmx.ne.3) then
-c$$$           print*,'nqmx should be 3 with these options...'
-c$$$		   print*,'(or check callphys.def)'
-c$$$           stop
-c$$$         endif
-c$$$       endif
-c$$$
-c$$$       if ((doubleq).and..not.(h2o)) then
-c$$$         print*,' 2 dust tracers (doubleq)'
-c$$$         if (nqmx.ne.2) then
-c$$$           print*,'nqmx should be 2 with these options...'
-c$$$		   print*,'(or check callphys.def)'
-c$$$           stop
-c$$$         endif
-c$$$       endif
-
-       if (.not.(doubleq).and.(h2o).and.
-!     $     (chem).and.(iceparty)) then
-     $     (chem).and.(watercond)) then
-         if (dustbin.gt.0) then
-           print*,dustbin,' dust bins'
-         endif
-         print*,nqmx-2-dustbin,' chemistry tracers'
-         print*,' 1 water vapour tracer'
-         print*,' 1 water ice tracer'
-       endif
-
-       if (.not.(doubleq).and.(h2o).and.
-!     $     (chem).and..not.(iceparty)) then
-     $     (chem).and..not.(watercond)) then
-         if (dustbin.gt.0) then
-           print*,dustbin,' dust bins'
-         endif
-         print*,nqmx-1-dustbin,' chemistry tracers'
-         print*,' 1 water vapour tracer'
-       endif
-
-       if (.not.(doubleq).and.(h2o).and.
-!     $     .not.(chem).and.(iceparty)) then
-     $     .not.(chem).and.(watercond)) then
-         if (dustbin.gt.0) then
-           print*,dustbin,' dust bins'
-         endif
-         print*,' 1 water vapour tracer'
-         print*,' 1 water ice tracer'
-
-         if (nqmx.gt.(dustbin+2)) then
-           print*,'nqmx should be ',(dustbin+2),
-     $            ' with these options...'
-		   print*,'(or check callphys.def)'
-         endif
-         if (nqmx.lt.(dustbin+2)) then
-            print*,dustbin,' dust bins, but this should be ok I think.'
-!           stop
-         endif
-       endif
-
-       if (.not.(doubleq).and.(h2o).and.
-!     $     .not.(chem).and..not.(iceparty)) then
-     $     .not.(chem).and..not.(watercond)) then
-         if (dustbin.gt.0) then
-           print*,dustbin,' dust bins'
-         endif
-         print*,' 1 water vapour tracer'
-         if (nqmx.gt.(dustbin+1)) then
-           print*,'nqmx should be ',(dustbin+1),
-     $            ' with these options...'
-		   print*,'(or check callphys.def)'
-         if (nqmx.lt.(dustbin+1)) then
-           stop
-         endif
-         endif
-       endif
-
-!       if (.not.(doubleq).and..not.(h2o)) then
-!         if (dustbin.gt.0) then
-!           print*,dustbin,' dust bins'
-!           if (nqmx.ne.dustbin) then
-!             print*,'nqmx should be ',dustbin,
-!     $              ' with these options...'
-!             print*,'(or check callphys.def)'
-!             stop
-!           endif
-!         else
-           print*,'dustbin=',dustbin,
-     $            ': tracer should be F with these options...'
-     $           ,'UNLESS you just want to move tracers around '
-!         endif
-!       endif
-
-      endif ! of if (tracer)
-
       RETURN
       END
Index: /trunk/LMDZ.GENERIC/libf/phystd/iniorbit.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/iniorbit.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/iniorbit.F	(revision 253)
@@ -1,4 +1,4 @@
       SUBROUTINE iniorbit
-     $     (paphelie,pperiheli,pyear_day,pperi_day,pobliq)
+     $     (papoastr,pperiastr,pyear_day,pperi_day,pobliq)
       IMPLICIT NONE
 
@@ -13,5 +13,5 @@
 c    Initialisation du sous programme orbite qui calcule
 c    a une date donnee de l'annee de duree year_day commencant
-c    a l'equinoxe de printemps et dont le perihelie se situe
+c    a l'equinoxe de printemps et dont le periastre se situe
 c    a la date peri_day, la distance au soleil et la declinaison.
 c
@@ -26,6 +26,6 @@
 c   Input:
 c   ------
-c   aphelie       \   aphelie et perihelie de l'orbite
-c   periheli      /   en millions de kilometres.
+c   apoastr       \   apoastron and periastron of the orbit
+c   periastr      /   in millions of kilometres.
 c
 c=======================================================================
@@ -41,5 +41,5 @@
 c   ----------
 
-      REAL paphelie,pperiheli,pyear_day,pperi_day,pobliq
+      REAL papoastr,pperiastr,pyear_day,pperi_day,pobliq
 
 c   Local:
@@ -53,16 +53,16 @@
       pi=2.*asin(1.)
 
-      aphelie =paphelie
-      periheli=pperiheli
+      apoastr =papoastr
+      periastr=pperiastr
       year_day=pyear_day
       obliquit=pobliq
       peri_day=pperi_day
 
-      PRINT*,'Perihelie en Mkm  ',periheli
-      PRINT*,'Aphelise  en Mkm  ',aphelie 
-      PRINT*,'obliquite en degres  :',obliquit
+      PRINT*,'Periastron in Mkm  ',periastr
+      PRINT*,'Apoastron in Mkm  ',apoastr 
+      PRINT*,'Obliquity in degrees  :',obliquit
       unitastr=149.597927
-      e_elips=(aphelie-periheli)/(periheli+aphelie)
-      p_elips=0.5*(periheli+aphelie)*(1-e_elips*e_elips)/unitastr
+      e_elips=(apoastr-periastr)/(periastr+apoastr)
+      p_elips=0.5*(periastr+apoastr)*(1-e_elips*e_elips)/unitastr
 
       print*,'e_elips',e_elips
@@ -97,5 +97,5 @@
 
       timeperi=2.*atan(sqrt((1.+e_elips)/(1.-e_elips))*tan(zx0/2.))
-      PRINT*,'longitude solaire du perihelie timeperi = ',timeperi
+      PRINT*,'Solar longitude of periastron timeperi = ',timeperi
 
       RETURN
Index: /trunk/LMDZ.GENERIC/libf/phystd/initracer.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/initracer.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/initracer.F	(revision 253)
@@ -62,5 +62,4 @@
 
 
-        print*,'nqmx=',nqmx
 ! Identify tracers by their names: (and set corresponding values of mmol)
       ! 0. initialize tracer indexes to zero:
@@ -92,6 +91,6 @@
 
 
-      print*,'Setting dustbin = 0 in initracer.F'
-      dustbin=0
+      !print*,'Setting dustbin = 0 in initracer.F'
+      !dustbin=0
 
       ! 1. find dust tracers
@@ -222,25 +221,24 @@
 c$$$      else
 
-      print*,dustbin
-
-       if (dustbin.gt.1) then
-        print*,'ATTENTION:',
-     $   ' properties of dust need input in initracer !!!'
-        stop
-
-       else if (dustbin.eq.1) then
-
-c       This will be used for 1 dust particle size:
-c       ------------------------------------------
-        radius(igcm_dustbin(1))=3.e-6
-        Qext(igcm_dustbin(1))=3.04
-        alpha_lift(igcm_dustbin(1))=0.0e-6
-        alpha_devil(igcm_dustbin(1))=7.65e-9
-        qextrhor(igcm_dustbin(1))=(3./4.)*Qext(igcm_dustbin(1))
-     &                         /(rho_dust*radius(igcm_dustbin(1)))
-        rho_q(igcm_dustbin(1))=rho_dust
-
-       endif
-!      end if    ! (doubleq)
+
+c$$$       if (dustbin.gt.1) then
+c$$$        print*,'ATTENTION:',
+c$$$     $   ' properties of dust need input in initracer !!!'
+c$$$        stop
+c$$$
+c$$$       else if (dustbin.eq.1) then
+c$$$
+c$$$c       This will be used for 1 dust particle size:
+c$$$c       ------------------------------------------
+c$$$        radius(igcm_dustbin(1))=3.e-6
+c$$$        Qext(igcm_dustbin(1))=3.04
+c$$$        alpha_lift(igcm_dustbin(1))=0.0e-6
+c$$$        alpha_devil(igcm_dustbin(1))=7.65e-9
+c$$$        qextrhor(igcm_dustbin(1))=(3./4.)*Qext(igcm_dustbin(1))
+c$$$     &                         /(rho_dust*radius(igcm_dustbin(1)))
+c$$$        rho_q(igcm_dustbin(1))=rho_dust
+c$$$
+c$$$       endif
+c$$$!      end if    ! (doubleq)
 
 c     Initialization for water vapor
@@ -260,8 +258,16 @@
 c        opacity not always realistic.
 
+
+!         if(ngridmx.eq.1)
+
+
+!     to be modified for BC+ version?
          do ig=1,ngridmx
            if (ngridmx.ne.1) watercaptag(ig)=.false.
            dryness(ig) = 1.
          enddo
+
+
+
 
 !         IF (caps) THEN
Index: /trunk/LMDZ.GENERIC/libf/phystd/interpolateH2H2.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/interpolateH2H2.F90	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/interpolateH2H2.F90	(revision 253)
@@ -0,0 +1,214 @@
+     subroutine interpolateH2H2(wn,temp,pres,abcoef,firstcall)
+      implicit none
+
+!==================================================================
+!     
+!     Purpose
+!     -------
+!     Calculates the H2-H2 CIA opacity, using a lookup table from
+!     Borysow (2002)
+!
+!     Authors
+!     -------
+!     R. Wordsworth (2009)
+!     
+!==================================================================
+
+#include "datafile.h"
+
+      ! input
+      double precision wn                 ! wavenumber             (cm^-1)
+      double precision temp               ! temperature            (Kelvin)
+      double precision pres               ! pressure               (Pascals)
+
+      ! output
+      double precision abcoef             ! absorption coefficient (m^-1)
+
+      integer nS,nT
+      parameter(nS=1649)
+!      parameter(nT=7)
+      parameter(nT=14)
+
+      double precision amagat
+      double precision wn_arr(nS)
+      double precision temp_arr(nT)
+      double precision abs_arr(nS,nT)
+      !double precision data_tmp(nT+1)
+      double precision data_tmp(nT/2+1)
+
+      integer k
+      logical firstcall
+
+      save wn_arr, temp_arr, abs_arr
+
+      character*100 dt_file
+      integer strlen,ios
+
+      amagat=(273.15/temp)*(pres/101325.0)
+
+      if(firstcall)then
+
+!     1.1 Open the ASCII files
+
+         ! cold
+         dt_file=datafile(1:LEN_TRIM(datafile))//'/H2H2_CIA_LT.dat'
+         open(33,file=dt_file,form='formatted',status='old',iostat=ios)
+         if (ios.ne.0) then        ! file not found
+            write(*,*) 'Error from interpolateH2H2.for'
+            write(*,*) 'Data file could not be found:'
+            write(*,*) dt_file
+            call abort
+         else
+            do k=1,nS
+               read(33,*) data_tmp
+               wn_arr(k)=data_tmp(1)
+               abs_arr(k,1:7)=data_tmp(2:8)
+            end do
+         endif
+         close(33)
+
+         ! hot
+         dt_file=datafile(1:LEN_TRIM(datafile))//'/H2H2_CIA_HT.dat'
+         open(34,file=dt_file,form='formatted',status='old',iostat=ios)
+         if (ios.ne.0) then        ! file not found
+            write(*,*) 'Error from interpolateH2H2.for'
+            write(*,*) 'Data file could not be found:'
+            write(*,*) dt_file
+            call abort
+         else
+            do k=1,nS
+               read(34,*) data_tmp
+               wn_arr(k)=data_tmp(1)
+               ! wn_arr is identical
+               abs_arr(k,8:14)=data_tmp(2:8)
+            end do
+         endif
+         close(34)
+
+         temp_arr(1)  = 60.
+         temp_arr(2)  = 100.
+         temp_arr(3)  = 150.
+         temp_arr(4)  = 200.
+         temp_arr(5)  = 250.
+         temp_arr(6)  = 300.
+         temp_arr(7)  = 350.
+         temp_arr(8)  = 400.
+         temp_arr(9)  = 500.
+         temp_arr(10) = 600.
+         temp_arr(11) = 700.
+         temp_arr(12) = 800.
+         temp_arr(13) = 900.
+         temp_arr(14) = 1000.
+
+
+         print*,'At wavenumber ',wn,' cm^-1'
+         print*,'   temperature ',temp,' K'
+         print*,'   pressure ',pres,' Pa'
+
+         call bilinear(wn_arr,temp_arr,nS,nT,abs_arr,wn,temp,abcoef)
+
+         print*,'the absorption is ',abcoef,' cm^-1 amg^-2'
+
+         abcoef=abcoef*100.0*amagat**2 ! convert to m^-1
+
+         print*,'We have ',amagat,' amagats'
+         print*,'So the absorption is ',abcoef,' m^-1'
+
+      else
+  
+         call bilinear(wn_arr,temp_arr,nS,nT,abs_arr,wn,temp,abcoef)
+         abcoef=abcoef*100.0*amagat**2 ! convert to m^-1
+         !print*,'The absorption is ',abcoef,' m^-1'
+
+         ! unlike for Rayleigh scattering, we do not currently weight by the BB function
+         ! however our bands are normally thin, so this is no big deal.
+
+      endif
+
+      return
+    end subroutine interpolateH2H2
+
+
+
+! put as separate file eventually
+
+!-------------------------------------------------------------------------
+      subroutine bilinear(x_arr,y_arr,nX,nY,f2d_arr,x_in,y_in,f)
+!     Necessary for interpolation of continuum data
+
+      implicit none
+
+      integer nX,nY,i,j,a,b
+
+      real*8 x_in,y_in,x,y,x1,x2,y1,y2
+      real*8 f,f11,f12,f21,f22,fA,fB
+      real*8 x_arr(nX)
+      real*8 y_arr(nY)
+      real*8 f2d_arr(nX,nY)
+      
+      integer strlen
+      character*100 label
+      label='subroutine bilinear'
+
+      x=x_in
+      y=y_in
+
+!     1st check we're within the wavenumber range
+      if ((x.lt.x_arr(2)).or.(x.gt.x_arr(nX-2))) then
+         f=0.0D+0
+         return
+      else
+         
+!     in the x (wavenumber) direction 1st
+         i=1
+ 10      if (i.lt.(nX+1)) then
+            if (x_arr(i).gt.x) then
+               x1=x_arr(i-1)
+               x2=x_arr(i)
+               a=i-1
+               i=9999
+            endif
+            i=i+1
+            goto 10
+         endif
+      endif
+      
+      if ((y.lt.y_arr(1)).or.(y.gt.y_arr(nY))) then
+         write(*,*) 'Warning from bilinear.for:'
+         write(*,*) 'Extrapolating outside H2-H2 CIA temperature range!'
+         if(y.lt.y_arr(1))then
+            y=y_arr(1)+0.01
+         endif
+         if(y.gt.y_arr(nY))then
+            y=y_arr(nY)-0.01
+         endif
+      else
+
+!     in the y (temperature) direction 2nd
+         j=1
+ 20      if (j.lt.(nY+1)) then
+            if (y_arr(j).gt.y) then
+               y1=y_arr(j-1)
+               y2=y_arr(j)
+               b=j-1
+               j=9999
+            endif
+            j=j+1
+            goto 20
+         endif
+      endif
+      
+      f11=f2d_arr(a,b)
+      f21=f2d_arr(a+1,b)
+      f12=f2d_arr(a,b+1)
+      f22=f2d_arr(a+1,b+1)
+      
+!     1st in x-direction
+      fA=f11*(x2-x)/(x2-x1)+f21*(x-x1)/(x2-x1)
+      fB=f12*(x2-x)/(x2-x1)+f22*(x-x1)/(x2-x1)
+      
+!     then in y-direction
+      f=fA*(y2-y)/(y2-y1)+fB*(y-y1)/(y2-y1)
+      
+      return
+    end subroutine bilinear
Index: unk/LMDZ.GENERIC/libf/phystd/kastprof_fn.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/kastprof_fn.F	(revision 252)
+++ 	(revision )
@@ -1,42 +1,0 @@
-      subroutine kastprof_fn(tsurf,temp,play,plev)
-      IMPLICIT NONE
-
-c     creates a kasting temperature profile
-
-#include "dimensions.h"
-#include "dimphys.h"
-#include "comcstfi.h"
-
-
-      REAL play(nlayermx)   ! Pressure at the middle of the layers (Pa)
-      REAL plev(nlayermx+1) ! intermediate pressure levels (pa)
-      REAL psurf,tsurf      
-      REAL tcond (nlayermx)
-      REAL temp(nlayermx)   ! temperature at the middle of the layers
-
-      real*8 Gamma, dz
-      integer l
-
-!     dTdp = (-RT/gp)*Gamma
-
-!     ideal gas lapse rate
-      Gamma = -5.0556 ! K / km
-
-!     1st layer
-      dz = (plev(1) - play(1)) * (R * tsurf / (g*play(1)))
-      temp(1)=tsurf+dz*Gamma/1000
-
-!     other layers
-      DO l=2,nlayermx
-         dz = (play(l-1) - play(l)) * (R * temp(l-1) / (g*play(l)))
-         temp(l)=temp(l-1)+dz*Gamma/1000 ! convective lower troposphere
-
-!        FORMULE FANALE POUR 100% CO2
-         tcond(l)=(-3167.8)/(log(.01*play(l))-23.23)
-         if (temp(l) .lt. tcond(l)) temp(l)= tcond(l) ! condensing upper troposphere
-         if (temp(l) .lt. 167.) temp(l)= 167.0 ! isothermal stratosphere
-
-      ENDDO
-
-      return
-      end
Index: /trunk/LMDZ.GENERIC/libf/phystd/kastprof_fn.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/kastprof_fn.F90	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/kastprof_fn.F90	(revision 253)
@@ -0,0 +1,142 @@
+      subroutine kastprof_fn(tsurf,temp,popsk,play,plev,qvap)
+      implicit none
+
+!     creates a kasting temperature profile
+
+#include "dimensions.h"
+#include "dimphys.h"
+#include "comcstfi.h"
+#include "callkeys.h"
+
+      REAL play(nlayermx)   ! Pressure at the middle of the layers (Pa)
+      REAL plev(nlayermx+1) ! intermediate pressure levels (pa)
+      REAL psurf,tsurf      
+      REAL tcond(nlayermx)
+      REAL qvap(nlayermx)
+      REAL temp(nlayermx)   ! temperature at the middle of the layers
+
+      real, parameter :: Rstar   = 8.314
+      real, parameter :: ptriple = 518000.0
+      real, parameter :: latcond = 5.9e5     ! as in condense_co2
+      real, parameter :: mn      = 0.02801   ! molar mass of background gas (N2)
+      real, parameter :: mv      = 0.04401   ! molar mass of background gas (CO2)
+
+      real popsk(nlayermx)  ! this is dodgy as in rest of code, zpopsk(ngridmx,nlayermx)
+                            ! but kastprof requires 1D, so its ok I guess
+
+      real ppco2
+      real vmr_local,q_local,gamma,dqdlnT,dlnqdlnT,dlnpdlnT,dpdT,dln_p
+
+      integer l,iter
+
+      logical co2mixedcond
+
+      co2mixedcond=.true.
+
+      if(ngridmx.gt.1)then
+         print*,'DO NOT RUN KASTPROF IN 3D!!!'
+         call abort
+      end if
+
+      ! 1st, we make pot. temperature constant everywhere
+      do l=1,nlayermx
+            temp(l)=TsurfK*popsk(l)
+      enddo
+
+!     then do all the other stuff
+      vmr_local = 1.-n2mixratio
+      q_local   = vmr_local*mv/mn
+
+      qvap(1)   = q_local
+
+      ppco2=vmr_local*play(1)
+
+      if(play(1).lt.ptriple)then !
+         tcond(1) = (-3167.8)/(log(.01*ppco2)-23.23)         ! Fanale's formula
+      else
+         tcond(1) = 684.2-92.3*log(ppco2)+4.32*log(ppco2)**2 ! liquid-vapour (CRC handbook 2003 data)
+      endif
+
+      do l=1,nlayermx-1
+
+         ppco2=vmr_local*play(l) ! this shld be implicit i.e. vmr_local(l+1) ??
+
+         if(play(l).le.ptriple)then ! ERROR
+            tcond(l) = (-3167.8)/(log(.01*ppco2)-23.23)         ! Fanale's formula
+         else
+            tcond(l) = 684.2-92.3*log(ppco2)+4.32*log(ppco2)**2 ! liquid-vapour (CRC handbook 2003 data)
+         endif
+
+         if(co2mixedcond)then
+            if (temp(l) .le. Tstrat)then
+               temp(l)  = Tstrat            ! isothermal stratosphere
+               temp(l+1) = Tstrat
+               qvap(l+1) = qvap(l)
+               !print*,'strato'
+
+            elseif(temp(l) .le. tcond(l))then
+
+               dln_p     = log(play(l+1))-log(play(l))
+               gamma     = cpp - q_local*latcond/temp(l)
+               dqdlnT    = (mv*latcond/(mn*temp(l)) - gamma) & 
+                            / (latcond/temp(l) + Rstar/(mn*q_local))
+               dlnqdlnT  = (1./q_local)*dqdlnT
+               dlnpdlnT  = mv*latcond/(Rstar*temp(l)) - dlnqdlnT/(1. + q_local*mn/mv)
+               dpdT      = (play(l)/temp(l))*dlnpdlnT
+               q_local   = q_local + dqdlnT*dln_p/dlnpdlnT
+
+               vmr_local = q_local*mn/mv
+
+
+               if(1.eq.1)then
+               print*,'l         =',l
+               print*,'gamma     =',gamma
+               print*,'gamma bit =',q_local*latcond/temp(l)
+               print*,'cpp       =',cpp
+               print*,'latcond   =',latcond
+               print*,'q_local   =',q_local
+               print*,'T         =',temp(l)
+               print*,'p         =',play(l)
+               print*,'dqdlnT    =',dqdlnT
+               print*,'dlnqdlnT  =',dlnqdlnT
+               print*,'dlnpdlnT  =',dlnpdlnT
+               print*,'dpdT      =',dpdT
+               call abort
+               endif
+
+               qvap(l+1) = q_local
+               temp(l+1) = temp(l) + temp(l)*dln_p/(dlnpdlnT)
+               !print*,'CO2co'
+            else
+               !print*,'tropo'
+
+
+               ! CO2 is not condensing; therefore dry convection
+               qvap(l+1) = qvap(l)
+            endif
+
+         else
+
+            if (temp(l) .le. Tstrat)then
+               temp(l) = Tstrat            
+               ! isothermal stratosphere
+            elseif(temp(l) .le. tcond(l))then
+               temp(l)=tcond(l)
+               ! pure CO2 condensation
+            else
+               ! CO2 is not condensing; therefore dry convection 
+            endif
+
+         endif
+
+      enddo ! vertical loop
+
+      temp(nlayermx) = Tstrat
+      qvap(nlayermx) = qvap(nlayermx-1)
+
+      print*,'---fin---'
+
+      call abort
+
+      return
+    end subroutine kastprof_fn
Index: /trunk/LMDZ.GENERIC/libf/phystd/largescale.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/largescale.F	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/largescale.F	(revision 253)
@@ -0,0 +1,140 @@
+      subroutine largescale(dtime, paprs, pplay, t, pq,
+     &                   pdt, d_t, d_q, d_ql, rneb, reffH2O)
+
+      use watercommon_h, only : RLVTT, RCPD, RVTMP2
+
+      IMPLICIT none
+
+!==================================================================
+!     
+!     Purpose
+!     -------
+!     Calculates large-scale (stratiform) H2O condensation.
+!     
+!     Authors
+!     -------
+!     Adapted from the LMDTERRE code by R. Wordsworth (2009)
+!     Original author Z. X. Li (1993)
+!     
+!==================================================================
+
+#include "dimensions.h" 
+#include "dimphys.h"
+#include "comcstfi.h"
+
+#include "fisice.h"
+#include "callkeys.h"
+#include "tracer.h"
+
+
+!     Pre-arguments (for universal model)
+      real pq(ngridmx,nlayermx,nqmx)       ! tracer (kg/kg)
+
+!     Arguments
+      REAL dtime                     ! intervalle du temps (s)
+      REAL paprs(ngridmx,nlayermx+1) ! pression a inter-couche
+      REAL pplay(ngridmx,nlayermx)   ! pression au milieu de couche
+      REAL t(ngridmx,nlayermx)       ! temperature (K)
+      REAL q(ngridmx,nlayermx)       ! humidite specifique (kg/kg)
+      REAL d_t(ngridmx,nlayermx)     ! incrementation de la temperature (K)
+      REAL d_q(ngridmx,nlayermx)     ! incrementation de la vapeur d'eau
+      REAL d_ql(ngridmx,nlayermx)    ! incrementation de l'eau liquide
+      REAL rneb(ngridmx,nlayermx)    ! fraction nuageuse
+      REAL reffH2O(ngridmx,nlayermx) ! cloud particle mean radius (m)
+
+      REAL pdt(ngridmx,nlayermx) ! added by Benjamin!
+
+!     Options du programme
+      REAL ratqs   ! determine largeur de la distribution de vapeur
+      PARAMETER (ratqs=0.2)
+
+!     Variables locales
+      REAL CBRT
+      EXTERNAL CBRT
+      INTEGER i, k
+      REAL zt(ngridmx), zq(ngridmx)
+      REAL zcond(ngridmx)
+      REAL zdelq(ngridmx)
+      REAL zqs(ngridmx), zdqs(ngridmx)
+
+      REAL zcor(ngridmx), zdelta(ngridmx), zcvm5(ngridmx)
+      REAL zx_q(ngridmx)
+
+!     GCM -----> subroutine variables, initialisation of outputs
+      DO k = 1, nlayermx
+      DO i = 1, ngridmx
+         q(i,k)    = pq(i,k,igcm_h2o_vap)
+         d_t(i,k)  = 0.0
+         d_q(i,k)  = 0.0
+         d_ql(i,k) = 0.0
+         rneb(i,k) = 0.0
+      ENDDO
+      ENDDO
+
+!     Boucle verticale (du haut vers le bas)
+      DO 9999 k = nlayermx, 1, -1
+
+      DO i = 1, ngridmx
+         zt(i)=t(i,k)+pdt(i,k)*dtime
+         zq(i)=q(i,k) ! no need to add tendency as we're already dealing with qevap
+      ENDDO
+
+!     Calculer la vapeur d'eau saturante et 
+!     determiner la condensation partielle
+      DO i = 1, ngridmx
+
+         call watersat(zt(i),pplay(i,k),zqs(i))
+         call watersat_grad(zt(i),zqs(i),zdqs(i))
+
+         !IF (zt(i).LT.t_coup) THEN
+         !   zqs(i) = qsats(zt(i))/pplay(i,k)
+         !   zdqs(i) = dqsats(zt(i),zqs(i))
+         !ELSE
+         !   zqs(i) = qsatl(zt(i))/pplay(i,k)
+         !   zdqs(i) = dqsatl(zt(i),zqs(i))
+         !ENDIF
+
+         zdelq(i) = ratqs * zq(i)
+         rneb(i,k) = (zq(i)+zdelq(i)-zqs(i)) / (2.0*zdelq(i))
+         zcond(i) = 0.0
+         zx_q(i) = (zq(i)+zdelq(i)+zqs(i))/2.0
+         if (rneb(i,k) .LE. 0.0) zx_q(i) = 0.0
+         if (rneb(i,k) .GE. 1.0) zx_q(i) = zq(i)
+         rneb(i,k) = MAX(0.0,MIN(1.0,rneb(i,k)))
+         !zcond(i) = MAX(0.0,(zx_q(i)-zqs(i)*rneb(i,k)/(1.+zdqs(i))))
+         zcond(i) = MAX(0.0,(zx_q(i)-zqs(i))*rneb(i,k)/(1.+zdqs(i)))
+!     zcond always postive! cannot evaporate clouds!
+!     this is why we must reevaporate before largescale
+
+
+         zcond(i) = zcond(i)/dtime ! added by RDW
+
+!     for varying particle size in rad tran and (possibly) sedimentation
+         if(.not.aerofixed)then
+            reffH2O(i,k) = CBRT( 3*zcond(i)/( 4*Nmix_h2o*pi*rho_ice))
+            reffH2O(i,k) = max(reffH2O(i,k),1.e-8)
+         endif
+
+      ENDDO
+
+!     Tendances de t et q
+      DO i = 1, ngridmx
+         d_q(i,k)  = - zcond(i)
+         d_ql(i,k) = zcond(i)
+         !d_t(i,k) = zcond(i)*RLVTT/cpp
+         d_t(i,k)  = zcond(i)*RLVTT/RCPD!/(1.0+RVTMP2*q(i,k))
+         ! this one is FAR TOO BIG
+      ENDDO
+
+ 9999 CONTINUE
+
+      !print*,'qsat=',zqs
+      !print*,'q=',q
+      !print*,'dq=',d_q*dtime
+      !print*,'dT in LS=',d_t*dtime
+
+      !print*,'rice=',rice
+      !print*,'rneb=',rneb
+
+      return
+      end
Index: unk/LMDZ.GENERIC/libf/phystd/largescale2.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/largescale2.F	(revision 252)
+++ 	(revision )
@@ -1,121 +1,0 @@
-      SUBROUTINE largescale2(dtime, paprs, pplay, t, q,
-     s                   d_t, d_q, d_ql, rneb)
-
-      use watercommon_h, only : RLVTT
-
-      IMPLICIT none
-
-!==================================================================
-!     
-!     Purpose
-!     -------
-!     Calculates large-scale (stratiform) H2O condensation.
-!     
-!     Authors
-!     -------
-!     Adapted from the LMDTERRE code by R. Wordsworth (2009)
-!     Original author Z. X. Li (1993)
-!     
-!==================================================================
-
-#include "dimensions.h" 
-#include "dimphys.h"
-#include "comcstfi.h"
-
-#include "fisice.h"
-#include "callkeys.h"
-#include "tracer.h"
-
-
-!     Arguments
-      REAL dtime ! intervalle du temps (s)
-      REAL paprs(ngridmx,nlayermx+1) ! pression a inter-couche
-      REAL pplay(ngridmx,nlayermx) ! pression au milieu de couche
-      REAL t(ngridmx,nlayermx) ! temperature (K)
-      REAL q(ngridmx,nlayermx) ! humidite specifique (kg/kg)
-      REAL d_t(ngridmx,nlayermx) ! incrementation de la temperature (K)
-      REAL d_q(ngridmx,nlayermx) ! incrementation de la vapeur d'eau
-      REAL d_ql(ngridmx,nlayermx) ! incrementation de l'eau liquide
-      REAL rneb(ngridmx,nlayermx) ! fraction nuageuse
-
-!     Options du programme
-      REAL ratqs   ! determine largeur de la distribution de vapeur
-      PARAMETER (ratqs=0.2)
-
-!     Variables locales
-      REAL CBRT
-      EXTERNAL CBRT
-      INTEGER i, k
-      REAL zt(ngridmx), zq(ngridmx)
-      REAL zcond(ngridmx)
-      REAL zdelq(ngridmx)
-      REAL zqs(ngridmx), zdqs(ngridmx)
-
-      REAL zcor(ngridmx), zdelta(ngridmx), zcvm5(ngridmx)
-      REAL zx_q(ngridmx)
-
-!     Initialisation des sorties
-      DO k = 1, nlayermx
-      DO i = 1, ngridmx
-         d_t(i,k)=0.
-         d_q(i,k)=0.
-         d_ql(i,k)=0.
-         rneb(i,k) = 0.0
-      ENDDO
-      ENDDO
-
-!     Boucle verticale (du haut vers le bas)
-      DO 9999 k = nlayermx, 1, -1
-
-      DO i = 1, ngridmx
-         zt(i)=t(i,k)
-         zq(i)=q(i,k)
-      ENDDO
-
-!     Calculer la vapeur d'eau saturante et 
-!     determiner la condensation partielle
-      DO i = 1, ngridmx
-
-         call watersat_2(zt(i),pplay(i,k),zqs(i))
-         call watersat_grad(zt(i),zqs(i),zdqs(i))
-
-         !IF (zt(i).LT.t_coup) THEN
-         !   zqs(i) = qsats(zt(i))/pplay(i,k)
-         !   zdqs(i) = dqsats(zt(i),zqs(i))
-         !ELSE
-         !   zqs(i) = qsatl(zt(i))/pplay(i,k)
-         !   zdqs(i) = dqsatl(zt(i),zqs(i))
-         !ENDIF
-
-         zdelq(i) = ratqs * zq(i)
-         rneb(i,k) = (zq(i)+zdelq(i)-zqs(i)) / (2.0*zdelq(i))
-         zcond(i) = 0.0
-         zx_q(i) = (zq(i)+zdelq(i)+zqs(i))/2.0
-         if (rneb(i,k) .LE. 0.0) zx_q(i) = 0.0
-         if (rneb(i,k) .GE. 1.0) zx_q(i) = zq(i)
-         rneb(i,k) = MAX(0.0,MIN(1.0,rneb(i,k)))
-         zcond(i) = MAX(0.0,zx_q(i)-zqs(i))*rneb(i,k)/(1.+zdqs(i))
-         zcond(i) = zcond(i)/dtime ! added by RDW
-
-!     for varying particle size in rad tran and (possibly) sedimentation
-!     to be dealt with in next version...
-
-!         rice(i,k) = CBRT( 3*zcond(i)/( 4*Nmix_h2o*pi*rho_ice))
-!         rice(i,k) = max(rice(i,k),1.e-16)
-
-      ENDDO
-
-!     Tendances de t et q
-      DO i = 1, ngridmx
-         d_q(i,k) = - zcond(i)
-         d_ql(i,k) = zcond(i)
-         d_t(i,k) = zcond(i)*RLVTT/cpp
-      ENDDO
-
- 9999 CONTINUE
-
-      !print*,'rice=',rice
-      !print*,'rneb=',rneb
-
-      RETURN
-      END
Index: /trunk/LMDZ.GENERIC/libf/phystd/moistadj.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/moistadj.F90	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/moistadj.F90	(revision 253)
@@ -1,3 +1,3 @@
-      subroutine moistadj(t, pq, pplev, pplay, dtmana, dqmana, ptimestep, rneb)
+subroutine moistadj(t, pq, pplev, pplay, dtmana, dqmana, ptimestep, rneb)
 
   use watercommon_h, only: To, RLVTT, RCPD
@@ -109,12 +109,13 @@
 
       DO k = 1, nlayermx
-      DO i = 1, ngridmx
-         local_q(i,k) = q(i,k)
-         local_t(i,k) = t(i,k)
-         rneb(i,k) = 0.0
-         d_ql(i,k) = 0.0
-         d_t(i,k)  = 0.0
-         d_q(i,k)  = 0.0
-      ENDDO
+         DO i = 1, ngridmx
+            local_q(i,k) = q(i,k)
+            local_t(i,k) = t(i,k)
+            rneb(i,k) = 0.0
+            d_ql(i,k) = 0.0
+            d_t(i,k)  = 0.0
+            d_q(i,k)  = 0.0
+         ENDDO
+         new_qb(k)=0.0
       ENDDO
 
@@ -132,5 +133,5 @@
             v_p = pplay(i,k)
 
-            call watersat_2(v_t,v_p,v_qs(i,k))
+            call watersat(v_t,v_p,v_qs(i,k))
             call watersat_grad(v_t,v_qs(i,k),v_qsd(i,k))
          ENDDO
@@ -141,5 +142,5 @@
 !         DO i = 1, ngridmx
 !            v_t = local_t(i,k)
-!            IF (v_t.LT.t_coup) THEN
+!            IF (v_t.LT.To) THEN
 !               print*,'RHs=',q(i,k) / v_qs(i,k)
 !            ELSE
@@ -223,5 +224,11 @@
          local_q(i,k) = new_qb(k)
          local_t(i,k) = cp_new_t(k) / RCPD
-      ENDDO
+
+!          print*,'v_qs in loop=',v_qs
+!          print*,'v_qsd in loop=',v_qsd
+!          print*,'new_qb in loop=',new_qb
+!          print*,'cp_delta_t in loop=',cp_delta_t
+      ENDDO
+
 
 !--------------------------------------------------- sounding downwards
@@ -242,5 +249,5 @@
 !           ENDIF
 
-         call watersat_2(v_t,v_p,v_qs(i,k))
+         call watersat(v_t,v_p,v_qs(i,k))
          call watersat_grad(v_t,v_qs(i,k),v_qsd(i,k))
 
@@ -332,4 +339,6 @@
       ENDDO
 
+!      print*,'local_q BEFORE=',local_q
+
       DO k = 1, nlayermx
       DO i = 1, ngridmx
@@ -361,8 +370,17 @@
 !      print*,'d_t=',d_t
 !      print*,'d_q=',d_q
+!      print*,'local_q=',local_q
+!      print*,'q=',q
+!      print*,'v_qs(i,k)=',v_qs
+!      print*,'v_qsd(i,k)=',v_qsd
+!      print*,'cp_delta_t(k)=',cp_delta_t
+
 !      print*,'d_ql=',d_ql
-!      print*,'i_h2o=',i_h2o
+!      print*,'delta_q=',delta_q
+!      print*,'zq1=',zq1
+!      print*,'zq2=',zq2
+!!      print*,'i_h2o=',i_h2o
 !      print*,'i_ice=',i_ice
-
+!
 !      print*,'IN MANABE:'
 !      print*,'d_q=',d_q
@@ -374,28 +392,28 @@
 
 !     Some conservation diagnostics...
-      dEtot=0.0
-      dL1tot=0.0
-      dL2tot=0.0
-      dqtot=0.0
-      masse=0.0
-      DO k = 1, nlayermx
-         DO i = 1, ngridmx
-
-            masse = (pplev(i,k) - pplev(i,k+1))/g
-
-            dEtot  = dEtot  + cpp*d_t(i,k)*masse
-            dL1tot = dL1tot + RLVTT*d_ql(i,k)*masse
-            dL2tot = dL2tot + RLVTT*d_q(i,k)*masse ! is this line necessary?
-
-            dqtot = dqtot + (d_q(i,k) + d_ql(i,k))*masse
-
-         ENDDO
-      ENDDO
-
-        print*,'In manabe energy change=',dEtot
-        print*,'In manabe condense energy change 1 =',dL1tot
-        print*,'In manabe condense energy change 2 =',dL2tot
-        print*,'In manabe water change=',dqtot
+!      dEtot=0.0
+!      dL1tot=0.0
+!      dL2tot=0.0
+!      dqtot=0.0
+!      masse=0.0
+!      DO k = 1, nlayermx
+!         DO i = 1, ngridmx
+!
+!            masse = (pplev(i,k) - pplev(i,k+1))/g
+!
+!            dEtot  = dEtot  + cpp*d_t(i,k)*masse
+!            dL1tot = dL1tot + RLVTT*d_ql(i,k)*masse
+!            dL2tot = dL2tot + RLVTT*d_q(i,k)*masse ! is this line necessary?
+!
+!            dqtot = dqtot + (d_q(i,k) + d_ql(i,k))*masse
+!
+!         ENDDO
+!      ENDDO
+
+!        print*,'In manabe energy change=',dEtot
+!        print*,'In manabe condense energy change 1 =',dL1tot
+!        print*,'In manabe condense energy change 2 =',dL2tot
+!        print*,'In manabe water change=',dqtot
 
       RETURN
-      END
+   END
Index: /trunk/LMDZ.GENERIC/libf/phystd/newsedim.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/newsedim.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/newsedim.F	(revision 253)
@@ -12,14 +12,14 @@
 !==================================================================
 
-c-----------------------------------------------------------------------
-c   declarations:
-c   -------------
+!-----------------------------------------------------------------------
+!   declarations
+!   ------------
 
 #include "dimensions.h"
 #include "dimphys.h"
 #include "comcstfi.h"
-c
-c   arguments:
-c   ----------
+
+!   arguments
+!   ---------
 
       INTEGER ngrid,nlay,naersize
@@ -57,9 +57,9 @@
 c    Physical constant
 c    ~~~~~~~~~~~~~~~~~
-!      REAL visc, molrad
+      REAL visc, molrad
 c     Gas molecular viscosity (N.s.m-2)
-!      data visc/1.e-5/       ! CO2
+      data visc/1.e-5/       ! CO2
 c     Effective gas molecular radius (m)
-!      data molrad/2.2e-10/   ! CO2
+      data molrad/2.2e-10/   ! CO2
 
 c     local and saved variable
@@ -69,4 +69,7 @@
 c    ** un petit test de coherence
 c       --------------------------
+
+
+      !print*,'temporary fixed particle rad in newsedim!!'
 
       IF (firstcall) THEN
@@ -81,4 +84,5 @@
 
 
+
 !=======================================================================
 !     Preliminary calculations for sedimenation velocity
@@ -95,9 +99,7 @@
 c   (correction = 0.85 for irregular particles, 0.5 for disk shaped particles)
 c        a = a    * 0.85
+
+
       ENDIF
-
-
-
-
 
 c-----------------------------------------------------------------------
@@ -116,6 +118,19 @@
             else
               i=ngrid*(l-1)+ig
-              rfall=rd(i)
+              rfall=rd(i) ! how can this be correct!!?
             endif  
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+! TEMPORARY MODIF BY RDW !!!!
+            !rfall=5.e-6
+            if(rfall.lt.1.e-7)then
+               rfall=1.e-7
+            endif
+            !if(rfall.gt.5.e-5)then
+            !   rfall=5.e-5
+            !endif
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
             vstokes(ig,l) = b * rho * rfall**2 *
      &      (1 + 1.333* ( a*pt(ig,l)/pplev(ig,l) )/rfall)
Index: /trunk/LMDZ.GENERIC/libf/phystd/newtrelax.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/newtrelax.F90	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/newtrelax.F90	(revision 253)
@@ -0,0 +1,128 @@
+subroutine newtrelax(mu0,sinlat,popsk,temp,pplay,pplev,dtrad,firstcall) 
+        
+  implicit none
+
+#include "dimensions.h"
+#include "dimphys.h"
+#include "comcstfi.h"
+#include "callkeys.h"
+#include "netcdf.inc"
+
+!==================================================================
+!     
+!     Purpose
+!     -------
+!     Alternative Newtonian radiative transfer scheme.
+!     
+!     Authors
+!     -------
+!     R. Wordsworth (2010)
+!     
+!==================================================================
+  
+  ! Input
+  real mu0(ngridmx)                    ! cosine of sun incident angle
+  real sinlat(ngridmx)                 ! sine of latitude
+  real temp(ngridmx,nlayermx)          ! temperature at each layer (K)
+  real pplay(ngridmx,nlayermx)         ! pressure at each layer (Pa)
+  real pplev(ngridmx,nlayermx+1)       ! pressure at each level (Pa)
+  real popsk(ngridmx,nlayermx)         ! pot. T to T converter
+
+  ! Output
+  real dtrad(ngridmx,nlayermx) 
+
+  ! Internal
+  real Trelax(ngridmx,nlayermx), Trelax_V, Trelax_H
+  save Trelax
+
+  real T_trop ! relaxation temperature at tropopause (K)
+  real T_surf ! relaxation temperature at surface (K)
+  real dT_EP  ! Equator-Pole relaxation temperature difference (K)
+
+  real sig, f_sig, sig_trop
+  integer l,ig
+  logical firstcall
+
+
+  logical tidallocked
+  parameter (tidallocked = .true.)
+
+  ! Setup relaxation temperature  
+  if(firstcall) then
+
+     print*,'-----------------------------------------------------'
+     print*,'| ATTENTION: You are using a Newtonian cooling scheme'
+     print*,'| for the radiative transfer. This means that ALL'
+     print*,'| other physics subroutines must be switched off.'
+     print*,'-----------------------------------------------------'
+
+     if(tidallocked)then
+        do ig=1,ngridmx
+
+           T_surf = 126. + 239.*mu0(ig)
+           T_trop = 140. + 52.*mu0(ig)
+           do l=1,nlayermx
+
+              if(mu0(ig).le.0.0)then ! night side
+                 Trelax(ig,l)=0.0
+              else                   ! day side
+                 Trelax(ig,l) = T_surf*popsk(ig,l)
+                 if (Trelax(ig,l).lt.T_trop) Trelax(ig,l) = T_trop
+              endif
+
+           enddo
+        enddo
+
+     else
+
+        T_trop = 200.
+        T_surf = 288.
+        dT_EP  = 70.
+
+        sig_trop=(T_trop/T_surf)**(1./rcp)
+
+        do l=1,nlayermx
+           do ig=1,ngridmx
+
+              ! vertically varying component
+              Trelax_V = T_surf*popsk(ig,l)
+              if (Trelax_V.lt.T_trop) Trelax_V = T_trop
+              
+              ! horizontally varying component
+              sig = pplay(ig,l)/pplev(ig,1)
+              if(sig.ge.sig_trop)then
+                 f_sig=sin((pi/2)*((sig-sig_trop)/(1-sig_trop)))
+              else
+                 f_sig=0.0
+              endif
+              Trelax_H = -f_sig*dT_EP*(sinlat(ig)**2 - 1./3.)
+              
+              Trelax(ig,l) = Trelax_V + Trelax_H            
+           
+           enddo
+        enddo
+
+     endif
+
+     firstcall=.false.
+ 
+  endif
+
+  ! Calculate radiative forcing
+  do l=1,nlayermx
+     do ig=1,ngridmx
+        dtrad(ig,l) = -(temp(ig,l) - Trelax(ig,l)) / tau_relax
+        if(temp(ig,l).gt.500.)then ! Trelax(ig,l))then
+           print*,'ig=',ig
+           print*,'l=',l
+           print*,'temp=',temp(ig,l)
+           print*,'Trelax=',Trelax(ig,l)
+        endif
+     enddo
+  enddo
+
+  call writediagfi(ngridmx,'Tref','rad forc temp','K',3,Trelax)
+  !call writediagfi(ngridmx,'ThetaZ','stellar zenith angle','deg',2,mu0)
+
+  return
+end subroutine newtrelax
Index: /trunk/LMDZ.GENERIC/libf/phystd/optci.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/optci.F90	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/optci.F90	(revision 253)
@@ -3,7 +3,6 @@
            TMID,PMID,TAUGSURF,QVAR)
 
-
       use radinc_h
-      use radcommon_h, only: gasi, tlimit, wrefVAR, Cmk,tgasref,pfgasref,wnoi
+      use radcommon_h, only: gasi, tlimit, wrefVAR, Cmk,tgasref,pfgasref,wnoi,scalep
       implicit none
 
@@ -31,4 +30,5 @@
 #include "comcstfi.h"
 #include "callkeys.h"
+#include "gases.h"
 
 
@@ -58,5 +58,6 @@
 
       real*8 taugsurf(L_NSPECTI,L_NGAUSS-1)
-      real*8 dco2
+      real*8 DCONT
+      double precision wn_cont, p_cont, T_cont
 
 !     Water mixing ratio variables
@@ -69,5 +70,20 @@
 
 !     variables for k in units m^-1
-      real*8 rho, dz
+      real*8 rho, dz(L_LEVELS)
+
+      integer igas
+
+      !--- Kasting's CIA ----------------------------------------
+      !real*8, parameter :: Ci(L_NSPECTI)=[                         &
+      !     3.8E-5, 1.2E-5, 2.8E-6, 7.6E-7, 4.5E-7, 2.3E-7,    &
+      !     5.4E-7, 1.6E-6, 0.0,                               &
+      !     0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,            & 
+      !     0.0, 4.0E-7, 4.0E-6, 1.4E-5,    &
+      !     1.0E-5, 1.2E-6, 2.0E-7, 5.0E-8, 3.0E-8, 0.0 ] 
+      !real*8, parameter :: Ti(L_NSPECTI)=[ -2.2, -1.9,             &
+      !     -1.7, -1.7, -1.7, -1.7, -1.7, -1.7,                &
+      !     0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, &
+      !     -1.7,-1.7,-1.7,-1.7,-1.7,-1.7,-1.7, -1.7,0.0 ]
+      !----------------------------------------------------------
 
 !=======================================================================
@@ -75,47 +91,73 @@
 !     spectral interval, NW, and each Gauss point, NG.
 
-      DO NG=1,L_NGAUSS-1
-         do NW=1,L_NSPECTI
-            TAUGSURF(NW,NG) = 0.0D0
-         end do
-      end do
+      taugsurf(:,:) = 0.0
+      dpr(:)        = 0.0
+      lkcoef(:,:)   = 0.0
 
       do K=2,L_LEVELS
          DPR(k) = PLEV(K)-PLEV(K-1)
-
-         rho  = PLEV(K)/(R*TMID(K))
-         dz   = -DPR(k)/(g*rho)
-         !print*,'rho=',rho
-         !print*,'dz=',dz
-
          U(k)   = Cmk*DPR(k)    ! only Cmk line in optci.F
-         ! soon to be replaced by m^-1 !!!
+
+         !--- Kasting's CIA ----------------------------------------
+         !dz(k)=dpr(k)*189.02*TMID(K)/(0.03720*PMID(K))
+         ! this is CO2 path length (in cm) as written by Francois
+         ! delta_z = delta_p * R_specific * T / (g * P)
+         ! But Kasting states that W is in units of _atmosphere_ cm
+         ! So we do
+         !dz(k)=dz(k)*(PMID(K)/1013.25)
+         !dz(k)=dz(k)/100.0 ! in m for SI calc
+         !----------------------------------------------------------
+
+         ! if we have continuum opacities, we need dz
+         dz(k)=dpr(k)*R*TMID(K)/(g*PMID(K))
 
          call tpindex(PMID(K),TMID(K),QVAR(K),pfgasref,tgasref,WREFVAR, &
               LCOEF,MT(K),MP(K),NVAR(K),WRATIO(K))
-
+         
          do LK=1,4
             LKCOEF(K,LK) = LCOEF(LK)
          end do
 
+
          DO NW=1,L_NSPECTI
             do iaer=1,naerkind
-               TAEROS(K,NW,IAER) = TAUAERO(K,IAER)  * QXIAER(K,NW,IAER)
+               TAEROS(K,NW,IAER) = TAUAERO(K,IAER) * QXIAER(K,NW,IAER)
             end do
          END DO
       end do                    ! levels
 
-
       do K=2,L_LEVELS
          do nw=1,L_NSPECTI
  
-             DCO2   = 0.0 ! continuum absorption (no longer used)
-
-             !if(varactive)then
-             !   call water_cont(PMID(K),TMID(K),WRATIO(K),WNOI(nw),DCO2)
-             !endif
-
-           do ng=1,L_NGAUSS-1
-
+            DCONT = 0.0 ! continuum absorption
+
+            ! include H2 continuum
+            do igas=1,ngasmx
+               if(gnom(igas).eq.'H2_')then 
+
+                  wn_cont = dble(wnoi(nw))
+                  T_cont  = dble(TMID(k))
+                  p_cont  = dble(PMID(k)*scalep*gfrac(igas))
+
+                  call interpolateH2H2(wn_cont,T_cont,p_cont,DCONT,.false.)
+
+                  DCONT=DCONT*dz(k)
+
+
+               endif
+            enddo
+
+            !--- Kasting's CIA ----------------------------------------
+            !DCO2   = dz(k)*Ci(nw)*(1.2859*PMID(k)/1000.0)*(TMID(k)/300.)**Ti(nw)
+            !DCO2 = 130*Ci(nw)*(pmid(k)/1013.25)**2*(tmid(k)/300.)**Ti(nw) * dz(k)
+            ! these two have been verified to give the same results
+            !----------------------------------------------------------
+
+            ! Water continuum currently inactive!
+            !if(varactive)then
+            !   call water_cont(PMID(K),TMID(K),WRATIO(K),WNOI(nw),DCO2)
+            !endif
+
+            do ng=1,L_NGAUSS-1
 
 !     Now compute TAUGAS
@@ -125,6 +167,5 @@
 !     the water data range
 
-
-               if (L_REFVAR.eq.1)then ! added by RW for special no variable case
+               if(L_REFVAR.eq.1)then ! added by RW for special no variable case
                   KCOEF(1) = GASI(MT(K),MP(K),1,NW,NG)
                   KCOEF(2) = GASI(MT(K),MP(K)+1,1,NW,NG)
@@ -133,35 +174,36 @@
                else
 
-              KCOEF(1) = GASI(MT(K),MP(K),NVAR(K),NW,NG) + WRATIO(K)*     &
-                   (GASI(MT(K),MP(K),NVAR(K)+1,NW,NG) -                   & 
-                   GASI(MT(K),MP(K),NVAR(K),NW,NG))
-
-               KCOEF(2) = GASI(MT(K),MP(K)+1,NVAR(K),NW,NG) + WRATIO(K)*  &
-                   (GASI(MT(K),MP(K)+1,NVAR(K)+1,NW,NG) -                 &
-                   GASI(MT(K),MP(K)+1,NVAR(K),NW,NG))
-
-             KCOEF(3) = GASI(MT(K)+1,MP(K)+1,NVAR(K),NW,NG) + WRATIO(K)*  &
-                   (GASI(MT(K)+1,MP(K)+1,NVAR(K)+1,NW,NG) -               &
-                   GASI(MT(K)+1,MP(K)+1,NVAR(K),NW,NG))
-
-               KCOEF(4) = GASI(MT(K)+1,MP(K),NVAR(K),NW,NG) + WRATIO(K)*  &
-                   (GASI(MT(K)+1,MP(K),NVAR(K)+1,NW,NG) -                 &
-                   GASI(MT(K)+1,MP(K),NVAR(K),NW,NG))
+                  KCOEF(1) = GASI(MT(K),MP(K),NVAR(K),NW,NG) + WRATIO(K)*     &
+                       (GASI(MT(K),MP(K),NVAR(K)+1,NW,NG) -                   & 
+                       GASI(MT(K),MP(K),NVAR(K),NW,NG))
+
+                  KCOEF(2) = GASI(MT(K),MP(K)+1,NVAR(K),NW,NG) + WRATIO(K)*   &
+                       (GASI(MT(K),MP(K)+1,NVAR(K)+1,NW,NG) -                 &
+                       GASI(MT(K),MP(K)+1,NVAR(K),NW,NG))
+
+                  KCOEF(3) = GASI(MT(K)+1,MP(K)+1,NVAR(K),NW,NG) + WRATIO(K)* &
+                       (GASI(MT(K)+1,MP(K)+1,NVAR(K)+1,NW,NG) -               &
+                       GASI(MT(K)+1,MP(K)+1,NVAR(K),NW,NG))
+
+                  KCOEF(4) = GASI(MT(K)+1,MP(K),NVAR(K),NW,NG) + WRATIO(K)*   &
+                       (GASI(MT(K)+1,MP(K),NVAR(K)+1,NW,NG) -                 &
+                       GASI(MT(K)+1,MP(K),NVAR(K),NW,NG))
                endif
 
 !     Interpolate the gaseous k-coefficients to the requested T,P values
 
-               ANS = LKCOEF(K,1)*KCOEF(1) + LKCOEF(K,2)*KCOEF(2) +        &
+               ANS = LKCOEF(K,1)*KCOEF(1) + LKCOEF(K,2)*KCOEF(2) +            &
                     LKCOEF(K,3)*KCOEF(3) + LKCOEF(K,4)*KCOEF(4)
-
+               
                TAUGAS  = U(k)*ANS
 
-               TAUGSURF(NW,NG) = TAUGSURF(NW,NG) + TAUGAS
-
-               DTAUKI(K,nw,ng) = TAUGAS
+               TAUGSURF(NW,NG) = TAUGSURF(NW,NG) + TAUGAS + DCONT
+               !TAUGSURF(NW,NG) = TAUGSURF(NW,NG) + TAUGAS
+
+               DTAUKI(K,nw,ng) = TAUGAS + DCONT ! For parameterized continuum absorption
+
                do iaer=1,naerkind
-                  DTAUKI(K,nw,ng) = DTAUKI(K,nw,ng) + TAEROS(K,NW,IAER)   &
-                       + DCO2 ! For Kasting CIA
-               end do
+                  DTAUKI(K,nw,ng) = DTAUKI(K,nw,ng) + TAEROS(K,NW,IAER)
+               end do ! a bug was here!
 
             end do
@@ -171,9 +213,9 @@
 
             NG              = L_NGAUSS
-            DTAUKI(K,nw,ng) = 0.0
+            DTAUKI(K,nw,ng) = 0.0 + DCONT ! For parameterized continuum absorption
+
             do iaer=1,naerkind
-               DTAUKI(K,nw,ng) = DTAUKI(K,nw,ng) +  TAEROS(K,NW,IAER)     &
-                    + DCO2 ! For parameterized continuum absorption
-            end do ! a bug was found here!!
+               DTAUKI(K,nw,ng) = DTAUKI(K,nw,ng) +  TAEROS(K,NW,IAER)
+            end do ! a bug was here!
 
          end do
@@ -275,11 +317,11 @@
 
 !-------------------------------------------------------------------------
-    subroutine water_cont(p,T,wratio,nu,DCO2)
+    subroutine water_cont(p,T,wratio,nu,DCONT)
 !   Calculates the continuum opacity for H2O
-!   must check somewhere that it actually _is_ H2O we are using...
+!   NOT CURRENTLY USED
 
       implicit none
 
-      real p, T, wratio, nu, DCO2
+      real p, T, wratio, nu, DCONT
       real h1, h2
 
@@ -287,9 +329,9 @@
       h2 = 1.25e-22 + 1.67e-19*exp(-2.62e-13*nu)
 
-!      DCO2 = h1*h2*p*(p*wratio)**2/(R*T)
-
-      DCO2=0.0 ! to be implemented...
+!      DCONT = h1*h2*p*(p*wratio)**2/(R*T)
+!      DCONT=0.0 ! to be implemented...
 
       return
 
     end subroutine water_cont
+
Index: unk/LMDZ.GENERIC/libf/phystd/optcv.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/optcv.F	(revision 252)
+++ 	(revision )
@@ -1,260 +1,0 @@
-      SUBROUTINE OPTCV(DTAUV,TAUV,TAUCUMV,PLEV,
-     &     QXVAER,QSVAER,GVAER,WBARV,COSBV,
-     &     TAURAY,TAUAERO,TMID,PMID,TAUGSURF,QVAR)
-
-      use radinc_h
-      use radcommon_h, only: gasv, tlimit, wrefVAR, Cmk, tgasref, 
-     &     pfgasref
-
-      implicit none
-
-!==================================================================
-!     
-!     Purpose
-!     -------
-!     Calculates shortwave optical constants at each level.
-!     
-!     Authors
-!     -------
-!     Adapted from the NASA Ames code by R. Wordsworth (2009)
-!     
-!==================================================================
-
-
-C     
-C     THIS SUBROUTINE SETS THE OPTICAL CONSTANTS IN THE VISUAL  
-C     IT CALCUALTES FOR EACH LAYER, FOR EACH SPECRAL INTERVAL IN THE VISUAL
-C     LAYER: WBAR, DTAU, COSBAR
-C     LEVEL: TAU
-C     
-C     TAUV(L,NW,NG) is the cumulative optical depth at the top of radiation code
-C     layer L. NW is spectral wavelength interval, ng the Gauss point index.
-C     
-C     TLEV(L) - Temperature at the layer boundary
-C     PLEV(L) - Pressure at the layer boundary (i.e. level)
-C     GASV(NT,NPS,NW,NG) - Visual CO2 k-coefficients 
-C     
-C----------------------------------------------------------------------C
-
-#include "callkeys.h"
-#include "comcstfi.h"
-
-      real*8 DTAUV(L_NLAYRAD,L_NSPECTV,L_NGAUSS)
-      real*8 DTAUKV(L_LEVELS+1,L_NSPECTV,L_NGAUSS)
-      real*8 TAUV(L_NLEVRAD,L_NSPECTV,L_NGAUSS)
-      real*8 TAUCUMV(L_LEVELS,L_NSPECTV,L_NGAUSS)
-      real*8 PLEV(L_LEVELS)
-      real*8 TMID(L_LEVELS), PMID(L_LEVELS)
-      real*8 COSBV(L_NLAYRAD,L_NSPECTV,L_NGAUSS)
-      real*8 WBARV(L_NLAYRAD,L_NSPECTV,L_NGAUSS)
-      real*8 TAURAY(L_NSPECTV)
-
-!     For aerosols
-      real*8 QXVAER(L_LEVELS+1,L_NSPECTV,NAERKIND)
-      real*8 QSVAER(L_LEVELS+1,L_NSPECTV,NAERKIND)
-      real*8 GVAER(L_LEVELS+1,L_NSPECTV,NAERKIND)
-      real*8 TAUAERO(L_LEVELS+1,NAERKIND)
-      real*8 TAUAEROLK(L_LEVELS+1,L_NSPECTV,NAERKIND)
-      real*8 TAEROS(L_LEVELS,L_NSPECTV,NAERKIND)
-
-      integer L, NW, NG, K, NG1(L_NSPECTV), LK, IAER
-      integer MT(L_LEVELS), MP(L_LEVELS), NP(L_LEVELS)
-      real*8  ANS, TAUGAS
-      real*8  TRAY(L_LEVELS,L_NSPECTV)
-      real*8  DPR(L_LEVELS), U(L_LEVELS)
-      real*8  LCOEF(4), LKCOEF(L_LEVELS,4)
-
-      real*8 taugsurf(L_NSPECTV,L_NGAUSS-1), TRAYAER
-
-!     Water mixing ratio variables
-      real*8 QVAR(L_LEVELS), WRATIO(L_LEVELS)
-      real*8 KCOEF(4)
-      integer NVAR(L_LEVELS)
-
-!     temporary variables for multiple aerosol calculation
-      real*8 atemp, btemp, ctemp
-
-!     variables for k in units m^-1
-      real*8 rho, dz
-
-!=======================================================================
-!     Determine the total gas opacity throughout the column, for each
-!     spectral interval, NW, and each Gauss point, NG.
-!     Calculate the continuum opacities, i.e., those that do not depend on
-!     NG, the Gauss index.
-
-      do K=2,L_LEVELS
-         DPR(k) = PLEV(K)-PLEV(K-1)
-
-
-         rho  = PLEV(K)/(R*TMID(K))
-         dz   = -DPR(k)/(g*rho)
-         !print*,'rho=',rho
-         !print*,'dz=',dz
-
-         U(k)   = Cmk*DPR(k)
-
-         call tpindex(PMID(K),TMID(K),QVAR(K),pfgasref,tgasref,WREFVAR,
-     *        LCOEF,MT(K),MP(K),NVAR(K),WRATIO(K))
-
-         do LK=1,4
-            LKCOEF(K,LK) = LCOEF(LK)
-         end do
-
-         DO NW=1,L_NSPECTV
-            TRAY(K,NW)   = TAURAY(NW) * DPR(K)
-
-            do iaer=1,naerkind
-               TAEROS(K,NW,IAER) = TAUAERO(K,IAER)  * QXVAER(K,NW,IAER)
-            end do
-!     
-
-         END DO
-      end do
-
-!     TRAYAER is Tau RAYleigh scattering, plus AERosol opacity
-
-
-!     we ignore K=1... hope this is ok...
-      do K=2,L_LEVELS
-         do NW=1,L_NSPECTV
-
-            TRAYAER = TRAY(K,NW)
-            do iaer=1,naerkind
-               TRAYAER = TRAYAER + TAEROS(K,NW,IAER)
-            end do
-
-            do NG=1,L_NGAUSS-1
-
-!=======================================================================
-!     Now compute TAUGAS
-!     Interpolate between water mixing ratios
-!     WRATIO = 0.0 if the requested water amount is equal to, or outside the
-!     the water data range
-
-               if (L_REFVAR.eq.1)then ! added by RW for special no variable case
-                  KCOEF(1) = GASV(MT(K),MP(K),1,NW,NG)
-                  KCOEF(2) = GASV(MT(K),MP(K)+1,1,NW,NG)
-                  KCOEF(3) = GASV(MT(K)+1,MP(K)+1,1,NW,NG)
-                  KCOEF(4) = GASV(MT(K)+1,MP(K),1,NW,NG)
-               else
-               KCOEF(1) = GASV(MT(K),MP(K),NVAR(K),NW,NG) + WRATIO(K)*
-     *              (GASV(MT(K),MP(K),NVAR(K)+1,NW,NG) - 
-     *              GASV(MT(K),MP(K),NVAR(K),NW,NG))
-
-               KCOEF(2) = GASV(MT(K),MP(K)+1,NVAR(K),NW,NG) + WRATIO(K)*
-     *              (GASV(MT(K),MP(K)+1,NVAR(K)+1,NW,NG) - 
-     *              GASV(MT(K),MP(K)+1,NVAR(K),NW,NG))
-
-             KCOEF(3) = GASV(MT(K)+1,MP(K)+1,NVAR(K),NW,NG) + WRATIO(K)*
-     *              (GASV(MT(K)+1,MP(K)+1,NVAR(K)+1,NW,NG) - 
-     *              GASV(MT(K)+1,MP(K)+1,NVAR(K),NW,NG))
-
-               KCOEF(4) = GASV(MT(K)+1,MP(K),NVAR(K),NW,NG) + WRATIO(K)*
-     *              (GASV(MT(K)+1,MP(K),NVAR(K)+1,NW,NG) - 
-     *              GASV(MT(K)+1,MP(K),NVAR(K),NW,NG))
-               endif
-
-!     Interpolate the gaseous k-coefficients to the requested T,P values
-               
-               ANS = LKCOEF(K,1)*KCOEF(1) + LKCOEF(K,2)*KCOEF(2) +
-     *              LKCOEF(K,3)*KCOEF(3) + LKCOEF(K,4)*KCOEF(4)
-
-               TAUGAS          = U(k)*ANS
-               TAUGSURF(NW,NG) = TAUGSURF(NW,NG) + TAUGAS
-               DTAUKV(K,nw,ng) = TAUGAS + TRAYAER 
-            end do
-
-
-!     Now fill in the "clear" part of the spectrum (NG = L_NGAUSS),
-!     which holds continuum opacity only
-
-            NG = L_NGAUSS
-            DTAUKV(K,nw,ng) = TRAY(K,NW)
-            do iaer=1,naerkind
-               DTAUKV(K,nw,ng) = DTAUKV(K,nw,ng) + TAEROS(K,NW,IAER)
-            end do
-
-         end do
-      end do
-
-
-!=======================================================================
-!     Now the full treatment for the layers, where besides the opacity
-!     we need to calculate the scattering albedo and asymmetry factors
-
-      DO NW=1,L_NSPECTV
-         DO K=2,L_LEVELS
-            do iaer=1,naerkind
-              TAUAEROLK(K,NW,IAER) = TAUAERO(K,IAER) * QSVAER(K,NW,IAER)
-            end do
-         ENDDO
-      ENDDO
-      
-
-      DO NW=1,L_NSPECTV
-         DO NG=1,L_NGAUSS
-            DO L=1,L_NLAYRAD-1
-               K              = 2*L+1
-
-               DTAUV(L,nw,ng) = DTAUKV(K,NW,NG)+DTAUKV(K+1,NW,NG)
-
-               atemp=0.
-               btemp=TRAY(K,NW) + TRAY(K+1,NW)
-               ctemp=0.9999*(TRAY(K,NW) + TRAY(K+1,NW))
-               do iaer=1,naerkind
-                  atemp = atemp + 
-     *                 GVAER(K,NW,IAER)   * TAUAEROLK(K,NW,IAER) + 
-     *                 GVAER(K+1,NW,IAER) * TAUAEROLK(K+1,NW,IAER)
-                  btemp = btemp + 
-     *                 TAUAEROLK(K,NW,IAER) + TAUAEROLK(K+1,NW,IAER)
-                  ctemp = ctemp + 
-     *                 TAUAEROLK(K,NW,IAER) + TAUAEROLK(K+1,NW,IAER)
-               end do
-
-               COSBV(L,NW,NG) = atemp/btemp
-               WBARV(L,nw,ng) = ctemp/DTAUV(L,nw,ng)
-
-            END DO
-
-!     No vertical averaging on bottom layer
-
-            L              = L_NLAYRAD
-            K              = 2*L+1
-            DTAUV(L,nw,ng) = DTAUKV(K,NW,NG)
-
-            atemp=0.
-            btemp=TRAY(K,NW)
-            ctemp=0.9999*TRAY(K,NW)
-            do iaer=1,naerkind
-               atemp = atemp + GVAER(K,NW,IAER) * TAUAEROLK(K,NW,IAER) 
-               btemp = btemp + TAUAEROLK(K,NW,IAER) 
-               ctemp = ctemp + TAUAEROLK(K,NW,IAER)
-            end do
-            COSBV(L,NW,NG) = atemp/btemp
-            WBARV(L,nw,ng) = ctemp/DTAUV(L,nw,ng)
-
-         END DO                 ! NG gauss point loop
-      END DO                    ! NW spectral loop
-
-
-
-!     Total extinction optical depths
-
-      DO NW=1,L_NSPECTV        
-         DO NG=1,L_NGAUSS       ! full gauss loop
-            TAUV(1,NW,NG)=0.0D0
-            DO L=1,L_NLAYRAD
-               TAUV(L+1,NW,NG)=TAUV(L,NW,NG)+DTAUV(L,NW,NG)
-            END DO
-
-            TAUCUMV(1,NW,NG)=0.0D0
-            DO K=2,L_LEVELS
-               TAUCUMV(K,NW,NG)=TAUCUMV(K-1,NW,NG)+DTAUKV(K,NW,NG)
-            END DO
-         END DO                 ! end full gauss loop
-      END DO
-
-
-      RETURN
-      END
Index: /trunk/LMDZ.GENERIC/libf/phystd/optcv.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/optcv.F90	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/optcv.F90	(revision 253)
@@ -0,0 +1,287 @@
+      SUBROUTINE OPTCV(DTAUV,TAUV,TAUCUMV,PLEV,  &
+          QXVAER,QSVAER,GVAER,WBARV,COSBV,       &
+          TAURAY,TAUAERO,TMID,PMID,TAUGSURF,QVAR)
+
+      use radinc_h
+      use radcommon_h, only: gasv, tlimit, wrefVAR, Cmk, tgasref, pfgasref,wnov,scalep
+
+      implicit none
+
+!==================================================================
+!     
+!     Purpose
+!     -------
+!     Calculates shortwave optical constants at each level.
+!     
+!     Authors
+!     -------
+!     Adapted from the NASA Ames code by R. Wordsworth (2009)
+!     
+!==================================================================
+!     
+!     THIS SUBROUTINE SETS THE OPTICAL CONSTANTS IN THE VISUAL  
+!     IT CALCUALTES FOR EACH LAYER, FOR EACH SPECRAL INTERVAL IN THE VISUAL
+!     LAYER: WBAR, DTAU, COSBAR
+!     LEVEL: TAU
+!     
+!     TAUV(L,NW,NG) is the cumulative optical depth at the top of radiation code
+!     layer L. NW is spectral wavelength interval, ng the Gauss point index.
+!     
+!     TLEV(L) - Temperature at the layer boundary
+!     PLEV(L) - Pressure at the layer boundary (i.e. level)
+!     GASV(NT,NPS,NW,NG) - Visual CO2 k-coefficients 
+!     
+!-------------------------------------------------------------------
+
+#include "callkeys.h"
+#include "comcstfi.h"
+#include "gases.h"
+
+      real*8 DTAUV(L_NLAYRAD,L_NSPECTV,L_NGAUSS)
+      real*8 DTAUKV(L_LEVELS+1,L_NSPECTV,L_NGAUSS)
+      real*8 TAUV(L_NLEVRAD,L_NSPECTV,L_NGAUSS)
+      real*8 TAUCUMV(L_LEVELS,L_NSPECTV,L_NGAUSS)
+      real*8 PLEV(L_LEVELS)
+      real*8 TMID(L_LEVELS), PMID(L_LEVELS)
+      real*8 COSBV(L_NLAYRAD,L_NSPECTV,L_NGAUSS)
+      real*8 WBARV(L_NLAYRAD,L_NSPECTV,L_NGAUSS)
+      real*8 TAURAY(L_NSPECTV)
+
+!     For aerosols
+      real*8 QXVAER(L_LEVELS+1,L_NSPECTV,NAERKIND)
+      real*8 QSVAER(L_LEVELS+1,L_NSPECTV,NAERKIND)
+      real*8 GVAER(L_LEVELS+1,L_NSPECTV,NAERKIND)
+      real*8 TAUAERO(L_LEVELS+1,NAERKIND)
+      real*8 TAUAEROLK(L_LEVELS+1,L_NSPECTV,NAERKIND)
+      real*8 TAEROS(L_LEVELS,L_NSPECTV,NAERKIND)
+
+      integer L, NW, NG, K, NG1(L_NSPECTV), LK, IAER
+      integer MT(L_LEVELS), MP(L_LEVELS), NP(L_LEVELS)
+      real*8  ANS, TAUGAS
+      real*8  TRAY(L_LEVELS,L_NSPECTV)
+      real*8  DPR(L_LEVELS), U(L_LEVELS)
+      real*8  LCOEF(4), LKCOEF(L_LEVELS,4)
+
+      real*8 taugsurf(L_NSPECTV,L_NGAUSS-1), TRAYAER
+
+!     Water mixing ratio variables
+      real*8 QVAR(L_LEVELS), WRATIO(L_LEVELS)
+      real*8 KCOEF(4)
+      integer NVAR(L_LEVELS)
+
+!     temporary variables for multiple aerosol calculation
+      real*8 atemp, btemp, ctemp
+
+!     variables for k in units m^-1
+      double precision wn_cont, p_cont, T_cont
+      real*8 dz(L_LEVELS), DCONT
+
+      integer igas
+
+!=======================================================================
+!     Determine the total gas opacity throughout the column, for each
+!     spectral interval, NW, and each Gauss point, NG.
+!     Calculate the continuum opacities, i.e., those that do not depend on
+!     NG, the Gauss index.
+
+      taugsurf(:,:) = 0.0
+      dpr(:)        = 0.0
+      lkcoef(:,:)   = 0.0
+
+      do K=2,L_LEVELS
+         DPR(k) = PLEV(K)-PLEV(K-1)
+
+         U(k)   = Cmk*DPR(k)
+
+         ! if we have continuum opacities, we need dz
+         dz(k)  = dpr(k)*R*TMID(K)/(g*PMID(K))
+
+         call tpindex(PMID(K),TMID(K),QVAR(K),pfgasref,tgasref,WREFVAR, &
+              LCOEF,MT(K),MP(K),NVAR(K),WRATIO(K))
+
+         do LK=1,4
+            LKCOEF(K,LK) = LCOEF(LK)
+         end do
+
+         DO NW=1,L_NSPECTV
+            TRAY(K,NW)   = TAURAY(NW) * DPR(K)
+
+            do iaer=1,naerkind
+               TAEROS(K,NW,IAER) = TAUAERO(K,IAER)  * QXVAER(K,NW,IAER)
+            end do
+!     
+
+         END DO
+      end do
+
+!     TRAYAER is Tau RAYleigh scattering, plus AERosol opacity
+
+!     we ignore K=1...
+      do K=2,L_LEVELS
+         do NW=1,L_NSPECTV
+
+            TRAYAER = TRAY(K,NW)
+            do iaer=1,naerkind
+               TRAYAER = TRAYAER + TAEROS(K,NW,IAER)
+            end do
+
+            DCONT = 0.0 ! continuum absorption
+
+            ! include H2 continuum
+            do igas=1,ngasmx
+               if(gnom(igas).eq.'H2_')then 
+
+                  wn_cont = dble(wnov(nw))
+                  T_cont  = dble(TMID(k))
+                  p_cont  = dble(PMID(k)*scalep*gfrac(igas))
+                  call interpolateH2H2(wn_cont,T_cont,p_cont,DCONT,.false.)
+
+                  DCONT=DCONT*dz(k) 
+
+                  if((.not.callgasvis))then
+                     DCONT=0.0
+                  endif
+
+
+               endif
+            enddo
+
+            do NG=1,L_NGAUSS-1
+
+!=======================================================================
+!     Now compute TAUGAS
+!     Interpolate between water mixing ratios
+!     WRATIO = 0.0 if the requested water amount is equal to, or outside the
+!     the water data range
+
+               if (L_REFVAR.eq.1)then ! added by RW for special no variable case
+                  KCOEF(1) = GASV(MT(K),MP(K),1,NW,NG)
+                  KCOEF(2) = GASV(MT(K),MP(K)+1,1,NW,NG)
+                  KCOEF(3) = GASV(MT(K)+1,MP(K)+1,1,NW,NG)
+                  KCOEF(4) = GASV(MT(K)+1,MP(K),1,NW,NG)
+               else
+                  KCOEF(1) = GASV(MT(K),MP(K),NVAR(K),NW,NG) + WRATIO(K)*    &
+                       (GASV(MT(K),MP(K),NVAR(K)+1,NW,NG) -                  &
+                       GASV(MT(K),MP(K),NVAR(K),NW,NG))
+
+                  KCOEF(2) = GASV(MT(K),MP(K)+1,NVAR(K),NW,NG) + WRATIO(K)*  &
+                       (GASV(MT(K),MP(K)+1,NVAR(K)+1,NW,NG) -                &
+                       GASV(MT(K),MP(K)+1,NVAR(K),NW,NG))
+
+                  KCOEF(3) = GASV(MT(K)+1,MP(K)+1,NVAR(K),NW,NG) + WRATIO(K)*&
+                       (GASV(MT(K)+1,MP(K)+1,NVAR(K)+1,NW,NG) -              &
+                       GASV(MT(K)+1,MP(K)+1,NVAR(K),NW,NG))
+
+                  KCOEF(4) = GASV(MT(K)+1,MP(K),NVAR(K),NW,NG) + WRATIO(K)*  &
+                       (GASV(MT(K)+1,MP(K),NVAR(K)+1,NW,NG) -                &
+                       GASV(MT(K)+1,MP(K),NVAR(K),NW,NG))
+               endif
+
+!     Interpolate the gaseous k-coefficients to the requested T,P values
+               
+               ANS = LKCOEF(K,1)*KCOEF(1) + LKCOEF(K,2)*KCOEF(2) +           &
+                    LKCOEF(K,3)*KCOEF(3) + LKCOEF(K,4)*KCOEF(4)
+
+               TAUGAS          = U(k)*ANS
+
+               !TAUGSURF(NW,NG) = TAUGSURF(NW,NG) + TAUGAS
+               TAUGSURF(NW,NG) = TAUGSURF(NW,NG) + TAUGAS + DCONT
+               DTAUKV(K,nw,ng) = TAUGAS + TRAYAER  & ! TRAYAER includes all scattering contributions
+                                 + DCONT             ! for continuum absorption
+
+            end do
+
+
+!     Now fill in the "clear" part of the spectrum (NG = L_NGAUSS),
+!     which holds continuum opacity only
+
+            NG = L_NGAUSS
+            DTAUKV(K,nw,ng) = TRAY(K,NW) + DCONT ! For parameterized continuum absorption
+            do iaer=1,naerkind
+               DTAUKV(K,nw,ng) = DTAUKV(K,nw,ng) + TAEROS(K,NW,IAER)
+!     &                           + DCONT          ! For parameterized continuum absorption
+            end do ! a bug was here!
+
+         end do
+      end do
+
+
+!=======================================================================
+!     Now the full treatment for the layers, where besides the opacity
+!     we need to calculate the scattering albedo and asymmetry factors
+
+      DO NW=1,L_NSPECTV
+         DO K=2,L_LEVELS
+            do iaer=1,naerkind
+              TAUAEROLK(K,NW,IAER) = TAUAERO(K,IAER) * QSVAER(K,NW,IAER)
+            end do
+         ENDDO
+      ENDDO
+      
+
+      DO NW=1,L_NSPECTV
+         DO NG=1,L_NGAUSS
+            DO L=1,L_NLAYRAD-1
+               K              = 2*L+1
+
+               DTAUV(L,nw,ng) = DTAUKV(K,NW,NG)+DTAUKV(K+1,NW,NG)
+
+               atemp=0.
+               btemp=TRAY(K,NW) + TRAY(K+1,NW)
+               ctemp=0.9999*(TRAY(K,NW) + TRAY(K+1,NW))
+               do iaer=1,naerkind
+                  atemp = atemp +                                     &
+                       GVAER(K,NW,IAER)   * TAUAEROLK(K,NW,IAER) +    &
+                       GVAER(K+1,NW,IAER) * TAUAEROLK(K+1,NW,IAER)
+                  btemp = btemp +                                     &
+                       TAUAEROLK(K,NW,IAER) + TAUAEROLK(K+1,NW,IAER)
+                  ctemp = ctemp +                                     &
+                       TAUAEROLK(K,NW,IAER) + TAUAEROLK(K+1,NW,IAER)
+               end do
+
+               COSBV(L,NW,NG) = atemp/btemp
+               WBARV(L,nw,ng) = ctemp/DTAUV(L,nw,ng)
+
+            END DO
+
+!     No vertical averaging on bottom layer
+
+            L              = L_NLAYRAD
+            K              = 2*L+1
+            DTAUV(L,nw,ng) = DTAUKV(K,NW,NG)
+
+            atemp=0.
+            btemp=TRAY(K,NW)
+            ctemp=0.9999*TRAY(K,NW)
+            do iaer=1,naerkind
+               atemp = atemp + GVAER(K,NW,IAER) * TAUAEROLK(K,NW,IAER) 
+               btemp = btemp + TAUAEROLK(K,NW,IAER) 
+               ctemp = ctemp + TAUAEROLK(K,NW,IAER)
+            end do
+            COSBV(L,NW,NG) = atemp/btemp
+            WBARV(L,nw,ng) = ctemp/DTAUV(L,nw,ng)
+
+         END DO                 ! NG gauss point loop
+      END DO                    ! NW spectral loop
+
+
+
+!     Total extinction optical depths
+
+      DO NW=1,L_NSPECTV        
+         DO NG=1,L_NGAUSS       ! full gauss loop
+            TAUV(1,NW,NG)=0.0D0
+            DO L=1,L_NLAYRAD
+               TAUV(L+1,NW,NG)=TAUV(L,NW,NG)+DTAUV(L,NW,NG)
+            END DO
+
+            TAUCUMV(1,NW,NG)=0.0D0
+            DO K=2,L_LEVELS
+               TAUCUMV(K,NW,NG)=TAUCUMV(K-1,NW,NG)+DTAUKV(K,NW,NG)
+            END DO
+         END DO                 ! end full gauss loop
+      END DO
+
+
+      RETURN
+    END SUBROUTINE OPTCV
Index: /trunk/LMDZ.GENERIC/libf/phystd/orbite.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/orbite.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/orbite.F	(revision 253)
@@ -1,32 +1,23 @@
-      SUBROUTINE orbite(pls,pdist_sol,pdecli)
-      IMPLICIT NONE
+      subroutine orbite(pls,pdist_star,pdecli)
+      implicit none
 
-c=======================================================================
-c
-c   Objet:
-c   ------
-c
-c   Distance from sun and declimation as a function of the solar
-c   longitude Ls
-c
-c   Interface:
-c   ----------
-c
-c
-c
-c   Arguments:
-c   ----------
-c
-c   Input:
-c   ------
-c   pls          Ls
-c
-c   Output:
-c   -------
-c   pdist_sol     Distance Sun-Planet in UA
-c   pdecli        declinaison ( en radians )
-c
-c=======================================================================
-c-----------------------------------------------------------------------
+!==================================================================
+!     
+!     Purpose
+!     -------
+!     Distance from star and declination as a function of the stellar
+!     longitude Ls
+!     
+!     Inputs
+!     ------
+!     pls          Ls
+!
+!     Outputs
+!     -------
+!     pdist_star    Distance Star-Planet in UA
+!     pdecli        declinaison ( in radians )
+!
+!=======================================================================
+
 c   Declarations:
 c   -------------
@@ -38,17 +29,17 @@
 c ----------
 
-      REAL pday,pdist_sol,pdecli,pls,i
+      REAL pday,pdist_star,pdecli,pls,i
 
 c-----------------------------------------------------------------------
 
-c Distance Sun-Planet
+c Star-Planet Distance
 
-      pdist_sol=p_elips/(1.+e_elips*cos(pls+timeperi))
+      pdist_star = p_elips/(1.+e_elips*cos(pls+timeperi))
 
-c Solar declination
+c Stellar declination
 
 c ********************* version before 01/01/2000 *******
 
-      pdecli= asin (sin(pls)*sin(obliquit*pi/180.))
+      pdecli = asin (sin(pls)*sin(obliquit*pi/180.))
 
 c ********************* version after 01/01/2000 *******
@@ -58,6 +49,4 @@
 c ******************************************************
 
-
-
       RETURN
       END
Index: /trunk/LMDZ.GENERIC/libf/phystd/phyetat0.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/phyetat0.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/phyetat0.F	(revision 253)
@@ -1,5 +1,5 @@
       SUBROUTINE phyetat0 (fichnom,tab0,Lmodif,nsoil,nq,
      .           day_ini,time,
-     .           tsurf,tsoil,emis,q2,qsurf)
+     .           tsurf,tsoil,emis,q2,qsurf,cloudfrac,totcloudfrac,hice)
       implicit none
 c======================================================================
@@ -39,4 +39,8 @@
       real qsurf(ngridmx,nq) ! tracers on surface
 !      real co2ice(ngridmx) ! co2 ice cover
+      real cloudfrac(ngridmx,nlayermx)
+      real hice(ngridmx), totcloudfrac(ngridmx)
+
+
 
 !======================================================================
@@ -487,4 +491,82 @@
       xmax = MAXVAL(emis)
       PRINT*,'Surface emissivity <emis>:', xmin, xmax
+
+c
+c Cloud fraction (added by BC 2010)
+c
+      ierr = NF_INQ_VARID (nid, "cloudfrac", nvarid)
+      IF (ierr.NE.NF_NOERR) THEN
+         PRINT*, 'phyetat0: Le champ <cloudfrac> est absent'
+      cloudfrac(:,:)=0.5
+!         CALL abort
+      ENDIF
+#ifdef NC_DOUBLE
+      ierr = NF_GET_VAR_DOUBLE(nid, nvarid, cloudfrac)
+#else
+      ierr = NF_GET_VAR_REAL(nid, nvarid, cloudfrac)
+#endif
+      IF (ierr.NE.NF_NOERR) THEN
+         PRINT*, 'phyetat0: Lecture echouee pour <cloudfrac>'
+         CALL abort
+      ENDIF
+      xmin = 1.0E+20
+      xmax = -1.0E+20
+      xmin = MINVAL(cloudfrac)
+      xmax = MAXVAL(cloudfrac)
+      PRINT*,'Cloud fraction <cloudfrac>:', xmin, xmax
+
+
+c
+c Total cloud fraction (added by BC 2010)
+c
+      ierr = NF_INQ_VARID (nid, "totcloudfrac", nvarid)
+!      ierr = NF_INQ_VARID (nid, "totalfrac", nvarid)
+      IF (ierr.NE.NF_NOERR) THEN
+         PRINT*, 'phyetat0: Le champ <totcloudfrac> est absent'
+      totcloudfrac(:)=0.5
+!         CALL abort
+      ENDIF
+#ifdef NC_DOUBLE
+      ierr = NF_GET_VAR_DOUBLE(nid, nvarid, totcloudfrac)
+#else
+      ierr = NF_GET_VAR_REAL(nid, nvarid, totcloudfrac)
+#endif
+      IF (ierr.NE.NF_NOERR) THEN
+         PRINT*, 'phyetat0: Lecture echouee pour <totcloudfrac>'
+         CALL abort
+      ENDIF
+      xmin = 1.0E+20
+      xmax = -1.0E+20
+      xmin = MINVAL(totcloudfrac)
+      xmax = MAXVAL(totcloudfrac)
+      PRINT*,'Cloud fraction <totcloudfrac>:', xmin, xmax
+
+
+
+
+c
+c Height of oceanic ice (added by BC 2010)
+c
+      ierr = NF_INQ_VARID (nid, "hice", nvarid)
+      IF (ierr.NE.NF_NOERR) THEN
+         PRINT*, 'phyetat0: Le champ <hice> est absent'
+         CALL abort
+      ENDIF
+#ifdef NC_DOUBLE
+      ierr = NF_GET_VAR_DOUBLE(nid, nvarid, hice)
+#else
+      ierr = NF_GET_VAR_REAL(nid, nvarid, hice)
+#endif
+      IF (ierr.NE.NF_NOERR) THEN
+         PRINT*, 'phyetat0: Lecture echouee pour <hice>'
+         CALL abort
+      ENDIF
+      xmin = 1.0E+20
+      xmax = -1.0E+20
+      xmin = MINVAL(hice)
+      xmax = MAXVAL(hice)
+      PRINT*,'Height of oceanic ice <hice>:', xmin, xmax
+
+
 c
 c pbl wind variance
@@ -524,11 +606,11 @@
            ELSE
              txt=tnom(iq)
-             if (txt.eq."h2o_vap") then
+!             if (txt.eq."h2o_vap") then
                ! There is no surface tracer for h2o_vap;
                ! "h2o_ice" should be loaded instead
-               txt="h2o_ice"
-               write(*,*) 'phyetat0: loading surface tracer',
-     &                     ' h2o_ice instead of h2o_vap'
-             endif
+!               txt="h2o_ice"
+!               write(*,*) 'phyetat0: loading surface tracer',
+!     &                     ' h2o_ice instead of h2o_vap'
+!             endif
            ENDIF ! of IF (oldtracernames) THEN
            ierr=NF_INQ_VARID(nid,txt,nvarid)
Index: /trunk/LMDZ.GENERIC/libf/phystd/physdem1.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/physdem1.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/physdem1.F	(revision 253)
@@ -2,20 +2,31 @@
      .                   phystep,day_ini,
      .                   time,tsurf,tsoil,emis,q2,qsurf,
-     .                   airefi,alb,ith,pzmea,pzstd,pzsig,pzgam,pzthe)
-
-
+     .                   airefi,alb,ith,pzmea,pzstd,pzsig,pzgam,pzthe,
+     .                   cloudfrac,totcloudfrac,hice)
 
       use radcommon_h, only: tauvis
-
+ 
       implicit none
-c-------------------------------------------------------------
-c
-c create physics (re-)start data file "restartfi.nc"
-c
-c
-c
+
+!==================================================================
+!     
+!     Purpose
+!     -------
+!     Create physics (re-)start data file "restartfi.nc"
+!     
+!     Called by
+!     ---------
+!     rcm1d.F90
+!     physiq.F90
+!     newstart.F
+!     
+!     Calls
+!     -----
+!     none
+!
+!==================================================================
+
 #include "dimensions.h"
 #include "paramet.h"
-c-----------------------------------------------------------------------
 #include "comvert.h"
 #include "comgeom2.h"
@@ -39,5 +50,4 @@
       integer ierr,idim1,idim2,idim3,idim4,idim5,nvarid
 
-c
       REAL phystep,time
       REAL latfi(ngridmx), lonfi(ngridmx)
@@ -48,9 +58,12 @@
       REAL tab_cntrl(length)
 
-c
+!     added by BC
+      REAL hice(ngridmx),cloudfrac(ngridmx,nlayermx)
+      REAL totcloudfrac(ngridmx)
+
 
 !      EXTERNAL defrun_new,iniconst,geopot,inigeom,massdair,pression
 !      EXTERNAL exner_hyb , SSUM
-c
+
 #include "serre.h"
 #include "clesph0.h"
@@ -178,7 +191,7 @@
 c Informations about Mars, only for physics
       tab_cntrl(14) = year_day  ! length of year (sols) ~668.6
-      tab_cntrl(15) = periheli  ! min. Sun-Mars distance (Mkm) ~206.66
-      tab_cntrl(16) = aphelie   ! max. SUn-Mars distance (Mkm) ~249.22
-      tab_cntrl(17) = peri_day  ! date of perihelion (sols since N. spring)
+      tab_cntrl(15) = periastr  ! min. star-planet distance (Mkm) ~206.66
+      tab_cntrl(16) = apoastr   ! max. star-planet distance (Mkm) ~249.22
+      tab_cntrl(17) = peri_day  ! date of periastron (sols since N. spring)
       tab_cntrl(18) = obliquit  ! Obliquity of the planet (deg) ~23.98
 
@@ -452,4 +465,8 @@
 !#endif
 
+
+
+
+
 ! Soil Thermal inertia
 
@@ -471,4 +488,7 @@
 #endif
 
+
+
+
 !  Surface temperature
 
@@ -527,5 +547,5 @@
       ierr = NF_REDEF (nid)
 #ifdef NC_DOUBLE
-      ierr = NF_DEF_VAR (nid, "q2", NF_DOUBLE, 2, (/idim2,idim4/),nvarid)
+      ierr = NF_DEF_VAR (nid,"q2", NF_DOUBLE, 2, (/idim2,idim4/),nvarid)
 #else
       ierr = NF_DEF_VAR (nid, "q2", NF_FLOAT, 2,(/idim2,idim4/),nvarid)
@@ -543,4 +563,71 @@
         CALL abort
       ENDIF
+
+
+
+
+
+
+
+c cloud fraction (added by BC 2010)
+
+      ierr = NF_REDEF (nid)
+#ifdef NC_DOUBLE
+      ierr = NF_DEF_VAR (nid, "cloudfrac", NF_DOUBLE, 1, idim2,nvarid)
+#else
+      ierr = NF_DEF_VAR (nid, "cloudfrac", NF_FLOAT, 1, idim2,nvarid)
+#endif
+      ierr = NF_PUT_ATT_TEXT (nid, nvarid, "title", 14,
+     .                        "Cloud fraction")
+      ierr = NF_ENDDEF(nid)
+#ifdef NC_DOUBLE
+      ierr = NF_PUT_VAR_DOUBLE (nid,nvarid,cloudfrac)
+#else
+      ierr = NF_PUT_VAR_REAL (nid,nvarid,cloudfrac)
+#endif
+
+c total cloud fraction (added by BC 2010)
+
+      ierr = NF_REDEF (nid)
+#ifdef NC_DOUBLE
+      ierr = NF_DEF_VAR (nid,"totcloudfrac", NF_DOUBLE, 1, idim2,nvarid)
+#else
+      ierr = NF_DEF_VAR (nid, "totcloudfrac", NF_FLOAT, 1, idim2,nvarid)
+#endif
+      ierr = NF_PUT_ATT_TEXT (nid, nvarid, "title", 14,
+     .                        "Total fraction")
+      ierr = NF_ENDDEF(nid)
+#ifdef NC_DOUBLE
+      ierr = NF_PUT_VAR_DOUBLE (nid,nvarid,totcloudfrac)
+#else
+      ierr = NF_PUT_VAR_REAL (nid,nvarid,totcloudfrac)
+#endif
+
+c oceanic ice (added by BC 2010)
+
+      ierr = NF_REDEF (nid)
+#ifdef NC_DOUBLE
+      ierr = NF_DEF_VAR (nid, "hice", NF_DOUBLE, 1, idim2,nvarid)
+#else
+      ierr = NF_DEF_VAR (nid, "hice", NF_FLOAT, 1, idim2,nvarid)
+#endif
+      ierr = NF_PUT_ATT_TEXT (nid, nvarid, "title", 21,
+     .                        "Height of oceanic ice")
+      ierr = NF_ENDDEF(nid)
+#ifdef NC_DOUBLE
+      ierr = NF_PUT_VAR_DOUBLE (nid,nvarid,hice)
+#else
+      ierr = NF_PUT_VAR_REAL (nid,nvarid,hice)
+#endif
+
+
+
+
+
+
+
+
+
+
 
 c tracers
@@ -591,5 +678,7 @@
          if ((i_h2o_vap.ne.0).and.(i_h2o_ice.eq.0)) then
           ! then the index of (surface) ice is i_h2o_vap
-          i_h2o_ice=i_h2o_vap
+            print*,'water vapour but no water ice, WTF?'
+            call abort
+            i_h2o_ice=i_h2o_vap
          endif
         endif ! of if (.not.oldtracernames) 
@@ -601,18 +690,27 @@
            ELSE
              txt=tnom(iq)
-             ! Exception: there is no water vapour surface tracer
-             if (txt.eq."h2o_vap") then
-               write(*,*)"physdem1: skipping water vapour tracer"
-               if (i_h2o_ice.eq.i_h2o_vap) then
-               ! then there is no "water ice" tracer; but still
-               ! there is some water ice on the surface
-                 write(*,*)"          writting water ice instead"
-                 txt="h2o_ice"
-               else
-               ! there is a "water ice" tracer which has been / will be
-               ! delt with in due time
-                 cycle
-               endif ! of if (igcm_h2o_ice.eq.igcm_h2o_vap)
-             endif ! of if (txt.eq."h2o_vap")
+
+
+!     in new version, h2o_vap acts as liquid surface tracer
+!     so the section below is now redundant
+!     ------------------------------------------------------------------
+!             ! Exception: there is no water vapour surface tracer
+!             if (txt.eq."h2o_vap") then
+!               write(*,*)"physdem1: skipping water vapour tracer"
+!               if (i_h2o_ice.eq.i_h2o_vap) then
+!               ! then there is no "water ice" tracer; but still
+!               ! there is some water ice on the surface
+!                 write(*,*)"          writting water ice instead"
+!                 txt="h2o_ice"
+!               else
+!               ! there is a "water ice" tracer which has been / will be
+!               ! delt with in due time
+!                 cycle
+!               endif ! of if (igcm_h2o_ice.eq.igcm_h2o_vap)
+!             endif ! of if (txt.eq."h2o_vap")
+!     ------------------------------------------------------------------
+
+
+
            ENDIF ! of IF (oldtracernames)
 
Index: unk/LMDZ.GENERIC/libf/phystd/physiq.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/physiq.F	(revision 252)
+++ 	(revision )
@@ -1,1455 +1,0 @@
-      subroutine physiq(ngrid,nlayer,nq,
-     *            firstcall,lastcall,
-     *            pday,ptime,ptimestep,
-     *            pplev,pplay,pphi,
-     *            pu,pv,pt,pq,
-     *            pw,
-     *            pdu,pdv,pdt,pdq,pdpsrf,tracerdyn)
-
-      use radinc_h, only : naerkind
-
-      implicit none
-
-
-!==================================================================
-!     
-!     Purpose
-!     -------
-!     Central subroutine for all the physics parameterisations in the
-!     universal model. Originally adapted from the Mars LMDZ model.
-!
-!     The model can be run without or with tracer transport
-!     depending on the value of "tracer" in file "callphys.def".
-!
-!
-!   It includes:
-!
-!      1.  Initialization:
-!      1.1 Firstcall initializations
-!      1.2 Initialization for every call to physiq
-!      1.2.5 Compute mean mass and cp, R and thermal conduction coeff.
-!      2. Compute radiative transfer tendencies
-!         (longwave and shortwave).
-!      4. Vertical diffusion (turbulent mixing):
-!      5. Convective adjustment
-!      6. Condensation and sublimation of gases (currently just CO2).
-!      7.  TRACERS :
-!       7a. water and water ice
-!       7c. other schemes for tracer transport (lifting, sedimentation)
-!       7d. updates (pressure variations, surface budget)
-!      9. Surface and sub-surface temperature calculations
-!     10. Write outputs :
-!           - "startfi", "histfi" if it's time
-!           - Saving statistics if "callstats = .true."
-!           - Output any needed variables in "diagfi" 
-!     10. Diagnostics: mass conservation of tracers, radiative energy balance etc.
-!
-!   arguments
-!   ---------
-!
-!   input
-!   -----
-!    ecri                  period (in dynamical timestep) to write output
-!    ngrid                 Size of the horizontal grid.
-!                          All internal loops are performed on that grid.
-!    nlayer                Number of vertical layers.
-!    nq                    Number of advected fields
-!    firstcall             True at the first call
-!    lastcall              True at the last call
-!    pday                  Number of days counted from the North. Spring
-!                          equinoxe.
-!    ptime                 Universal time (0<ptime<1): ptime=0.5 at 12:00 UT
-!    ptimestep             timestep (s)
-!    pplay(ngrid,nlayer)   Pressure at the middle of the layers (Pa)
-!    pplev(ngrid,nlayer+1) intermediate pressure levels (pa)
-!    pphi(ngrid,nlayer)    Geopotential at the middle of the layers (m2s-2)
-!    pu(ngrid,nlayer)      u component of the wind (ms-1)
-!    pv(ngrid,nlayer)      v component of the wind (ms-1)
-!    pt(ngrid,nlayer)      Temperature (K)
-!    pq(ngrid,nlayer,nq)   Advected fields
-!    pudyn(ngrid,nlayer)    \ 
-!    pvdyn(ngrid,nlayer)     \ Dynamical temporal derivative for the
-!    ptdyn(ngrid,nlayer)     / corresponding variables
-!    pqdyn(ngrid,nlayer,nq) /
-!    pw(ngrid,?)           vertical velocity
-!
-!   output
-!   ------
-!
-!    pdu(ngrid,nlayermx)        \
-!    pdv(ngrid,nlayermx)         \  Temporal derivative of the corresponding
-!   pdt(ngrid,nlayermx)         /  variables due to physical processes.
-!    pdq(ngrid,nlayermx)        /
-!    pdpsrf(ngrid)             /
-!    tracerdyn                 call tracer in dynamical part of GCM ?
-!
-!
-!     Authors
-!     -------
-!           Frederic Hourdin	15/10/93
-!           Francois Forget	1994
-!           Christophe Hourdin	02/1997 
-!           Subroutine completly rewritten by F.Forget (01/2000)
-!           Water ice clouds: Franck Montmessin (update 06/2003)
-!           Radiatively active tracers: J.-B. Madeleine (10/2008-06/2009)
-!           New correlated-k radiative scheme: R. Wordsworth (2009)
-!           Many specifically Martian subroutines removed: R. Wordsworth (2009)       
-!     
-!==================================================================
-
-
-c    0.  Declarations :
-c    ------------------
-
-#include "dimensions.h"
-#include "dimphys.h"
-#include "comgeomfi.h"
-#include "surfdat.h"
-#include "comsoil.h"
-#include "comdiurn.h"
-#include "callkeys.h"
-#include "comcstfi.h"
-#include "planete.h"
-#include "comsaison.h"
-#include "control.h"
-#include "comg1d.h"
-#include "tracer.h"
-
-#include "watercap.h"
-
-#include "netcdf.inc"
-
-
-
-c Arguments :
-c -----------
-
-c   inputs:
-c   -------
-      INTEGER ngrid,nlayer,nq
-      REAL ptimestep
-      REAL pplev(ngridmx,nlayer+1),pplay(ngridmx,nlayer)
-      REAL pphi(ngridmx,nlayer)
-      REAL pu(ngridmx,nlayer),pv(ngridmx,nlayer)
-      REAL pt(ngridmx,nlayer),pq(ngridmx,nlayer,nq)
-      REAL pw(ngridmx,nlayer)        ! pvervel transmitted by dyn3d
-      REAL zh(ngridmx,nlayermx)      ! potential temperature (K)
-      LOGICAL firstcall,lastcall
-
-      REAL pday
-      REAL ptime 
-      logical tracerdyn
-
-c   outputs:
-c   --------
-c     physical tendencies
-      REAL pdu(ngridmx,nlayer),pdv(ngridmx,nlayer)
-      REAL pdt(ngridmx,nlayer),pdq(ngridmx,nlayer,nq)
-      REAL pdpsrf(ngridmx) ! surface pressure tendency
-
-
-c Local saved variables:
-c ----------------------
-c     aerosol (dust or ice) extinction optical depth  at reference wavelength 
-c     "longrefvis" set in dimradmars.h , for one of the "naerkind"  kind of
-c      aerosol optical properties:
-c      REAL aerosol(ngridmx,nlayermx,naerkind) 
-!     this is now internal to callcorrk and hence no longer needed here
-
-      INTEGER day_ini  ! Initial date of the run (sol since Ls=0) 
-      INTEGER icount     ! counter of calls to physiq during the run.
-      REAL tsurf(ngridmx)            ! Surface temperature (K)
-      REAL tsoil(ngridmx,nsoilmx)    ! sub-surface temperatures (K)
-      REAL albedo(ngridmx)           ! Surface albedo
-
-      real albedo0(ngridmx)           ! Surface albedo
-      save albedo0
-
-      REAL emis(ngridmx)             ! Thermal IR surface emissivity
-      REAL dtrad(ngridmx,nlayermx)   ! Net atm. radiative heating rate (K.s-1)
-      REAL fluxrad_sky(ngridmx)      ! rad. flux from sky absorbed by surface (W.m-2)
-      REAL fluxrad(ngridmx)          ! Net radiative surface flux (W.m-2)
-      REAL capcal(ngridmx)           ! surface heat capacity (J m-2 K-1)
-      REAL fluxgrd(ngridmx)          ! surface conduction flux (W.m-2)
-      REAL qsurf(ngridmx,nqmx)       ! tracer on surface (e.g. kg.m-2)
-      REAL q2(ngridmx,nlayermx+1)    ! Turbulent Kinetic Energy 
-
-      SAVE day_ini, icount
-      SAVE tsurf,tsoil
-      SAVE albedo,emis, q2
-      SAVE capcal,fluxgrd,dtrad,fluxrad,fluxrad_sky,qsurf
-
-      REAL stephan   
-      DATA stephan/5.67e-08/  ! Stephan Boltzman constant
-      SAVE stephan
-
-c Local variables :
-c -----------------
-
-!     aerosol (dust or ice) extinction optical depth  at reference wavelength 
-!     for the "naerkind" optically active aerosols:
-      REAL aerosol(ngridmx,nlayermx,naerkind) 
-
-      CHARACTER*80 fichier 
-      INTEGER l,ig,ierr,igout,iq,i, tapphys
-!      INTEGER iqmin                     ! Used if iceparty engaged
-
-      REAL fluxsurf_lw(ngridmx)      ! incident LW (IR) surface flux (W.m-2)
-      REAL fluxsurf_sw(ngridmx)      ! incident SW (solar) surface flux (W.m-2)
-      REAL fluxtop_lw(ngridmx)       ! Outgoing LW (IR) flux to space (W.m-2)
-      REAL fluxtop_sw(ngridmx)       ! Outgoing SW (solar) flux to space (W.m-2)
-
-!     included by RW for equilibration test
-      real fluxtop_dn(ngridmx)
-      real fluxabs_sw(ngridmx) ! absorbed shortwave radiation
-      real fluxdyn(ngridmx)    ! horizontal heat transport by dynamics      
-
-      REAL zls                       ! solar longitude (rad)
-      REAL zday                      ! date (time since Ls=0, in martian days)
-      REAL zzlay(ngridmx,nlayermx)   ! altitude at the middle of the layers
-      REAL zzlev(ngridmx,nlayermx+1) ! altitude at layer boundaries
-      REAL latvl1,lonvl1             ! Viking Lander 1 point (for diagnostic)
-
-c     Aerosol effective radius used for radiative transfer (units=meters)
-      REAL reffrad(ngridmx,nlayermx,naerkind)
-
-c     Tendencies due to various processes:
-      REAL dqsurf(ngridmx,nqmx)
-      REAL zdtlw(ngridmx,nlayermx)      ! (K/s)
-      REAL zdtsw(ngridmx,nlayermx)      ! (K/s)
-      REAL cldtlw(ngridmx,nlayermx)     ! (K/s) LW heating rate for clear areas
-      REAL cldtsw(ngridmx,nlayermx)     ! (K/s) SW heating rate for clear areas
-      REAL zdtsurf(ngridmx)             ! (K/s)
-      REAL zdtlscale(ngridmx,nlayermx)
-      REAL zdvdif(ngridmx,nlayermx),zdudif(ngridmx,nlayermx)  ! (m.s-2)
-      REAL zdhdif(ngridmx,nlayermx), zdtsdif(ngridmx)         ! (K/s)
-      REAL zdvadj(ngridmx,nlayermx),zduadj(ngridmx,nlayermx)  ! (m.s-2)
-      REAL zdhadj(ngridmx,nlayermx)                           ! (K/s)
-      REAL zdtgw(ngridmx,nlayermx)                            ! (K/s)
-      REAL zdugw(ngridmx,nlayermx),zdvgw(ngridmx,nlayermx)    ! (m.s-2)
-      REAL zdtc(ngridmx,nlayermx),zdtsurfc(ngridmx)
-      REAL zdvc(ngridmx,nlayermx),zduc(ngridmx,nlayermx)
-
-      REAL zdqdif(ngridmx,nlayermx,nqmx), zdqsdif(ngridmx,nqmx)
-      REAL zdqsed(ngridmx,nlayermx,nqmx), zdqssed(ngridmx,nqmx)
-      REAL zdqdev(ngridmx,nlayermx,nqmx), zdqsdev(ngridmx,nqmx)
-      REAL zdqadj(ngridmx,nlayermx,nqmx)
-      REAL zdqc(ngridmx,nlayermx,nqmx)
-      REAL zdqlscale(ngridmx,nlayermx,nqmx)
-      REAL zdqslscale(ngridmx,nqmx)
-      REAL zdqchim(ngridmx,nlayermx,nqmx)
-      REAL zdqschim(ngridmx,nqmx)
-
-      REAL zdteuv(ngridmx,nlayermx)    ! (K/s)
-      REAL zdtconduc(ngridmx,nlayermx) ! (K/s)
-      REAL zdumolvis(ngridmx,nlayermx)
-      REAL zdvmolvis(ngridmx,nlayermx)
-      real zdqmoldiff(ngridmx,nlayermx,nqmx)
-
-c     Local variable for local intermediate calcul:
-      REAL zflubid(ngridmx)
-      REAL zplanck(ngridmx),zpopsk(ngridmx,nlayermx)
-      REAL zdum1(ngridmx,nlayermx)
-      REAL zdum2(ngridmx,nlayermx)
-      REAL ztim1,ztim2,ztim3, z1,z2
-      REAL ztime_fin
-      REAL zdh(ngridmx,nlayermx)
-      INTEGER length
-      PARAMETER (length=100)
-
-c local variables only used for diagnostic (output in file "diagfi" or "stats")
-c -----------------------------------------------------------------------------
-      REAL ps(ngridmx), zt(ngridmx,nlayermx)
-      REAL zu(ngridmx,nlayermx),zv(ngridmx,nlayermx)
-      REAL zq(ngridmx,nlayermx,nqmx)
-      REAL fluxtop_sw_tot(ngridmx), fluxsurf_sw_tot(ngridmx)
-      character*2 str2
-      character*5 str5
-      real zdtdif(ngridmx,nlayermx), zdtadj(ngridmx,nlayermx)
-      real zdtdyn(ngridmx,nlayermx),ztprevious(ngridmx,nlayermx)
-      save ztprevious 
-      real reff(ngridmx,nlayermx) ! effective dust radius (used if doubleq=T)
-      real qtot1,qtot2            ! total aerosol mass
-      integer igmin, lmin
-      logical tdiag
-
-      real co2col(ngridmx) ! CO2 column
-      REAL zplev(ngrid,nlayermx+1),zplay(ngrid,nlayermx)
-      REAL zstress(ngrid), cd
-      real hco2(nqmx),tmean, zlocal(nlayermx)
-      real rho(ngridmx,nlayermx) ! density
-      real vmr(ngridmx,nlayermx) ! volume mixing ratio
-
-      REAL time_phys
-
-!     included by RW for kastprof scheme
-      logical kastprof
-
-!     reinstated by RW for diagnostic
-      REAL tau_col(ngrid)
-
-!     included by RW for tidally locked dynamics
-!      logical tlocked
-
-!     included by RW to reduce insanity of code
-      real flux1,flux2,flux3,ts1,ts2,ts3
-
-!     included by RW for temporary comparison
-      REAL zdtnirco2(ngridmx,nlayermx) ! (K/s)
-
-!     included by RW to compute tracer column densities
-      real qcol(ngridmx,nqmx)
-
-!     included by RW for H2O precipitation
-      REAL zdtrain(ngridmx,nlayermx)
-      REAL zdqrain(ngridmx,nlayermx,nqmx)
-      REAL zdqsrain(ngridmx)
-      REAL zdqssnow(ngridmx)
-      REAL rainout(ngridmx)
-      
-!     included by RW for H2O Manabe scheme
-      REAL dtmoist(ngridmx,nlayermx)
-      REAL dqmoist(ngridmx,nlayermx,nqmx)
-
-      real qvap(ngridmx,nlayermx)
-      real dqvaplscale(ngridmx,nlayermx)
-      real dqcldlscale(ngridmx,nlayermx)
-      real cloudfrac(ngridmx,nlayermx)
-      real rneb_man(ngridmx,nlayermx)
-      real rneb_lsc(ngridmx,nlayermx)
-
-!    included by RW to account for surface cooling by evaporation
-      REAL dtsurfh2olat(ngridmx)
-
-!     included by RW to test energy conservation
-      REAL dEtot, dEtots, masse, vabs, dvabs
-
-!     included by RW to test water conservation
-      real h2otot
-
-!     included by RW to allow variations in cp with location
-      REAL cpp3D(ngridmx,nlayermx)   ! specific heat capacity at const. pressure
-      REAL rcp3D(ngridmx,nlayermx)   ! R / specific heat capacity
-      real cppNI, rcpNI, nnu ! last one just for Seb version
-      REAL zpopskNI(ngridmx,nlayermx)
-
-!     included by RW to make 1D saves not every timestep
-      integer countG1D
-      save countG1D
-
-c=======================================================================
-
-      kastprof=.false.
-
-c 1. Initialisation:
-c -----------------
-
-c  1.1   Initialisation only at first call
-c  ---------------------------------------
-      IF (firstcall) THEN
-
-         if(ngrid.eq.1)then
-            !saveG1D=day_step*10
-            saveG1D=1
-            countG1D=1
-         endif
-
-c        variables set to 0
-c        ~~~~~~~~~~~~~~~~~~
-         call zerophys(ngrid*nlayer,dtrad)
-         call zerophys(ngrid,fluxrad)
-
-c        initialize tracer names, indexes and properties
-c        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-         tracerdyn=tracer
-         IF (tracer) THEN
-            CALL initracer()
-         ENDIF  ! end tracer
-
-
-c        read startfi (initial parameters)
-c        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-         
-         CALL phyetat0 ("startfi.nc",0,0,
-     &         nsoilmx,nq,
-     &         day_ini,time_phys,
-     &         tsurf,tsoil,emis,q2,qsurf)
-
-         if (pday.ne.day_ini) then
-           write(*,*) "PHYSIQ: ERROR: bad synchronization between ",
-     &                "physics and dynamics"
-           write(*,*) "dynamics day: ",pday
-           write(*,*) "physics day:  ",day_ini
-           stop
-         endif
-
-         write (*,*) 'In physiq day_ini =', day_ini
-
-
-c        Initialize albedo and orbital calculation
-c        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-         CALL surfini(ngrid,qsurf,albedo)
-! surely for good CO2 ice feedback this must be called every turn?
-         CALL iniorbit(aphelie,periheli,year_day,peri_day,obliquit)
-
-
-         if(tlocked)then
-            print*,'Planet is tidally locked at resonance n=',nres
-            print*,'Make sure you have the right rotation rate!!!'
-         endif
-
-
-c        initialize soil 
-c        ~~~~~~~~~~~~~~~
-         IF (callsoil) THEN
-            CALL soil(ngrid,nsoilmx,firstcall,inertiedat,
-     s          ptimestep,tsurf,tsoil,capcal,fluxgrd)
-         ELSE
-            PRINT*,'WARNING! Thermal conduction in the soil turned off'
-            DO ig=1,ngrid
-               capcal(ig)=1.e6
-               fluxgrd(ig)=0.
-            ENDDO
-         ENDIF
-         icount=1
-
-c        Set temperature just above condensation temperature (for Early Mars)
-c        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-         if(nearco2cond) then
-            write(*,*)' WARNING, starting at Tcond+1K !!!'
-            DO l=1, nlayer
-               DO ig=1,ngrid
-                  pdt(ig,l)= ((-3167.8)/(log(.01*pplay(ig,l))-23.23)+4
-     &                 -pt(ig,l)) / ptimestep
-               ENDDO
-            ENDDO
-         endif
-
-         if(meanOLR)then
-            ! to record global radiative balance
-            call system('rm -f rad_bal.out')
-         endif
-
-         if(water)then
-            ! initialise variables for water cycle
-
-            if(ngrid.eq.1)then
-               qsurf(1,igcm_h2o_ice) = 100.0
-               DO l=1, nlayer
-                  pq(1,l,igcm_h2o_ice)=0.0!1.0e-2 
-               enddo
-            endif
-
-         endif
-         call su_watercycle ! even if we don't have a water cycle, we might
-                            ! need epsi for the wvp definitions in callcorrk.F
-
-      ENDIF        !  (end of "if firstcall")
-
-c ---------------------------------------------------
-c 1.2   Initializations done at every physical timestep:
-c ---------------------------------------------------
-c
-      IF (ngrid.NE.ngridmx) THEN
-         PRINT*,'STOP in PHYSIQ'
-         PRINT*,'Probleme de dimensions :'
-         PRINT*,'ngrid     = ',ngrid
-         PRINT*,'ngridmx   = ',ngridmx
-         STOP
-      ENDIF
-
-c     Initialize various variables
-c     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-      call zerophys(ngrid*nlayer, pdv)
-      call zerophys(ngrid*nlayer, pdu)
-      if ( (.not.nearco2cond).and.(.not.firstcall) ) then
-         call zerophys(ngrid*nlayer,pdt)
-      endif ! this was the source of an evil bug...
-      call zerophys(ngrid*nlayer*nq, pdq)
-      call zerophys(ngrid, pdpsrf)
-      call zerophys(ngrid, zflubid)
-      call zerophys(ngrid, zdtsurf)
-      call zerophys(ngrid*nq, dqsurf)
-      igout=ngrid/2+1 
-
-      zday=pday+ptime ! compute time, in sols (and fraction thereof)
-
-c     Compute Solar Longitude (Ls) :
-c     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-      if (season) then
-         call solarlong(zday,zls)
-      else
-         call solarlong(float(day_ini),zls)
-      end if
-
-c     Compute geopotential between layers
-c     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-      DO l=1,nlayer
-         DO ig=1,ngrid
-            zzlay(ig,l)=pphi(ig,l)/g
-         ENDDO
-      ENDDO
-      DO ig=1,ngrid
-         zzlev(ig,1)=0.
-         zzlev(ig,nlayer+1)=1.e7    ! dummy top of last layer above 10000 km...
-      ENDDO
-      DO l=2,nlayer
-         DO ig=1,ngrid
-            z1=(pplay(ig,l-1)+pplev(ig,l))/(pplay(ig,l-1)-pplev(ig,l))
-            z2=(pplev(ig,l)+pplay(ig,l))/(pplev(ig,l)-pplay(ig,l))
-            zzlev(ig,l)=(z1*zzlay(ig,l-1)+z2*zzlay(ig,l))/(z1+z2)
-         ENDDO
-      ENDDO
-
-!     Potential temperature calculation not the same in physiq and dynamic...
-
-c     Compute potential temperature
-c     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-      if(nonideal)then
-
-         DO l=1,nlayer
-            DO ig=1,ngrid 
-               call calc_cpp3d(cppNI,rcpNI,pt(ig,l),pplay(ig,l))
-               cpp3D(ig,l)  = cppNI
-               rcp3D(ig,l)  = rcpNI
-            ENDDO
-         ENDDO
-
-         DO l=1,nlayer
-            DO ig=1,ngrid
-
-!               nnu=0.35
-!               zh(ig,l)   = (pt(ig,l)**nnu +
-!     &              nnu*(460**nnu)*(8.314/1000.)*
-!     &           log(pplev(ig,1)/pplay(ig,l)) )**(-nnu) ! Sebastian's version
-!               zpopskNI(ig,l) = (pplay(ig,l)/pplev(ig,1))**rcp3D(ig,l)
-
-               zh(ig,l)       = pt(ig,l)*1.0024 - 0.659
-               zpopskNI(ig,l) = pt(ig,l)/zh(ig,l)
-               ! we're only after zpopskNI here, not zh
-               ! zh is calculated seperately before both vdifc and convadj
-            ENDDO
-         ENDDO
-
-      endif
-!      else
-         
-      DO l=1,nlayer
-         DO ig=1,ngrid 
-            zpopsk(ig,l)=(pplay(ig,l)/pplev(ig,1))**rcp
-            zh(ig,l)=pt(ig,l)/zpopsk(ig,l)
-         ENDDO
-      ENDDO
-
-!      endif
-
-
-c-----------------------------------------------------------------------
-c    2. Compute radiative tendencies :
-c-----------------------------------------------------------------------
-
-      IF (callrad) THEN
-         IF( MOD(icount-1,iradia).EQ.0) THEN
-
-c          Local stellar zenith angle
-c          ~~~~~~~~~~~~~~~~~~~~~~~~~~
-           CALL orbite(zls,dist_sol,declin)
-
-           IF (tlocked) THEN
-              ztim1=SIN(declin)
-              ztim2=COS(declin)*COS(2.*pi*(zday/year_day) - zls*nres)
-              ztim3=-COS(declin)*SIN(2.*pi*(zday/year_day) - zls*nres)
-
-               CALL solang(ngrid,sinlon,coslon,sinlat,coslat,
-     s         ztim1,ztim2,ztim3,mu0,fract)
-
-           ELSEIF (diurnal) THEN
-               ztim1=SIN(declin)
-               ztim2=COS(declin)*COS(2.*pi*(zday-.5))
-               ztim3=-COS(declin)*SIN(2.*pi*(zday-.5))
-
-               CALL solang(ngrid,sinlon,coslon,sinlat,coslat,
-     s         ztim1,ztim2,ztim3,mu0,fract)
-
-           ELSE
-
-               CALL mucorr(ngrid,declin,lati,mu0,fract,10000.,rad)
-               ! WARNING: this function appears not to work in 1D
-
-           ENDIF
-
-c          Call main radiative transfer scheme
-c          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-c          Radiative transfer
-c          ------------------
-
-           if (corrk) then
-              if(kastprof)then
-                 call kastprof_fn(tsurf,pt,pplay,pplev)
-                 print*,'pt',pt
-                 print*,'pplay',pplay
-              endif
-
-              CALL callcorrk(icount,ngrid,nlayer,pq,nq,qsurf,
-     &             albedo,emis,mu0,pplev,pplay,pt,
-     &             tsurf,fract,dist_sol,igout,aerosol,cpp3D,
-     &             zdtlw,zdtsw,fluxsurf_lw,fluxsurf_sw,fluxtop_lw,
-     &             fluxtop_sw,fluxtop_dn,reffrad,tau_col,ptime,pday,
-     &             firstcall,lastcall)
-            
-
-
-c          Radiative flux from the sky absorbed by the surface (W.m-2)
-c          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-              DO ig=1,ngrid
-                 fluxrad_sky(ig)=emis(ig)*fluxsurf_lw(ig)
-     &                +fluxsurf_sw(ig)*(1.-albedo(ig))
-              ENDDO
-
-c          Net atmospheric radiative heating rate (K.s-1)
-c          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-              DO l=1,nlayer
-                 DO ig=1,ngrid
-                    dtrad(ig,l)=zdtsw(ig,l)+zdtlw(ig,l)
-                 ENDDO
-              ENDDO
-
-           else
-
-c          Atmosphere has no radiative effect
-c          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-              DO ig=1,ngrid
-                 fluxtop_dn(ig)  = fract(ig)*mu0(ig)*Fat1AU/dist_sol**2
-                 fluxrad_sky(ig) = fluxtop_dn(ig)*(1.-albedo(ig))
-                 fluxtop_sw(ig)  = fluxtop_dn(ig)*albedo(ig)
-                 fluxtop_lw(ig)  = emis(ig)*stephan*tsurf(ig)**4
-              ENDDO ! radiation skips the atmosphere entirely
-
-
-              DO l=1,nlayer
-                 DO ig=1,ngrid
-                    dtrad(ig,l)=0.0
-                 ENDDO
-              ENDDO ! hence no atmospheric radiative heating
-
-           endif                ! if corrk
-
-        ENDIF ! of if(mod(icount-1,iradia).eq.0)
-
-!    Transformation of the radiative tendencies:
-!    -------------------------------------------
-
-!          Net radiative surface flux (W.m-2)
-!          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-        DO ig=1,ngrid
-           zplanck(ig)=tsurf(ig)*tsurf(ig)
-           zplanck(ig)=emis(ig)*
-     &          stephan*zplanck(ig)*zplanck(ig)
-           fluxrad(ig)=fluxrad_sky(ig)-zplanck(ig)
-        ENDDO
-
-        DO l=1,nlayer
-           DO ig=1,ngrid
-              pdt(ig,l)=pdt(ig,l)+dtrad(ig,l)
-           ENDDO
-        ENDDO
-
-!-------------------------
-! test energy conservation
-         if(enertest)then
-            dEtot=0.0
-            dEtots=0.0
-            DO ig = 1, ngrid
-               DO l = 1, nlayer
-                  masse = (pplev(ig,l) - pplev(ig,l+1))/g
-                  dEtot = dEtot + cpp*masse*dtrad(ig,l)*area(ig)
-                  !print*,'l=',l,'dEtot=',cpp*masse*dtrad(ig,l)*area(ig)
-               ENDDO
-               dEtots = dEtots + fluxrad(ig)*area(ig)
-            ENDDO
-            dEtot=dEtot/totarea
-            dEtots=dEtots/totarea
-            print*,'In corrk atmospheric energy change=',dEtot,' W m-2'
-            print*,'In corrk surface energy change=',dEtots,' W m-2'
-         endif
-!-------------------------
-
-      ENDIF ! of IF (callrad)
-
-
-!-----------------------------------------------------------------------
-!    4. Vertical diffusion (turbulent mixing):
-!    -----------------------------------------
-
-      IF (calldifv) THEN
-
-         DO ig=1,ngrid
-            zflubid(ig)=fluxrad(ig)+fluxgrd(ig)
-         ENDDO
-
-         CALL zerophys(ngrid*nlayer,zdum1)
-         CALL zerophys(ngrid*nlayer,zdum2)
-         do l=1,nlayer
-            do ig=1,ngrid
-               zdh(ig,l)=pdt(ig,l)/zpopsk(ig,l)
-            enddo
-         enddo
-         
-c        Calling vdif (Martian version WITH CO2 condensation)
-         CALL vdifc(ngrid,nlayer,nq,zpopsk,
-     &        ptimestep,capcal,lwrite,
-     &        pplay,pplev,zzlay,zzlev,z0,
-     &        pu,pv,zh,pq,tsurf,emis,qsurf,
-     &        zdum1,zdum2,zdh,pdq,zflubid,
-     &        zdudif,zdvdif,zdhdif,zdtsdif,q2,
-     &        zdqdif,zdqsdif)
-
-         DO l=1,nlayer
-            DO ig=1,ngrid
-               pdv(ig,l)=pdv(ig,l)+zdvdif(ig,l)
-               pdu(ig,l)=pdu(ig,l)+zdudif(ig,l)
-               pdt(ig,l)=pdt(ig,l)+zdhdif(ig,l)*zpopsk(ig,l)
-
-               zdtdif(ig,l)=zdhdif(ig,l)*zpopsk(ig,l) ! for diagnostic only
-            ENDDO
-         ENDDO
-
-         DO ig=1,ngrid
-            zdtsurf(ig)=zdtsurf(ig)+zdtsdif(ig)
-         ENDDO
-
-         if (tracer) then 
-           DO iq=1, nq
-            DO l=1,nlayer
-              DO ig=1,ngrid
-                 pdq(ig,l,iq)=pdq(ig,l,iq)+ zdqdif(ig,l,iq) 
-              ENDDO
-            ENDDO
-           ENDDO
-           DO iq=1, nq
-              DO ig=1,ngrid
-                 dqsurf(ig,iq)=dqsurf(ig,iq) + zdqsdif(ig,iq)
-              ENDDO
-           ENDDO
-
-         end if ! of if (tracer)
-
-         !print*,'surface temp loss:'
-         !print*, dtsurfh2olat
-
-!-------------------------
-! test energy conservation
-         if(enertest)then
-            dEtot=0.0
-            dEtots=0.0
-            DO ig = 1, ngrid
-               DO l = 1, nlayer
-                  masse = (pplev(ig,l) - pplev(ig,l+1))/g
-
-                  dEtot = dEtot + cpp*masse*zdtdif(ig,l)*area(ig)
-                  
-                  vabs  = sqrt(pdu(ig,l)**2 + pdv(ig,l)**2)
-                  dvabs = sqrt(zdudif(ig,l)**2 + zdvdif(ig,l)**2)
-                  dEtot = dEtot + masse*vabs*dvabs*area(ig)
-               ENDDO
-               dEtots = dEtots + capcal(ig)*zdtsdif(ig)*area(ig)
-            ENDDO
-            dEtot=dEtot/totarea
-            dEtots=dEtots/totarea
-            print*,'In difv atmospheric energy change=',dEtot,' W m-2'
-            print*,'In difv surface energy change=',dEtots,' W m-2'
-         endif
-!-------------------------
-
-      ELSE    
-
-         DO ig=1,ngrid
-            zdtsurf(ig)=zdtsurf(ig)+
-     s      (fluxrad(ig)+fluxgrd(ig))/capcal(ig)
-         ENDDO
-
-      ENDIF ! of IF (calldifv)
-
-
-!-----------------------------------------------------------------------
-!   5. Dry convective adjustment:
-!   -----------------------------
-
-      IF(calladj) THEN
-
-         DO l=1,nlayer
-            DO ig=1,ngrid
-               if(nonideal)then
-                  zdh(ig,l)=pdt(ig,l)/zpopskNI(ig,l)
-               else
-                  zdh(ig,l)=pdt(ig,l)/zpopsk(ig,l)
-               endif
-            ENDDO
-         ENDDO
-         CALL zerophys(ngrid*nlayer,zduadj)
-         CALL zerophys(ngrid*nlayer,zdvadj)
-         CALL zerophys(ngrid*nlayer,zdhadj)
-
-         if(nonideal)then
-            CALL convadj(ngrid,nlayer,nq,ptimestep,
-     &           pplay,pplev,zpopskNI,
-     &           pu,pv,zh,pq,
-     &           pdu,pdv,zdh,pdq,
-     &           zduadj,zdvadj,zdhadj,
-     &           zdqadj)
-         else
-            CALL convadj(ngrid,nlayer,nq,ptimestep,
-     &           pplay,pplev,zpopsk,
-     &           pu,pv,zh,pq,
-     &           pdu,pdv,zdh,pdq,
-     &           zduadj,zdvadj,zdhadj,
-     &           zdqadj)
-         endif
-
-
-         DO l=1,nlayer
-            DO ig=1,ngrid
-               pdu(ig,l)=pdu(ig,l)+zduadj(ig,l)
-               pdv(ig,l)=pdv(ig,l)+zdvadj(ig,l)
-               if(nonideal)then
-                  pdt(ig,l)=pdt(ig,l)+zdhadj(ig,l)*zpopskNI(ig,l)
-                  zdtadj(ig,l)=zdhadj(ig,l)*zpopskNI(ig,l) ! for diagnostic only
-               else
-                  pdt(ig,l)=pdt(ig,l)+zdhadj(ig,l)*zpopsk(ig,l)
-                  zdtadj(ig,l)=zdhadj(ig,l)*zpopsk(ig,l) ! for diagnostic only
-               endif
-            ENDDO
-         ENDDO
-
-         if(tracer) then 
-           DO iq=1, nq
-            DO l=1,nlayer
-              DO ig=1,ngrid
-                 pdq(ig,l,iq)=pdq(ig,l,iq)+ zdqadj(ig,l,iq) 
-              ENDDO
-            ENDDO
-           ENDDO
-         end if
-
-!-------------------------
-! test energy conservation
-         if(enertest)then
-            dEtot=0.0
-            DO ig = 1, ngrid
-               DO l = 1, nlayer
-                  masse = (pplev(ig,l) - pplev(ig,l+1))/g
-                  dEtot = dEtot + cpp*masse*zdtadj(ig,l)*area(ig)
-               ENDDO
-            ENDDO
-            dEtot=dEtot/totarea
-          print*,'In convadj atmospheric energy change=',dEtot,' W m-2'
-         endif
-!-------------------------
-
-      ENDIF ! of IF(calladj)
-
-!-----------------------------------------------------------------------
-!   6. Carbon dioxide condensation-sublimation:
-!   -------------------------------------------
-
-      IF (co2cond) THEN
-         if (.not.tracer) then
-            print*,'We need a CO2 ice tracer to condense CO2'
-            call abort
-         endif
-
-         call condens_co2cloud(ngrid,nlayer,nq,ptimestep,
-     &        capcal,pplay,pplev,tsurf,pt,
-     &        pphi,pdt,pdu,pdv,zdtsurf,pu,pv,pq,pdq,
-     &        qsurf(1,igcm_co2_ice),albedo,emis,
-     &        zdtc,zdtsurfc,pdpsrf,zduc,zdvc,
-     &        zdqc,reffrad,cpp3D)
-
-         DO l=1,nlayer
-           DO ig=1,ngrid
-             pdt(ig,l)=pdt(ig,l)+zdtc(ig,l)
-             pdv(ig,l)=pdv(ig,l)+zdvc(ig,l)
-             pdu(ig,l)=pdu(ig,l)+zduc(ig,l)
-           ENDDO
-         ENDDO
-         DO ig=1,ngrid
-            zdtsurf(ig) = zdtsurf(ig) + zdtsurfc(ig)
-         ENDDO
-
-!         IF (tracer) THEN
-           DO iq=1, nq ! should use new notation here !
-            DO l=1,nlayer
-              DO ig=1,ngrid
-                pdq(ig,l,iq)=pdq(ig,l,iq)+ zdqc(ig,l,iq) 
-              ENDDO
-            ENDDO
-           ENDDO
-           !NB: we do not add tendency on surface co2ice ; 
-           ! since qsurf(:,igcm_co2_ice) is updated in condens_co2cloud
-!         ENDIF ! of IF (tracer)
-
-
-!-------------------------
-! test energy conservation
-         if(enertest)then
-            dEtot=0.0
-            DO ig = 1, ngrid
-               DO l = 1, nlayer
-                  masse = (pplev(ig,l) - pplev(ig,l+1))/g
-                  dEtot = dEtot + cpp*masse*zdtc(ig,l)
-               ENDDO
-               dEtot = dEtot + capcal(ig)*zdtsurfc(ig)
-            ENDDO
-            print*,'In co2cloud energy change=',dEtot,' W m-2'
-         endif ! we're missing the latent heat...
-!-------------------------
-
-      ENDIF  ! of IF (co2cond)
-
-
-
-c-----------------------------------------------------------------------
-c   7. Specific parameterizations for tracers 
-c   -----------------------------------------
-
-      if (tracer) then 
-
-c   7a. Water and ice
-c     ---------------
-
-c        ---------------------------------------
-c        Water ice condensation in the atmosphere
-c        ----------------------------------------
-         IF (water) THEN
-
-            if(watercond)then
-
-               if(1.eq.2)then
-                  call moistadj(pt,pq,pplev,pplay,dtmoist,dqmoist,
-     &                 ptimestep,rneb_man)
-
-                  DO l=1,nlayer
-                     DO ig=1,ngrid
-                        pdq(ig,l,igcm_h2o_vap)=pdq(ig,l,igcm_h2o_vap)+
-     &                       dqmoist(ig,l,igcm_h2o_vap)
-                        pdq(ig,l,igcm_h2o_ice)=pdq(ig,l,igcm_h2o_ice)+
-     &                       dqmoist(ig,l,igcm_h2o_ice)
-                        pdt(ig,l)=pdt(ig,l)+dtmoist(ig,l)
-                     ENDDO
-                  ENDDO
-               endif            ! moistadj turned off for now
-
-              DO l=1,nlayer
-                 DO ig=1,ngrid
-                     qvap(ig,l)=pq(ig,l,igcm_h2o_vap)
-                 ENDDO
-              ENDDO
-              call largescale2(ptimestep,pplev,pplay,pt,qvap,
-     s             zdtlscale, dqvaplscale,dqcldlscale,rneb_lsc)
-              DO l=1,nlayer
-                 DO ig=1,ngrid
-                    pdq(ig,l,igcm_h2o_vap)=pdq(ig,l,igcm_h2o_vap)+
-     &                   dqvaplscale(ig,l)
-                    pdq(ig,l,igcm_h2o_ice)=pdq(ig,l,igcm_h2o_ice)+
-     &                   dqcldlscale(ig,l)
-                !    pdt(ig,l)=pdt(ig,l)+zdtlscale(ig,l)
-                    ! for the moment this is removed, as it dont conserve energy
-                 ENDDO
-              ENDDO
-
-              ! compute cloud fraction
-              DO l = 1, nlayer
-                 DO ig = 1,ngrid
-                    cloudfrac(ig,l)=MAX(rneb_lsc(ig,l),rneb_man(ig,l)) 
-                 ENDDO
-              ENDDO
-
-           endif                ! of IF (watercondense)
-           
-           if(waterrain)then
-
-              call rain(ptimestep,pplev,pplay,pt,pdt,pq,pdq,
-     &             zdtrain,zdqrain,zdqsrain,zdqssnow,cloudfrac)
-
-              DO l=1,nlayer
-                 DO ig=1,ngrid
-                    pdq(ig,l,igcm_h2o_vap)=pdq(ig,l,igcm_h2o_vap)+
-     &                   zdqrain(ig,l,igcm_h2o_vap)
-                    pdq(ig,l,igcm_h2o_ice)=pdq(ig,l,igcm_h2o_ice)+
-     &                   zdqrain(ig,l,igcm_h2o_ice)
-                    !pdt(ig,l)=pdt(ig,l)+zdtrain(ig,l)
-                 ENDDO
-              ENDDO
-
-              DO ig=1,ngrid
-                 dqsurf(ig,igcm_h2o_ice)=dqsurf(ig,igcm_h2o_ice)+
-     &                zdqsrain(ig)+zdqssnow(ig)
-                 rainout(ig)=zdqsrain(ig)+zdqssnow(ig) ! diagnostic   
-                 !rainout(ig)=zdqssnow(ig)
-              ENDDO
-
-         end if                 ! of IF (waterrain)
-
-      end if                    ! of IF (water)
-
-
-c   7c. Aerosol particles
-c     -------------------
-
-c        ------------- 
-c        Sedimentation
-c        ------------- 
-         IF (sedimentation) THEN 
-           call zerophys(ngrid*nlayer*nq, zdqsed)
-           call zerophys(ngrid*nq, zdqssed)
-
-           call callsedim(ngrid,nlayer, ptimestep,
-     &          pplev,zzlev, pt,
-     &          pq, pdq, zdqsed, zdqssed,nq)
-
-           DO iq=2, nq ! should be updated
-             DO l=1,nlayer
-               DO ig=1,ngrid
-                    pdq(ig,l,iq)=pdq(ig,l,iq)+ zdqsed(ig,l,iq)
-               ENDDO
-             ENDDO
-           ENDDO
-           DO iq=2, nq
-             DO ig=1,ngrid
-                dqsurf(ig,iq)= dqsurf(ig,iq) + zdqssed(ig,iq)
-             ENDDO
-           ENDDO
-         END IF   ! of IF (sedimentation)
-
-
-c   7d. Updates
-c     ---------
-
-        DO iq=1, nq
-          DO ig=1,ngrid
-
-c       ---------------------------------
-c       Updating tracer budget on surface
-c       ---------------------------------
-            qsurf(ig,iq)=qsurf(ig,iq)+ptimestep*dqsurf(ig,iq)
-
-          ENDDO  ! (ig)
-        ENDDO    ! (iq)
-
-      endif !  of if (tracer) 
-
-
-!-----------------------------------------------------------------------
-!   9. Surface and sub-surface soil temperature
-!-----------------------------------------------------------------------
-!
-!
-!   9.1 Increment Surface temperature:
-!   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-      DO ig=1,ngrid
-         tsurf(ig)=tsurf(ig)+ptimestep*zdtsurf(ig) 
-      ENDDO
-
-!
-!   9.2 Compute soil temperatures and subsurface heat flux:
-!   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-      IF (callsoil) THEN
-         CALL soil(ngrid,nsoilmx,.false.,inertiedat,
-     &          ptimestep,tsurf,tsoil,capcal,fluxgrd)
-      ENDIF
-
-!-------------------------
-! test energy conservation
-         if(enertest)then
-            dEtots=0.0
-            DO ig = 1, ngrid
-               dEtots = dEtots + capcal(ig)*zdtsurf(ig)*area(ig)
-            ENDDO
-            dEtots=dEtots/totarea
-            print*,'Surface energy change=',dEtots,' W m-2'
-         endif
-!-------------------------
-
-
-
-
-!-----------------------------------------------------------------------
-!  10. Perform diagnostics and write output files
-!-----------------------------------------------------------------------
-
-!     ---------------------------------------------------------
-!     Check the energy balance of the simulation during the run
-!     ---------------------------------------------------------
-      flux1 = 0
-      flux2 = 0
-      flux3 = 0
-      do ig=1,ngrid
-
-	    flux1 = flux1 + 
-     &        area(ig)*(fluxtop_dn(ig) - fluxtop_sw(ig))
-	    flux2 = flux2 + area(ig)*fluxtop_lw(ig) 
-	    flux3 = flux3 + area(ig)*fluxtop_dn(ig) 
-            fluxabs_sw(ig)=fluxtop_dn(ig) - fluxtop_sw(ig)
-
-      end do
-      print*,'Incident solar flux, absorbed solar flux, OLR (W/m2)'
-      print*, flux3/totarea, '      ',  flux1/totarea ,
-     & '           = ', flux2/totarea 
-
-      if(meanOLR)then
-         ! to record global radiative balance
-         open(92,file="rad_bal.out",form='formatted',access='append')
-         write(92,*) zday,flux3/totarea,flux1/totarea,flux2/totarea
-         close(92)
-      endif
-
-      if(kastprof)then ! for f(p,T) computation (not needed in universal model)
-         open(15,file='ene_bal.out',form='formatted',access='append')
-         write(15,*) flux1
-         close(15)
-         stop
-      endif
-
-!     Surface temperature information
-      ts1 = 0
-      ts2 = 999
-      ts3 = 0
-      do ig=1,ngrid
-         ts1 = ts1 + area(ig)*tsurf(ig)
-         ts2 = min(ts2,tsurf(ig))  
-	 ts3 = max(ts3,tsurf(ig))  
-      end do
-      print*,'Mean Tsurf =',ts1/totarea , ' Min Tsurf=',ts2, 
-     &          ' Max Tsurf =',ts3
-
-!    -------------------------------
-!    Dynamical fields incrementation
-!    -------------------------------
-! (FOR OUTPUT ONLY : the actual model integration is performed in the dynamics)
-      ! temperature, zonal and meridional wind
-      DO l=1,nlayer
-        DO ig=1,ngrid
-          zt(ig,l)=pt(ig,l) + pdt(ig,l)*ptimestep
-          zu(ig,l)=pu(ig,l) + pdu(ig,l)*ptimestep
-          zv(ig,l)=pv(ig,l) + pdv(ig,l)*ptimestep
-
-      ! diagnostic
-            zdtdyn(ig,l)=ztprevious(ig,l)-pt(ig,l)
-            ztprevious(ig,l)=zt(ig,l)
-        ENDDO
-      ENDDO
-      if(firstcall)call zerophys(zdtdyn)
-
-      ! dynamical heating diagnostic
-      DO ig=1,ngrid
-         fluxdyn(ig)=0.
-         DO l=1,nlayer
-            if(nonideal)then
-               fluxdyn(ig)=fluxdyn(ig) - (zdtdyn(ig,l)/ptimestep)
-     &              *(pplev(ig,l)-pplev(ig,l+1))*cpp3D(ig,l)/g
-            else
-               fluxdyn(ig)=fluxdyn(ig) - (zdtdyn(ig,l)/ptimestep)
-     &              *(pplev(ig,l)-pplev(ig,l+1))*cpp/g
-            endif
-         ENDDO
-      ENDDO
-
-
-      ! tracers
-      DO iq=1, nq
-        DO l=1,nlayer
-          DO ig=1,ngrid
-            zq(ig,l,iq)=pq(ig,l,iq) +pdq(ig,l,iq)*ptimestep
-          ENDDO
-        ENDDO
-      ENDDO
-
-      ! surface pressure
-      DO ig=1,ngrid
-          ps(ig)=pplev(ig,1) + pdpsrf(ig)*ptimestep
-      ENDDO
-
-      ! pressure
-      DO l=1,nlayer
-        DO ig=1,ngrid
-             zplev(ig,l)=pplev(ig,l)/pplev(ig,1)*ps(ig)
-             zplay(ig,l)=pplay(ig,l)/pplev(ig,1)*ps(ig)
-        ENDDO
-      ENDDO
-
-    
-!     ---------------------------------------------------------
-!     Compute column amounts (kg m-2) if tracers are enabled
-!     ---------------------------------------------------------
-      if(tracer)then
-         call zerophys(ngrid*nq,qcol)
-         do iq=1,nq
-            DO ig=1,ngrid
-               DO l=1,nlayer
-                  qcol(ig,iq) = qcol(ig,iq) + zq(ig,l,iq) *
-     &                      (pplev(ig,l) - pplev(ig,l+1)) / g
-               enddo
-            enddo
-         enddo
-      endif
-
-
-!     ---------------------------------------------------------
-!     Test for water conservation if water is enabled
-!     ---------------------------------------------------------
-      if(water)then
-
-         h2otot = 0
-         do ig=1,ngrid
-            h2otot = h2otot + area(ig)*
-     &      (qcol(ig,igcm_h2o_ice)+qcol(ig,igcm_h2o_vap)
-     &      +qsurf(ig,igcm_h2o_ice)+qsurf(ig,igcm_h2o_vap))
-         end do
-         print*,'Total water amount (kg): ',h2otot!/totarea
-      endif   
-
-
-!     TEMPORARY: save water cycle diagnostics
-!         IF((ngrid.eq.1).and.lastcall) THEN
-!            open(13,file='Ts.out')
-!            open(14,file='T.out')
-!            open(15,file='p.out')
-!            open(16,file='vap.out')
-!            open(17,file='alt.out')
-!            ig=1
-!            write(13,*) tsurf(ig)
-!            DO l=1,nlayer
-!               write(14,*) pt(ig,l)
-!              write(15,*) pplay(ig,l)
-!               write(16,*) pq(ig,l,igcm_h2o_vap)
-!               write(17,*) zzlay(ig,l)
-!            enddo
-!            close(13)
-!            close(14)
-!            close(15)
-!            close(16)
-!            close(17)
-!         ENDIF
-
-
-!     TEMPORARY: save data for LBL
-!         IF((ngrid.eq.1).and.lastcall) THEN
-!            open(14,file='T.dat')
-!            open(15,file='p.dat')
-!            ig=1
-!            write(14,*) nlayer+1
-!            write(15,*) nlayer+1
-!            write(14,*) tsurf(ig)
-!            write(15,*) pplev(ig,1)
-!            DO l=1,nlayer
-!               write(14,*) pt(ig,l)
-!              write(15,*) pplay(ig,l)
-!            enddo
-!            close(14)
-!            close(15)
-!         ENDIF
-
-
-      IF (ngrid.NE.1) THEN
-         print*,'Ls =',zls*180./pi
-
-!        -------------------------------------------------------------------
-!        Writing NetCDF file  "RESTARTFI" at the end of the run
-!        -------------------------------------------------------------------
-!        Note: 'restartfi' is stored just before dynamics are stored
-!              in 'restart'. Between now and the writting of 'restart',
-!              there will have been the itau=itau+1 instruction and
-!              a reset of 'time' (lastacll = .true. when itau+1= itaufin)
-!              thus we store for time=time+dtvr
-
-         IF(lastcall) THEN
-            ztime_fin = ptime + ptimestep/(float(iphysiq)*daysec)
-
-            write(*,*)'PHYSIQ: for physdem ztime_fin =',ztime_fin
-            call physdem1("restartfi.nc",long,lati,nsoilmx,nq,
-     .              ptimestep,pday,
-     .              ztime_fin,tsurf,tsoil,emis,q2,qsurf,
-     .              area,albedodat,inertiedat,zmea,zstd,zsig,
-     .              zgam,zthe)
-         ENDIF
-
-!        -----------------------------------------------------------------
-!        Saving statistics :
-!        -----------------------------------------------------------------
-!        ("stats" stores and accumulates 8 key variables in file "stats.nc"
-!        which can later be used to make the statistic files of the run:
-!        "stats")          only possible in 3D runs !
-
-         
-         IF (callstats) THEN
-
-            call wstats(ngrid,"ps","Surface pressure","Pa",2,ps)
-            call wstats(ngrid,"tsurf","Surface temperature","K",2,tsurf)
-             call wstats(ngrid,"fluxsurf_lw",
-     .                 "Thermal IR radiative flux to surface","W.m-2",2,
-     .                 fluxsurf_lw)
-             call wstats(ngrid,"fluxsurf_sw",
-     .                  "Solar radiative flux to surface","W.m-2",2,
-     .                   fluxsurf_sw_tot)
-             call wstats(ngrid,"fluxtop_lw",
-     .                  "Thermal IR radiative flux to space","W.m-2",2,
-     .                  fluxtop_lw)
-             call wstats(ngrid,"fluxtop_sw",
-     .                  "Solar radiative flux to space","W.m-2",2,
-     .                  fluxtop_sw_tot)
-
-            call wstats(ngrid,"temp","Atmospheric temperature","K",3,zt)
-            call wstats(ngrid,"u","Zonal (East-West) wind","m.s-1",3,zu)
-            call wstats(ngrid,"v","Meridional (North-South) wind",
-     .                  "m.s-1",3,zv)
-            call wstats(ngrid,"w","Vertical (down-up) wind",
-     .                  "m.s-1",3,pw)
-             call wstats(ngrid,"q2",
-     .               "Boundary layer eddy kinetic energy","m2.s-2",3,q2)
-
-           if (tracer) then
-            if (water) then
-               vmr=zq(1:ngridmx,1:nlayermx,igcm_h2o_vap)
-     &                  *mugaz/mmol(igcm_h2o_vap)
-               call wstats(ngrid,"vmr_h2ovapor",
-     .                    "H2O vapor volume mixing ratio","mol/mol",
-     .                    3,vmr)
-            endif ! of if (water)
-
-           endif !tracer 
-
-            IF(lastcall) THEN
-              write (*,*) "Writing stats..."
-              call mkstats(ierr)
-            ENDIF
-          ENDIF !if callstats
-
-
-
-!        ----------------------------------------------------------------------
-!        output in netcdf file "DIAGFI", containing any variable for diagnostic
-!        (output with  period "ecritphy", set in "run.def")
-!        ----------------------------------------------------------------------
-!        WRITEDIAGFI can ALSO be called from any other subroutine
-!        for any variable!
-
-!     is it not preferable to keep all the calls in one place?
-
-        call WRITEDIAGFI(ngrid,"tsurf","Surface temperature","K",2,
-     &                  tsurf)
-        call WRITEDIAGFI(ngrid,"ps","surface pressure","Pa",2,ps)
-        call WRITEDIAGFI(ngrid,"temp","temperature","K",3,zt)
-!        call WRITEDIAGFI(ngrid,"tau","tau"," ",2,tau)
-!        call WRITEDIAGFI(ngrid,"u","Zonal wind","m.s-1",3,zu)
-!        call WRITEDIAGFI(ngrid,"v","Meridional wind","m.s-1",3,zv)
-!        call WRITEDIAGFI(ngrid,"w","Vertical wind","m.s-1",3,pw)
-!        call WRITEDIAGFI(ngrid,"rho","density","none",3,rho)
-!        call WRITEDIAGFI(ngrid,"q2","q2","kg.m-3",3,q2)
-!        call WRITEDIAGFI(ngridm,'Teta','T potentielle','K',3,zh)
-!        call WRITEDIAGFI(ngridm,'Pression','Pression','Pa',3,pplay)
-
-!     Total energy balance diagnostics
-        call WRITEDIAGFI(ngrid,"ISR","incoming stellar rad.","W m-2",
-     &       2,fluxtop_dn)
-        call WRITEDIAGFI(ngrid,"ASR","absorbed stellar rad.","W m-2",
-     &       2,fluxabs_sw)
-        call WRITEDIAGFI(ngrid,"OLR","outgoing longwave rad.","W m-2",
-     &       2,fluxtop_lw)
-        call WRITEDIAGFI(ngrid,"DYN","dynamical heat input","W m-2",
-     &       2,fluxdyn)
-
-!     Temporary inclusions for heating diagnostics
-!        call WRITEDIAGFI(ngrid,"zdtdyn","Dyn. heating","T s-1",3,zdtdyn)
-!        call WRITEDIAGFI(ngrid,"zdtsw","SW heating","T s-1",3,zdtsw)
-!        call WRITEDIAGFI(ngrid,"zdtlw","LW heating","T s-1",3,zdtlw)
-
-!     Output tracers
-       if (tracer) then
-        do iq=1,nq
-!          call WRITEDIAGFI(ngrid,noms(iq),noms(iq),'kg/kg',3,zq(1,1,iq))
-          call WRITEDIAGFI(ngridmx,trim(noms(iq))//'_surf',
-     &                    trim(noms(iq))//'_surf',
-     &                    'kg/kg',2,qsurf(1,iq) )
-
-          call WRITEDIAGFI(ngridmx,trim(noms(iq))//'_col',
-     &                    trim(noms(iq))//'_col',
-     &                    'kg m^-2',2,qcol(1,iq) )
-
-
-
-          if(waterrain)then
-             CALL WRITEDIAGFI(ngridmx,"rain",
-     &            "total precipitation","kg m-2 s-1",2,rainout)
-          endif
-
-!          call WRITEDIAGFI(ngridmx,trim(noms(iq))//'_aero',
-!     &                    trim(noms(iq))//'_aero',
-!     &                    'kg/kg',3,aerosol(1,1,iq))
-
-          call WRITEDIAGFI(ngridmx,"tau_col",
-     &         "Total aerosol optical depth","[]",2,tau_col)
-
-!          call WRITEDIAGFI(ngridmx,trim(noms(iq))//'_reff',
-!     &                    trim(noms(iq))//'_reff',
-!     &                    'm',3,reffrad(1,1,iq))
-
-        enddo
-       endif
-
-      ELSE         ! if(ngrid.eq.1)
-
-
-!      ----------------------------------------------------------------------
-!      Output in grads file "g1d" (ONLY when using testphys1d)
-!      ----------------------------------------------------------------------
-
-         if(countG1D.eq.saveG1D)then
-         
-!         call WRITEDIAGFI(ngrid,"tsurf","Surface temperature", 
-!     &                  "K",0,tsurf)
-         CALL writeg1d(ngrid,1,tsurf,'tsurf','K')
-         CALL writeg1d(ngrid,1,ps,'ps','Pa')
-         CALL writeg1d(ngrid,nlayer,zt,'T','K')
-         CALL writeg1d(ngrid,nlayer,pq(1,1,1),'q','kg/kg')
-         CALL writeg1d(ngrid,nlayer,aerosol,'aerosol','SI')
-         CALL writeg1d(ngrid,nlayer,reffrad,'reffrad','SI')
-         CALL writeg1d(ngrid,nlayer,zdtlw,'dtlw','SI')
-         CALL writeg1d(ngrid,nlayer,zdtsw,'dtsw','SI')
-         CALL writeg1d(ngrid,nlayer,zdtdyn,'dtdyn','SI')
-
-!        radiation balance (optional)
-         CALL writeg1d(ngrid,1,flux3/totarea,'ISR','W m-2')
-         CALL writeg1d(ngrid,1,flux1/totarea,'ASR','W m-2')
-         CALL writeg1d(ngrid,1,flux2/totarea,'OLR','W m-2')   
-
-         if(tracer) then
-            do iq=1,nq
-              CALL writeg1d(ngrid,1,qsurf(1,iq),
-     &              trim(noms(iq))//'_s','kg m^-2') 
-              CALL writeg1d(ngrid,1,qcol(1,iq),
-     &              trim(noms(iq))//'_c','kg m^-2') 
-              CALL writeg1d(ngrid,nlayer,zq(1,1,iq),noms(iq),'kg/kg') 
-            end do
-
-            if(waterrain)then
-               CALL writeg1d(ngrid,1,rainout,
-     &              'rainfall','kg m-2 s-1')
-            endif
-         end if
-
-         countG1D=1
-         else
-            countG1D=countG1D+1
-         endif ! if time to save
-
-      END IF       ! if(ngrid.ne.1)
-
-      icount=icount+1
-
-      RETURN
-      END
Index: /trunk/LMDZ.GENERIC/libf/phystd/physiq.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/physiq.F90	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/physiq.F90	(revision 253)
@@ -0,0 +1,2154 @@
+     subroutine physiq(ngrid,nlayer,nq,   &
+                  firstcall,lastcall,      &
+                  pday,ptime,ptimestep,    &
+                  pplev,pplay,pphi,        &
+                  pu,pv,pt,pq,             &
+                  pw,                      &
+                  pdu,pdv,pdt,pdq,pdpsrf,tracerdyn)
+ 
+      use radinc_h, only : naerkind
+      use watercommon_h, only : mx_eau_sol, To, RLVTT
+     
+      implicit none
+
+
+!==================================================================
+!     
+!     Purpose
+!     -------
+!     Central subroutine for all the physics parameterisations in the
+!     universal model. Originally adapted from the Mars LMDZ model.
+!
+!     The model can be run without or with tracer transport
+!     depending on the value of "tracer" in file "callphys.def".
+!
+!
+!   It includes:
+!
+!      1.  Initialization:
+!      1.1 Firstcall initializations
+!      1.2 Initialization for every call to physiq
+!      1.2.5 Compute mean mass and cp, R and thermal conduction coeff.
+!      2. Compute radiative transfer tendencies
+!         (longwave and shortwave).
+!      4. Vertical diffusion (turbulent mixing):
+!      5. Convective adjustment
+!      6. Condensation and sublimation of gases (currently just CO2).
+!      7. TRACERS
+!       7a. water and water ice
+!       7c. other schemes for tracer transport (lifting, sedimentation)
+!       7d. updates (pressure variations, surface budget)
+!      9. Surface and sub-surface temperature calculations
+!     10. Write outputs :
+!           - "startfi", "histfi" if it's time
+!           - Saving statistics if "callstats = .true."
+!           - Output any needed variables in "diagfi" 
+!     10. Diagnostics: mass conservation of tracers, radiative energy balance etc.
+!
+!   arguments
+!   ---------
+!
+!   input
+!   -----
+!    ecri                  period (in dynamical timestep) to write output
+!    ngrid                 Size of the horizontal grid.
+!                          All internal loops are performed on that grid.
+!    nlayer                Number of vertical layers.
+!    nq                    Number of advected fields
+!    firstcall             True at the first call
+!    lastcall              True at the last call
+!    pday                  Number of days counted from the North. Spring
+!                          equinoxe.
+!    ptime                 Universal time (0<ptime<1): ptime=0.5 at 12:00 UT
+!    ptimestep             timestep (s)
+!    pplay(ngrid,nlayer)   Pressure at the middle of the layers (Pa)
+!    pplev(ngrid,nlayer+1) intermediate pressure levels (pa)
+!    pphi(ngrid,nlayer)    Geopotential at the middle of the layers (m2s-2)
+!    pu(ngrid,nlayer)      u component of the wind (ms-1)
+!    pv(ngrid,nlayer)      v component of the wind (ms-1)
+!    pt(ngrid,nlayer)      Temperature (K)
+!    pq(ngrid,nlayer,nq)   Advected fields
+!    pudyn(ngrid,nlayer)    \ 
+!    pvdyn(ngrid,nlayer)     \ Dynamical temporal derivative for the
+!    ptdyn(ngrid,nlayer)     / corresponding variables
+!    pqdyn(ngrid,nlayer,nq) /
+!    pw(ngrid,?)           vertical velocity
+!
+!   output
+!   ------
+!
+!    pdu(ngrid,nlayermx)        \
+!    pdv(ngrid,nlayermx)         \  Temporal derivative of the corresponding
+!    pdt(ngrid,nlayermx)         /  variables due to physical processes.
+!    pdq(ngrid,nlayermx)        /
+!    pdpsrf(ngrid)             /
+!    tracerdyn                 call tracer in dynamical part of GCM ?
+!
+!
+!     Authors
+!     -------
+!           Frederic Hourdin	15/10/93
+!           Francois Forget	1994
+!           Christophe Hourdin	02/1997 
+!           Subroutine completely rewritten by F. Forget (01/2000)
+!           Water ice clouds: Franck Montmessin (update 06/2003)
+!           Radiatively active tracers: J.-B. Madeleine (10/2008-06/2009)
+!           New correlated-k radiative scheme: R. Wordsworth (2009)
+!           Many specifically Martian subroutines removed: R. Wordsworth (2009)       
+!           Improved water cycle: R. Wordsworth / B. Charnay (2010)
+!           To F90: R. Wordsworth (2010)
+!     
+!==================================================================
+
+
+!    0.  Declarations :
+!    ------------------
+
+#include "dimensions.h"
+#include "dimphys.h"
+#include "comgeomfi.h"
+#include "surfdat.h"
+#include "comsoil.h"
+#include "comdiurn.h"
+#include "callkeys.h"
+#include "comcstfi.h"
+#include "planete.h"
+#include "comsaison.h"
+#include "control.h"
+#include "comg1d.h"
+#include "tracer.h"
+#include "watercap.h"
+#include "netcdf.inc"
+
+! Arguments :
+! -----------
+
+!   inputs:
+!   -------
+      integer ngrid,nlayer,nq
+      real ptimestep
+      real pplev(ngridmx,nlayer+1),pplay(ngridmx,nlayer)
+      real pphi(ngridmx,nlayer)
+      real pu(ngridmx,nlayer),pv(ngridmx,nlayer)
+      real pt(ngridmx,nlayer),pq(ngridmx,nlayer,nq)
+      real pw(ngridmx,nlayer)        ! pvervel transmitted by dyn3d
+      real zh(ngridmx,nlayermx)      ! potential temperature (K)
+      logical firstcall,lastcall
+
+      real pday
+      real ptime 
+      logical tracerdyn
+
+!   outputs:
+!   --------
+!     physical tendencies
+      real pdu(ngridmx,nlayer),pdv(ngridmx,nlayer)
+      real pdt(ngridmx,nlayer),pdq(ngridmx,nlayer,nq)
+      real pdpsrf(ngridmx) ! surface pressure tendency
+
+
+! Local saved variables:
+! ----------------------
+!     aerosol (dust or ice) extinction optical depth  at reference wavelength 
+!     "longrefvis" set in dimradmars.h , for one of the "naerkind"  kind of
+!      aerosol optical properties:
+!      real aerosol(ngridmx,nlayermx,naerkind) 
+!     this is now internal to callcorrk and hence no longer needed here
+
+      integer day_ini                ! Initial date of the run (sol since Ls=0) 
+      integer icount                 ! counter of calls to physiq during the run.
+      real tsurf(ngridmx)            ! Surface temperature (K)
+      real tsoil(ngridmx,nsoilmx)    ! sub-surface temperatures (K)
+      real albedo(ngridmx)           ! Surface albedo
+
+      real albedo0(ngridmx)          ! Surface albedo
+      integer rnat(ngridmx)          ! added by BC
+      save rnat
+
+      real emis(ngridmx)             ! Thermal IR surface emissivity
+      real dtrad(ngridmx,nlayermx)   ! Net atm. radiative heating rate (K.s-1)
+      real fluxrad_sky(ngridmx)      ! rad. flux from sky absorbed by surface (W.m-2)
+      real fluxrad(ngridmx)          ! Net radiative surface flux (W.m-2)
+      real capcal(ngridmx)           ! surface heat capacity (J m-2 K-1)
+      real fluxgrd(ngridmx)          ! surface conduction flux (W.m-2)
+      real qsurf(ngridmx,nqmx)       ! tracer on surface (e.g. kg.m-2)
+      real q2(ngridmx,nlayermx+1)    ! Turbulent Kinetic Energy 
+
+      save day_ini, icount
+      save tsurf,tsoil
+      save albedo0,albedo,emis,q2
+      save capcal,fluxgrd,dtrad,fluxrad,fluxrad_sky,qsurf
+
+      real, parameter :: stephan = 5.67e-08 ! Stephan Boltzman constant (should really be elsewhere)
+
+! Local variables :
+! -----------------
+
+!     aerosol (dust or ice) extinction optical depth  at reference wavelength 
+!     for the "naerkind" optically active aerosols:
+      real aerosol(ngridmx,nlayermx,naerkind) 
+
+      character*80 fichier 
+      integer l,ig,ierr,iq,i, tapphys
+
+      real fluxsurf_lw(ngridmx)      ! incident LW (IR) surface flux (W.m-2)
+      real fluxsurf_sw(ngridmx)      ! incident SW (stellar) surface flux (W.m-2)
+      real fluxtop_lw(ngridmx)       ! Outgoing LW (IR) flux to space (W.m-2)
+      real fluxabs_sw(ngridmx)       ! Absorbed SW (stellar) flux (W.m-2)
+
+      real fluxtop_dn(ngridmx)
+      real fluxdyn(ngridmx)          ! horizontal heat transport by dynamics      
+      save fluxsurf_lw,fluxsurf_sw,fluxtop_lw,fluxabs_sw,fluxtop_dn,fluxdyn
+
+
+      real zls                       ! solar longitude (rad)
+      real zday                      ! date (time since Ls=0, in martian days)
+      real zzlay(ngridmx,nlayermx)   ! altitude at the middle of the layers
+      real zzlev(ngridmx,nlayermx+1) ! altitude at layer boundaries
+      real latvl1,lonvl1             ! Viking Lander 1 point (for diagnostic)
+
+      real reffrad(ngridmx,nlayermx,naerkind)                 ! aerosol effective radius (m)
+
+!     Tendencies due to various processes:
+      real dqsurf(ngridmx,nqmx)
+      real zdtlw(ngridmx,nlayermx)                            ! (K/s)
+      real zdtsw(ngridmx,nlayermx)                            ! (K/s)
+      save zdtlw, zdtsw
+
+      real cldtlw(ngridmx,nlayermx)                           ! (K/s) LW heating rate for clear areas
+      real cldtsw(ngridmx,nlayermx)                           ! (K/s) SW heating rate for clear areas
+      real zdtsurf(ngridmx)                                   ! (K/s)
+      real dtlscale(ngridmx,nlayermx)
+      real zdvdif(ngridmx,nlayermx),zdudif(ngridmx,nlayermx)  ! (m.s-2)
+      real zdhdif(ngridmx,nlayermx), zdtsdif(ngridmx)         ! (K/s)
+      real zdvadj(ngridmx,nlayermx),zduadj(ngridmx,nlayermx)  ! (m.s-2)
+      real zdhadj(ngridmx,nlayermx)                           ! (K/s)
+      real zdtgw(ngridmx,nlayermx)                            ! (K/s)
+      real zdugw(ngridmx,nlayermx),zdvgw(ngridmx,nlayermx)    ! (m.s-2)
+      real zdtc(ngridmx,nlayermx),zdtsurfc(ngridmx)
+      real zdvc(ngridmx,nlayermx),zduc(ngridmx,nlayermx)
+
+      real zdqdif(ngridmx,nlayermx,nqmx), zdqsdif(ngridmx,nqmx)
+      real zdqsed(ngridmx,nlayermx,nqmx), zdqssed(ngridmx,nqmx)
+      real zdqdev(ngridmx,nlayermx,nqmx), zdqsdev(ngridmx,nqmx)
+      real zdqadj(ngridmx,nlayermx,nqmx)
+      real zdqc(ngridmx,nlayermx,nqmx)
+      real zdqlscale(ngridmx,nlayermx,nqmx)
+      real zdqslscale(ngridmx,nqmx)
+      real zdqchim(ngridmx,nlayermx,nqmx)
+      real zdqschim(ngridmx,nqmx)
+
+      real zdteuv(ngridmx,nlayermx)    ! (K/s)
+      real zdtconduc(ngridmx,nlayermx) ! (K/s)
+      real zdumolvis(ngridmx,nlayermx)
+      real zdvmolvis(ngridmx,nlayermx)
+      real zdqmoldiff(ngridmx,nlayermx,nqmx)
+
+!     Local variables for local calculations:
+      real zflubid(ngridmx)
+      real zplanck(ngridmx),zpopsk(ngridmx,nlayermx)
+      real zdum1(ngridmx,nlayermx)
+      real zdum2(ngridmx,nlayermx)
+      real ztim1,ztim2,ztim3, z1,z2
+      real ztime_fin
+      real zdh(ngridmx,nlayermx)
+      integer length
+      parameter (length=100)
+
+! local variables only used for diagnostics (output in file "diagfi" or "stats")
+! ------------------------------------------------------------------------------
+      real ps(ngridmx), zt(ngridmx,nlayermx)
+      real zu(ngridmx,nlayermx),zv(ngridmx,nlayermx)
+      real zq(ngridmx,nlayermx,nqmx)
+      character*2 str2
+      character*5 str5
+      real zdtdif(ngridmx,nlayermx), zdtadj(ngridmx,nlayermx)
+      real zdtdyn(ngridmx,nlayermx),ztprevious(ngridmx,nlayermx)
+      save ztprevious 
+      real reff(ngridmx,nlayermx) ! effective dust radius (used if doubleq=T)
+      real qtot1,qtot2            ! total aerosol mass
+      integer igmin, lmin
+      logical tdiag
+
+      real zplev(ngrid,nlayermx+1),zplay(ngrid,nlayermx)
+      real zstress(ngrid), cd
+      real hco2(nqmx), tmean, zlocal(nlayermx)
+      real vmr(ngridmx,nlayermx) ! volume mixing ratio
+
+      real time_phys
+
+!     reinstated by RW for diagnostic
+      real tau_col(ngridmx)
+      save tau_col
+
+!     included by RW to reduce insanity of code
+      real ISR,ASR,OLR,GND,DYN,GSR,Ts1,Ts2,Ts3,TsS
+
+!     included by RW for temporary comparison
+      real zdtnirco2(ngridmx,nlayermx) ! (K/s)
+
+!     included by RW to compute tracer column densities
+      real qcol(ngridmx,nqmx)
+
+!     included by RW for H2O precipitation
+      real zdtrain(ngridmx,nlayermx)
+      real zdqrain(ngridmx,nlayermx,nqmx)
+      real zdqsrain(ngridmx)
+      real zdqssnow(ngridmx)
+      real rainout(ngridmx)
+
+!     included by RW for H2O Manabe scheme
+      real dtmoist(ngridmx,nlayermx)
+      real dqmoist(ngridmx,nlayermx,nqmx)
+
+      real qvap(ngridmx,nlayermx)
+      real dqvaplscale(ngridmx,nlayermx)
+      real dqcldlscale(ngridmx,nlayermx)
+      real rneb_man(ngridmx,nlayermx)
+      real rneb_lsc(ngridmx,nlayermx)
+
+!     included by RW to account for surface cooling by evaporation
+      real dtsurfh2olat(ngridmx)
+
+!     included by RW to test energy conservation
+      real dEtot, dEtots, masse, vabs, dvabs
+      real dEtotSW, dEtotsSW, dEtotLW, dEtotsLW
+
+      real dItot, dVtot
+
+!     included by RW to test water conservation
+      real h2otot
+
+!     included by RW to allow variations in cp with location
+      real cpp3D(ngridmx,nlayermx)   ! specific heat capacity at const. pressure
+      real rcp3D(ngridmx,nlayermx)   ! R / specific heat capacity
+      real cppNI, rcpNI, nnu         ! last one just for Seb version
+      real zpopskNI(ngridmx,nlayermx)
+
+!     included by RW to make 1D saves not every timestep
+      integer countG1D
+      save countG1D
+
+!     included by BC for evaporation     
+      real qevap(ngridmx,nlayermx,nqmx)
+      real tevap(ngridmx,nlayermx)
+      real dqevap(ngridmx,nlayermx)
+      real dtevap(ngridmx,nlayermx)
+
+!     included by BC for hydrology
+      real hice(ngridmx)
+
+!     included by RW to test water conservation (by routine)
+      real dWtot, dWtots
+      real h2o_surf_all
+      logical watertest
+      save watertest
+
+!     included by RW for RH diagnostic
+      real qsat(ngridmx,nlayermx), RH(ngridmx,nlayermx), H2Omaxcol(ngridmx)
+
+!     included by RW for hydrology
+      real dqs_hyd(ngridmx,nqmx)
+      real zdtsurf_hyd(ngridmx)
+
+!     included by RW for water cycle conservation tests
+      real icesrf,liqsrf,icecol,vapcol
+
+!     included by BC for double radiative transfer call
+      logical clearsky
+
+      real zdtsw1(ngridmx,nlayermx),zdtsw2(ngridmx,nlayermx)
+      real zdtlw1(ngridmx,nlayermx),zdtlw2(ngridmx,nlayermx)
+      real fluxsurf_lw1(ngridmx), fluxsurf_lw2(ngridmx)     
+      real fluxsurf_sw1(ngridmx), fluxsurf_sw2(ngridmx)    
+      real fluxtop_lw1(ngridmx), fluxtop_lw2(ngridmx)     
+      real fluxabs_sw1(ngridmx), fluxabs_sw2(ngridmx)   
+      real tau_col1(ngrid), tau_col2(ngrid)
+      real tf, ntf
+
+!     included by BC for cloud fraction computations
+      real cloudfrac(ngridmx,nlayermx)
+      real totcloudfrac(ngridmx)
+
+!     included by RW for Tmax test
+      integer iTmax
+
+!     included by RW for vdifc water conservation test
+      real nconsMAX
+      real vdifcncons(ngridmx)
+      real cadjncons(ngridmx)
+      real qzero1D
+      save qzero1D
+
+!      double precision qsurf_hist(ngridmx,nqmx)
+      real qsurf_hist(ngridmx,nqmx)
+      save qsurf_hist
+
+!     included by RW for temp convadj conservation test
+      real playtest(nlayermx)
+      real plevtest(nlayermx)
+      real ttest(nlayermx)
+      real qtest(nlayermx)
+      integer igtest
+
+!     included by RW for pressure broadening broadening study
+      integer gascut
+
+!     included by RW for variable H2O particle sizes
+      real reffH2O(ngridmx,nlayermx)
+      real reffcol(ngridmx,2)
+
+!     included by RW for flexible 3D energy conservation testing
+      real vdifcdE(ngridmx), madjdE(ngridmx), lscaledE(ngridmx)
+
+!     included by RW for sourceevol
+      real ice_initial(ngridmx)!, isoil
+      real ice_min(ngridmx)
+      save ice_min
+      save ice_initial
+
+      integer num_run
+      logical ice_update
+      save ice_update
+
+!=======================================================================
+      
+
+! 1. Initialisation
+! -----------------
+
+!  1.1   Initialisation only at first call
+!  ---------------------------------------
+      if (firstcall) then
+
+         if(ngrid.eq.1)then
+            saveG1D=day_step*10
+            !saveG1D=1
+            !saveG1D=-1 ! to never save 
+            countG1D=1
+         endif
+
+!        variables set to 0
+!        ~~~~~~~~~~~~~~~~~~
+         dtrad(:,:) = 0.0
+         fluxrad(:) = 0.0
+         tau_col(:) = 0.0
+         zdtsw(:,:) = 0.0
+         zdtlw(:,:) = 0.0
+      
+!        initialize tracer names, indexes and properties
+!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+         tracerdyn=tracer
+         if (tracer) then
+            call initracer()
+         endif ! end tracer
+
+!        read startfi (initial parameters)
+!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+         
+         call phyetat0("startfi.nc",0,0,nsoilmx,nq,           &
+               day_ini,time_phys,tsurf,tsoil,emis,q2,qsurf,   &
+               cloudfrac,totcloudfrac,hice)
+
+
+         if (pday.ne.day_ini) then
+           write(*,*) "ERROR in physiq.F90:"
+           write(*,*) "bad synchronization between physics and dynamics"
+           write(*,*) "dynamics day: ",pday
+           write(*,*) "physics day:  ",day_ini
+           stop
+         endif
+
+         write (*,*) 'In physiq day_ini =', day_ini
+
+!        Initialize albedo and orbital calculation
+!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+         call surfini(ngrid,qsurf,albedo0)
+         call iniorbit(apoastr,periastr,year_day,peri_day,obliquit)
+
+         do ig=1,ngrid
+            albedo(ig)=albedo0(ig)
+         enddo
+
+         if(tlocked)then
+            print*,'Planet is tidally locked at resonance n=',nres
+            print*,'Make sure you have the right rotation rate!!!'
+         endif
+
+!        initialize soil 
+!        ~~~~~~~~~~~~~~~
+         if (callsoil) then
+            call soil(ngrid,nsoilmx,firstcall,inertiedat,     &
+                ptimestep,tsurf,tsoil,capcal,fluxgrd)
+         else
+            print*,'WARNING! Thermal conduction in the soil turned off'
+            do ig=1,ngrid
+               capcal(ig)=1.e6
+               fluxgrd(ig)=0.
+               if(noradsurf)then
+                  fluxgrd(ig)=10.0
+               endif
+            enddo
+            print*,'Flux from ground = ',fluxgrd,' W m^-2'
+         endif
+         icount=1
+
+!        decide whether to update ice at end of run
+!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+         ice_update=.false.
+         if(sourceevol)then
+            open(128,file='num_run',form='formatted')
+            read(128,*) num_run 
+            close(128)
+        
+            if(num_run.ne.0.and.mod(num_run,6).eq.0)then
+               print*,'Updating ice at end of this year!'
+               ice_update=.true.
+               ice_min(:)=1.e4
+            endif  
+         endif
+
+!        define surface as continent or ocean
+!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+!         print*,'OCEAN EVERYWHERE FOR GJ581d RUNS'
+         do ig=1,ngridmx
+            rnat(ig)=1
+
+!            if(iceball.or.oceanball.or.(inertiedat(ig,1).gt.1.E4))then
+            if(inertiedat(ig,1).gt.1.E4)then
+            rnat(ig)=0
+            endif
+         enddo
+
+         print*,'WARNING! Surface type currently decided by surface inertia'
+         print*,'This should be improved e.g. in newstart.F'
+
+
+!        initialise surface history variable 
+!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+         do ig=1,ngridmx
+            do iq=1,nqmx
+               qsurf_hist(ig,iq)=qsurf(ig,iq)
+            enddo
+         enddo
+
+!        initialise variable for dynamical heating diagnostic
+!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+         ztprevious(:,:)=pt(:,:)
+
+!        Set temperature just above condensation temperature (for Early Mars)
+!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+         if(nearco2cond) then
+            write(*,*)' WARNING! Starting at Tcond+1K'
+            do l=1, nlayer
+               do ig=1,ngrid
+                  pdt(ig,l)= ((-3167.8)/(log(.01*pplay(ig,l))-23.23)+4     &
+                      -pt(ig,l)) / ptimestep
+               enddo
+            enddo
+         endif
+
+         if(meanOLR)then
+            ! to record global radiative balance
+            call system('rm -f rad_bal.out')
+            ! to record global mean/max/min temperatures
+            call system('rm -f tem_bal.out')
+            ! to record global hydrological balance
+            call system('rm -f h2o_bal.out')
+         endif
+
+         watertest=.false.
+         if(water)then
+            ! initialise variables for water cycle
+
+            qzero1D=0.0
+
+            watertest=.true. ! standard for now
+            if(ngrid.eq.1)then
+               qzero1D               = 0.0
+               qsurf(1,igcm_h2o_vap) = qzero1D
+               do l=1, nlayer
+                  pq(1,l,igcm_h2o_vap)=0.0
+                  pq(1,l,igcm_h2o_ice)=0.0
+               enddo
+            endif
+
+            do ig=1,ngrid
+               qsurf_hist(ig,igcm_h2o_vap) = qsurf(ig,igcm_h2o_vap)
+               if(ice_update)then
+                  ice_initial(ig)=qsurf(ig,igcm_h2o_ice)
+               endif
+            enddo
+
+         endif
+         call su_watercycle ! even if we don't have a water cycle, we might
+                            ! need epsi for the wvp definitions in callcorrk.F
+
+      endif        !  (end of "if firstcall")
+
+! ---------------------------------------------------
+! 1.2   Initializations done at every physical timestep:
+! ---------------------------------------------------
+
+      if (ngrid.NE.ngridmx) then
+         print*,'STOP in PHYSIQ'
+         print*,'Probleme de dimensions :'
+         print*,'ngrid     = ',ngrid
+         print*,'ngridmx   = ',ngridmx
+         stop
+      endif
+
+!     Initialize various variables
+!     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+      pdu(:,:) = 0.0
+      pdv(:,:) = 0.0
+!      if ( (.not.nearco2cond).and.(.not.firstcall) ) then
+      if ( .not.nearco2cond ) then
+         pdt(:,:) = 0.0
+      endif ! this was the source of an evil bug...
+      pdq(:,:,:)  = 0.0
+      pdpsrf(:)   = 0.0
+      zflubid(:)  = 0.0
+      zdtsurf(:)  = 0.0
+      dqsurf(:,:) = 0.0
+
+      zday=pday+ptime ! compute time, in sols (and fraction thereof)
+
+!     Compute Stellar Longitude (Ls)
+!     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+      if (season) then
+         call stellarlong(zday,zls)
+      else
+         call stellarlong(float(day_ini),zls)
+      end if
+
+!     Compute geopotential between layers
+!     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+      do l=1,nlayer
+         do ig=1,ngrid
+            zzlay(ig,l)=pphi(ig,l)/g
+         enddo
+      enddo
+      do ig=1,ngrid
+         zzlev(ig,1)=0.
+         zzlev(ig,nlayer+1)=1.e7    ! dummy top of last layer above 10000 km...
+      enddo
+      do l=2,nlayer
+         do ig=1,ngrid
+            z1=(pplay(ig,l-1)+pplev(ig,l))/(pplay(ig,l-1)-pplev(ig,l))
+            z2=(pplev(ig,l)+pplay(ig,l))/(pplev(ig,l)-pplay(ig,l))
+            zzlev(ig,l)=(z1*zzlay(ig,l-1)+z2*zzlay(ig,l))/(z1+z2)
+         enddo
+      enddo
+!     Potential temperature calculation may not be the same in physiq and dynamic...
+
+!     Compute potential temperature
+!     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+      do l=1,nlayer
+         do ig=1,ngrid 
+            call calc_cpp3d(cppNI,rcpNI,pt(ig,l),pplay(ig,l))
+            cpp3D(ig,l)  = cppNI
+            rcp3D(ig,l)  = rcpNI
+         enddo
+      enddo
+
+      do l=1,nlayer
+         do ig=1,ngrid
+            zh(ig,l)       = pt(ig,l)
+            zpopskNI(ig,l) = pt(ig,l)/zh(ig,l)
+            zpopsk(ig,l)   = pt(ig,l)/zh(ig,l)
+            ! we're only after zpopskNI here, not zh
+            ! zh is calculated seperately before both vdifc and convadj
+         enddo
+      enddo
+         
+      do l=1,nlayer
+         do ig=1,ngrid 
+            zpopsk(ig,l)=(pplay(ig,l)/pplev(ig,1))**rcp
+            zh(ig,l)=pt(ig,l)/zpopsk(ig,l)
+         enddo
+      enddo
+
+!-----------------------------------------------------------------------
+!    2. Compute radiative tendencies
+!-----------------------------------------------------------------------
+
+      if (callrad) then
+         if( mod(icount-1,iradia).eq.0) then
+
+!          Compute local stellar zenith angles
+!          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+           call orbite(zls,dist_star,declin)
+
+           if (tlocked) then
+              ztim1=SIN(declin)
+              ztim2=COS(declin)*COS(2.*pi*(zday/year_day) - zls*nres)
+              ztim3=-COS(declin)*SIN(2.*pi*(zday/year_day) - zls*nres)
+
+               call stelang(ngrid,sinlon,coslon,sinlat,coslat,    &
+               ztim1,ztim2,ztim3,mu0,fract)
+
+           elseif (diurnal) then
+               ztim1=SIN(declin)
+               ztim2=COS(declin)*COS(2.*pi*(zday-.5))
+               ztim3=-COS(declin)*SIN(2.*pi*(zday-.5))
+
+               call stelang(ngrid,sinlon,coslon,sinlat,coslat,    &
+               ztim1,ztim2,ztim3,mu0,fract)
+
+           else
+
+               call mucorr(ngrid,declin,lati,mu0,fract,10000.,rad)
+               ! WARNING: this function appears not to work in 1D
+
+           endif
+
+           if (corrk) then
+
+!          a) Call correlated-k radiative transfer scheme
+!          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+              if(kastprof)then
+                 ISR=fract(1)*Fat1AU/dist_star**2/2.0
+
+                 call simpleprof_fn(tsurf,pt,zpopsk,ISR,pplev(1,1))
+                 open(116,file='profpres.out',form='formatted')
+                 open(117,file='proftemp.out',form='formatted')
+                 do l=1,nlayer
+                    write(116,*) pplay(1,l)
+                    write(117,*) pt(1,l)
+                 enddo
+                 close(116)
+                 close(117)
+              endif
+
+
+!             Option to call scheme once for clear regions, once for cloudy regions (BC)
+              if(CLFvarying)then
+
+                 clearsky=.true.
+                 call callcorrk(icount,ngrid,nlayer,pq,nq,qsurf,           &
+                      albedo,emis,mu0,pplev,pplay,pt,                      &
+                      tsurf,fract,dist_star,aerosol,cpp3D,                 &
+                      zdtlw1,zdtsw1,fluxsurf_lw1,fluxsurf_sw1,fluxtop_lw1, &
+                      fluxabs_sw1,fluxtop_dn,reffrad,tau_col1,ptime,pday,  &
+                      cloudfrac,totcloudfrac,clearsky,firstcall,lastcall)
+
+                 clearsky=.false.
+                 call callcorrk(icount,ngrid,nlayer,pq,nq,qsurf,           &
+                      albedo,emis,mu0,pplev,pplay,pt,                      &
+                      tsurf,fract,dist_star,aerosol,cpp3D,                 &
+                      zdtlw2,zdtsw2,fluxsurf_lw2,fluxsurf_sw2,fluxtop_lw2, &
+                      fluxabs_sw2,fluxtop_dn,reffrad,tau_col2,ptime,pday,  &
+                      cloudfrac,totcloudfrac,clearsky,firstcall,lastcall)
+
+                 ! Sum the fluxes and heating rates from cloudy/clear cases
+                 do ig=1,ngrid
+                    tf=totcloudfrac(ig)
+                    ntf=1.-tf
+                    
+                    fluxsurf_lw(ig) = ntf*fluxsurf_lw1(ig) + tf*fluxsurf_lw2(ig)
+                    fluxsurf_sw(ig) = ntf*fluxsurf_sw1(ig) + tf*fluxsurf_sw2(ig)
+                    fluxtop_lw(ig)  = ntf*fluxtop_lw1(ig)  + tf*fluxtop_lw2(ig)
+                    fluxabs_sw(ig)  = ntf*fluxabs_sw1(ig)  + tf*fluxabs_sw2(ig)
+                    tau_col(ig)     = ntf*tau_col1(ig)     + tf*tau_col2(ig)
+                    
+                    do l=1,nlayer
+                       zdtlw(ig,l) = ntf*zdtlw1(ig,l) + tf*zdtlw2(ig,l)
+                       zdtsw(ig,l) = ntf*zdtsw1(ig,l) + tf*zdtsw2(ig,l)
+                    enddo
+                 enddo
+
+!             Otherwise standard callcorrk
+              else
+
+                 clearsky=.false.
+                 call callcorrk(icount,ngrid,nlayer,pq,nq,qsurf,         &
+                      albedo,emis,mu0,pplev,pplay,pt,                    &
+                      tsurf,fract,dist_star,aerosol,cpp3D,               &
+                      zdtlw,zdtsw,fluxsurf_lw,fluxsurf_sw,fluxtop_lw,    &
+                      fluxabs_sw,fluxtop_dn,reffrad,tau_col,ptime,pday,  &
+                      cloudfrac,totcloudfrac,clearsky,firstcall,lastcall)
+
+              endif
+
+!             Radiative flux from the sky absorbed by the surface (W.m-2)
+              GSR=0.0
+              do ig=1,ngrid
+                 fluxrad_sky(ig)=emis(ig)*fluxsurf_lw(ig)             &
+                      +fluxsurf_sw(ig)*(1.-albedo(ig))
+
+                 if(noradsurf)then ! no lower surface; SW flux just disappears
+                    GSR = GSR + fluxsurf_sw(ig)*area(ig)
+                    fluxrad_sky(ig)=emis(ig)*fluxsurf_lw(ig)
+                 endif
+
+              enddo
+              if(noradsurf)then
+                 print*,'SW lost in deep atmosphere = ',GSR/totarea,' W m^-2'
+              endif
+
+!             Net atmospheric radiative heating rate (K.s-1)
+              do l=1,nlayer
+                 do ig=1,ngrid
+                    dtrad(ig,l)=zdtsw(ig,l)+zdtlw(ig,l)
+                 enddo
+              enddo
+
+
+           elseif(newtonian)then
+
+!          b) Call Newtonian cooling scheme
+!          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+              call newtrelax(mu0,sinlat,zpopsk,pt,pplay,pplev,dtrad,firstcall)
+
+              do ig=1,ngrid
+                 zdtsurf(ig) = +(pt(ig,1)-tsurf(ig))/ptimestep
+              enddo
+              ! e.g. surface becomes proxy for 1st atmospheric layer ?
+
+           else
+
+!          c) Atmosphere has no radiative effect
+!          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+              do ig=1,ngrid
+                 fluxtop_dn(ig)  = fract(ig)*mu0(ig)*Fat1AU/dist_star**2
+                 if(ngrid.eq.1)then ! / by 4 globally in 1D case...
+                    fluxtop_dn(1)  = fract(1)*Fat1AU/dist_star**2/2.0
+                 endif
+                 fluxsurf_sw(ig) = fluxtop_dn(ig)
+                 fluxrad_sky(ig) = fluxtop_dn(ig)*(1.-albedo(ig))
+                 fluxtop_lw(ig)  = emis(ig)*stephan*tsurf(ig)**4
+              enddo ! radiation skips the atmosphere entirely
+
+              do l=1,nlayer
+                 do ig=1,ngrid
+                    dtrad(ig,l)=0.0
+                 enddo
+              enddo ! hence no atmospheric radiative heating
+
+           endif                ! if corrk
+
+        endif ! of if(mod(icount-1,iradia).eq.0)
+
+
+!    Transformation of the radiative tendencies
+!    ------------------------------------------
+
+        do ig=1,ngrid
+           zplanck(ig)=tsurf(ig)*tsurf(ig)
+           zplanck(ig)=emis(ig)*stephan*zplanck(ig)*zplanck(ig)
+           fluxrad(ig)=fluxrad_sky(ig)-zplanck(ig)
+        enddo
+
+        do l=1,nlayer
+           do ig=1,ngrid
+              pdt(ig,l)=pdt(ig,l)+dtrad(ig,l)
+           enddo
+        enddo
+
+!-------------------------
+! test energy conservation
+         if(enertest)then
+            dEtotSW  = 0.0
+            dEtotLW  = 0.0
+            dEtotsSW = 0.0
+            dEtotsLW = 0.0
+            do ig = 1, ngrid
+               do l = 1, nlayer
+                  masse  = (pplev(ig,l) - pplev(ig,l+1))/g
+                  dEtotSW = dEtotSW + cpp3D(ig,l)*masse*zdtsw(ig,l)*area(ig)
+                  dEtotLW = dEtotLW + cpp3D(ig,l)*masse*zdtlw(ig,l)*area(ig)
+               enddo
+               dEtotsSW = dEtotsSW + fluxsurf_sw(ig)*(1.-albedo(ig))*area(ig)
+               dEtotsLW = dEtotsLW + emis(ig)*fluxsurf_lw(ig)*area(ig)-zplanck(ig)*area(ig)
+            enddo
+            dEtotSW  = dEtotSW/totarea
+            dEtotLW  = dEtotLW/totarea
+            dEtotsSW = dEtotsSW/totarea
+            dEtotsLW = dEtotsLW/totarea
+            print*,'---------------------------------------------------------------'
+            print*,'In corrk SW atmospheric energy change =',dEtotSW,' W m-2'
+            print*,'In corrk LW atmospheric energy change =',dEtotLW,' W m-2'
+            print*,'In corrk SW surface energy change     =',dEtotsSW,' W m-2'
+            print*,'In corrk LW surface energy change     =',dEtotsLW,' W m-2'
+         endif
+!-------------------------
+
+      endif ! of if (callrad)
+
+	
+!-----------------------------------------------------------------------
+!    4. Vertical diffusion (turbulent mixing):
+!    -----------------------------------------
+
+      if (calldifv) then
+
+         do ig=1,ngrid
+            zflubid(ig)=fluxrad(ig)+fluxgrd(ig)
+         enddo
+
+         zdum1(:,:)=0.0
+         zdum2(:,:)=0.0
+         do l=1,nlayer
+            do ig=1,ngrid
+               zdh(ig,l)=pdt(ig,l)/zpopsk(ig,l)
+            enddo
+         enddo
+
+         call vdifc(ngrid,nlayer,nq,rnat,zpopsk,     &
+              ptimestep,capcal,lwrite,               &
+              pplay,pplev,zzlay,zzlev,z0,            &
+              pu,pv,zh,pq,tsurf,emis,qsurf,          &
+              zdum1,zdum2,zdh,pdq,zflubid,           &
+              zdudif,zdvdif,zdhdif,zdtsdif,q2,       &
+              zdqdif,zdqsdif)
+
+         do l=1,nlayer
+            do ig=1,ngrid
+               pdv(ig,l)=pdv(ig,l)+zdvdif(ig,l)
+               pdu(ig,l)=pdu(ig,l)+zdudif(ig,l)
+               pdt(ig,l)=pdt(ig,l)+zdhdif(ig,l)*zpopsk(ig,l)
+               zdtdif(ig,l)=zdhdif(ig,l)*zpopsk(ig,l) ! for diagnostic only
+            enddo
+         enddo
+
+         do ig=1,ngrid
+            zdtsurf(ig)=zdtsurf(ig)+zdtsdif(ig)
+         enddo
+
+         if (tracer) then 
+           do iq=1, nq
+            do l=1,nlayer
+              do ig=1,ngrid
+                 pdq(ig,l,iq)=pdq(ig,l,iq)+ zdqdif(ig,l,iq) 
+              enddo
+            enddo
+           enddo
+           do iq=1, nq
+              do ig=1,ngrid
+                 dqsurf(ig,iq)=dqsurf(ig,iq) + zdqsdif(ig,iq)
+              enddo
+           enddo
+
+         end if ! of if (tracer)
+
+         !-------------------------
+         ! test energy conservation
+         if(enertest)then
+            dEtot=0.0
+            dEtots=0.0
+            vdifcdE(:)=0.0
+            do ig = 1, ngrid
+               do l = 1, nlayer
+                  masse = (pplev(ig,l) - pplev(ig,l+1))/g
+                  dEtot = dEtot + cpp3D(ig,l)*masse*zdtdif(ig,l)*area(ig)
+                 
+                  vabs  = sqrt(pdu(ig,l)**2 + pdv(ig,l)**2)
+                  dvabs = sqrt(zdudif(ig,l)**2 + zdvdif(ig,l)**2)
+                  dEtot = dEtot + masse*vabs*dvabs*area(ig)
+
+                  vdifcdE(ig) = vdifcdE(ig) + masse*vabs*dvabs
+
+               enddo
+               dEtots = dEtots + capcal(ig)*zdtsdif(ig)*area(ig)
+               vdifcdE(ig) = vdifcdE(ig) + capcal(ig)*zdtsdif(ig)
+            enddo
+            dEtot  = dEtot/totarea
+            dEtots = dEtots/totarea
+            print*,'In difv atmospheric energy change     =',dEtot,' W m-2'
+            print*,'In difv surface energy change         =',dEtots,' W m-2'
+            !print*,'Note we ignore the wind change...'
+            ! and latent heat for that matter...
+         endif
+         !-------------------------
+
+         !-------------------------
+         ! test water conservation
+         if(watertest.and.water)then
+            dWtot=0.0
+            dWtots=0.0
+            nconsMAX=0.0
+            do ig = 1, ngrid
+
+               vdifcncons(ig)=0.0
+               do l = 1, nlayer
+                  masse = (pplev(ig,l) - pplev(ig,l+1))/g
+
+                  iq    = igcm_h2o_vap
+                  dWtot = dWtot + masse*zdqdif(ig,l,iq)*ptimestep*area(ig)
+                  vdifcncons(ig)=vdifcncons(ig) + masse*zdqdif(ig,l,iq)
+
+                  iq    = igcm_h2o_ice
+                  dWtot = dWtot + masse*zdqdif(ig,l,iq)*ptimestep*area(ig)
+                  vdifcncons(ig)=vdifcncons(ig) + masse*zdqdif(ig,l,iq)
+               
+               enddo
+
+               iq     = igcm_h2o_vap
+               dWtots = dWtots + zdqsdif(ig,iq)*ptimestep*area(ig)
+               vdifcncons(ig)=vdifcncons(ig)+zdqsdif(ig,iq)
+
+               iq     = igcm_h2o_ice
+               dWtots = dWtots + zdqsdif(ig,iq)*ptimestep*area(ig)
+               vdifcncons(ig)=vdifcncons(ig)+zdqsdif(ig,iq)
+
+               if(vdifcncons(ig).gt.nconsMAX)then
+                  nconsMAX=vdifcncons(ig)
+               endif
+
+            enddo
+
+            dWtot  = dWtot/totarea
+            dWtots = dWtots/totarea
+            print*,'---------------------------------------------------------------'
+            print*,'In difv atmospheric water change        =',dWtot,' kg m-2'
+            print*,'In difv surface water change            =',dWtots,' kg m-2'
+            print*,'In difv non-cons factor                 =',dWtot+dWtots,' kg m-2'
+            print*,'In difv MAX non-cons factor             =',nconsMAX,' kg m-2 s-1'
+
+
+         endif
+         !-------------------------
+
+      else    
+
+         if(.not.newtonian)then
+
+            do ig=1,ngrid
+               zdtsurf(ig) = zdtsurf(ig) + (fluxrad(ig) + fluxgrd(ig))/capcal(ig)
+            enddo
+
+         endif
+
+      endif ! of if (calldifv)
+
+
+!-----------------------------------------------------------------------
+!   5. Dry convective adjustment:
+!   -----------------------------
+
+      if(calladj) then
+
+         do l=1,nlayer
+            do ig=1,ngrid
+               if(nonideal)then
+                  zdh(ig,l) = pdt(ig,l)/zpopskNI(ig,l)
+               else
+                  zdh(ig,l) = pdt(ig,l)/zpopsk(ig,l)
+               endif
+            enddo
+         enddo
+         zduadj(:,:)=0.0
+         zdvadj(:,:)=0.0
+         zdhadj(:,:)=0.0
+
+         if(nonideal)then
+            print*,'Nonideal is not used at the moment'
+            call abort
+            call convadj(ngrid,nlayer,nq,ptimestep,    &
+                 pplay,pplev,zpopskNI,                 &
+                 pu,pv,zh,pq,                          &
+                 pdu,pdv,zdh,pdq,                      &
+                 zduadj,zdvadj,zdhadj,                 &
+                 zdqadj)
+         else
+            
+            call convadj(ngrid,nlayer,nq,ptimestep,    &
+                 pplay,pplev,zpopsk,                   &
+                 pu,pv,zh,pq,                          &
+                 pdu,pdv,zdh,pdq,                      &
+                 zduadj,zdvadj,zdhadj,                 &
+                 zdqadj)
+
+         endif
+
+         do l=1,nlayer
+            do ig=1,ngrid
+               pdu(ig,l) = pdu(ig,l) + zduadj(ig,l)
+               pdv(ig,l) = pdv(ig,l) + zdvadj(ig,l)
+               if(nonideal)then
+                  pdt(ig,l)    = pdt(ig,l) + zdhadj(ig,l)*zpopskNI(ig,l)
+                  zdtadj(ig,l) = zdhadj(ig,l)*zpopskNI(ig,l) ! for diagnostic only
+               else
+                  pdt(ig,l)    = pdt(ig,l) + zdhadj(ig,l)*zpopsk(ig,l)
+                  zdtadj(ig,l) = zdhadj(ig,l)*zpopsk(ig,l) ! for diagnostic only
+               endif
+            enddo
+         enddo
+
+         if(tracer) then 
+           do iq=1, nq
+            do l=1,nlayer
+              do ig=1,ngrid
+                 pdq(ig,l,iq) = pdq(ig,l,iq) + zdqadj(ig,l,iq) 
+              enddo
+            enddo
+           enddo
+         end if
+
+         !-------------------------
+         ! test energy conservation
+         if(enertest)then
+            dEtot=0.0
+            do ig = 1, ngrid
+               do l = 1, nlayer
+                  masse = (pplev(ig,l) - pplev(ig,l+1))/g
+                  dEtot = dEtot + cpp3D(ig,l)*masse*zdtadj(ig,l)*area(ig)
+               enddo
+            enddo
+            dEtot=dEtot/totarea
+          print*,'In convadj atmospheric energy change    =',dEtot,' W m-2'
+         endif
+         !-------------------------
+
+         !-------------------------
+         ! test water conservation
+         if(watertest)then
+            dWtot=0.0
+            do ig = 1, ngrid
+               cadjncons(ig)=0.0
+               do l = 1, nlayer
+                  masse = (pplev(ig,l) - pplev(ig,l+1))/g
+                  
+                  iq    = igcm_h2o_vap
+                  dWtot = dWtot + masse*zdqadj(ig,l,iq)*ptimestep*area(ig)
+                  cadjncons(ig)=cadjncons(ig) + masse*zdqadj(ig,l,iq)
+                  
+                  iq    = igcm_h2o_ice
+                  dWtot = dWtot + masse*zdqadj(ig,l,iq)*ptimestep*area(ig)
+                  cadjncons(ig)=cadjncons(ig) + masse*zdqadj(ig,l,iq)
+                  
+               enddo
+
+            enddo
+            dWtot=dWtot/totarea
+            print*,'In convadj atmospheric water change     =',dWtot,' kg m-2'
+         endif
+         !-------------------------
+               
+      endif ! of if(calladj)
+
+!-----------------------------------------------------------------------
+!   6. Carbon dioxide condensation-sublimation:
+!   -------------------------------------------
+
+      if (co2cond) then
+         if (.not.tracer) then
+            print*,'We need a CO2 ice tracer to condense CO2'
+            call abort
+         endif
+
+         call condens_co2cloud(ngrid,nlayer,nq,ptimestep,   &
+              capcal,pplay,pplev,tsurf,pt,                  &
+              pphi,pdt,pdu,pdv,zdtsurf,pu,pv,pq,pdq,        &
+              qsurf(1,igcm_co2_ice),albedo,emis,            &
+              zdtc,zdtsurfc,pdpsrf,zduc,zdvc,               &
+              zdqc,reffrad,cpp3D)
+
+         do l=1,nlayer
+           do ig=1,ngrid
+             pdt(ig,l)=pdt(ig,l)+zdtc(ig,l)
+             pdv(ig,l)=pdv(ig,l)+zdvc(ig,l)
+             pdu(ig,l)=pdu(ig,l)+zduc(ig,l)
+           enddo
+         enddo
+         do ig=1,ngrid
+            zdtsurf(ig) = zdtsurf(ig) + zdtsurfc(ig)
+         enddo
+
+         do iq=1,nq ! should use new notation here !
+            do l=1,nlayer
+               do ig=1,ngrid
+                  pdq(ig,l,iq)=pdq(ig,l,iq)+ zdqc(ig,l,iq) 
+               enddo
+            enddo
+         enddo
+         ! Note: we do not add surface co2ice tendency
+         ! because qsurf(:,igcm_co2_ice) is updated in condens_co2cloud
+
+         !-------------------------
+         ! test energy conservation
+         if(enertest)then
+            dEtot=0.0
+            dEtots=0.0
+            do ig = 1, ngrid
+               do l = 1, nlayer
+                  masse = (pplev(ig,l) - pplev(ig,l+1))/g
+                  dEtot = dEtot + cpp3D(ig,l)*masse*zdtc(ig,l)*area(ig)
+               enddo
+               dEtots = dEtots + capcal(ig)*zdtsurfc(ig)*area(ig)
+            enddo
+            dEtot=dEtot/totarea
+            dEtots=dEtots/totarea
+            print*,'In co2cloud atmospheric energy change   =',dEtot,' W m-2'
+            print*,'In co2cloud surface energy change       =',dEtots,' W m-2'
+         endif
+         !-------------------------
+
+      endif  ! of if (co2cond)
+
+
+!-----------------------------------------------------------------------
+!   7. Specific parameterizations for tracers 
+!   -----------------------------------------
+
+      if (tracer) then 
+
+!   7a. Water and ice
+!     ---------------
+         if (water) then
+
+!        ----------------------------------------
+!        Water ice condensation in the atmosphere
+!        ----------------------------------------
+            if(watercond)then
+
+	       if(RLVTT.gt.1.e-8)then
+
+               ! Re-evaporate cloud water/ice
+               call evap(ptimestep,pt,pq,pdq,pdt,dqevap,dtevap,qevap,tevap)
+               DO l = 1, nlayer  
+                  DO ig = 1, ngrid        	
+                     pdq(ig,l,igcm_h2o_vap) = pdq(ig,l,igcm_h2o_vap)+dqevap(ig,l)
+                     pdq(ig,l,igcm_h2o_ice) = pdq(ig,l,igcm_h2o_ice)-dqevap(ig,l)
+                     pdt(ig,l)              = pdt(ig,l)+dtevap(ig,l)
+                  enddo
+               enddo
+
+               call moistadj(pt,qevap,pplev,pplay,dtmoist,dqmoist,ptimestep,rneb_man)
+               do l=1,nlayer
+                  do ig=1,ngrid
+                     pdq(ig,l,igcm_h2o_vap) = pdq(ig,l,igcm_h2o_vap)+dqmoist(ig,l,igcm_h2o_vap)
+                     pdq(ig,l,igcm_h2o_ice) = pdq(ig,l,igcm_h2o_ice)+dqmoist(ig,l,igcm_h2o_ice)
+                     pdt(ig,l)              = pdt(ig,l)+dtmoist(ig,l)
+                  enddo
+               enddo
+
+               !-------------------------
+               ! test energy conservation
+               if(enertest)then
+                  dEtot=0.0
+                  madjdE(:)=0.0
+                  do ig = 1, ngrid
+                     do l = 1, nlayer
+                        masse = (pplev(ig,l) - pplev(ig,l+1))/g
+                        dEtot = dEtot + cpp3D(ig,l)*masse*(dtmoist(ig,l)+dtevap(ig,l))*area(ig)
+                        madjdE(ig) = madjdE(ig) + cpp3D(ig,l)*masse*(dtmoist(ig,l)+dtevap(ig,l))
+                     enddo
+                  enddo
+                  dEtot=dEtot/totarea
+                  print*,'In moistadj atmospheric energy change   =',dEtot,' W m-2'
+               endif
+               !-------------------------
+
+               !-------------------------
+               ! test water conservation
+               if(watertest)then
+                  dWtot=0.0
+                  do ig = 1, ngrid
+                     do iq = 1 , nq
+                        do l = 1, nlayer
+                           masse = (pplev(ig,l) - pplev(ig,l+1))/g
+                           dWtot = dWtot + masse*dqmoist(ig,l,igcm_h2o_vap)*area(ig)*ptimestep
+                           dWtot = dWtot + masse*dqmoist(ig,l,igcm_h2o_ice)*area(ig)*ptimestep
+                        enddo
+                     enddo
+                  enddo
+                  dWtot=dWtot/totarea
+                  print*,'In moistadj atmospheric water change    =',dWtot,' kg m-2'
+               endif
+               !-------------------------
+               
+
+	       endif
+	       
+
+               ! Re-evaporate cloud water/ice
+               call evap(ptimestep,pt,pq,pdq,pdt,dqevap,dtevap,qevap,tevap)
+               do l = 1, nlayer  
+                  do ig = 1, ngrid
+                     pdq(ig,l,igcm_h2o_vap) = pdq(ig,l,igcm_h2o_vap)+dqevap(ig,l)
+                     pdq(ig,l,igcm_h2o_ice) = pdq(ig,l,igcm_h2o_ice)-dqevap(ig,l)
+                     pdt(ig,l)              = pdt(ig,l)+dtevap(ig,l)
+                  enddo
+               enddo ! note: we use qevap but not tevap in largescale/moistadj
+                     ! otherwise is a big mess
+
+               call largescale(ptimestep,pplev,pplay,pt,qevap,        & ! a bug was here!
+                    pdt,dtlscale,dqvaplscale,dqcldlscale,rneb_lsc,reffH2O)
+               do l=1,nlayer
+                  do ig=1,ngrid
+                     pdq(ig,l,igcm_h2o_vap) = pdq(ig,l,igcm_h2o_vap)+dqvaplscale(ig,l)
+                     pdq(ig,l,igcm_h2o_ice) = pdq(ig,l,igcm_h2o_ice)+dqcldlscale(ig,l)
+                     pdt(ig,l)              = pdt(ig,l)+dtlscale(ig,l)
+
+                     if(.not.aerofixed)then
+                        reffrad(ig,l,2)=reffH2O(ig,l)
+                     endif
+
+                  enddo
+               enddo
+
+               !-------------------------
+               ! test energy conservation
+               if(enertest)then
+                  dEtot=0.0
+                  lscaledE(:)=0.0
+                  do ig = 1, ngrid
+                     do l = 1, nlayer
+                        masse = (pplev(ig,l) - pplev(ig,l+1))/g
+                        dEtot = dEtot + cpp3D(ig,l)*masse*(dtlscale(ig,l)+dtevap(ig,l))*area(ig)
+                        lscaledE(ig) = lscaledE(ig) + cpp3D(ig,l)*masse*(dtlscale(ig,l)+dtevap(ig,l))
+                     enddo
+                  enddo
+                  dEtot=dEtot/totarea
+                  print*,'In largescale atmospheric energy change =',dEtot,' W m-2'
+               endif
+               !-------------------------
+
+               !-------------------------
+               ! test water conservation
+               if(watertest)then
+                  dWtot=0.0
+                  do ig = 1, ngrid
+                     do iq = 1 , nq
+                        do l = 1, nlayer
+                           masse = (pplev(ig,l) - pplev(ig,l+1))/g
+                           dWtot = dWtot + masse*dqvaplscale(ig,l)*area(ig)*ptimestep
+                           dWtot = dWtot + masse*dqcldlscale(ig,l)*area(ig)*ptimestep
+                        enddo
+                     enddo
+                  enddo
+                  dWtot=dWtot/totarea
+                  print*,'In largescale atmospheric water change  =',dWtot,' kg m-2'
+               endif
+               !-------------------------
+
+               ! compute cloud fraction
+               do l = 1, nlayer
+                  do ig = 1,ngrid
+                     cloudfrac(ig,l)=MAX(rneb_lsc(ig,l),rneb_man(ig,l)) 
+                  enddo
+               enddo
+
+               ! compute total cloud fraction in column
+               call totalcloudfrac(cloudfrac,totcloudfrac)
+
+           endif                ! of if (watercondense)
+           
+
+!        --------------------------------
+!        Water ice / liquid precipitation
+!        --------------------------------
+           if(waterrain)then
+
+              zdqrain(:,:,:) = 0.0
+              zdqsrain(:)    = 0.0
+              zdqssnow(:)    = 0.0
+
+              call rain(ptimestep,pplev,pplay,pt,pdt,pq,pdq,            &
+                   zdtrain,zdqrain,zdqsrain,zdqssnow,cloudfrac)
+
+              do l=1,nlayer
+                 do ig=1,ngrid
+                    pdq(ig,l,igcm_h2o_vap) = pdq(ig,l,igcm_h2o_vap)+zdqrain(ig,l,igcm_h2o_vap)
+                    pdq(ig,l,igcm_h2o_ice) = pdq(ig,l,igcm_h2o_ice)+zdqrain(ig,l,igcm_h2o_ice)
+                    pdt(ig,l)              = pdt(ig,l)+zdtrain(ig,l)
+                 enddo
+              enddo
+
+              do ig=1,ngrid
+                 dqsurf(ig,igcm_h2o_vap) = dqsurf(ig,igcm_h2o_vap)+zdqsrain(ig) ! a bug was here
+                 dqsurf(ig,igcm_h2o_ice) = dqsurf(ig,igcm_h2o_ice)+zdqssnow(ig)
+                 rainout(ig)             = zdqsrain(ig)+zdqssnow(ig) ! diagnostic   
+              enddo
+
+              !-------------------------
+              ! test energy conservation
+              if(enertest)then
+                 dEtot=0.0
+                 do ig = 1, ngrid
+                    do l = 1, nlayer
+                       masse = (pplev(ig,l) - pplev(ig,l+1))/g
+                       dEtot = dEtot + cpp3D(ig,l)*masse*zdtrain(ig,l)*area(ig)
+                    enddo
+                 enddo
+                 dEtot=dEtot/totarea
+                 print*,'In rain atmospheric energy change       =',dEtot,' W m-2'
+              endif
+              !-------------------------
+
+
+              !-------------------------
+              ! test energy conservation
+              if(enertest)then
+                 dEtot=0.0
+                 do ig = 1, ngrid
+                    do l = 1, nlayer
+                       masse = (pplev(ig,l) - pplev(ig,l+1))/g
+                       dEtot = dEtot + cpp3D(ig,l)*masse*zdtrain(ig,l)*area(ig)
+                    enddo
+                 enddo
+                 dEtot=dEtot/totarea
+                 print*,'In rain atmospheric T energy change       =',dEtot,' W m-2'
+
+                 dEtot=0.0
+                 do ig = 1, ngrid
+                    do l = 1, nlayer
+                       masse = (pplev(ig,l) - pplev(ig,l+1))/g
+                       dItot = dItot + masse*zdqrain(ig,l,igcm_h2o_ice)*area(ig)
+                       dVtot = dVtot + masse*zdqrain(ig,l,igcm_h2o_vap)*area(ig)
+                    enddo
+                    dItot = dItot + zdqssnow(ig)*area(ig)
+                    dVtot = dVtot + zdqsrain(ig)*area(ig)
+                 enddo
+                 dEtot=(dItot*RLVTT/cpp + dVtot*RLVTT/cpp)/totarea
+                 print*,'In rain dItot =',dItot*RLVTT/(cpp*totarea),' W m-2'
+                 print*,'In rain dVtot =',dVtot*RLVTT/(cpp*totarea),' W m-2'
+                 print*,'In rain atmospheric L energy change       =',dEtot,' W m-2'
+              endif
+              !-------------------------
+
+              !-------------------------
+              ! test water conservation
+              if(watertest)then
+                 dWtot=0.0
+                 dWtots=0.0
+                 do ig = 1, ngrid
+                    !do iq = 1 , nq
+                       do l = 1, nlayer
+                          masse = (pplev(ig,l) - pplev(ig,l+1))/g ! equiv to l2c in rain
+                          dWtot = dWtot + masse*zdqrain(ig,l,igcm_h2o_vap)*area(ig)*ptimestep
+                          dWtot = dWtot + masse*zdqrain(ig,l,igcm_h2o_ice)*area(ig)*ptimestep
+                       enddo
+                    !enddo
+                    dWtots = dWtots + (zdqsrain(ig)+zdqssnow(ig))*area(ig)*ptimestep
+                 enddo
+                 dWtot=dWtot/totarea
+                 dWtots=dWtots/totarea
+                 print*,'In rain atmospheric water change        =',dWtot,' kg m-2'
+                 print*,'In rain surface water change            =',dWtots,' kg m-2'
+                 print*,'In rain non-cons factor                 =',dWtot+dWtots,' kg m-2'
+              endif
+              !-------------------------
+
+           end if                 ! of if (waterrain)
+        end if                    ! of if (water)
+
+
+!   7c. Aerosol particles
+!     -------------------
+!        ------------- 
+!        Sedimentation
+!        ------------- 
+        if (sedimentation) then 
+           zdqsed(:,:,:) = 0.0
+           zdqssed(:,:)  = 0.0
+
+
+           !-------------------------
+           ! find qtot
+           if(watertest)then
+              dWtot=0.0
+              dWtots=0.0
+              iq=3
+              do ig = 1, ngrid
+                 do l = 1, nlayer
+                    masse = (pplev(ig,l) - pplev(ig,l+1))/g ! equiv to l2c in rain
+                    dWtot  = dWtot  + masse*pq(ig,l,iq)*area(ig)*ptimestep
+                    dWtots = dWtots + masse*pdq(ig,l,iq)*area(ig)*ptimestep
+                 enddo
+              enddo
+              dWtot=dWtot/totarea
+              dWtots=dWtots/totarea
+              print*,'Before sedim pq  =',dWtot,' kg m-2'
+              print*,'Before sedim pdq =',dWtots,' kg m-2'
+           endif
+           !-------------------------
+
+           call callsedim(ngrid,nlayer,ptimestep,           &
+                pplev,zzlev,pt,pq,pdq,zdqsed,zdqssed,nq,reffH2O)
+
+           !-------------------------
+           ! find qtot
+           if(watertest)then
+              dWtot=0.0
+              dWtots=0.0
+              iq=3
+              do ig = 1, ngrid
+                 do l = 1, nlayer
+                    masse = (pplev(ig,l) - pplev(ig,l+1))/g ! equiv to l2c in rain
+                    dWtot  = dWtot  + masse*pq(ig,l,iq)*area(ig)*ptimestep
+                    dWtots = dWtots + masse*pdq(ig,l,iq)*area(ig)*ptimestep
+                 enddo
+              enddo
+              dWtot=dWtot/totarea
+              dWtots=dWtots/totarea
+              print*,'After sedim pq  =',dWtot,' kg m-2'
+              print*,'After sedim pdq =',dWtots,' kg m-2'
+           endif
+           !-------------------------
+
+           do iq=1,nq
+              ! for now, we only allow H2O ice to sediment
+              ! and as in rain.F90, whether it falls as rain or snow depends
+              ! only on the surface temperature
+              do ig=1,ngrid
+                 do l=1,nlayer
+                    pdq(ig,l,iq) = pdq(ig,l,iq) + zdqsed(ig,l,iq)
+                 enddo
+                 dqsurf(ig,iq) = dqsurf(ig,iq) + zdqssed(ig,iq)
+              enddo
+           enddo
+
+           !-------------------------
+           ! test water conservation
+           if(watertest)then
+              dWtot=0.0
+              dWtots=0.0
+              do iq=1,nq
+              do ig = 1, ngrid
+                 do l = 1, nlayer
+                    masse = (pplev(ig,l) - pplev(ig,l+1))/g ! equiv to l2c in rain
+                    dWtot = dWtot + masse*zdqsed(ig,l,iq)*area(ig)*ptimestep
+                 enddo
+                 dWtots   = dWtots + zdqssed(ig,iq)*area(ig)*ptimestep
+              enddo
+              enddo
+              dWtot=dWtot/totarea
+              dWtots=dWtots/totarea
+              print*,'In sedim atmospheric ice change         =',dWtot,' kg m-2'
+              print*,'In sedim surface ice change             =',dWtots,' kg m-2'
+              print*,'In sedim non-cons factor                =',dWtot+dWtots,' kg m-2'
+           endif
+           !-------------------------
+
+        end if   ! of if (sedimentation)
+
+
+!   7d. Updates
+!     ---------
+
+!       ---------------------------------
+!       Updating tracer budget on surface
+!       ---------------------------------
+
+         if(hydrology)then
+
+            call hydrol(ptimestep,rnat,tsurf,qsurf,dqsurf,dqs_hyd,    &
+               capcal,albedo0,albedo,mu0,zdtsurf,zdtsurf_hyd,hice)
+            ! note: for now, also changes albedo in the subroutine
+
+            do ig=1,ngrid
+               zdtsurf(ig) = zdtsurf(ig) + zdtsurf_hyd(ig)
+               do iq=1,nq
+                  qsurf(ig,iq) = qsurf(ig,iq)+ptimestep*dqs_hyd(ig,iq)
+               enddo
+            enddo
+            ! when hydrology is used, other dqsurf tendencies are all added to dqs_hyd inside
+
+            !-------------------------
+            ! test energy conservation
+            if(enertest)then
+               dEtot=0.0
+               do ig = 1, ngrid
+                  dEtots = dEtots + capcal(ig)*zdtsurf_hyd(ig)*area(ig)
+               enddo
+               dEtot=dEtot/totarea
+               print*,'In hydrol atmospheric energy change     =',dEtot,' W m-2'
+            endif
+            !-------------------------
+
+            !-------------------------
+            ! test water conservation
+            if(watertest)then
+               dWtots=0.0
+               do ig = 1, ngrid
+                  dWtots = dWtots + dqs_hyd(ig,igcm_h2o_ice)*area(ig)*ptimestep
+               enddo
+               dWtots=dWtots/totarea
+               print*,'In hydrol surface ice change            =',dWtots,' kg m-2'
+               dWtots=0.0
+               do ig = 1, ngrid
+                  dWtots = dWtots + dqs_hyd(ig,igcm_h2o_vap)*area(ig)*ptimestep
+               enddo
+               dWtots=dWtots/totarea
+               print*,'In hydrol surface water change          =',dWtots,' kg m-2'
+               print*,'---------------------------------------------------------------'
+            endif
+            !-------------------------
+
+         ELSE     ! of if (hydrology)
+
+            do iq=1,nq
+               do ig=1,ngrid
+                  qsurf(ig,iq)=qsurf(ig,iq)+ptimestep*dqsurf(ig,iq)
+               enddo
+            enddo           
+
+         END IF   ! of if (hydrology)
+
+         ! Add qsurf to qsurf_hist, which is what we save in
+         ! diagfi.nc etc. At the same time, we set the water 
+         ! content of ocean gridpoints back to zero, in order
+         ! to avoid rounding errors in vdifc, rain
+         do ig = 1, ngrid
+            do iq = 1, nq
+               if(iq.eq.igcm_h2o_vap .and. rnat(ig).eq.0)then ! if liquid water and terrain = ocean 
+                  qsurf_hist(ig,iq) = qsurf(ig,iq)
+                  !qsurf(ig,iq)      = qcol(ig,iq) 
+                  ! the value of qsurf we choose here makes NO DIFFERENCE TO ANYTHING AT ALL
+               else
+                  qsurf_hist(ig,iq) = qsurf(ig,iq)
+               endif
+            enddo
+         enddo
+
+         if(ice_update)then
+            do ig = 1, ngrid
+               ice_min(ig)=min(ice_min(ig),qsurf(ig,igcm_h2o_ice))
+            enddo
+         endif
+
+      endif   !  of if (tracer) 
+
+
+!      print*,'we got this far 1'
+
+!-----------------------------------------------------------------------
+!   9. Surface and sub-surface soil temperature
+!-----------------------------------------------------------------------
+
+
+!     Increment surface temperature
+      if(.not.kastprof)then
+         do ig=1,ngrid
+            tsurf(ig)=tsurf(ig)+ptimestep*zdtsurf(ig) 
+         enddo
+      endif
+
+!     Compute soil temperatures and subsurface heat flux
+      if (callsoil) then
+         call soil(ngrid,nsoilmx,.false.,inertiedat,        &
+                ptimestep,tsurf,tsoil,capcal,fluxgrd)
+      endif
+
+!-------------------------
+! test energy conservation
+      if(enertest)then
+         dEtots=0.0
+         do ig = 1, ngrid
+            dEtots = dEtots + capcal(ig)*zdtsurf(ig)*area(ig)
+         enddo
+         dEtots=dEtots/totarea
+         print*,'Surface energy change=',dEtots,' W m-2'
+      endif
+!-------------------------
+
+!-----------------------------------------------------------------------
+!  10. Perform diagnostics and write output files
+!-----------------------------------------------------------------------
+
+!    -------------------------------
+!    Dynamical fields incrementation
+!    -------------------------------
+!    For output only: the actual model integration is performed in the dynamics
+ 
+      ! temperature, zonal and meridional wind
+      do l=1,nlayer
+        do ig=1,ngrid
+          zt(ig,l) = pt(ig,l) + pdt(ig,l)*ptimestep
+          zu(ig,l) = pu(ig,l) + pdu(ig,l)*ptimestep
+          zv(ig,l) = pv(ig,l) + pdv(ig,l)*ptimestep
+
+          ! diagnostic
+          zdtdyn(ig,l)     = ztprevious(ig,l)-pt(ig,l)
+          ztprevious(ig,l) = zt(ig,l)
+        enddo
+      enddo
+
+      if(firstcall)then
+         zdtdyn(:,:)=0.0
+      endif
+
+      ! dynamical heating diagnostic
+      fluxdyn(:)=0.
+      do ig=1,ngrid
+         do l=1,nlayer
+            fluxdyn(ig)=fluxdyn(ig) - (zdtdyn(ig,l)/ptimestep)   &
+                 *(pplev(ig,l)-pplev(ig,l+1))*cpp3D(ig,l)/g
+         enddo
+      enddo
+
+      ! tracers
+      do iq=1, nq
+        do l=1,nlayer
+          do ig=1,ngrid
+            zq(ig,l,iq) = pq(ig,l,iq) + pdq(ig,l,iq)*ptimestep
+          enddo
+        enddo
+      enddo
+
+      ! surface pressure
+      do ig=1,ngrid
+          ps(ig) = pplev(ig,1) + pdpsrf(ig)*ptimestep
+      enddo
+
+      ! pressure
+      do l=1,nlayer
+        do ig=1,ngrid
+             zplev(ig,l) = pplev(ig,l)/pplev(ig,1)*ps(ig)
+             zplay(ig,l) = pplay(ig,l)/pplev(ig,1)*ps(ig)
+        enddo
+      enddo
+
+!     ---------------------------------------------------------
+!     Surface and soil temperature information
+!     ---------------------------------------------------------
+
+      Ts1 = 0.0
+      Ts2 = 99999.9
+      Ts3 = 0.0
+      TsS = 0.0 ! mean temperature at bottom soil layer
+      do ig=1,ngrid
+         Ts1 = Ts1 + area(ig)*tsurf(ig)
+         Ts2 = min(Ts2,tsurf(ig))  
+	 Ts3 = max(Ts3,tsurf(ig))
+         TsS = TsS + area(ig)*tsoil(ig,nsoilmx)
+      end do
+      Ts1=Ts1/totarea
+      TsS=TsS/totarea
+      if(callsoil)then
+         print*,'  ave[Tsurf]     min[Tsurf]     max[Tsurf]     ave[Tdeep]'
+         print*,Ts1,Ts2,Ts3,TsS
+      else
+         print*,'  ave[Tsurf]     min[Tsurf]     max[Tsurf]'
+         print*,Ts1,Ts2,Ts3
+      endif
+
+!     ---------------------------------------------------------
+!     Check the energy balance of the simulation during the run
+!     ---------------------------------------------------------
+
+      if(corrk)then
+
+         ISR = 0.0
+         ASR = 0.0
+         OLR = 0.0
+         GND = 0.0
+         DYN = 0.0
+         do ig=1,ngrid 
+            ISR = ISR + area(ig)*fluxtop_dn(ig) 
+            ASR = ASR + area(ig)*fluxabs_sw(ig)
+            OLR = OLR + area(ig)*fluxtop_lw(ig) 
+            GND = GND + area(ig)*fluxgrd(ig) 
+            DYN = DYN + area(ig)*fluxdyn(ig) 
+            
+            if(fluxtop_dn(ig).lt.0.0)then
+               print*,'fluxtop_dn has gone crazy'
+               print*,'fluxtop_dn=',fluxtop_dn(ig)
+               print*,'tau_col=',tau_col(ig)
+               print*,'aerosol=',aerosol(ig,:,:)
+               print*,'temp=   ',pt(ig,:)
+               print*,'pplay=  ',pplay(ig,:)
+               call abort
+            endif
+         end do
+                     
+         if(ngridmx.eq.1)then
+            DYN=0.0
+         endif
+
+         print*,'  ISR            ASR            OLR            GND            DYN [W m^-2]'
+         print*, ISR/totarea,ASR/totarea,OLR/totarea,GND/totarea,DYN/totarea
+         
+         if(enertest)then
+            print*,'SW energy balance SW++ - ASR = ',dEtotSW+dEtotsSW-ASR/totarea,' W m-2'
+         endif
+
+         if(meanOLR)then
+            if((ngridmx.gt.1) .or. (countG1D.eq.saveG1D))then
+               ! to record global radiative balance
+               open(92,file="rad_bal.out",form='formatted',access='append')
+               write(92,*) zday,ISR/totarea,ASR/totarea,OLR/totarea
+               close(92)
+               open(93,file="tem_bal.out",form='formatted',access='append')
+               write(93,*) zday,Ts1,Ts2,Ts3,TsS
+               close(93)
+            endif
+         endif
+
+         if(kastprof)then ! for f(p,T) computation (not needed in universal model)
+            open(15,file='ene_bal.out',form='formatted',access='append')
+            write(15,*) pplev(1,1), Tsurf(1), ISR, OLR, ASR
+            close(15)
+            open(16,file='Seff.out',form='formatted')
+            write(16,*) OLR/ASR
+            close(16)
+            open(17,file='alb.out',form='formatted')
+            write(17,*) 1.0-ASR/ISR
+            close(17)
+            call abort
+         endif
+
+      endif
+
+!     ------------------------------------------------------------------
+!     Diagnostic to test radiative-convective timescales in code
+!     ------------------------------------------------------------------
+      if(testradtimes)then
+         open(38,file="tau_phys.out",form='formatted',access='append')
+         ig=1
+         do l=1,nlayer
+            write(38,*) -1./pdt(ig,l),pt(ig,l),pplay(ig,l)
+         enddo
+         close(38)
+         print*,'As testradtimes enabled, exiting physics on first call'
+         call abort
+      endif
+
+!     ---------------------------------------------------------
+!     Compute column amounts (kg m-2) if tracers are enabled
+!     ---------------------------------------------------------
+      if(tracer)then
+         qcol(:,:)=0.0
+         do iq=1,nq
+            do ig=1,ngrid
+               do l=1,nlayer
+                  qcol(ig,iq) = qcol(ig,iq) + zq(ig,l,iq) *    &
+                            (pplev(ig,l) - pplev(ig,l+1)) / g
+               enddo
+            enddo
+         enddo
+
+         ! not generalised for arbitrary aerosols yet!!!
+         reffcol(:,:)=0.0
+         do ig=1,ngrid
+            do l=1,nlayer
+               reffcol(ig,1) = reffcol(ig,1) + zq(ig,l,igcm_co2_ice) * reffrad(ig,l,1) *    &
+                    (pplev(ig,l) - pplev(ig,l+1)) / g
+               if(water)then
+               reffcol(ig,2) = reffcol(ig,2) + zq(ig,l,igcm_h2o_ice) * reffrad(ig,l,2) *    &
+                    (pplev(ig,l) - pplev(ig,l+1)) / g
+
+               endif
+            enddo
+         enddo
+
+      endif
+
+!     ---------------------------------------------------------
+!     Test for water conservation if water is enabled
+!     ---------------------------------------------------------
+
+      if(water)then
+
+         icesrf = 0.0
+         liqsrf = 0.0
+         icecol = 0.0
+         vapcol = 0.0
+
+         h2otot = 0.0
+         do ig=1,ngrid
+
+            icesrf = icesrf + area(ig)*qsurf_hist(ig,igcm_h2o_ice)
+            liqsrf = liqsrf + area(ig)*qsurf_hist(ig,igcm_h2o_vap)
+            icecol = icecol + area(ig)*qcol(ig,igcm_h2o_ice)
+            vapcol = vapcol + area(ig)*qcol(ig,igcm_h2o_vap)
+
+            h2otot = h2otot + area(ig)*                       &
+            (qcol(ig,igcm_h2o_ice)+qcol(ig,igcm_h2o_vap)      &
+            +qsurf_hist(ig,igcm_h2o_ice)+qsurf_hist(ig,igcm_h2o_vap))
+         end do
+
+         print*,' Total water amount [kg m^-2]: ',h2otot/totarea
+         print*,' Surface ice    Surface liq.   Atmos. con.     Atmos. vap. [kg m^-2] '
+         print*, icesrf/totarea,liqsrf/totarea,icecol/totarea,vapcol/totarea
+
+         if(meanOLR)then
+            if((ngridmx.gt.1) .or. (countG1D.eq.saveG1D))then
+               ! to record global water balance
+               open(98,file="h2o_bal.out",form='formatted',access='append')
+               write(98,*) zday,icesrf/totarea,liqsrf/totarea,icecol/totarea,vapcol/totarea
+               close(98)
+            endif
+         endif
+
+      endif
+
+!     ---------------------------------------------------------
+!     Calculate RH for diagnostic if water is enabled
+!     ---------------------------------------------------------
+
+      if(water)then
+         do l = 1, nlayer
+            do ig = 1, ngrid
+               call watersat(pt(ig,l),pplay(ig,l),qsat(ig,l))
+               RH(ig,l) = zq(ig,l,igcm_h2o_vap) / qsat(ig,l)
+            enddo
+         enddo
+
+         ! compute maximum possible H2O column amount (100% saturation)
+         do ig=1,ngrid
+            H2Omaxcol(ig)=0.0
+            do l=1,nlayer
+               H2Omaxcol(ig) = H2Omaxcol(ig) + qsat(ig,l) *    &
+                    (pplev(ig,l) - pplev(ig,l+1))/g
+            enddo
+         enddo
+
+      endif
+
+
+      if (ngrid.ne.1) then
+         print*,''
+         print*,'--> Ls =',zls*180./pi
+!        -------------------------------------------------------------------
+!        Writing NetCDF file  "RESTARTFI" at the end of the run
+!        -------------------------------------------------------------------
+!        Note: 'restartfi' is stored just before dynamics are stored
+!              in 'restart'. Between now and the writting of 'restart',
+!              there will have been the itau=itau+1 instruction and
+!              a reset of 'time' (lastacll = .true. when itau+1= itaufin)
+!              thus we store for time=time+dtvr
+
+         if(lastcall) then
+            ztime_fin = ptime + ptimestep/(float(iphysiq)*daysec)
+
+
+!           Update surface ice distribution to iterate to steady state if requested
+            if(ice_update)then
+               do ig = 1, ngrid
+
+                  ! if ice amount is declining, set it to zero
+                  if(qsurf_hist(ig,igcm_h2o_ice).lt.ice_initial(ig))then
+                     qsurf_hist(ig,igcm_h2o_ice)=0.0 
+                     qsurf_hist(ig,igcm_h2o_vap)=0.0
+                  endif
+ 
+                  ! if ice amount is increasing and was never less than 0.5 kg/m2,
+                  ! set value in gridbox to 1x10^3 kg/m2
+                  !if(qsurf_hist(ig,igcm_h2o_ice).gt.0.0 .and. ice_min(ig).gt.0.5)then
+                  if(qsurf_hist(ig,igcm_h2o_ice).gt.ice_initial(ig))then
+                     if(ice_min(ig).gt.0.5)then ! ignore seasonal ice
+                        qsurf_hist(ig,igcm_h2o_ice)=1.e3
+                        qsurf_hist(ig,igcm_h2o_vap)=0.0
+                     endif
+                  endif
+
+               enddo
+            endif
+
+            write(*,*)'PHYSIQ: for physdem ztime_fin =',ztime_fin
+            call physdem1("restartfi.nc",long,lati,nsoilmx,nq,            &
+!                    ptimestep,pday,ztime_fin,tsurf,tsoil,emis,q2,qsurf,      &
+                    ptimestep,pday,ztime_fin,tsurf,tsoil,emis,q2,qsurf_hist, &
+                    area,albedodat,inertiedat,zmea,zstd,zsig,zgam,zthe,      &
+                    cloudfrac,totcloudfrac,hice)
+         endif
+
+!        -----------------------------------------------------------------
+!        Saving statistics :
+!        -----------------------------------------------------------------
+!        ("stats" stores and accumulates 8 key variables in file "stats.nc"
+!        which can later be used to make the statistic files of the run:
+!        "stats")          only possible in 3D runs !
+
+         
+         if (callstats) then
+
+            call wstats(ngrid,"ps","Surface pressure","Pa",2,ps)
+            call wstats(ngrid,"tsurf","Surface temperature","K",2,tsurf)
+            call wstats(ngrid,"fluxsurf_lw",                               &
+                        "Thermal IR radiative flux to surface","W.m-2",2,  &
+                         fluxsurf_lw)
+!            call wstats(ngrid,"fluxsurf_sw",                               &
+!                        "Solar radiative flux to surface","W.m-2",2,       &
+!                         fluxsurf_sw_tot)
+            call wstats(ngrid,"fluxtop_lw",                                &
+                        "Thermal IR radiative flux to space","W.m-2",2,    &
+                        fluxtop_lw)
+!            call wstats(ngrid,"fluxtop_sw",                                &
+!                        "Solar radiative flux to space","W.m-2",2,         &
+!                        fluxtop_sw_tot)
+            call wstats(ngrid,"temp","Atmospheric temperature","K",3,zt)
+            call wstats(ngrid,"u","Zonal (East-West) wind","m.s-1",3,zu)
+            call wstats(ngrid,"v","Meridional (North-South) wind","m.s-1",3,zv)
+            call wstats(ngrid,"w","Vertical (down-up) wind","m.s-1",3,pw)
+            call wstats(ngrid,"q2","Boundary layer eddy kinetic energy","m2.s-2",3,q2)
+
+           if (tracer) then
+            if (water) then
+               vmr=zq(1:ngridmx,1:nlayermx,igcm_h2o_vap)*mugaz/mmol(igcm_h2o_vap)
+               call wstats(ngrid,"vmr_h2ovapor",                           &
+                          "H2O vapour volume mixing ratio","mol/mol",       & 
+                          3,vmr)
+            endif ! of if (water)
+
+           endif !tracer 
+
+            if(lastcall) then
+              write (*,*) "Writing stats..."
+              call mkstats(ierr)
+            endif
+          endif !if callstats
+
+
+!        ----------------------------------------------------------------------
+!        output in netcdf file "DIAGFI", containing any variable for diagnostic
+!        (output with  period "ecritphy", set in "run.def")
+!        ----------------------------------------------------------------------
+!        writediagfi can also be called from any other subroutine for any variable.
+!        but its preferable to keep all the calls in one place...
+
+        call writediagfi(ngrid,"tsurf","Surface temperature","K",2,tsurf)
+        call writediagfi(ngrid,"ps","Surface pressure","Pa",2,ps)
+
+        if(1.eq.2)then
+        call writediagfi(ngrid,"temp","temperature","K",3,zt)
+        call writediagfi(ngrid,"u","Zonal wind","m.s-1",3,zu)
+        call writediagfi(ngrid,"v","Meridional wind","m.s-1",3,zv)
+        call writediagfi(ngrid,"w","Vertical wind","m.s-1",3,pw)
+        call writediagfi(ngrid,'p','Pressure','Pa',3,pplay)
+        endif
+
+!     Total energy balance diagnostics
+        if(callrad.and.(.not.newtonian))then
+           call writediagfi(ngrid,'ALB','Surface albedo',' ',2,albedo)
+           call writediagfi(ngrid,"ISR","incoming stellar rad.","W m-2",2,fluxtop_dn)
+           call writediagfi(ngrid,"ASR","absorbed stellar rad.","W m-2",2,fluxabs_sw)
+           call writediagfi(ngrid,"OLR","outgoing longwave rad.","W m-2",2,fluxtop_lw)
+           call writediagfi(ngrid,"GND","heat flux from ground","W m-2",2,fluxgrd)
+           call writediagfi(ngrid,"DYN","dynamical heat input","W m-2",2,fluxdyn)
+           !call writediagfi(ngrid,"lscaledE","heat from largescale","W m-2",2,lscaledE)
+           !call writediagfi(ngrid,"madjdE","heat from moistadj","W m-2",2,madjdE)
+           !call writediagfi(ngrid,"vdifcdE","heat from vdifc surface","W m-2",2,vdifcdE)
+        endif
+
+!     Temporary inclusions for heating diagnostics
+!        call writediagfi(ngrid,"zdtdyn","Dyn. heating","T s-1",3,zdtdyn)
+!        call writediagfi(ngrid,"zdtsw","SW heating","T s-1",3,zdtsw)
+!        call writediagfi(ngrid,"zdtlw","LW heating","T s-1",3,zdtlw)
+!        call writediagfi(ngrid,"dtrad","radiative heating","K s-1",3,dtrad)
+
+        ! debugging
+        !call writediagfi(ngrid,"vdifNC","H2O loss vdifc","kg m-2 s-1",2,vdifcncons)
+        !call writediagfi(ngrid,"cadjNC","H2O loss convadj","kg m-2 s-1",2,cadjncons)
+        call writediagfi(ngrid,'rnat','Terrain type',' ',2,real(rnat))
+        !call writediagfi(ngrid,'pphi','Geopotential',' ',3,pphi)
+        !print*,vdifcncons
+        !call abort
+
+!     Output aerosols
+!        call writediagfi(ngridmx,'CO2ice_reff','CO2ice_reff','m',3,reffrad(1,1,1))
+!        call writediagfi(ngridmx,'H2Oice_reff','H2Oice_reff','m',3,reffrad(1,1,2))
+!        call writediagfi(ngridmx,'CO2ice_reffcol','CO2ice_reffcol','um kg m^-2',2,reffcol(1,1))
+!        call writediagfi(ngridmx,'H2Oice_reffcol','H2Oice_reffcol','um kg m^-2',2,reffcol(1,2))
+
+!     Output tracers
+       if (tracer) then
+        do iq=1,nq
+!          call writediagfi(ngrid,noms(iq),noms(iq),'kg/kg',3,zq(1,1,iq))
+!          call writediagfi(ngridmx,trim(noms(iq))//'_surf',trim(noms(iq))//'_surf',  & 
+!                          'kg m^-2',2,qsurf(1,iq) )
+          call writediagfi(ngridmx,trim(noms(iq))//'_surf',trim(noms(iq))//'_surf',  & 
+                          'kg m^-2',2,qsurf_hist(1,iq) )
+          call writediagfi(ngridmx,trim(noms(iq))//'_col',trim(noms(iq))//'_col',    & 
+                          'kg m^-2',2,qcol(1,iq) )
+
+          if(water)then
+             call writediagfi(ngridmx,"H2Omaxcol","max. poss. H2O column","kg m^-2",2,H2Omaxcol)
+          endif
+
+          if(watercond)then
+             !call writediagfi(ngrid,"CLF","H2O cloud fraction"," ",3,cloudfrac)
+             call writediagfi(ngrid,"CLFt","H2O column cloud fraction"," ",2,totcloudfrac)
+          endif
+
+          if(waterrain)then
+             call writediagfi(ngridmx,"rain","rainfall","kg m-2 s-1",2,zdqsrain)
+             call writediagfi(ngridmx,"snow","snowfall","kg m-2 s-1",2,zdqssnow)
+          endif
+
+          if(hydrology)then
+             call writediagfi(ngridmx,"hice","oceanic ice height","m",2,hice)
+          endif
+
+          if(ice_update)then
+             call writediagfi(ngridmx,"ice_min","min annual ice","m",2,ice_min)
+             call writediagfi(ngridmx,"ice_ini","initial annual ice","m",2,ice_initial)
+          endif
+
+          do ig=1,ngrid
+             if(tau_col(ig).gt.1.e3)then
+                print*,'WARNING: tau_col=',tau_col(ig)
+                print*,'at ig=',ig,'in PHYSIQ'
+	        !call abort
+             endif
+          end do
+
+          call writediagfi(ngridmx,"tau_col","Total aerosol optical depth","[]",2,tau_col)
+
+        enddo
+       endif
+
+!        ----------------------------------------------------------
+!        Output in netcdf file "diagsoil.nc" for subterranean
+!        variables (output every "ecritphy", as for writediagfi)
+!        ----------------------------------------------------------
+
+       ! Write soil temperature
+       !call writediagsoil(ngrid,"soiltemp","Soil temperature","K",3,tsoil)
+
+      else         ! if(ngrid.eq.1)
+
+!        ----------------------------------------------------------------------
+!        Output in grads file "g1d" (ONLY when using testphys1d)
+!        ----------------------------------------------------------------------
+
+         if(countG1D.eq.saveG1D)then
+         
+            call writeg1d(ngrid,1,tsurf,'tsurf','K')
+            call writeg1d(ngrid,1,ps,'ps','Pa')
+            call writeg1d(ngrid,nlayer,zt,'T','K')
+            call writeg1d(ngrid,nlayer,pq(1,1,1),'q','kg/kg')
+            call writeg1d(ngrid,nlayer,aerosol,'aerosol','SI')
+            call writeg1d(ngrid,nlayer,reffrad,'reffrad','SI')
+            call writeg1d(ngrid,nlayer,zdtlw,'dtlw','SI')
+            call writeg1d(ngrid,nlayer,zdtsw,'dtsw','SI')
+            call writeg1d(ngrid,nlayer,zdtdyn,'dtdyn','SI')
+
+!           radiation balance
+            call writeg1d(ngrid,1,ISR/totarea,'ISR','W m-2')
+            call writeg1d(ngrid,1,ASR/totarea,'ASR','W m-2')
+            call writeg1d(ngrid,1,OLR/totarea,'OLR','W m-2')  
+
+            if(tracer) then
+               do iq=1,nq
+                  call writeg1d(ngrid,1,qsurf(1,iq),trim(noms(iq))//'_s','kg m^-2') 
+                  call writeg1d(ngrid,1,qcol(1,iq),trim(noms(iq))//'_c','kg m^-2') 
+                  call writeg1d(ngrid,nlayer,zq(1,1,iq),noms(iq),'kg/kg') 
+               end do
+               
+               if(waterrain)then
+                  CALL writeg1d(ngrid,1,zdqsrain,'rainfall','kg m-2 s-1')
+                  CALL writeg1d(ngrid,1,zdqssnow,'snowfall','kg m-2 s-1')
+               endif
+               
+            end if
+
+            countG1D=1
+         else
+            countG1D=countG1D+1
+         endif ! if time to save
+
+      endif        ! if(ngrid.ne.1)
+
+      icount=icount+1
+
+      return
+    end subroutine physiq
Index: /trunk/LMDZ.GENERIC/libf/phystd/planete.h
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/planete.h	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/planete.h	(revision 253)
@@ -1,15 +1,15 @@
-c-----------------------------------------------------------------------
-c INCLUDE planet.h
+!-----------------------------------------------------------------------
+! INCLUDE planet.h
 
-      COMMON/planet/aphelie,periheli,year_day,peri_day,
-     $       obliquit,nres,
-     $       z0,lmixmin,emin_turb,coefvis,coefir,
-     $       timeperi,e_elips,p_elips,unitastr
+      COMMON/planet/apoastr,periastr,year_day,peri_day,                 &
+     &       obliquit,nres,                                             &
+     &       z0,lmixmin,emin_turb,coefvis,coefir,                       &
+     &       timeperi,e_elips,p_elips,unitastr           
 
-      REAL aphelie,periheli,year_day,peri_day,
-     $     obliquit,nres,
-     $     z0,lmixmin,emin_turb,coefvis,coefir,
-     $       timeperi,e_elips,p_elips,unitastr
+      real apoastr,periastr,year_day,peri_day,                          &
+     &     obliquit,nres,                                               &
+     &     z0,lmixmin,emin_turb,coefvis,coefir,                         &
+     &       timeperi,e_elips,p_elips,unitastr     
       
 
-c-----------------------------------------------------------------------
+!-----------------------------------------------------------------------
Index: /trunk/LMDZ.GENERIC/libf/phystd/profile.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/profile.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/profile.F	(revision 253)
@@ -4,5 +4,5 @@
       IMPLICIT NONE
 c=======================================================================
-c     Subroutine utilisee dans le modele 1-D  "testphys1d"
+c     Subroutine utilisee dans "rcm1d"
 c     pour l'initialisation du profil atmospherique
 c=======================================================================
Index: /trunk/LMDZ.GENERIC/libf/phystd/radinc_h.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/radinc_h.F90	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/radinc_h.F90	(revision 253)
@@ -64,5 +64,5 @@
 !     values manually before compiling, each time you want to change the
 !     dataset.
-
+ 
       integer, parameter :: L_NGAUSS  = 17
 
@@ -70,8 +70,26 @@
       integer, parameter :: L_NTREF   = 7
       integer, parameter :: L_REFVAR  = 7   ! earth / earlymars
+      ! CO2_H2Ovar / N2OCO2rich_H2Ovar / N2OCO2poor_H2Ovar
+!       integer, parameter :: L_REFVAR = 4    ! N2_CH4
+
+!      integer, parameter :: L_NPREF   = 8
+!      integer, parameter :: L_NTREF   = 5
+!      integer, parameter :: L_REFVAR  = 1   ! therm_test2
+
+!      integer, parameter :: L_NPREF   = 12
+!      integer, parameter :: L_NTREF   = 20
+!      integer, parameter :: L_REFVAR  = 1   ! null (for H2 etc.)
+
+!      integer, parameter :: L_NPREF   = 10
+!      integer, parameter :: L_NTREF   = 5
+!      integer, parameter :: L_REFVAR  = 7   ! N2_CO2var
 
 !      integer, parameter :: L_NPREF   = 8
 !      integer, parameter :: L_NTREF   = 6
 !      integer, parameter :: L_REFVAR  = 1   ! pureCO2
+
+!      integer, parameter :: L_NPREF   = 7
+!      integer, parameter :: L_NTREF   = 5
+!      integer, parameter :: L_REFVAR  = 1   ! degraded_pure
 
 !      integer, parameter :: L_NPREF   = 9
@@ -84,10 +102,14 @@
       integer, parameter :: L_PINT    = (L_NPREF-1)*5+1
       integer, parameter :: NAERKIND  = 2
-      integer, parameter :: L_TAUMAX  = 35
+      real,    parameter :: L_TAUMAX  = 35
+      !integer, parameter :: L_TAUMAX  = 35
+      !integer, parameter :: L_TAUMAX  = 40
 
       ! For Planck function integration: 
       ! equivalent temperatures are 1/10 of these values
       integer, parameter :: NTstar = 500
-      integer, parameter :: NTstop = 4000
+!      integer, parameter :: NTstop = 9000 ! for hotstuff runs
+      integer, parameter :: NTstop = 6000 ! for GJ581d / earlymars runs
+!      integer, parameter :: NTstop = 10000 ! for H2 warming runs
 
 ! Maximum number of grain size classes
Index: /trunk/LMDZ.GENERIC/libf/phystd/rain.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/rain.F90	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/rain.F90	(revision 253)
@@ -1,4 +1,4 @@
-
 subroutine rain(ptimestep,pplev,pplay,t,pdt,pq,pdq,d_t,dqrain,dqsrain,dqssnow,rneb)
+
 
   use watercommon_h, only: To, RLVTT, RCPD, RCPV, RV, RVTMP2
@@ -39,5 +39,6 @@
       REAL pplev(ngridmx,nlayermx+1)    ! inter-layer pressure
       REAL pplay(ngridmx,nlayermx)      ! mid-layer pressure
-      REAL t(ngridmx,nlayermx)          ! temperature (K)
+      REAL t(ngridmx,nlayermx)          ! input temperature (K)
+      REAL zt(ngridmx,nlayermx)         ! working temperature (K)
       REAL ql(ngridmx,nlayermx)         ! liquid water (Kg/Kg)
       REAL q(ngridmx,nlayermx)          ! specific humidity (Kg/Kg)
@@ -50,7 +51,7 @@
       PARAMETER (seuil_neb=0.001)
 
-      REAL ct                           ! Inverse of cloud precipitation time
+!      REAL ct                           ! Inverse of cloud precipitation time
 !      PARAMETER (ct=1./1800.)
-      PARAMETER (ct=1./1849.479)
+!      PARAMETER (ct=1./1849.479)
 
       REAL cl                           ! Precipitation threshold
@@ -92,5 +93,7 @@
       real tnext(ngridmx,nlayermx)
 
-      REAL l2c(ngridmx,nlayermx)
+      real l2c(ngridmx,nlayermx)
+      real dWtot
+
 
 !     Indices of water vapour and water ice tracers
@@ -118,13 +121,12 @@
          PRINT*, 'in rain.F, evap_prec=', evap_prec
 
-         print*,ptimestep
-         print*,1./ct
-
-         if(.not.simple)then
-            IF (ABS(ptimestep-1./ct).GT.0.001) THEN
-               PRINT*, 'Must talk to Laurent Li!!!'
-               call abort
-            ENDIF
-         endif
+         !print*,ptimestep
+         !print*,1./ct
+         !if(.not.simple)then
+         !   IF (ABS(ptimestep-1./ct).GT.0.001) THEN
+         !      PRINT*, 'Must talk to Laurent Li!!!'
+         !      call abort
+         !   ENDIF
+         !endif
 
          firstcall = .false.
@@ -135,6 +137,10 @@
       DO i = 1, ngridmx
 
-         q(i,k)    = pq(i,k,i_vap)!+pdq(i,k,i_vap)
-         ql(i,k)   = pq(i,k,i_ice)!+pdq(i,k,i_ice)
+	 zt(i,k)   = t(i,k)+pdt(i,k)*ptimestep ! a big fat bug was here
+         q(i,k)    = pq(i,k,i_vap)+pdq(i,k,i_vap)*ptimestep
+         ql(i,k)   = pq(i,k,i_ice)+pdq(i,k,i_ice)*ptimestep
+
+         !q(i,k)    = pq(i,k,i_vap)!+pdq(i,k,i_vap)
+         !ql(i,k)   = pq(i,k,i_ice)!+pdq(i,k,i_ice)
 
          if(q(i,k).lt.0.)then ! if this is not done, we don't conserve water
@@ -167,14 +173,15 @@
       DO k = 1, nlayermx
          DO i = 1, ngridmx
-            ttemp = t(i,k) 
+            ttemp = zt(i,k) 
             ptemp = pplay(i,k)
-            call watersat_2(ttemp,ptemp,zqs(i,k))
+            call watersat(ttemp,ptemp,zqs(i,k))
          ENDDO
       ENDDO
 
-      ! get column / layer conversion factor (+ptimstep)
+      ! get column / layer conversion factor
       DO k = 1, nlayermx
          DO i = 1, ngridmx
-            l2c(i,k)=(pplev(i,k)-pplev(i,k+1))/(g*ptimestep)
+            !l2c(i,k)=(pplev(i,k)-pplev(i,k+1))/(g*ptimestep)
+            l2c(i,k)=(pplev(i,k)-pplev(i,k+1))/g
          ENDDO
       ENDDO
@@ -189,16 +196,26 @@
             DO i = 1, ngridmx
                IF (zrfl(i) .GT.0.) THEN
+
+                  zqev     = MAX (0.0, (zqs(i,k)-q(i,k)))/ptimestep! BC modif here
+                  zqevt    = 2.0e-5*(1.0-q(i,k)/zqs(i,k))    &
+                       *sqrt(zrfl(i))*l2c(i,k)/pplay(i,k)*zt(i,k)*R ! BC modif here
+                  zqevt    = MAX (zqevt, 0.0)
+                  zqev     = MIN (zqev, zqevt)
+                  zqev     = MAX (zqev, 0.0)
+                  zrfln(i) = zrfl(i) - zqev
+		  zrfln(i) = max(zrfln(i),0.0)
+
                   !zqev     = MAX (0.0, (zqs(i,k)-q(i,k))*eeff1 )
                   !zqevt    = (zrfl(i)/l2c(i,k))*eeff2
                   !zqev     = MIN (zqev, zqevt)
                   !zrfln(i) = zrfl(i) - zqev*l2c(i,k)
-
-                  zrfln(i)  = zrfl(i) - 1.5e-5*(1.0-q(i,k)/zqs(i,k))*sqrt(zrfl(i))
-                  zrfln(i)  = min(zrfln(i),zrfl(i))
+                  !zrfln(i)  = zrfl(i) - 1.5e-5*(1.0-q(i,k)/zqs(i,k))*sqrt(zrfl(i))
+                  !zrfln(i)  = min(zrfln(i),zrfl(i))
                   ! this is what is actually written in the manual
 
-                  d_q(i,k) = - (zrfln(i)-zrfl(i))/l2c(i,k)
-                  d_t(i,k) = d_q(i,k) * RLVTT/RCPD/(1.0+RVTMP2*q(i,k))
-                 
+                  d_q(i,k) = - (zrfln(i)-zrfl(i))/l2c(i,k)*ptimestep
+                  !d_t(i,k) = d_q(i,k) * RLVTT/RCPD!/(1.0+RVTMP2*q(i,k)) ! double BC modif here
+                  d_t(i,k) = - d_q(i,k) * RLVTT/RCPD ! was bugged!
+  
                   zrfl(i)  = zrfln(i)
                ENDIF
@@ -214,17 +231,22 @@
 
             DO i = 1, ngridmx
-            ttemp = t(i,k)
-            IF (ttemp .ge. To) THEN
-               lconvert=rainthreshold
-            ELSEIF (ttemp .gt. t_crit) THEN
-               lconvert=rainthreshold*(1.- t_crit/ttemp)
-            ELSE
-               lconvert=0.
-            ENDIF
-
-            IF (ql(i,k).gt.lconvert)THEN ! precipitate!
-               d_ql(i,k) = (lconvert-ql(i,k))/ptimestep             
-               zrfl(i)   = zrfl(i) + max(ql(i,k) - lconvert,0.0)*l2c(i,k)
-            ENDIF 
+               ttemp = zt(i,k)
+               IF (ttemp .ge. To) THEN
+                  lconvert=rainthreshold
+               ELSEIF (ttemp .gt. t_crit) THEN
+                  lconvert=rainthreshold*(1.- t_crit/ttemp)
+                  lconvert=MAX(0.0,lconvert)              
+               ELSE
+                  lconvert=0.
+               ENDIF
+
+
+               IF (ql(i,k).gt.1.e-9) then
+                  zneb(i)  = MAX(rneb(i,k), seuil_neb)
+                  IF ((ql(i,k)/zneb(i)).gt.lconvert)THEN ! precipitate!
+                     d_ql(i,k) = -MAX((ql(i,k)-lconvert),0.0)
+                     zrfl(i)   = zrfl(i) - d_ql(i,k)*l2c(i,k)/ptimestep
+                  ENDIF
+               ENDIF
             ENDDO
 
@@ -234,7 +256,7 @@
                IF (rneb(i,k).GT.0.0) THEN
                   zoliq(i) = ql(i,k)
-                  zrho(i)  = pplay(i,k) / ( t(i,k) * R )
+                  zrho(i)  = pplay(i,k) / ( zt(i,k) * R )
                   zdz(i)   = (pplev(i,k)-pplev(i,k+1)) / (zrho(i)*g)
-                  zfrac(i) = (t(i,k)-ztglace) / (To-ztglace)
+                  zfrac(i) = (zt(i,k)-ztglace) / (To-ztglace)
                   zfrac(i) = MAX(zfrac(i), 0.0)
                   zfrac(i) = MIN(zfrac(i), 1.0)
@@ -246,6 +268,8 @@
                DO i = 1, ngridmx
                   IF (rneb(i,k).GT.0.0) THEN
-                     zchau(i) = ct*ptimestep/FLOAT(ninter) * zoliq(i)      &
+                     zchau(i) = (1./FLOAT(ninter)) * zoliq(i)      &
                           * (1.0-EXP(-(zoliq(i)/zneb(i)/cl)**2)) * zfrac(i)
+                     ! warning: this may give dodgy results for physics calls .ne. 48 per day...
+
                      ! this is the ONLY place where zneb, ct and cl are used
                      zrhol(i) = zrho(i) * zoliq(i) / zneb(i)
@@ -258,5 +282,5 @@
                      ztot(i)  = MIN(MAX(ztot(i),0.0),zoliq(i))
                      zoliq(i) = MAX(zoliq(i)-ztot(i), 0.0)
-                     
+
                   ENDIF
                ENDDO
@@ -266,6 +290,6 @@
             DO i = 1, ngridmx
                IF (rneb(i,k).GT.0.0) THEN
-                  d_ql(i,k) = (zoliq(i) - ql(i,k))/ptimestep
-                  zrfl(i)   = zrfl(i)+ MAX(ql(i,k)-zoliq(i),0.0)*l2c(i,k)
+                  d_ql(i,k) = (zoliq(i) - ql(i,k))!/ptimestep
+                  zrfl(i)   = zrfl(i)+ MAX(ql(i,k)-zoliq(i),0.0)*l2c(i,k)/ptimestep
                ENDIF
             ENDDO
@@ -277,7 +301,13 @@
 !     Rain or snow on the ground
       DO i = 1, ngridmx
+         if(zrfl(i).lt.0.0)then
+            print*,'Droplets of negative rain are falling...'
+            call abort
+         endif
          IF (t(i,1) .LT. To) THEN
             dqssnow(i) = zrfl(i)
+            dqsrain(i) = 0.0
          ELSE
+            dqssnow(i) = 0.0
             dqsrain(i) = zrfl(i) ! liquid water = ice for now
          ENDIF
@@ -295,25 +325,9 @@
                d_t(i,k)          = 0.0
             endif
-            dqrain(i,k,i_ice) = d_ql(i,k)
+            dqrain(i,k,i_ice) = d_ql(i,k)/ptimestep
          
          ENDDO
       ENDDO
 
-!     debugging
-    !  print*,'zrfl=',zrfl
-    !  print*,'dqrain=',dqrain
-    !  print*,'q=',q
-    !  print*,'ql=',ql
-    !  print*,'dql=',d_ql
-    !  DO k = 1, nlayermx
-    !     DO i = 1, ngridmx
-    !        if(ql(i,k).lt.0.0) then
-    !           print*,'below zero!!!!'
-    !           call abort
-    !        endif
-    !     ENDDO
-    !  ENDDO
-
-
       RETURN
     end subroutine rain
Index: /trunk/LMDZ.GENERIC/libf/phystd/rcm1d.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/rcm1d.F	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/rcm1d.F	(revision 253)
@@ -0,0 +1,792 @@
+      program rcm1d
+
+      use radcommon_h, only: tauvis
+! to use  'getin'
+      use ioipsl_getincom 
+
+      implicit none
+
+!==================================================================
+!     
+!     Purpose
+!     -------
+!     Run the physics package of the universal model in a 1D column.
+!     
+!     It can be compiled with a command like (e.g. for 25 layers):
+!                                  "makegcm -p std -d 25 rcm1d"
+!     It requires the files "callphys.def", "z2sig.def",
+!     "traceur.def", and "run.def" with a line "INCLUDEDEF=callphys.def"
+!
+!     Authors
+!     -------
+!     Frederic Hourdin
+!     R. Fournier
+!     F. Forget
+!     F. Montmessin (water ice added)
+!     R. Wordsworth
+!
+!==================================================================
+
+#include "dimensions.h"
+#include "dimphys.h"
+#include "comgeomfi.h"
+#include "surfdat.h"
+#include "comsoil.h"
+#include "comdiurn.h"
+#include "callkeys.h"
+#include "comcstfi.h"
+#include "planete.h"
+#include "comsaison.h"
+#include "control.h"
+#include "comvert.h"
+#include "netcdf.inc"
+#include "comg1d.h"
+#include "watercap.h" 
+#include "fisice.h"
+#include "logic.h"
+#include "advtrac.h"
+
+c --------------------------------------------------------------
+c  Declarations
+c --------------------------------------------------------------
+c
+      INTEGER unitstart      ! unite d'ecriture de "startfi"
+      INTEGER nlayer,nlevel,nsoil,ndt
+      INTEGER ilayer,ilevel,isoil,idt,iq
+      LOGICAl firstcall,lastcall
+c
+      INTEGER day0          ! date initial (sol ; =0 a Ls=0)
+      REAL day           ! date durant le run
+      REAL time             ! time (0<time<1 ; time=0.5 a midi)
+      REAL play(nlayermx)   ! Pressure at the middle of the layers (Pa)
+      REAL plev(nlayermx+1) ! intermediate pressure levels (pa)
+      REAL psurf,tsurf      
+      REAL u(nlayermx),v(nlayermx)  ! zonal, meridional wind
+      REAL gru,grv   ! prescribed "geostrophic" background wind
+      REAL temp(nlayermx)   ! temperature at the middle of the layers
+      REAL q(nlayermx,nqmx) ! tracer mixing ratio (e.g. kg/kg)
+      REAL qsurf(nqmx)      ! tracer surface budget (e.g. kg.m-2)
+      REAL tsoil(nsoilmx)   ! subsurface soik temperature (K)
+!      REAL co2ice           ! co2ice layer (kg.m-2) !not used anymore
+      integer :: i_co2_ice=0  ! tracer index of co2 ice
+      integer :: i_h2o_ice=0  ! tracer index of co2 ice
+      REAL emis             ! surface layer
+      REAL q2(nlayermx+1)   ! Turbulent Kinetic Energy
+      REAL zlay(nlayermx)   ! altitude estimee dans les couches (km)
+
+c    Physical and dynamical tandencies (e.g.  m.s-2, K/s, Pa/s)
+      REAL du(nlayermx),dv(nlayermx),dtemp(nlayermx)
+      REAL dudyn(nlayermx),dvdyn(nlayermx),dtempdyn(nlayermx)
+      REAL dpsurf    
+      REAL dq(nlayermx,nqmx)
+      REAL dqdyn(nlayermx,nqmx)
+
+c   Various intermediate variables
+!      INTEGER thermo
+      REAL zls
+      REAL phi(nlayermx),h(nlayermx),s(nlayermx)
+      REAL pks, ptif, w(nlayermx)
+      REAL qtotinit, mqtot(nqmx),qtot
+      INTEGER ierr, aslun
+      REAL tmp1(0:nlayermx),tmp2(0:nlayermx)
+      Logical  tracerdyn
+      integer :: nq=1 ! number of tracers
+ 
+      character*2 str2
+      character (len=7) :: str7
+
+      logical oldcompare, earthhack,saveprofile
+
+!     added by RW for zlay computation
+      real Hscale, Hmax, rho, dz
+
+!     added by RW for autozlevs computation
+      real nu, xx, pMIN, zlev, Htop
+      real logplevs(nlayermx)
+
+!     added by RDW to allow variations in cp with location
+      REAL cpp3D(ngridmx,nlayermx)   ! specific heat capacity at const. pressure
+      REAL rcp3D(ngridmx,nlayermx)   ! R / specific heat capacity
+      
+!     added by BC
+      REAL cloudfrac(ngridmx,nlayermx)
+      REAL hice(ngridmx),totcloudfrac(ngridmx)
+
+
+c=======================================================================
+
+c=======================================================================
+c INITIALISATION
+c=======================================================================
+
+      saveprofile=.true.
+
+c ------------------------------------------------------
+c  Default values for constants (corresponding to Mars)
+c ------------------------------------------------------
+
+      pi=2.E+0*asin(1.E+0)
+
+c     Constante de la Planete Mars
+c     ----------------------------
+      rad=3397200.               ! rayon de mars (m)  ~3397200 m
+      daysec=88775.              ! duree du sol (s)  ~88775 s
+      omeg=4.*asin(1.)/(daysec)  ! vitesse de rotation (rad.s-1)
+      g=3.72                     ! gravite (m.s-2) ~3.72  
+      mugaz=43.49                ! Masse molaire de l'atm (g.mol-1) ~43.49
+      rcp=.256793                ! = r/cp  ~0.256793
+      r= 8.314511E+0 *1000.E+0/mugaz
+      cpp= r/rcp
+      year_day = 669           ! duree de l'annee (sols) ~668.6
+      periastr = 206.66          ! min. dist. star-planet (Mkm) ~206.66
+      apoastr = 249.22           ! max. dist. star-planet (Mkm) ~249.22
+      peri_day =  485.           ! date du periastron (sols depuis printemps)
+      obliquit = 25.2           ! Obliquite de la planete (deg) ~25.2         
+ 
+c     Parametres Couche limite et Turbulence 
+c     --------------------------------------
+      z0 =  1.e-2                ! surface roughness (m) ~0.01 
+      emin_turb = 1.e-6          ! energie minimale ~1.e-8
+      lmixmin = 30               ! longueur de melange ~100
+ 
+c     propriete optiques des calottes et emissivite du sol
+c     ----------------------------------------------------
+      emissiv= 0.95              ! Emissivite du sol martien ~.95
+      emisice(1)=0.95            ! Emissivite calotte nord
+      emisice(2)=0.95            ! Emissivite calotte sud  
+
+      albedice(1)=0.5            ! Albedo calotte nord
+      albedice(2)=0.5            ! Albedo calotte sud
+      iceradius(1) = 100.e-6     ! mean scat radius of CO2 snow (north)
+      iceradius(2) = 100.e-6     ! mean scat radius of CO2 snow (south)
+      dtemisice(1) = 2.          ! time scale for snow metamorphism (north)
+      dtemisice(2) = 2.          ! time scale for snow metamorphism (south
+      hybrid=.false.
+
+c ------------------------------------------------------
+c  Load parameters from "run.def" 
+c ------------------------------------------------------
+
+! also check if 'run1d.def' file is around (otherwise reading parameters
+! from callphys.def via getin() routine won't work.
+      open(90,file='run.def',status='old',form='formatted',
+     &     iostat=ierr)
+      if (ierr.ne.0) then
+        write(*,*) 'Cannot find required file "run.def"'
+        write(*,*) '  (which should contain some input parameters'
+        write(*,*) '   along with the following line:'
+        write(*,*) '   INCLUDEDEF=callphys.def'
+        write(*,*) '   )'
+        write(*,*) ' ... might as well stop here ...'
+        stop
+      else
+        close(90)
+      endif
+
+! check if we are going to run with or without tracers
+      write(*,*) "Run with or without tracer transport ?"
+      tracer=.false. ! default value
+      call getin("tracer",tracer)
+      write(*,*) " tracer = ",tracer
+
+! while we're at it, check if there is a 'traceur.def' file
+! and preocess it, if necessary. Otherwise initialize tracer names
+      if (tracer) then
+      ! load tracer names from file 'traceur.def'
+        open(90,file='traceur.def',status='old',form='formatted',
+     &       iostat=ierr)
+        if (ierr.eq.0) then
+          write(*,*) "rcm1d: Reading file traceur.def"
+          ! read number of tracers:
+          read(90,*,iostat=ierr) nq
+          if (ierr.ne.0) then
+            write(*,*) "rcm1d: error reading number of tracers"
+            write(*,*) "   (first line of traceur.def) "
+            stop
+          else
+            ! check that the number of tracers is indeed nqmx
+            if (nq.ne.nqmx) then
+              write(*,*) "rcm1d: error, wrong number of tracers:"
+              write(*,*) "nq=",nq," whereas nqmx=",nqmx
+              stop
+            endif
+          endif
+        
+          ! initialize advection schemes to Van-Leer for all tracers
+          do iq=1,nq
+            iadv(iq)=3 ! Van-Leer
+          enddo
+        
+          do iq=1,nq
+          ! minimal version, just read in the tracer names, 1 per line
+            read(90,*,iostat=ierr) tnom(iq)
+            if (ierr.ne.0) then
+              write(*,*) 'rcm1d: error reading tracer names...'
+              stop
+            endif
+          enddo !of do iq=1,nq
+! check for co2_ice / h2o_ice tracers:
+         i_co2_ice=0
+         i_h2o_ice=0
+         do iq=1,nq
+           if (tnom(iq)=="co2_ice") then
+             i_co2_ice=iq
+           elseif (tnom(iq)=="h2o_ice") then
+             i_h2o_ice=iq
+           endif
+         enddo
+         !if (i_co2_ice==0) then
+         !  write(*,*) "rcm1d: error, we need a 'co2_ice' tracer"
+         !  write(*,*) "   (add one to traceur.def)"
+         !  stop
+         !endif
+        else
+          write(*,*) 'Cannot find required file "traceur.def"'
+          write(*,*) ' If you want to run with tracers, I need it'
+          write(*,*) ' ... might as well stop here ...'
+          stop
+        endif
+        close(90)
+
+      else
+      ! we still need to set (dummy) tracer names for physdem1
+        nq=nqmx
+        do iq=1,nq
+          write(str7,'(a1,i2.2)')'q',iq
+          tnom(iq)=str7
+        enddo
+        ! actually, we'll need at least one "co2_ice" tracer
+        ! (for surface CO2 ice)
+        tnom(1)="co2_ice"
+        i_co2_ice=1
+      endif ! of if (tracer)
+
+
+c  Date et heure locale du debut du run
+c  ------------------------------------
+c    Date (en sols depuis le solstice de printemps) du debut du run
+      day0 = 0 ! default value for day0
+      write(*,*) 'Initial date (in martian sols ; =0 at Ls=0)?'
+      call getin("day0",day0)
+      day=float(day0)
+      write(*,*) " day0 = ",day0
+c  Heure de demarrage
+      time=0 ! default value for time
+      write(*,*)'Initial local time (in hours, between 0 and 24)?'
+      call getin("time",time)
+      write(*,*)" time = ",time
+      time=time/24.E+0 ! convert time (hours) to fraction of sol
+
+c  Discretisation (Definition de la grille et des pas de temps)
+c  --------------
+c
+      nlayer=nlayermx
+      nlevel=nlayer+1
+      nsoil=nsoilmx
+
+      day_step=48 ! default value for day_step
+      PRINT *,'Number of time steps per sol ?'
+      call getin("day_step",day_step)
+      write(*,*) " day_step = ",day_step
+
+      ndt=10 ! default value for ndt
+      PRINT *,'Number of sols to run ?'
+      call getin("ndt",ndt)
+      write(*,*) " ndt = ",ndt
+
+      ndt=ndt*day_step     
+      dtphys=daysec/day_step  
+
+
+c Pression de surface sur la planete
+c ------------------------------------
+c
+      psurf=100000. ! default value for psurf
+      PRINT *,'Surface pressure (Pa) ?'
+      call getin("psurf",psurf)
+      write(*,*) " psurf = ",psurf
+c Pression de reference
+      pa=20.
+      preff=610. ! these values are not needed in 1D  
+
+c Gravity of planet
+c -----------------
+      g=10.0 ! default value for g
+      PRINT *,'Gravity ?'
+      call getin("g",g)
+      write(*,*) " g = ",g
+
+      mugaz=0.
+      cpp=0.
+
+      call su_gases
+      call calc_cpp_mugaz
+      
+
+c Proprietes des poussiere aerosol
+c --------------------------------
+      tauvis=0.2 ! default value for tauvis
+      print *,'Reference dust opacity at 700 Pa ?'
+      call getin("tauvis",tauvis)
+      write(*,*) " tauvis = ",tauvis
+ 
+c  latitude/longitude
+c  ------------------
+      lati(1)=0 ! default value for lati(1)
+      PRINT *,'latitude (in degrees) ?'
+      call getin("latitude",lati(1))
+      write(*,*) " latitude = ",lati(1)
+      lati(1)=lati(1)*pi/180.E+0
+      long(1)=0.E+0
+      long(1)=long(1)*pi/180.E+0
+
+c  periastron/apoastron
+c  --------------------
+      periastr=227.94
+      apoastr=227.94 ! default = mean martian values
+      PRINT *,'periastron (in AU) ?'
+      call getin("periastr",periastr)
+      write(*,*) "periastron = ",periastr
+      periastr=periastr*149.598 ! AU to Mkm
+      PRINT *,'apoastron (in AU) ?'
+      call getin("apoastr",apoastr)
+      write(*,*) "apoastron = ",apoastr
+      apoastr=apoastr*149.598 ! AU to Mkm
+
+c  obliquity
+c  ---------
+      obliquit=0.0! default=zero in 1d
+      PRINT *,'obliquity (in AU) ?'
+      call getin("obliquit",obliquit)
+      write(*,*) "obliquity = ",obliquit
+
+c  Initialisation albedo / inertie du sol
+c  --------------------------------------
+      albedodat(1)=0.2 ! default value for albedodat
+      PRINT *,'Albedo of bare ground ?'
+      call getin("albedo",albedodat(1))
+      write(*,*) " albedo = ",albedodat(1)
+
+      inertiedat(1,1)=400 ! default value for inertiedat
+      PRINT *,'Soil thermal inertia (SI) ?'
+      call getin("inertia",inertiedat(1,1))
+      write(*,*) " inertia = ",inertiedat(1,1)
+c
+c  pour le schema d'ondes de gravite
+c  ---------------------------------
+c
+      zmea(1)=0.E+0
+      zstd(1)=0.E+0
+      zsig(1)=0.E+0
+      zgam(1)=0.E+0
+      zthe(1)=0.E+0
+
+c    Initialisation des traceurs
+c    ---------------------------
+
+      DO iq=1,nqmx
+        DO ilayer=1,nlayer
+           q(ilayer,iq) = 0.
+        ENDDO
+      ENDDO
+     
+      DO iq=1,nqmx
+        qsurf(iq) = 0.
+      ENDDO
+
+c   Initialisation speciales "physiq"
+c   ---------------------------------
+c   la surface de chaque maille est inutile en 1D --->
+      area(1)=1.E+0
+
+c   le geopotentiel au sol est inutile en 1D car tout est controle
+c   par la pression de surface --->
+      phisfi(1)=0.E+0
+
+c  "inifis" reproduit un certain nombre d'initialisations deja faites
+c  + lecture des clefs de callphys.def
+c  + calcul de la frequence d'appel au rayonnement
+c  + calcul des sinus et cosinus des longitude latitude
+
+!Mars possible issue with dtphys in input and include!!!
+      CALL inifis(1,llm,day0,daysec,dtphys,
+     .            lati,long,area,rad,g,r,cpp)
+c   Initialisation pour prendre en compte les vents en 1-D
+c   ------------------------------------------------------
+      ptif=2.E+0*omeg*sinlat(1)
+ 
+
+c    vent geostrophique
+      gru=10. ! default value for gru
+      PRINT *,'zonal eastward component of the geostrophic wind (m/s) ?'
+      call getin("u",gru)
+      write(*,*) " u = ",gru
+      grv=0. !default value for grv
+      PRINT *,'meridional northward component of the geostrophic',
+     &' wind (m/s) ?'
+      call getin("v",grv)
+      write(*,*) " v = ",grv
+
+c     Initialisation des vents  au premier pas de temps
+      DO ilayer=1,nlayer
+         u(ilayer)=gru
+         v(ilayer)=grv
+      ENDDO
+
+c     energie cinetique turbulente
+      DO ilevel=1,nlevel
+         q2(ilevel)=0.E+0
+      ENDDO
+
+c  emissivity / surface co2 ice ( + h2o ice??)
+c  -------------------------------------------
+      emis=emissiv ! default value for emissivity
+      PRINT *,'Emissivity of bare ground ?'
+      call getin("emis",emis)
+      write(*,*) " emis = ",emis
+      emissiv=emis ! we do this so that condense_co2 sets things to the right
+                   ! value if there is no snow
+
+      if(i_co2_ice.gt.0)then
+         qsurf(i_co2_ice)=0 ! default value for co2ice
+         print*,'Initial CO2 ice on the surface (kg.m-2)'
+         call getin("co2ice",qsurf(i_co2_ice))
+         write(*,*) " co2ice = ",qsurf(i_co2_ice)
+         IF (qsurf(i_co2_ice).ge.1.E+0) THEN
+            ! if we have some CO2 ice on the surface, change emissivity
+            if (lati(1).ge.0) then ! northern hemisphere
+              emis=emisice(1)
+            else ! southern hemisphere
+              emis=emisice(2)
+            endif
+         ENDIF
+      endif
+
+c  calcul des pressions et altitudes en utilisant les niveaux sigma
+c  ----------------------------------------------------------------
+
+c    Vertical Coordinates
+c    """"""""""""""""""""
+      hybrid=.true.
+      PRINT *,'Hybrid coordinates ?'
+      call getin("hybrid",hybrid)
+      write(*,*) " hybrid = ", hybrid
+
+
+      autozlevs=.false.
+      PRINT *,'Auto-discretise vertical levels ?'
+      call getin("autozlevs",autozlevs)
+      write(*,*) " autozlevs = ", autozlevs
+
+      pceil=100.0 ! Pascals
+      PRINT *,'Ceiling pressure (Pa) ?'
+      call getin("pceil",pceil)
+      write(*,*) " pceil = ", pceil
+
+! Test of incompatibility:
+! if autozlevs used, cannot have hybrid too
+
+      if (autozlevs.and.hybrid) then
+         print*,'Cannot use autozlevs and hybrid together!'
+         call abort
+      endif
+
+      if(autozlevs)then
+         if(kastprof)then
+            Hscale=10.0
+            Hmax=400.0
+         else
+            
+            open(91,file="z2sig.def",form='formatted')
+            read(91,*) Hscale
+            DO ilayer=1,nlayer-2
+               read(91,*) Hmax
+            enddo
+            close(91)
+ 
+         endif
+            
+         print*,'Hmax = ',Hmax,' km'
+         print*,'Auto-shifting Hscale to:'
+!     Hscale = Hmax / log(psurf/100.0)
+         Hscale = Hmax / log(psurf/pceil)
+         print*,'Hscale = ',Hscale,' km'
+         
+! none of this matters if we dont care about zlay
+         
+      endif
+
+      call disvert
+
+         if(.not.autozlevs)then
+            ! we want only the scale height from z2sig, in order to compute zlay
+            open(91,file="z2sig.def",form='formatted')
+            read(91,*) Hscale
+            close(91)
+         endif
+
+!         if(autozlevs)then
+!            open(94,file="Hscale.temp",form='formatted')
+!            read(94,*) Hscale
+!            close(94)
+!         endif
+
+         DO ilevel=1,nlevel
+            plev(ilevel)=ap(ilevel)+psurf*bp(ilevel)
+         ENDDO
+         
+         DO ilayer=1,nlayer
+            play(ilayer)=aps(ilayer)+psurf*bps(ilayer)
+         ENDDO
+         
+
+
+         DO ilayer=1,nlayer
+!     zlay(ilayer)=-300.E+0 *r*log(play(ilayer)/plev(1))
+!     &   /g
+            zlay(ilayer)=-1000.0*Hscale*log(play(ilayer)/plev(1))
+         ENDDO
+
+!      endif
+
+c  profil de temperature au premier appel
+c  --------------------------------------
+      pks=psurf**rcp
+
+c altitude en km dans profile: on divise zlay par 1000
+      tmp1(0)=0.E+0
+      DO ilayer=1,nlayer
+        tmp1(ilayer)=zlay(ilayer)/1000.E+0
+      ENDDO
+      call profile(nlayer+1,tmp1,tmp2)
+
+      tsurf=tmp2(0)
+      DO ilayer=1,nlayer
+        temp(ilayer)=tmp2(ilayer)
+      ENDDO
+      
+
+
+! Initialize soil properties and temperature
+! ------------------------------------------
+      volcapa=1.e6 ! volumetric heat capacity
+      DO isoil=1,nsoil
+         inertiedat(1,isoil)=inertiedat(1,1) ! soil thermal inertia
+         tsoil(isoil)=tsurf  ! soil temperature
+      ENDDO
+
+! Initialize depths
+! -----------------
+      do isoil=0,nsoil-1
+        mlayer(isoil)=2.e-4*(2.**(isoil-0.5)) ! mid-layer depth
+      enddo
+      do isoil=1,nsoil
+        layer(isoil)=2.e-4*(2.**(isoil-1)) ! layer depth
+      enddo
+
+c    Initialisation pour les sorties GRADS dans "g1d.dat" et "g1d.ctl"
+c    ----------------------------------------------------------------
+c    (effectuee avec "writeg1d" a partir de "physiq.F"
+c    ou tout autre subroutine physique, y compris celle ci).
+
+        g1d_nlayer=nlayer
+        g1d_nomfich='g1d.dat'
+        g1d_unitfich=40
+        g1d_nomctl='g1d.ctl'
+        g1d_unitctl=41
+        g1d_premier=.true.
+        g2d_premier=.true.
+
+c  Ecriture de "startfi"
+c  --------------------
+c  (Ce fichier sera aussitot relu au premier
+c   appel de "physiq", mais il est necessaire pour passer
+c   les variables purement physiques a "physiq"...
+
+      call physdem1("startfi.nc",long,lati,nsoilmx,nqmx,
+     &              dtphys,float(day0),
+     &              time,tsurf,tsoil,emis,q2,qsurf,
+     &              area,albedodat,inertiedat,zmea,zstd,zsig,zgam,zthe,
+     &              cloudfrac,totcloudfrac,hice)
+
+c=======================================================================
+c  BOUCLE TEMPORELLE DU MODELE 1D 
+c=======================================================================
+
+      firstcall=.true.
+      lastcall=.false.
+
+      DO idt=1,ndt
+        IF (idt.eq.ndt-day_step-1) then       !test
+         lastcall=.true.
+         call stellarlong(day*1.0,zls)
+         write(103,*) 'Ls=',zls*180./pi
+         write(103,*) 'Lat=', lati(1)*180./pi
+         write(103,*) 'Tau=', tauvis/700*psurf
+         write(103,*) 'RunEnd - Atmos. Temp. File'
+         write(103,*) 'RunEnd - Atmos. Temp. File'
+         write(104,*) 'Ls=',zls*180./pi
+         write(104,*) 'Lat=', lati(1)
+         write(104,*) 'Tau=', tauvis/700*psurf
+         write(104,*) 'RunEnd - Atmos. Temp. File'
+        ENDIF
+
+c    calcul du geopotentiel 
+c     ~~~~~~~~~~~~~~~~~~~~~
+
+        if(nonideal)then
+
+           DO ilayer=1,nlayer
+              call calc_cpp3d(cpp3D(1,ilayer),
+     $             rcp3D(1,ilayer),temp(ilayer),play(ilayer))
+           ENDDO
+
+           DO ilayer=1,nlayer
+
+!              if(autozlevs)then
+!                 s(ilayer)=(play(ilayer)/psurf)**rcp3D(1,ilayer)
+!              else
+                 s(ilayer)=
+     &                (aps(ilayer)/psurf+bps(ilayer))**rcp3D(1,ilayer)
+!              endif
+
+              h(ilayer)=cpp3D(1,ilayer)*temp(ilayer)/(pks*s(ilayer))
+           ENDDO
+
+        else
+           DO ilayer=1,nlayer
+
+!              if(autozlevs)then
+!                 s(ilayer)=(play(ilayer)/psurf)**rcp
+!              else
+                 s(ilayer)=(aps(ilayer)/psurf+bps(ilayer))**rcp
+!              endif
+              !s(ilayer)=(aps(ilayer)/psurf+bps(ilayer))**rcp
+              h(ilayer)=cpp*temp(ilayer)/(pks*s(ilayer))
+           ENDDO
+        endif
+!      DO ilayer=1,nlayer
+!        s(ilayer)=(aps(ilayer)/psurf+bps(ilayer))**rcp
+!        h(ilayer)=cpp*temp(ilayer)/(pks*s(ilayer))
+!      ENDDO
+      phi(1)=pks*h(1)*(1.E+0-s(1))
+      DO ilayer=2,nlayer
+         phi(ilayer)=phi(ilayer-1)+
+     &               pks*(h(ilayer-1)+h(ilayer))*.5E+0
+     &                  *(s(ilayer-1)-s(ilayer))
+
+      ENDDO
+
+c       appel de la physique
+c       --------------------
+
+
+      CALL physiq (1,llm,nqmx,
+     ,     firstcall,lastcall,
+     ,     day,time,dtphys,
+     ,     plev,play,phi,
+     ,     u, v,temp, q,  
+     ,     w,
+C - sorties
+     s     du, dv, dtemp, dq,dpsurf,tracerdyn)
+
+
+c       evolution du vent : modele 1D
+c       -----------------------------
+ 
+c       la physique calcule les derivees temporelles de u et v.
+c       on y rajoute betement un effet Coriolis.
+c
+c       DO ilayer=1,nlayer
+c          du(ilayer)=du(ilayer)+ptif*(v(ilayer)-grv)
+c          dv(ilayer)=dv(ilayer)+ptif*(-u(ilayer)+gru)
+c       ENDDO
+
+c       Pour certain test : pas de coriolis a l'equateur
+c       if(lati(1).eq.0.) then
+          DO ilayer=1,nlayer
+             du(ilayer)=du(ilayer)+ (gru-u(ilayer))/1.e4
+             dv(ilayer)=dv(ilayer)+ (grv-v(ilayer))/1.e4
+          ENDDO
+c       end if
+c      
+c
+c       Calcul du temps au pas de temps suivant
+c       ---------------------------------------
+        firstcall=.false.
+        time=time+dtphys/daysec
+        IF (time.gt.1.E+0) then
+            time=time-1.E+0
+            day=day+1
+        ENDIF
+
+c       calcul des vitesses et temperature au pas de temps suivant
+c       ----------------------------------------------------------
+
+        DO ilayer=1,nlayer
+           u(ilayer)=u(ilayer)+dtphys*du(ilayer)
+           v(ilayer)=v(ilayer)+dtphys*dv(ilayer)
+           temp(ilayer)=temp(ilayer)+dtphys*dtemp(ilayer)
+        ENDDO
+
+c       calcul des pressions au pas de temps suivant
+c       ----------------------------------------------------------
+
+           psurf=psurf+dtphys*dpsurf   ! evolution de la pression de surface
+           DO ilevel=1,nlevel
+              plev(ilevel)=ap(ilevel)+psurf*bp(ilevel)
+           ENDDO
+           DO ilayer=1,nlayer
+                 play(ilayer)=aps(ilayer)+psurf*bps(ilayer)
+           ENDDO
+
+c       calcul traceur au pas de temps suivant
+c       --------------------------------------
+
+        DO iq = 1, nqmx
+          DO ilayer=1,nlayer
+             q(ilayer,iq)=q(ilayer,iq)+dtphys*dq(ilayer,iq)
+          ENDDO
+        END DO
+
+      ENDDO   ! fin de la boucle temporelle
+
+c    ========================================================
+c    GESTION DES SORTIE
+c    ========================================================
+
+c    fermeture pour conclure les sorties format grads dans "g1d.dat"
+c    et "g1d.ctl" (effectuee avec "writeg1d" a partir de "physiq.F"
+c    ou tout autre subroutine physique, y compris celle ci).
+
+! save temperature profile
+      if(saveprofile)then
+         OPEN(12,file='profile.out',form='formatted')
+         DO ilayer=1,nlayermx
+	    write(12,*) temp(ilayer), play(ilayer)
+         ENDDO
+         CLOSE(12)
+      endif
+
+      logplevs(1)=log(plev(1)/100000.0)
+      do ilayer=2,nlayer
+         logplevs(ilayer)=log(play(ilayer)/100000.0)
+      enddo
+      CALL endg1d(1,nlayer,logplevs,ndt) ! now simply log(p) with p in bars
+
+c    ========================================================
+      end                       !rcm1d
+ 
+c***********************************************************************
+c***********************************************************************
+c     Subroutines Bidons utilise seulement en 3D, mais
+c     necessaire a la compilation de rcm1d en 1D
+
+      subroutine gr_fi_dyn
+      RETURN
+      END
+ 
+c***********************************************************************
+c***********************************************************************
+
+#include "../dyn3d/disvert.F"
Index: /trunk/LMDZ.GENERIC/libf/phystd/setspi.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/setspi.F90	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/setspi.F90	(revision 253)
@@ -157,4 +157,5 @@
       ! force planck=sigma*eps*T^4 for each temperature in array
       if(forceEC)then
+         print*,'Force F=sigma*eps*T^4 for all values of T!'
          do nt=NTstar,NTstop
             plancksum=0.0
Index: /trunk/LMDZ.GENERIC/libf/phystd/setspv.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/setspv.F90	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/setspv.F90	(revision 253)
@@ -110,5 +110,5 @@
 
       write(*,*)'Interpolating stellar spectrum from the hires data...'
-      call ave_stelspec(startype,STELLAR)
+      call ave_stelspec(STELLAR)
 
 !     Sum the stellar flux, and write out the result.  
@@ -120,4 +120,5 @@
       write(6,'(" Stellar flux at 1 AU = ",f7.2," W m-2")') sum
       print*,' '
+
 
 !=======================================================================
Index: /trunk/LMDZ.GENERIC/libf/phystd/sfluxi.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/sfluxi.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/sfluxi.F	(revision 253)
@@ -32,5 +32,5 @@
       real*8 taugsurf(L_NSPECTI,L_NGAUSS-1), fzero
 
-      real*8 BSURFtest ! by RW for test
+!      real*8 BSURFtest ! by RW for test
 
       real*8 fup_tmp(L_NSPECTI),fdn_tmp(L_NSPECTI)
@@ -45,4 +45,5 @@
     
       NFLUXTOPI = 0.0
+
       DO NW=1,L_NSPECTI
         NFLUXTOPI_nu(NW) = 0.0
@@ -68,8 +69,10 @@
       TSURF = TLEV(L_LEVELS)
 
-      NTS   = TSURF*10.0D0-499
-      NTT   = TTOP *10.0D0-499
+      NTS   = int(TSURF*10.0D0)-NTstar+1
+      NTT   = int(TTOP *10.0D0)-NTstar+1
+!      NTS   = TSURF*10.0D0-499
+!      NTT   = TTOP *10.0D0-499
 
-      BSURFtest=0.0
+!      BSURFtest=0.0
 
       DO 501 NW=1,L_NSPECTI
@@ -78,11 +81,4 @@
         BSURF = (1.-RSFI)*PLANCKIR(NW,NTS) ! interpolate for accuracy??
         PLTOP = PLANCKIR(NW,NTT)
-
-        !BSURFtest=BSURFtest+BSURF*DWNI(NW)
-        !if(NW.eq.L_NSPECTI)then
-        !     print*,'eps*sigma*T^4',5.67e-8*(1.-RSFI)*TSURF**4
-        !     print*,'BSURF in sfluxi=',pi*BSURFtest
-        !endif
-
 
 C  If FZEROI(NW) = 1, then the k-coefficients are zero - skip to the
@@ -116,4 +112,5 @@
 
 
+
 C         NOW CALCULATE THE CUMULATIVE IR NET FLUX
 
@@ -137,16 +134,9 @@
      *                                (1.0-FZEROI(NW))
 
-
 c         and same thing by spectral band... (RW)
             FLUXUPI_nu(L,NW) = FLUXUPI_nu(L,NW) + 
      *                FMUPI(L)*DWNI(NW)*GWEIGHT(NG)*(1.0-FZEROI(NW))
 
-
           END DO
-
-         !fup_tmp(nw)=fup_tmp(nw)+FMUPI(L_NLEVRAD-1)*DWNI(NW)*GWEIGHT(NG)
-         !fdn_tmp(nw)=fdn_tmp(nw)+FMDI(L_NLEVRAD-1)*DWNI(NW)*GWEIGHT(NG)
-         !fup_tmp(nw)=fup_tmp(nw)+FMUPI(1)*DWNI(NW)*GWEIGHT(NG)
-         !fdn_tmp(nw)=fdn_tmp(nw)+FMDI(1)*DWNI(NW)*GWEIGHT(NG)
 
    30     CONTINUE
@@ -154,16 +144,7 @@
        END DO       !End NGAUSS LOOP
 
-           ! print*,'-----------------------------------'
-            !print*,'FMDI(',nw,')=',FMDI(L_NLEVRAD-1)
-            !print*,'FMUPI(',nw,')=',FMUPI(L_NLEVRAD-1)
-            !print*,'DWNI(',nw,')=',DWNI(nw)
-           ! print*,'-----------------------------------'
-
    40  CONTINUE
 
 C      SPECIAL 17th Gauss point
-
-    !   print*,'fzero for ng=17',fzero
-
 
        NG     = L_NGAUSS
@@ -203,27 +184,8 @@
        END DO
 
-       !     print*,'-----------------------------------'
-       !     print*,'nw=',nw
-       !     print*,'ng=',ng
-       !     print*,'FMDI=',FMDI(L_NLEVRAD-1)
-       !     print*,'FMUPI=',FMUPI(L_NLEVRAD-1)
-       !     print*,'-----------------------------------'
-
   501 CONTINUE      !End Spectral Interval LOOP
 
 C *** END OF MAJOR SPECTRAL INTERVAL LOOP IN THE INFRARED****
 
-            !print*,'-----------------------------------'
-            !print*,'gweight=',gweight
-            !print*,'FLUXDNI=',FLUXDNI(L_NLEVRAD-1)
-            !print*,'FLUXUPI=',FLUXUPI(L_NLEVRAD-1)
-            !print*,'-----------------------------------'
-
-            !do nw=1,L_NSPECTI
-            !   print*,'fup_tmp(',nw,')=',fup_tmp(nw)
-            !   print*,'fdn_tmp(',nw,')=',fdn_tmp(nw)
-            !enddo
-
-
       RETURN
       END
Index: /trunk/LMDZ.GENERIC/libf/phystd/sfluxv.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/sfluxv.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/sfluxv.F	(revision 253)
@@ -1,4 +1,4 @@
       SUBROUTINE SFLUXV(DTAUV,TAUV,TAUCUMV,RSFV,DWNV,WBARV,COSBV,
-     *                  UBAR0,STEL,GWEIGHT,NFLUXTOPV,NFLUXTOPV_nu,
+     *                  UBAR0,STEL,GWEIGHT,NFLUXTOPV,NFLUXGNDV_nu,
      *                  FMNETV,FLUXUPV,FLUXDNV,FZEROV,taugsurf)
 
@@ -19,6 +19,6 @@
       real*8 NFLUXTOPV, FLUXUP, FLUXDN
       real*8 NFLUXTOPV_nu(L_NSPECTV)
+      real*8 NFLUXGNDV_nu(L_NSPECTV)
       real*8 GWEIGHT(L_NGAUSS)
-
 
       integer L, NG, NW, NG1,k
@@ -27,5 +27,4 @@
 
       real*8 DIFFV, DIFFVT
-
       real*8 taugsurf(L_NSPECTV,L_NGAUSS-1), fzero
 
@@ -38,4 +37,8 @@
       NFLUXTOPV = 0.0
 
+      DO NW=1,L_NSPECTV
+         NFLUXTOPV_nu(NW)=0.0
+         NFLUXGNDV_nu(NW)=0.0
+      END DO
 
       DO L=1,L_NLAYRAD
@@ -54,5 +57,4 @@
         F0PI = STEL(NW)
 
-
         FZERO = FZEROV(NW)
         IF(FZERO.ge.0.99) goto 40
@@ -68,11 +70,16 @@
 C         SET UP THE UPPER AND LOWER BOUNDARY CONDITIONS ON THE VISIBLE
 
-          BTOP = 0.0
-
+          BTOP  = 0.0
+          !BSURF = 0./0. ! why was this here?
+          BSURF = 0.
 C         LOOP OVER THE NTERMS BEGINNING HERE
  
+
+!      FACTOR    = 1.0D0 - WDEL(1)*CDEL(1)**2
+!      TAU(1)    = TDEL(1)*FACTOR
+
+
           ETERM = MIN(TAUV(L_NLEVRAD,NW,NG),TAUMAX)
           BSURF = RSFV*UBAR0*STEL(NW)*EXP(-ETERM/UBAR0)
-
 
 C         WE CAN NOW SOLVE FOR THE COEFFICIENTS OF THE TWO STREAM
@@ -84,9 +91,7 @@
 
 
-
           CALL GFLUXV(DTAUV(1,NW,NG),TAUV(1,NW,NG),TAUCUMV(1,NW,NG),
      *                WBARV(1,NW,NG),COSBV(1,NW,NG),UBAR0,F0PI,RSFV,
      *                BTOP,BSURF,FMUPV,FMDV,DIFFV,FLUXUP,FLUXDN)
-
 
 C         NOW CALCULATE THE CUMULATIVE VISIBLE NET FLUX 
@@ -103,8 +108,14 @@
           END DO
 
-c         and same thing by spectral band... (RDW)
+c     and same thing by spectral band... (RDW)
           NFLUXTOPV_nu(NW) = NFLUXTOPV_nu(NW)
      *      +(FLUXUP-FLUXDN)*GWEIGHT(NG)*
      *                          (1.0-FZEROV(NW))
+
+
+c     flux at gnd (RDW)
+          NFLUXGNDV_nu(NW) = NFLUXGNDV_nu(NW)
+     *      +FMDV(L_NLAYRAD)*GWEIGHT(NG)*(1.0-FZEROV(NW))
+
 
 C         THE DIFFUSE COMPONENT OF THE DOWNWARD STELLAR FLUX
@@ -145,9 +156,4 @@
 C       NOW CALCULATE THE CUMULATIVE VISIBLE NET FLUX 
 
-
-        !print*,'fmdv',fmdv
-        !print*,'fzero',fzero
-
-
         NFLUXTOPV = NFLUXTOPV+(FLUXUP-FLUXDN)*FZERO
         DO L=1,L_NLAYRAD
@@ -161,4 +167,7 @@
      *      +(FLUXUP-FLUXDN)*FZERO
 
+c     flux at gnd (RDW)
+          NFLUXGNDV_nu(NW) = NFLUXGNDV_nu(NW)+FMDV(L_NLAYRAD)*FZERO
+
 
 C       THE DIFFUSE COMPONENT OF THE DOWNWARD STELLAR FLUX
@@ -169,4 +178,5 @@
   500 CONTINUE
 
+
 C     *** END OF MAJOR SPECTRAL INTERVAL LOOP IN THE VISIBLE*****
 
Index: /trunk/LMDZ.GENERIC/libf/phystd/simpleprof_fn.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/simpleprof_fn.F90	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/simpleprof_fn.F90	(revision 253)
@@ -0,0 +1,58 @@
+      subroutine simpleprof_fn(tsurf,temp,popsk,ISR,psurf)
+!     creates a kasting temperature profile
+use radcommon_h, only: sigma
+      implicit none
+
+#include "dimensions.h"
+#include "dimphys.h"
+#include "comcstfi.h"
+#include "callkeys.h"
+
+!      REAL play(nlayermx)   ! Pressure at the middle of the layers (Pa)
+!      REAL plev(nlayermx+1) ! intermediate pressure levels (pa)
+      REAL psurf,tsurf      
+      REAL temp(nlayermx)   ! temperature at the middle of the layers
+      real ISR, ALB
+
+      real popsk(nlayermx)  ! this is dodgy as in rest of code, zpopsk(ngridmx,nlayermx)
+                            ! but kastprof requires 1D, so its ok I guess
+      integer l,iter
+
+
+      if(startype.eq.1)then
+         ALB=0.2+0.1*log10(psurf/100000.)
+      else
+         ALB=0.15
+      end if
+
+      Tstrat=((1-ALB)*ISR/(2*sigma))**0.25 ! skin temperature (gray approx.)
+      !Tstrat=60.                           ! minimum possible given H2-H2 CIA
+      print*,'psurf',psurf/100000.
+      print*,'ALB',ALB
+      print*,'Tstrat=',Tstrat
+
+      if(ngridmx.gt.1)then
+         print*,'DO NOT RUN KASTPROF IN 3D!!!'
+         call abort
+      end if
+
+      ! 1st, we make pot. temperature constant everywhere
+      do l=1,nlayermx
+            temp(l)=tsurf*popsk(l)
+      enddo
+
+      if(1.eq.1)then
+
+      do l=1,nlayermx-1
+            if (temp(l) .le. Tstrat)then
+               temp(l) = Tstrat            
+            endif
+      enddo
+
+      temp(nlayermx) = Tstrat
+
+      endif
+
+   
+   return
+ end subroutine simpleprof_fn
Index: /trunk/LMDZ.GENERIC/libf/phystd/soil.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/soil.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/soil.F	(revision 253)
@@ -35,15 +35,28 @@
 
 ! local saved variables:
-!      real,save :: layer(ngridmx,nsoilmx)	! layer depth
-      real,save :: mthermdiff(ngridmx,0:nsoilmx-1) ! mid-layer thermal diffusivity
-      real,save :: thermdiff(ngridmx,nsoilmx-1) ! inter-layer thermal diffusivity
-      real,save :: coefq(0:nsoilmx-1)		! q_{k+1/2} coefficients
-      real,save :: coefd(ngridmx,nsoilmx-1)	! d_k coefficients
-      real,save :: alph(ngridmx,nsoilmx-1)	! alpha_k coefficients
-      real,save :: beta(ngridmx,nsoilmx-1)	! beta_k coefficients
-      real,save :: mu
-      
+      !real,save :: mthermdiff(ngridmx,0:nsoilmx-1) ! mid-layer thermal diffusivity
+      !real,save :: thermdiff(ngridmx,nsoilmx-1) ! inter-layer thermal diffusivity
+      !real,save :: coefq(0:nsoilmx-1)		! q_{k+1/2} coefficients
+      !real,save :: coefd(ngridmx,nsoilmx-1)	! d_k coefficients
+      !real,save :: alph(ngridmx,nsoilmx-1)	! alpha_k coefficients
+      !real,save :: beta(ngridmx,nsoilmx-1)	! beta_k coefficients
+      !real,save :: mu
+
+      real mthermdiff(ngridmx,0:nsoilmx-1) ! mid-layer thermal diffusivity
+      real thermdiff(ngridmx,nsoilmx-1)    ! inter-layer thermal diffusivity
+      real coefq(0:nsoilmx-1)		   ! q_{k+1/2} coefficients
+      real coefd(ngridmx,nsoilmx-1)	   ! d_k coefficients
+      real alph(ngridmx,nsoilmx-1)	   ! alpha_k coefficients
+      real beta(ngridmx,nsoilmx-1)	   ! beta_k coefficients
+      real mu
+            
+      save mthermdiff,thermdiff,coefq,coefd,alph,beta,mu
+
 ! local variables:
       integer ig,ik
+
+
+!      print*,'tsoil=',tsoil
+!      print*,'tsurf=',tsurf
 
 ! 0. Initialisations and preprocessing step
@@ -104,8 +117,9 @@
         capcal(ig)=capcal(ig)/(1.+mu*(1.0-alph(ig,1))*
      &                         thermdiff(ig,1)/mthermdiff(ig,0))
-!      write(*,*)'soil: ig=',ig,' capcal(ig)=',capcal(ig)
+      !write(*,*)'soil: ig=',ig,' capcal(ig)=',capcal(ig)
       enddo ! of do ig=1,ngrid
             
       else ! of if (firstcall)
+
 
 !  1. Compute soil temperatures
@@ -142,4 +156,5 @@
       enddo
 
+
 !  3. Compute surface diffusive flux & calorific capacity
       do ig=1,ngrid
@@ -149,4 +164,12 @@
 !     &              (timestep*(1.-alph(ig,1)))
 ! Fstar
+
+!         print*,'this far in soil 1'
+!         print*,'thermdiff=',thermdiff(ig,1)
+!         print*,'mlayer=',mlayer
+!         print*,'beta=',beta(ig,1)
+!         print*,'alph=',alph(ig,1)
+!         print*,'tsoil=',tsoil(ig,1)
+
         fluxgrd(ig)=(thermdiff(ig,1)/(mlayer(1)-mlayer(0)))*
      &              (beta(ig,1)+(alph(ig,1)-1.0)*tsoil(ig,1))
@@ -163,4 +186,5 @@
       enddo
 
+
       end
 
Index: unk/LMDZ.GENERIC/libf/phystd/solang.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/solang.F	(revision 252)
+++ 	(revision )
@@ -1,114 +1,0 @@
-      subroutine solang ( kgrid,psilon,pcolon,psilat,pcolat,
-     &                    ptim1,ptim2,ptim3,pmu0,pfract )
-      IMPLICIT NONE
-
-C
-C**** *LW*   - ORGANIZES THE LONGWAVE CALCULATIONS
-C
-C     PURPOSE.
-C     --------
-C          CALCULATES THE SOLAR ANGLE FOR ALL THE POINTS OF THE GRID
-C
-C**   INTERFACE.
-C     ----------
-C      SUBROUTINE SOLANG ( KGRID )
-C
-C        EXPLICIT ARGUMENTS :
-C        --------------------
-C     ==== INPUTS  ===
-C
-C PSILON(KGRID)   : SINUS OF THE LONGITUDE
-C PCOLON(KGRID)   : COSINUS OF THE LONGITUDE
-C PSILAT(KGRID)   : SINUS OF THE LATITUDE
-C PCOLAT(KGRID)   : COSINUS OF THE LATITUDE
-C PTIM1           : SIN(DECLI)
-C PTIM2           : COS(DECLI)*COS(TIME)
-C PTIM3           : SIN(DECLI)*SIN(TIME)
-C
-C     ==== OUTPUTS ===
-C
-C PMU0 (KGRID)    : SOLAR ANGLE
-C PFRACT(KGRID)   : DAY FRACTION OF THE TIME INTERVAL
-C
-C        IMPLICIT ARGUMENTS :   NONE
-C        --------------------
-C
-C     METHOD.
-C     -------
-C
-C     EXTERNALS.
-C     ----------
-C
-C         NONE
-C
-C     REFERENCE.
-C     ----------
-C
-C         RADIATIVE PROCESSES IN METEOROLOGIE AND CLIMATOLOGIE
-C         PALTRIDGE AND PLATT
-C
-C     AUTHOR.
-C     -------
-C        FREDERIC HOURDIN
-C
-C     MODIFICATIONS.
-C     --------------
-C        ORIGINAL :90-01-14
-C                  92-02-14 CALCULATIONS DONE THE ENTIER GRID (J.Polcher)
-C-----------------------------------------------------------------------
-C
-C     ------------------------------------------------------------------
-
-C-----------------------------------------------------------------------
-C
-C*      0.1   ARGUMENTS
-C             ---------
-C
-      INTEGER kgrid
-      REAL ptim1,ptim2,ptim3
-      REAL psilon(kgrid),pcolon(kgrid),pmu0(kgrid),pfract(kgrid)
-      REAL psilat(kgrid), pcolat(kgrid)
-C
-      INTEGER jl
-      REAL ztim1,ztim2,ztim3
-C------------------------------------------------------------------------
-C------------------------------------------------------------------------
-C------------------------------------------------------------------------
-C
-C------------------------------------------------------------------------
-C
-C*     1.     INITIALISATION
-C             --------------
-C
- 100  CONTINUE
-C
-      DO jl=1,kgrid
-        pmu0(jl)=0.
-        pfract(jl)=0.
-      ENDDO
-C
-C*     1.1     COMPUTATION OF THE SOLAR ANGLE
-C              ------------------------------
-C
-      DO jl=1,kgrid
-        ztim1=psilat(jl)*ptim1
-        ztim2=pcolat(jl)*ptim2
-        ztim3=pcolat(jl)*ptim3
-        pmu0(jl)=ztim1+ztim2*pcolon(jl)+ztim3*psilon(jl)
-      ENDDO
-C
-C*     1.2      DISTINCTION BETWEEN DAY AND NIGHT
-C               ---------------------------------
-C
-      DO jl=1,kgrid
-        IF (pmu0(jl).gt.0.) THEN
-          pfract(jl)=1.
-c       pmu0(jl)=sqrt(1224.*pmu0(jl)*pmu0(jl)+1.)/35.
-      ELSE
-c       pmu0(jl)=0.
-        pfract(jl)=0.
-        ENDIF
-      ENDDO
-C
-      RETURN
-      END
Index: unk/LMDZ.GENERIC/libf/phystd/solarlong.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/solarlong.F	(revision 252)
+++ 	(revision )
@@ -1,106 +1,0 @@
-      SUBROUTINE solarlong(pday,psollong)
-      IMPLICIT NONE
-
-c=======================================================================
-c
-c   Objet:
-c   ------
-c
-c      Calcul de la distance soleil-planete et de la declinaison
-c   en fonction du jour de l'annee.
-c
-c
-c   Methode:
-c   --------
-c
-c      Calcul complet de l'elipse
-c
-c   Interface:
-c   ----------
-c
-c      Uncommon comprenant les parametres orbitaux.
-c
-c   Arguments:
-c   ----------
-c
-c   Input:
-c   ------
-c   pday          jour de l'annee (le jour 0 correspondant a l'equinoxe)
-c
-c   Output:
-c   -------
-c   pdist_sol     distance entre le soleil et la planete
-c                 ( en unite astronomique pour utiliser la constante 
-c                  solaire terrestre 1370 Wm-2 )
-c   pdecli        declinaison ( en radians )
-c
-c=======================================================================
-c-----------------------------------------------------------------------
-c   Declarations:
-c   -------------
-
-#include "planete.h"
-#include "comcstfi.h"
-
-c arguments:
-c ----------
-
-      REAL pday,pdist_sol,pdecli,psollong
-      LOGICAL lwrite
-
-c Local:
-c ------
-
-      REAL zanom,xref,zx0,zdx,zteta,zz
-      INTEGER iter
-
-
-c-----------------------------------------------------------------------
-c calcul de l'angle polaire et de la distance au soleil :
-c -------------------------------------------------------
-
-c   Initialisation eventuelle:
-      if(.not.unitastr.gt.1.e-4) then
-         call iniorbit(249.22,206.66,669.,485.,25.2)
-      endif
-
-c  calcul de l'zanomalie moyenne
-
-      zz=(pday-peri_day)/year_day
-      pi=2.*asin(1.)
-      zanom=2.*pi*(zz-nint(zz))
-      xref=abs(zanom)
-
-c  resolution de l'equation horaire  zx0 - e * sin (zx0) = xref
-c  methode de Newton
-
-      zx0=xref+e_elips*sin(xref)
-      DO 110 iter=1,10
-         zdx=-(zx0-e_elips*sin(zx0)-xref)/(1.-e_elips*cos(zx0))
-         if(abs(zdx).le.(1.e-7)) goto 120
-         zx0=zx0+zdx
-110   continue
-120   continue
-      zx0=zx0+zdx
-      if(zanom.lt.0.) zx0=-zx0
-
-c zteta est la longitude solaire
-
-      zteta=2.*atan(sqrt((1.+e_elips)/(1.-e_elips))*tan(zx0/2.))
-
-      psollong=zteta-timeperi
-
-      IF(psollong.LT.0.) psollong=psollong+2.*pi
-      IF(psollong.GT.2.*pi) psollong=psollong-2.*pi
-c-----------------------------------------------------------------------
-c   sorties eventuelles:
-c   ---------------------
-
-c     IF (lwrite) THEN
-c        PRINT*,'jour de l"annee   :',pday
-c        PRINT*,'distance au soleil (en unite astronomique) :',pdist_sol
-c        PRINT*,'declinaison (en degres) :',pdecli*180./pi
-c     ENDIF
-
-      RETURN
-      END
Index: /trunk/LMDZ.GENERIC/libf/phystd/stelang.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/stelang.F	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/stelang.F	(revision 253)
@@ -0,0 +1,114 @@
+      subroutine stelang(kgrid,psilon,pcolon,psilat,pcolat,
+     &                    ptim1,ptim2,ptim3,pmu0,pfract )
+      IMPLICIT NONE
+
+C
+C**** *LW*   - ORGANIZES THE LONGWAVE CALCULATIONS
+C
+C     PURPOSE.
+C     --------
+C          CALCULATES THE STELLAR ANGLE FOR ALL THE POINTS OF THE GRID
+C
+C**   INTERFACE.
+C     ----------
+C      SUBROUTINE STELANG ( KGRID )
+C
+C        EXPLICIT ARGUMENTS :
+C        --------------------
+C     ==== INPUTS  ===
+C
+C PSILON(KGRID)   : SINUS OF THE LONGITUDE
+C PCOLON(KGRID)   : COSINUS OF THE LONGITUDE
+C PSILAT(KGRID)   : SINUS OF THE LATITUDE
+C PCOLAT(KGRID)   : COSINUS OF THE LATITUDE
+C PTIM1           : SIN(DECLI)
+C PTIM2           : COS(DECLI)*COS(TIME)
+C PTIM3           : SIN(DECLI)*SIN(TIME)
+C
+C     ==== OUTPUTS ===
+C
+C PMU0 (KGRID)    : SOLAR ANGLE
+C PFRACT(KGRID)   : DAY FRACTION OF THE TIME INTERVAL
+C
+C        IMPLICIT ARGUMENTS :   NONE
+C        --------------------
+C
+C     METHOD.
+C     -------
+C
+C     EXTERNALS.
+C     ----------
+C
+C         NONE
+C
+C     REFERENCE.
+C     ----------
+C
+C         RADIATIVE PROCESSES IN METEOROLOGIE AND CLIMATOLOGIE
+C         PALTRIDGE AND PLATT
+C
+C     AUTHOR.
+C     -------
+C        FREDERIC HOURDIN
+C
+C     MODIFICATIONS.
+C     --------------
+C        ORIGINAL :90-01-14
+C                  92-02-14 CALCULATIONS DONE THE ENTIER GRID (J.Polcher)
+C-----------------------------------------------------------------------
+C
+C     ------------------------------------------------------------------
+
+C-----------------------------------------------------------------------
+C
+C*      0.1   ARGUMENTS
+C             ---------
+C
+      INTEGER kgrid
+      REAL ptim1,ptim2,ptim3
+      REAL psilon(kgrid),pcolon(kgrid),pmu0(kgrid),pfract(kgrid)
+      REAL psilat(kgrid), pcolat(kgrid)
+C
+      INTEGER jl
+      REAL ztim1,ztim2,ztim3
+C------------------------------------------------------------------------
+C------------------------------------------------------------------------
+C------------------------------------------------------------------------
+C
+C------------------------------------------------------------------------
+C
+C*     1.     INITIALISATION
+C             --------------
+C
+ 100  CONTINUE
+C
+      DO jl=1,kgrid
+        pmu0(jl)=0.
+        pfract(jl)=0.
+      ENDDO
+C
+C*     1.1     COMPUTATION OF THE SOLAR ANGLE
+C              ------------------------------
+C
+      DO jl=1,kgrid
+        ztim1=psilat(jl)*ptim1
+        ztim2=pcolat(jl)*ptim2
+        ztim3=pcolat(jl)*ptim3
+        pmu0(jl)=ztim1+ztim2*pcolon(jl)+ztim3*psilon(jl)
+      ENDDO
+C
+C*     1.2      DISTINCTION BETWEEN DAY AND NIGHT
+C               ---------------------------------
+C
+      DO jl=1,kgrid
+        IF (pmu0(jl).gt.0.) THEN
+          pfract(jl)=1.
+c       pmu0(jl)=sqrt(1224.*pmu0(jl)*pmu0(jl)+1.)/35.
+      ELSE
+c       pmu0(jl)=0.
+        pfract(jl)=0.
+        ENDIF
+      ENDDO
+C
+      RETURN
+      END
Index: /trunk/LMDZ.GENERIC/libf/phystd/stellarlong.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/stellarlong.F	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/stellarlong.F	(revision 253)
@@ -0,0 +1,106 @@
+      SUBROUTINE stellarlong(pday,pstellong)
+      IMPLICIT NONE
+
+c=======================================================================
+c
+c   Objet:
+c   ------
+c
+c      Calcul de la distance soleil-planete et de la declinaison
+c   en fonction du jour de l'annee.
+c
+c
+c   Methode:
+c   --------
+c
+c      Calcul complet de l'elipse
+c
+c   Interface:
+c   ----------
+c
+c      Uncommon comprenant les parametres orbitaux.
+c
+c   Arguments:
+c   ----------
+c
+c   Input:
+c   ------
+c   pday          jour de l'annee (le jour 0 correspondant a l'equinoxe)
+c
+c   Output:
+c   -------
+c   pdist_star     distance entre le soleil et la planete
+c                 ( en unite astronomique pour utiliser la constante 
+c                  solaire terrestre 1370 Wm-2 )
+c   pdecli        declinaison ( en radians )
+c
+c=======================================================================
+c-----------------------------------------------------------------------
+c   Declarations:
+c   -------------
+
+#include "planete.h"
+#include "comcstfi.h"
+
+c arguments:
+c ----------
+
+      REAL pday,pdist_star,pdecli,pstellong
+      LOGICAL lwrite
+
+c Local:
+c ------
+
+      REAL zanom,xref,zx0,zdx,zteta,zz
+      INTEGER iter
+
+
+c-----------------------------------------------------------------------
+c calcul de l'angle polaire et de la distance au soleil :
+c -------------------------------------------------------
+
+c   Initialisation eventuelle:
+      if(.not.unitastr.gt.1.e-4) then
+         call iniorbit(249.22,206.66,669.,485.,25.2)
+      endif
+
+c  calcul de l'zanomalie moyenne
+
+      zz=(pday-peri_day)/year_day
+      pi=2.*asin(1.)
+      zanom=2.*pi*(zz-nint(zz))
+      xref=abs(zanom)
+
+c  resolution de l'equation horaire  zx0 - e * sin (zx0) = xref
+c  methode de Newton
+
+      zx0=xref+e_elips*sin(xref)
+      DO 110 iter=1,10
+         zdx=-(zx0-e_elips*sin(zx0)-xref)/(1.-e_elips*cos(zx0))
+         if(abs(zdx).le.(1.e-7)) goto 120
+         zx0=zx0+zdx
+110   continue
+120   continue
+      zx0=zx0+zdx
+      if(zanom.lt.0.) zx0=-zx0
+
+c zteta est la longitude solaire
+
+      zteta=2.*atan(sqrt((1.+e_elips)/(1.-e_elips))*tan(zx0/2.))
+
+      pstellong=zteta-timeperi
+
+      IF(pstellong.LT.0.) pstellong=pstellong+2.*pi
+      IF(pstellong.GT.2.*pi) pstellong=pstellong-2.*pi
+c-----------------------------------------------------------------------
+c   sorties eventuelles:
+c   ---------------------
+
+c     IF (lwrite) THEN
+c        PRINT*,'jour de l"annee   :',pday
+c        PRINT*,'distance au soleil (en unite astronomique) :',pdist_star
+c        PRINT*,'declinaison (en degres) :',pdecli*180./pi
+c     ENDIF
+
+      RETURN
+      END
Index: /trunk/LMDZ.GENERIC/libf/phystd/stokes.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/stokes.F90	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/stokes.F90	(revision 253)
@@ -30,6 +30,6 @@
 
 !     locally saved variables
-!     -----------------------
-      real a,b
+!     ---------------------
+      real a,b,molrad,visc
       save a,b
   
@@ -43,6 +43,18 @@
 	 !stop
          !a = 0.707*Rgas/(4*pi*molrad**2 * avocado)
+
+         molrad=2.2e-10   ! CO2 (only used in condense_co2cloud at the moment)
+         visc=1.e-5       ! CO2
+
+
          a = 0.707*R/(4*pi*molrad**2 * avocado)
-         b = (2./9.) * rho_aer * g / visc  
+         b = (2./9.) * rho_aer * g / visc 
+	!print*,'molrad=',molrad
+	!print*,'visc=',visc
+	!print*,'a=',a
+	!print*,'b=',b
+	!print*,'rho_aer=',rho_aer
+	!stop
+ 
          firstcall=.false.
       end if
@@ -52,5 +64,4 @@
 !     slip-flow correction according to Rossow (Icarus 36, 1-50, 1978)
       w = b * rd*rd * (1 + 1.333* (a*T/P)/rd )  
-
       return
     end subroutine stokes
Index: /trunk/LMDZ.GENERIC/libf/phystd/su_gases.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/su_gases.F90	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/su_gases.F90	(revision 253)
@@ -0,0 +1,74 @@
+subroutine su_gases
+
+  implicit none
+
+#include "gases.h"
+
+       integer ngas, igas, ierr
+
+!==================================================================
+!     
+!     Purpose
+!     -------
+!     Load atmospheric composition info
+!     
+!     Authors
+!     -------
+!     R. Wordsworth (2011)
+!     
+!==================================================================
+
+       ! load gas names from file 'gases.def'
+       open(90,file='gases.def',status='old',form='formatted',iostat=ierr)
+       if (ierr.eq.0) then
+          write(*,*) "sugases.F90: reading file gases.def"
+          read(90,*)
+          read(90,*,iostat=ierr) ngas
+          if (ierr.ne.0) then
+             write(*,*) "sugases.F90: error reading number of gases"
+             write(*,*) "   (first line of gases.def) "
+             call abort
+          endif
+          ! check that the number of gases is indeed ngasmx
+          if (ngas.ne.ngasmx) then
+             write(*,*) "sugases.F90: error, wrong number of gases:"
+             write(*,*) "ngas=",ngas," whereas ngasmx=",ngasmx
+             call abort
+          endif
+
+          do igas=1,ngas
+             read(90,*,iostat=ierr) gnom(igas)
+             if (ierr.ne.0) then
+                write(*,*) 'sugases.F90: error reading gas names...'
+                call abort
+             endif
+          enddo                  !of do igas=1,ngas
+          
+          vgas=0
+          do igas=1,ngas
+             read(90,*,iostat=ierr) gfrac(igas)
+             if (ierr.ne.0) then
+                write(*,*) 'sugases.F90: error reading gas molar fractions...'
+                call abort
+             endif
+
+             ! find variable gas (if any)
+             if(gfrac(igas).eq.-1.0)then 
+                if(vgas.eq.0)then
+                   vgas=igas
+                else
+                   print*,'You seem to be choosing two variable gases'
+                   print*,'Check that gases.def is correct'
+                   call abort
+                endif
+             endif
+             
+          enddo                  !of do igas=1,ngas
+
+       else
+          write(*,*) 'Cannot find required file "gases.def"'
+          call abort
+       endif
+       close(90)
+
+end subroutine su_gases
Index: /trunk/LMDZ.GENERIC/libf/phystd/su_watercycle.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/su_watercycle.F90	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/su_watercycle.F90	(revision 253)
@@ -21,8 +21,11 @@
       RCPD   = cpp 
 
-      RV     = 1000.*R/mH2O
-      RCPV   = 4. *RV
-      RVTMP2 = RCPV/RCPD-1.
+      !RV = 1000.*R/mH2O
+      RV = 1000.*8.314/mH2O ! caution! R is R/mugaz already!
 
+      RCPV   = 4. *RV	 ! could be more precise...
+      !RCPV   = 5/2 *8.31*1000/mH2O ! BC modif here: doesn't appear to be correct
+
+      RVTMP2 = RCPV/RCPD-1. ! not currently used...
 
       end subroutine su_watercycle
Index: /trunk/LMDZ.GENERIC/libf/phystd/suaer_corrk.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/suaer_corrk.F90	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/suaer_corrk.F90	(revision 253)
@@ -77,6 +77,6 @@
 !     the single scattering parameters)
 
-      REAL lamref              ! reference wavelengths
-      REAL epref                ! reference extinction ep
+      REAL lamref                      ! reference wavelengths
+      REAL epref                       ! reference extinction ep
 
 !      REAL epav(L_NSPECTI)            ! Average ep (= <Qext>/Qext(lamref) if epref=1)
@@ -103,5 +103,5 @@
       forgetit=.true.
 
-!     naerkind=1: overrides dust
+!     naerkind=1
 !     visible
       if(forgetit)then
@@ -121,6 +121,6 @@
          
 ! NOTE: these lamref's are currently for dust, not CO2 ice.
-! JB thinks this shouldn't matter too much, but it needs to be fixed for the 
-! final version.
+! JB thinks this shouldn't matter too much, but it needs to be 
+! fixed / decided for the final version.
 
       IF (naerkind .gt. 1) THEN
@@ -132,10 +132,22 @@
          file_id(2,2) = 'optprop_iceir_n50.dat'
          lamrefir(2)=12.1E-6   ! 825cm-1 TES/MGS
-!         ENDIF
       ENDIF
 
-      IF (naerkind .gt. 2) THEN
+      IF (naerkind .eq. 3) THEN
+!     naerkind=3
+!     visible
+         file_id(naerkind,1) = 'optprop_dustvis_n50.dat'
+         !lamrefvis(3)=1.5E-6   ! 1.5um OMEGA/MEx
+         lamrefvis(naerkind)=0.67e-6
+!     infrared
+         file_id(naerkind,2) = 'optprop_dustir_n50.dat'
+         !lamrefir(3)=12.1E-6   ! 825cm-1 TES/MGS
+         lamrefir(naerkind)=9.3E-6
+
+      ENDIF
+
+      IF (naerkind .gt. 3) THEN
          print*,'naerkind = ',naerkind
-         print*,'but we only have data for 2 types, exiting.'
+         print*,'but we only have data for 3 types, exiting.'
          call abort
       ENDIF
@@ -144,12 +156,4 @@
 
 !     Initializations:
-
-!      call zerophys(nsizemax*2*naerkind,radiustab)
-!      call zerophys(nsizemax*naerkind*L_NSPECTV,gvis)
-!      call zerophys(nsizemax*naerkind*L_NSPECTV,omegavis)
-!      call zerophys(nsizemax*naerkind*L_NSPECTV,QVISsQREF)
-!      call zerophys(nsizemax*naerkind*L_NSPECTI,gIR)
-!      call zerophys(nsizemax*naerkind*L_NSPECTI,omegaIR)
-!      call zerophys(nsizemax*naerkind*L_NSPECTI,QIRsQREF)
 
       radiustab(:,:,:) = 0.0
@@ -308,4 +312,9 @@
       endif
 
+
+
+
+
+
 !==================================================================
 !     2. AVERAGED PROPERTIES AND VARIABLE ASSIGNMENTS
@@ -392,5 +401,4 @@
       END SELECT domain
 
-
 !========================================================================
 !     3. Deallocate temporary variables that were read in the ASCII files
@@ -406,5 +414,9 @@
       END DO                    ! Loop on idomain
 !========================================================================
+
       RETURN
+
+
+
     END subroutine suaer_corrk
       
Index: /trunk/LMDZ.GENERIC/libf/phystd/sugas_corrk.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/sugas_corrk.F90	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/sugas_corrk.F90	(revision 253)
@@ -2,5 +2,5 @@
 
 !==================================================================
-!     
+!
 !     Purpose
 !     -------
@@ -8,12 +8,12 @@
 !     This subroutine is a replacement for the old 'setrad', which contained
 !     both absorption and scattering data.
-!     
+!
 !     Authors
 !     -------
 !     Adapted and generalised from the NASA Ames code by Robin Wordsworth (2009)
-!     
+!
 !     Summary
 !     -------
-!     
+!
 !==================================================================
 
@@ -28,4 +28,5 @@
 #include "datafile.h"
 #include "callkeys.h"
+#include "gases.h"
 
 !==================================================================
@@ -44,6 +45,8 @@
       real*8 x, xi(4), yi(4), ans, p
 
-      integer Nspecies
-
+      integer ngas, igas
+
+      ! temporary special for addh2
+      double precision testH2
 
 !=======================================================================
@@ -51,4 +54,5 @@
       file_id='/corrk_data/' // corrkdir(1:LEN_TRIM(corrkdir)) // '/Q.dat'
       file_path=datafile(1:LEN_TRIM(datafile))//file_id(1:LEN_TRIM(file_id))
+
 
       ! check that the file exists
@@ -62,24 +66,35 @@
       ! check that database matches varactive toggle
       open(111,file=file_path(1:LEN_TRIM(file_path)),form='formatted')
-      read(111,*) Nspecies
-
-      if(Nspecies.eq.1 .and. (varactive.or.varfixed))then
+      read(111,*) ngas
+
+      if(ngas.ne.ngasmx)then
+         print*,'Number of gases in radiative transfer data (',ngas,') does not', &
+                'match that in gases.def (',ngasmx,'), exiting.'
+         call abort
+      endif 
+
+      if(ngas.eq.1 .and. (varactive.or.varfixed))then
          print*,'You have varactive/fixed=.true. but the database [',  &
                      corrkdir(1:LEN_TRIM(corrkdir)),           &
                 '] has no variable species, exiting.'
          call abort
-      elseif(Nspecies.eq.2 .and. (.not.varactive) .and. (.not.varfixed))then
+      elseif(ngas.eq.2 .and. (.not.varactive) .and. (.not.varfixed))then
          print*,'You have varactive and varfixed=.false. and the database [', &
                      corrkdir(1:LEN_TRIM(corrkdir)),           &
                 '] has a variable species.'
          call abort
-      elseif(Nspecies.gt.3 .or. Nspecies.lt.1)then
-         print*,Nspecies,' species in database [',               &
+      elseif(ngas.gt.4 .or. ngas.lt.1)then
+         print*,ngas,' species in database [',               &
                      corrkdir(1:LEN_TRIM(corrkdir)),           &
                 '], radiative code cannot handle this.'
          call abort
-      endif
-
-      do n=1,Nspecies
+      endif 
+
+      if(ngas.gt.3)then
+         print*,'ngas>3, EXPERIMENTAL!'
+      endif
+
+
+      do n=1,ngas
          read(111,*) gastype(n)
          print*,'Gas ',n,' is ',gastype(n)
@@ -89,5 +104,7 @@
       open(111,file=file_path(1:LEN_TRIM(file_path)),form='formatted')
       read(111,*) L_REFVARcheck
-      if(.not.(L_REFVARcheck.eq.L_REFVAR)) then      
+      if(.not.(L_REFVARcheck.eq.L_REFVAR)) then   
+         print*,   L_REFVARcheck
+         print*,   L_REFVAR
          print*,'The size of your radiative transfer mixing ratio array does '
          print*,'not match the value given in Q.dat, exiting.'
@@ -96,12 +113,22 @@
       read(111,*) wrefvar
       close(111)
+
+      ! Check that gastype and gnom match
+      do n=1,ngas
+         print*,'Gas ',n,' is ',gnom(n)
+         if(gnom(n).ne.gastype(n))then
+            print*,'Name of a gas in radiative transfer data (',gastype(n),') does not', &
+                 'match that in gases.def (',gnom(n),'), exiting.'
+         endif
+      enddo
+      print*,'Confirmed gas match in radiative transfer and gases.def!'
 
       ! display the values
       print*,'Variable gas mixing ratios:'
       do n=1,L_REFVAR
-         print*,n,'.',wrefvar(n),' kg/kg'
+         !print*,n,'.',wrefvar(n),' kg/kg' ! pay attention!
+         print*,n,'.',wrefvar(n),' mol/mol'
       end do
       print*,''
-
 
 !=======================================================================
@@ -184,6 +211,5 @@
       end do
       pfgasref(L_PINT) = pgasref(L_NPREF)
-      ! Warning! this may need to be generalised if we want to use uneven grids!
-
+      print*,'Warning, pfgasref needs generalisation to uneven grids!!'
 
 !-----------------------------------------------------------------------
@@ -225,6 +251,6 @@
 !     Get gaseous k-coefficients and interpolate onto finer pressure grid
 
-         ! VISIBLE
-      if (callgasvis) then
+      ! VISIBLE
+      if (callgasvis.and..not.corrkdir(1:LEN_TRIM(corrkdir)).eq.'null') then
          file_id='/corrk_data/'//trim(adjustl(banddir))//'/corrk_gcm_VI.dat' 
          file_path=datafile(1:LEN_TRIM(datafile))//file_id(1:LEN_TRIM(file_id))
@@ -244,30 +270,37 @@
          
       else
-         print*,'Visible gaseous absorption is set to zero.'
+         print*,'Visible corrk gaseous absorption is set to zero.'
+         gasv8(:,:,:,:,:)=0.0
       endif
 
       ! INFRA-RED
-      file_id='/corrk_data/'//trim(adjustl(banddir))//'/corrk_gcm_IR.dat' 
-      file_path=datafile(1:LEN_TRIM(datafile))//file_id(1:LEN_TRIM(file_id))
+      if (.not.corrkdir(1:LEN_TRIM(corrkdir)).eq.'null') then
+         file_id='/corrk_data/'//trim(adjustl(banddir))//'/corrk_gcm_IR.dat' 
+         file_path=datafile(1:LEN_TRIM(datafile))//file_id(1:LEN_TRIM(file_id))
       
-      ! check that the file exists
-      inquire(FILE=file_path,EXIST=file_ok)
-      if(.not.file_ok) then
-         write(*,*)'The file ',file_path(1:LEN_TRIM(file_path))
-         write(*,*)'was not found by sugas_corrk.F90.'
-         write(*,*)'Are you sure you have absorption data for these bands?'
-         call abort
-      endif
+         ! check that the file exists
+         inquire(FILE=file_path,EXIST=file_ok)
+         if(.not.file_ok) then
+            write(*,*)'The file ',file_path(1:LEN_TRIM(file_path))
+            write(*,*)'was not found by sugas_corrk.F90.'
+            write(*,*)'Are you sure you have absorption data for these bands?'
+            call abort
+         endif
+         
+         open(111,file=file_path(1:LEN_TRIM(file_path)),form='formatted')
+         read(111,*) gasi8
+         close(111)
       
-      open(111,file=file_path(1:LEN_TRIM(file_path)),form='formatted')
-      read(111,*) gasi8
-      close(111)
-      
-      do nw=1,L_NSPECTI
-         fzeroi(nw) = 0.
-      end do
-      do nw=1,L_NSPECTV
-         fzerov(nw) = 0.
-      end do
+         do nw=1,L_NSPECTI
+            fzeroi(nw) = 0.
+         end do
+         do nw=1,L_NSPECTV
+            fzerov(nw) = 0.
+         end do
+
+      else
+         print*,'Infrared corrk gaseous absorption is set to zero.'
+         gasi8(:,:,:,:,:)=0.0
+      endif
 
 !     Take log10 of the values - this is what we will interpolate.
@@ -440,4 +473,11 @@
       end do
 
+      do igas=1,ngasmx
+         if(gnom(igas).eq.'H2_')then 
+            call interpolateH2H2(500.D+0,250.D+0,17500.D+0,testH2,.true.)
+         endif
+      enddo
+
+
       return
     end subroutine sugas_corrk
Index: /trunk/LMDZ.GENERIC/libf/phystd/surface_nature.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/surface_nature.F	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/surface_nature.F	(revision 253)
@@ -0,0 +1,66 @@
+      SUBROUTINE surface_nature(obliquit,qsurf,qsurfliquid
+     &   ,qsurfsnow,rnat,oceanarea)
+      IMPLICIT none
+
+!==================================================================
+!     
+!     Purpose
+!     -------
+!     Defines a few things
+!     
+!     Authors
+!     ------- 
+!     B. Charnay (2010)
+!     
+!     Called by
+!     ---------
+!     physiq.F
+!     
+!     Calls
+!     -----
+!     none
+!
+!     Notes
+!     -----
+!     rnat is terrain type: 0-ocean; 1-continent; 2-continental ice
+!     
+!==================================================================
+
+#include "dimensions.h"
+#include "dimphys.h"
+#include "comcstfi.h"
+#include "callkeys.h"
+#include "tracer.h"
+#include "fisice.h"
+#include "comgeomfi.h"
+#include "surfdat.h"
+#include "comsoil.h"
+
+	REAL qsurf(ngridmx,nqmx),ps(ngridmx)
+	REAL qsurfliquid(ngridmx)
+	REAL qsurfsnow(ngridmx)
+	INTEGER iq, ig
+	INTEGER rnat(ngridmx)
+ 	REAL oceanarea
+	REAL obliquit
+
+	do ig=1,ngridmx
+           rnat(ig)=1
+           dryness(ig)=1        !(coefficient for evaporation)
+           if (inertiedat(ig,1).gt.1E4) then
+              rnat(ig)=0
+           end if
+	end do
+
+! surface of all the oceans
+        
+        oceanarea=0.
+	do ig=1,ngridmx
+           if (rnat(ig).eq.0)then
+              oceanarea=oceanarea+area(ig)
+           end if
+	enddo
+
+        return
+        end
+
Index: /trunk/LMDZ.GENERIC/libf/phystd/tabfi.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/tabfi.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/tabfi.F	(revision 253)
@@ -102,13 +102,13 @@
 c----------------------------------------------
       year_day = 669.           ! length of year (sols) ~668.6
-      periheli = 206.66         ! min. Star-Planet distance (Mkm) ~206.66
-      aphelie = 249.22          ! max. Star-Planet distance (Mkm) ~249.22
-      peri_day =  485.          ! date of perihelion (sols since N. spring)
+      periastr = 206.66         ! min. Star-Planet distance (Mkm) ~206.66
+      apoastr = 249.22          ! max. Star-Planet distance (Mkm) ~249.22
+      peri_day =  485.          ! date of periastron (sols since N. spring)
       obliquit = 25.19          ! Obliquity of the planet (deg) ~25.19
 
 c additional for stokes.F added by RDW
 c-------------------------------------
-      molrad=2.2e-10   ! CO2
-      visc=1.e-5       ! CO2
+!      molrad=2.2e-10   ! CO2
+!      visc=1.e-5       ! CO2
 
 c Boundary layer and turbulence
@@ -180,6 +180,6 @@
 c Informations about planet for the physics only
       year_day = tab_cntrl(tab0+14)
-      periheli = tab_cntrl(tab0+15)
-      aphelie = tab_cntrl(tab0+16)
+      periastr = tab_cntrl(tab0+15)
+      apoastr = tab_cntrl(tab0+16)
       peri_day = tab_cntrl(tab0+17)
       obliquit = tab_cntrl(tab0+18)
@@ -239,6 +239,6 @@
 
       write(*,5) '(14)       year_day',tab_cntrl(tab0+14),year_day
-      write(*,5) '(15)       periheli',tab_cntrl(tab0+15),periheli
-      write(*,5) '(16)        aphelie',tab_cntrl(tab0+16),aphelie
+      write(*,5) '(15)       periastr',tab_cntrl(tab0+15),periastr
+      write(*,5) '(16)        apoastr',tab_cntrl(tab0+16),apoastr
       write(*,5) '(17)       peri_day',tab_cntrl(tab0+17),peri_day
       write(*,5) '(18)       obliquit',tab_cntrl(tab0+18),obliquit
@@ -288,10 +288,10 @@
       write(*,*) '(27)        tauvis : mean dust vis. reference ',
      &           'opacity'
-      write(*,*) '(35)         volcapa : soil volumetric heat capacity'
-      write(*,*) '(18)        obliquit : planet obliquity (deg)'
-      write(*,*) '(17)      peri_day : perihelion date (sol since Ls=0)'
-      write(*,*) '(15)      periheli : min. sun-mars dist (Mkm)'
-      write(*,*) '(16)      aphelie  : max. sun-mars dist (Mkm)'
-      write(*,*) '(14)      year_day : length of year (in sols)'
+      write(*,*) '(35)      volcapa : soil volumetric heat capacity'
+      write(*,*) '(18)     obliquit : planet obliquity (deg)'
+      write(*,*) '(17)     peri_day : periastron date (sols since Ls=0)'
+      write(*,*) '(15)     periastr : min. star-planet dist (Mkm)'
+      write(*,*) '(16)     apoastr  : max. star-planet (Mkm)'
+      write(*,*) '(14)     year_day : length of year (in sols)'
       write(*,*) '(5) rad : radius of the planet (m)'
       write(*,*) '(6) omeg : planet rotation rate (rad/s)'
@@ -445,21 +445,21 @@
           write(*,*) ' peri_day (new value):',peri_day
 
-        else if (modif(1:len_trim(modif)) .eq. 'periheli') then
-          write(*,*) 'current value:',periheli
-          write(*,*) 'perihelion should be 206.66 on current Mars'
-          write(*,*) 'enter new value:'
- 117      read(*,*,iostat=ierr) periheli
+        else if (modif(1:len_trim(modif)) .eq. 'periastr') then
+          write(*,*) 'current value:',periastr
+          write(*,*) 'periastr should be 206.66 on present-day Mars'
+          write(*,*) 'enter new value:'
+ 117      read(*,*,iostat=ierr) periastr
           if(ierr.ne.0) goto 117
           write(*,*) 
-          write(*,*) ' periheli (new value):',periheli
- 
-        else if (modif(1:len_trim(modif)) .eq. 'aphelie') then
-          write(*,*) 'current value:',aphelie
-          write(*,*) 'aphelion should be 249.22 on current Mars'
-          write(*,*) 'enter new value:'
- 118      read(*,*,iostat=ierr) aphelie
+          write(*,*) ' periastr (new value):',periastr
+ 
+        else if (modif(1:len_trim(modif)) .eq. 'apoastr') then
+          write(*,*) 'current value:',apoastr
+          write(*,*) 'apoastr should be 249.22 on present-day Mars'
+          write(*,*) 'enter new value:'
+ 118      read(*,*,iostat=ierr) apoastr
           if(ierr.ne.0) goto 118
           write(*,*) 
-          write(*,*) ' aphelie (new value):',aphelie
+          write(*,*) ' apoastr (new value):',apoastr
  
         else if (modif(1:len_trim(modif)) .eq. 'volcapa') then
@@ -556,6 +556,6 @@
  
       write(*,5) '(14)       year_day',tab_cntrl(tab0+14),year_day
-      write(*,5) '(15)       periheli',tab_cntrl(tab0+15),periheli
-      write(*,5) '(16)        aphelie',tab_cntrl(tab0+16),aphelie
+      write(*,5) '(15)       periastr',tab_cntrl(tab0+15),periastr
+      write(*,5) '(16)        apoastr',tab_cntrl(tab0+16),apoastr
       write(*,5) '(17)       peri_day',tab_cntrl(tab0+17),peri_day
       write(*,5) '(18)       obliquit',tab_cntrl(tab0+18),obliquit
Index: unk/LMDZ.GENERIC/libf/phystd/testphys1d.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/testphys1d.F	(revision 252)
+++ 	(revision )
@@ -1,743 +1,0 @@
-      PROGRAM testphys1d
-
-      use radcommon_h, only: tauvis
-! to use  'getin'
-      USE ioipsl_getincom 
-
-      IMPLICIT NONE
-
-!==================================================================
-!     
-!     Purpose
-!     -------
-!     Run the physics package of the universal model in a 1D column.
-!     
-!     It can be compiled with a command like (e.g. for 25 layers):
-!                                  "makegcm -p mars -d 25 testphys1d"
-!     It requires the files "callphys.def", "z2sig.def",
-!     "traceur.def", and "run1d.def" with a line "INCLUDEDEF=callphys.def"
-!
-!     Authors
-!     -------
-!     Frederic Hourdin
-!     R. Fournier
-!     F. Forget
-!     F. Montmessin (water ice added)
-
-!==================================================================
-
-#include "dimensions.h"
-#include "dimphys.h"
-#include "comgeomfi.h"
-#include "surfdat.h"
-#include "comsoil.h"
-#include "comdiurn.h"
-#include "callkeys.h"
-#include "comcstfi.h"
-#include "planete.h"
-#include "comsaison.h"
-#include "control.h"
-#include "comvert.h"
-#include "netcdf.inc"
-#include "comg1d.h"
-#include "watercap.h"
-#include "fisice.h"
-#include "logic.h"
-#include "advtrac.h"
-
-c --------------------------------------------------------------
-c  Declarations
-c --------------------------------------------------------------
-c
-      INTEGER unitstart      ! unite d'ecriture de "startfi"
-      INTEGER nlayer,nlevel,nsoil,ndt
-      INTEGER ilayer,ilevel,isoil,idt,iq
-      LOGICAl firstcall,lastcall
-c
-      INTEGER day0          ! date initial (sol ; =0 a Ls=0)
-      REAL day           ! date durant le run
-      REAL time             ! time (0<time<1 ; time=0.5 a midi)
-      REAL play(nlayermx)   ! Pressure at the middle of the layers (Pa)
-      REAL plev(nlayermx+1) ! intermediate pressure levels (pa)
-      REAL psurf,tsurf      
-      REAL u(nlayermx),v(nlayermx)  ! zonal, meridional wind
-      REAL gru,grv   ! prescribed "geostrophic" background wind
-      REAL temp(nlayermx)   ! temperature at the middle of the layers
-      REAL q(nlayermx,nqmx) ! tracer mixing ratio (e.g. kg/kg)
-      REAL qsurf(nqmx)      ! tracer surface budget (e.g. kg.m-2)
-      REAL tsoil(nsoilmx)   ! subsurface soik temperature (K)
-!      REAL co2ice           ! co2ice layer (kg.m-2) !not used anymore
-      integer :: i_co2_ice=0  ! tracer index of co2 ice
-      integer :: i_h2o_ice=0  ! tracer index of co2 ice
-      REAL emis             ! surface layer
-      REAL q2(nlayermx+1)   ! Turbulent Kinetic Energy
-      REAL zlay(nlayermx)   ! altitude estimee dans les couches (km)
-
-c    Physical and dynamical tandencies (e.g.  m.s-2, K/s, Pa/s)
-      REAL du(nlayermx),dv(nlayermx),dtemp(nlayermx)
-      REAL dudyn(nlayermx),dvdyn(nlayermx),dtempdyn(nlayermx)
-      REAL dpsurf    
-      REAL dq(nlayermx,nqmx)
-      REAL dqdyn(nlayermx,nqmx)
-
-c   Various intermediate variables
-!      INTEGER thermo
-      REAL zls
-      REAL phi(nlayermx),h(nlayermx),s(nlayermx)
-      REAL pks, ptif, w(nlayermx)
-      REAL qtotinit, mqtot(nqmx),qtot
-      INTEGER ierr, aslun
-      REAL tmp1(0:nlayermx),tmp2(0:nlayermx)
-      Logical  tracerdyn
-      integer :: nq=1 ! number of tracers
-
-      character*2 str2
-      character (len=7) :: str7
-
-      logical oldcompare, earthhack,saveprofile
-
-!     added by RW for zlay computation
-      real Hscale, rho, dz
-
-
-!     added by RDW to allow variations in cp with location
-      REAL cpp3D(ngridmx,nlayermx)   ! specific heat capacity at const. pressure
-      REAL rcp3D(ngridmx,nlayermx)   ! R / specific heat capacity
-
-c=======================================================================
-
-c=======================================================================
-c INITIALISATION
-c=======================================================================
-
-      saveprofile=.true.
-
-c ------------------------------------------------------
-c  Default values for constants (corresponding to Mars)
-c ------------------------------------------------------
-
-      pi=2.E+0*asin(1.E+0)
-
-c     Constante de la Planete Mars
-c     ----------------------------
-      rad=3397200.               ! rayon de mars (m)  ~3397200 m
-      daysec=88775.              ! duree du sol (s)  ~88775 s
-      omeg=4.*asin(1.)/(daysec)  ! vitesse de rotation (rad.s-1)
-      g=3.72                     ! gravite (m.s-2) ~3.72  
-      mugaz=43.49                ! Masse molaire de l'atm (g.mol-1) ~43.49
-      rcp=.256793                ! = r/cp  ~0.256793
-      r= 8.314511E+0 *1000.E+0/mugaz
-      cpp= r/rcp
-      year_day = 669           ! duree de l'annee (sols) ~668.6
-      periheli = 206.66          ! dist.min. soleil-mars (Mkm) ~206.66
-      aphelie = 249.22           ! dist.max. soleil-mars (Mkm) ~249.22
-      peri_day =  485.           ! date du perihelie (sols depuis printemps)
-      obliquit = 25.2           ! Obliquite de la planete (deg) ~25.2         
- 
-c     Parametres Couche limite et Turbulence 
-c     --------------------------------------
-      z0 =  1.e-2                ! surface roughness (m) ~0.01 
-      emin_turb = 1.e-6          ! energie minimale ~1.e-8
-      lmixmin = 30               ! longueur de melange ~100
- 
-c     propriete optiques des calottes et emissivite du sol
-c     ----------------------------------------------------
-      emissiv= 0.95              ! Emissivite du sol martien ~.95
-      emisice(1)=0.95            ! Emissivite calotte nord
-      emisice(2)=0.95            ! Emissivite calotte sud  
-
-      albedice(1)=0.5            ! Albedo calotte nord
-      albedice(2)=0.5            ! Albedo calotte sud
-      iceradius(1) = 100.e-6     ! mean scat radius of CO2 snow (north)
-      iceradius(2) = 100.e-6     ! mean scat radius of CO2 snow (south)
-      dtemisice(1) = 2.          ! time scale for snow metamorphism (north)
-      dtemisice(2) = 2.          ! time scale for snow metamorphism (south
-      hybrid=.false.
-
-!     Constants for stokes.F90
-      molrad=2.2e-10 ! CO2 only!!!
-      visc=1.e-5     ! CO2 only!!!
-
-      print*,'Warning, stokes.F constants are defined for pure CO2.'
-
-
-
-c ------------------------------------------------------
-c  Load parameters from "run.def" 
-c ------------------------------------------------------
-
-! also check if 'run1d.def' file is around (otherwise reading parameters
-! from callphys.def via getin() routine won't work.
-      open(90,file='run.def',status='old',form='formatted',
-     &     iostat=ierr)
-      if (ierr.ne.0) then
-        write(*,*) 'Cannot find required file "run.def"'
-        write(*,*) '  (which should contain some input parameters'
-        write(*,*) '   along with the following line:'
-        write(*,*) '   INCLUDEDEF=callphys.def'
-        write(*,*) '   )'
-        write(*,*) ' ... might as well stop here ...'
-        stop
-      else
-        close(90)
-      endif
-
-! check if we are going to run with or without tracers
-      write(*,*) "Run with or without tracer transport ?"
-      tracer=.false. ! default value
-      call getin("tracer",tracer)
-      write(*,*) " tracer = ",tracer
-
-! while we're at it, check if there is a 'traceur.def' file
-! and preocess it, if necessary. Otherwise initialize tracer names
-      if (tracer) then
-      ! load tracer names from file 'traceur.def'
-        open(90,file='traceur.def',status='old',form='formatted',
-     &       iostat=ierr)
-        if (ierr.eq.0) then
-          write(*,*) "testphys1d: Reading file traceur.def"
-          ! read number of tracers:
-          read(90,*,iostat=ierr) nq
-          if (ierr.ne.0) then
-            write(*,*) "testphys1d: error reading number of tracers"
-            write(*,*) "   (first line of traceur.def) "
-            stop
-          else
-            ! check that the number of tracers is indeed nqmx
-            if (nq.ne.nqmx) then
-              write(*,*) "testphys1d: error, wrong number of tracers:"
-              write(*,*) "nq=",nq," whereas nqmx=",nqmx
-              stop
-            endif
-          endif
-        
-          ! initialize advection schemes to Van-Leer for all tracers
-          do iq=1,nq
-            iadv(iq)=3 ! Van-Leer
-          enddo
-        
-          do iq=1,nq
-          ! minimal version, just read in the tracer names, 1 per line
-            read(90,*,iostat=ierr) tnom(iq)
-            if (ierr.ne.0) then
-              write(*,*) 'testphys1d: error reading tracer names...'
-              stop
-            endif
-          enddo !of do iq=1,nq
-! check for co2_ice / h2o_ice tracers:
-         i_co2_ice=0
-         i_h2o_ice=0
-         do iq=1,nq
-           if (tnom(iq)=="co2_ice") then
-             i_co2_ice=iq
-           elseif (tnom(iq)=="h2o_ice") then
-             i_h2o_ice=iq
-           endif
-         enddo
-         !if (i_co2_ice==0) then
-         !  write(*,*) "testphys1d: error, we need a 'co2_ice' tracer"
-         !  write(*,*) "   (add one to traceur.def)"
-         !  stop
-         !endif
-        else
-          write(*,*) 'Cannot find required file "traceur.def"'
-          write(*,*) ' If you want to run with tracers, I need it'
-          write(*,*) ' ... might as well stop here ...'
-          stop
-        endif
-        close(90)
-
-      else
-      ! we still need to set (dummy) tracer names for physdem1
-        nq=nqmx
-        do iq=1,nq
-          write(str7,'(a1,i2.2)')'q',iq
-          tnom(iq)=str7
-        enddo
-        ! actually, we'll need at least one "co2_ice" tracer
-        ! (for surface CO2 ice)
-        tnom(1)="co2_ice"
-        i_co2_ice=1
-      endif ! of if (tracer)
-
-c  Date et heure locale du debut du run
-c  ------------------------------------
-c    Date (en sols depuis le solstice de printemps) du debut du run
-      day0 = 0 ! default value for day0
-      write(*,*) 'Initial date (in martian sols ; =0 at Ls=0)?'
-      call getin("day0",day0)
-      day=float(day0)
-      write(*,*) " day0 = ",day0
-c  Heure de demarrage
-      time=0 ! default value for time
-      write(*,*)'Initial local time (in hours, between 0 and 24)?'
-      call getin("time",time)
-      write(*,*)" time = ",time
-      time=time/24.E+0 ! convert time (hours) to fraction of sol
-
-c  Discretisation (Definition de la grille et des pas de temps)
-c  --------------
-c
-      nlayer=nlayermx
-      nlevel=nlayer+1
-      nsoil=nsoilmx
-
-      day_step=48 ! default value for day_step
-      PRINT *,'Number of time steps per sol ?'
-      call getin("day_step",day_step)
-      write(*,*) " day_step = ",day_step
-
-      ndt=10 ! default value for ndt
-      PRINT *,'Number of sols to run ?'
-      call getin("ndt",ndt)
-      write(*,*) " ndt = ",ndt
-
-      ndt=ndt*day_step     
-      dtphys=daysec/day_step  
-c Pression de surface sur la planete
-c ------------------------------------
-c
-      psurf=610. ! default value for psurf
-      PRINT *,'Surface pressure (Pa) ?'
-      call getin("psurf",psurf)
-      write(*,*) " psurf = ",psurf
-c Pression de reference
-!      pa=20.
-!      preff=610. ! these values are not needed in 1D  
-
-c Gravity of planet
-c -----------------
-      g=3.72 ! default value for g
-      PRINT *,'Gravity ?'
-      call getin("g",g)
-      write(*,*) " g = ",g
-
-c Molar mass of atmosphere
-c ------------------------
-      mugaz=44.01 ! default value = for CO2
-      PRINT *,'Molar mass of atmosphere ?'
-      call getin("mugaz",mugaz)
-      write(*,*) " mugaz = ",mugaz
-
-c Specific heat capacity of atmosphere
-c ------------------------------------
-      cpp=744.0 ! default value = for CO2
-      PRINT *,'Specific heat capacity of atmosphere ?'
-      call getin("cpp",cpp)
-      write(*,*) " cpp = ",cpp
-
-      r= 8.314511E+0 *1000.E+0/mugaz
-      rcp=r/cpp
-
-c Proprietes des poussiere aerosol
-c --------------------------------
-      tauvis=0.2 ! default value for tauvis
-      print *,'Reference dust opacity at 700 Pa ?'
-      call getin("tauvis",tauvis)
-      write(*,*) " tauvis = ",tauvis
- 
-c  latitude/longitude
-c  ------------------
-      lati(1)=0 ! default value for lati(1)
-      PRINT *,'latitude (in degrees) ?'
-      call getin("latitude",lati(1))
-      write(*,*) " latitude = ",lati(1)
-      lati(1)=lati(1)*pi/180.E+0
-      long(1)=0.E+0
-      long(1)=long(1)*pi/180.E+0
-
-c  periastron/apoastron
-c  --------------------
-      periheli=227.94
-      aphelie=227.94 ! default=mean martian values
-      PRINT *,'periastron (in AU) ?'
-      call getin("periheli",periheli)
-      write(*,*) "periastron = ",periheli
-      periheli=periheli*149.598 ! AU to Mkm
-      PRINT *,'apoastron (in AU) ?'
-      call getin("aphelie",aphelie)
-      write(*,*) "apoastron = ",aphelie
-      aphelie=aphelie*149.598 ! AU to Mkm
-
-c  obliquity
-c  ---------
-      obliquit=0.0! default=zero in 1d
-      PRINT *,'obliquity (in AU) ?'
-      call getin("obliquit",obliquit)
-      write(*,*) "obliquity = ",obliquit
-
-c  Initialisation albedo / inertie du sol
-c  --------------------------------------
-      albedodat(1)=0.2 ! default value for albedodat
-      PRINT *,'Albedo of bare ground ?'
-      call getin("albedo",albedodat(1))
-      write(*,*) " albedo = ",albedodat(1)
-
-      inertiedat(1,1)=400 ! default value for inertiedat
-      PRINT *,'Soil thermal inertia (SI) ?'
-      call getin("inertia",inertiedat(1,1))
-      write(*,*) " inertia = ",inertiedat(1,1)
-c
-c  pour le schema d'ondes de gravite
-c  ---------------------------------
-c
-      zmea(1)=0.E+0
-      zstd(1)=0.E+0
-      zsig(1)=0.E+0
-      zgam(1)=0.E+0
-      zthe(1)=0.E+0
-
-c    Initialisation des traceurs
-c    ---------------------------
-
-      DO iq=1,nqmx
-        DO ilayer=1,nlayer
-           q(ilayer,iq) = 0.
-        ENDDO
-      ENDDO
-     
-      DO iq=1,nqmx
-        qsurf(iq) = 0.
-      ENDDO
-
-c   Initialisation speciales "physiq"
-c   ---------------------------------
-c   la surface de chaque maille est inutile en 1D --->
-      area(1)=1.E+0
-
-c   le geopotentiel au sol est inutile en 1D car tout est controle
-c   par la pression de surface --->
-      phisfi(1)=0.E+0
-
-c  "inifis" reproduit un certain nombre d'initialisations deja faites
-c  + lecture des clefs de callphys.def
-c  + calcul de la frequence d'appel au rayonnement
-c  + calcul des sinus et cosinus des longitude latitude
-
-!Mars possible issue with dtphys in input and include!!!
-      CALL inifis(1,llm,day0,daysec,dtphys,
-     .            lati,long,area,rad,g,r,cpp)
-c   Initialisation pour prendre en compte les vents en 1-D
-c   ------------------------------------------------------
-      ptif=2.E+0*omeg*sinlat(1)
- 
-
-c    vent geostrophique
-      gru=10. ! default value for gru
-      PRINT *,'zonal eastward component of the geostrophic wind (m/s) ?'
-      call getin("u",gru)
-      write(*,*) " u = ",gru
-      grv=0. !default value for grv
-      PRINT *,'meridional northward component of the geostrophic',
-     &' wind (m/s) ?'
-      call getin("v",grv)
-      write(*,*) " v = ",grv
-
-c     Initialisation des vents  au premier pas de temps
-      DO ilayer=1,nlayer
-         u(ilayer)=gru
-         v(ilayer)=grv
-      ENDDO
-
-c     energie cinetique turbulente
-      DO ilevel=1,nlevel
-         q2(ilevel)=0.E+0
-      ENDDO
-
-c  emissivity / surface co2 ice ( + h2o ice??)
-c  -------------------------------------------
-      emis=emissiv ! default value for emissivity
-      PRINT *,'Emissivity of bare ground ?'
-      call getin("emis",emis)
-      write(*,*) " emis = ",emis
-      emissiv=emis ! we do this so that condense_co2 sets things to the right
-                   ! value if there is no snow
-
-      if(i_co2_ice.gt.0)then
-         qsurf(i_co2_ice)=0 ! default value for co2ice
-         print*,'Initial CO2 ice on the surface (kg.m-2)'
-         call getin("co2ice",qsurf(i_co2_ice))
-         write(*,*) " co2ice = ",qsurf(i_co2_ice)
-         IF (qsurf(i_co2_ice).ge.1.E+0) THEN
-            ! if we have some CO2 ice on the surface, change emissivity
-            if (lati(1).ge.0) then ! northern hemisphere
-              emis=emisice(1)
-            else ! southern hemisphere
-              emis=emisice(2)
-            endif
-         ENDIF
-      endif
-
-c  calcul des pressions et altitudes en utilisant les niveaux sigma
-c  ----------------------------------------------------------------
-
-c    Vertical Coordinates
-c    """"""""""""""""""""
-      hybrid=.true.
-      PRINT *,'Hybrid coordinates ?'
-      call getin("hybrid",hybrid)
-      write(*,*) " hybrid = ", hybrid
-
-      CALL disvert
-
-      ! we want only the scale height from z2sig, in order to compute zlay
-      open(91,file="z2sig.def",form='formatted')
-      read(91,*) Hscale
-      close(91)
-
-      DO ilevel=1,nlevel
-        plev(ilevel)=ap(ilevel)+psurf*bp(ilevel)
-      ENDDO
-
-      DO ilayer=1,nlayer
-        play(ilayer)=aps(ilayer)+psurf*bps(ilayer)
-      ENDDO
-
-      DO ilayer=1,nlayer
-!        zlay(ilayer)=-300.E+0 *r*log(play(ilayer)/plev(1))
-!     &   /g
-        zlay(ilayer)=-1000.0*Hscale*log(play(ilayer)/plev(1))
-      ENDDO
-
-
-c  profil de temperature au premier appel
-c  --------------------------------------
-      pks=psurf**rcp
-
-c altitude en km dans profile: on divise zlay par 1000
-      tmp1(0)=0.E+0
-      DO ilayer=1,nlayer
-        tmp1(ilayer)=zlay(ilayer)/1000.E+0
-      ENDDO
-      call profile(nlayer+1,tmp1,tmp2)
-
-      tsurf=tmp2(0)
-      DO ilayer=1,nlayer
-        temp(ilayer)=tmp2(ilayer)
-      ENDDO
-      
-
-
-! Initialize soil properties and temperature
-! ------------------------------------------
-      volcapa=1.e6 ! volumetric heat capacity
-      DO isoil=1,nsoil
-         inertiedat(1,isoil)=inertiedat(1,1) ! soil thermal inertia
-         tsoil(isoil)=tsurf  ! soil temperature
-      ENDDO
-
-! Initialize depths
-! -----------------
-      do isoil=0,nsoil-1
-        mlayer(isoil)=2.e-4*(2.**(isoil-0.5)) ! mid-layer depth
-      enddo
-      do isoil=1,nsoil
-        layer(isoil)=2.e-4*(2.**(isoil-1)) ! layer depth
-      enddo
-
-c    Initialisation pour les sorties GRADS dans "g1d.dat" et "g1d.ctl"
-c    ----------------------------------------------------------------
-c    (effectuee avec "writeg1d" a partir de "physiq.F"
-c    ou tout autre subroutine physique, y compris celle ci).
-
-        g1d_nlayer=nlayer
-        g1d_nomfich='g1d.dat'
-        g1d_unitfich=40
-        g1d_nomctl='g1d.ctl'
-        g1d_unitctl=41
-        g1d_premier=.true.
-        g2d_premier=.true.
-
-c  Ecriture de "startfi"
-c  --------------------
-c  (Ce fichier sera aussitot relu au premier
-c   appel de "physiq", mais il est necessaire pour passer
-c   les variables purement physiques a "physiq"...
-
-      call physdem1("startfi.nc",long,lati,nsoilmx,nqmx,
-     .              dtphys,float(day0),
-     .              time,tsurf,tsoil,emis,q2,qsurf,
-     .              area,albedodat,inertiedat,zmea,zstd,zsig,zgam,zthe)
-c=======================================================================
-c  BOUCLE TEMPORELLE DU MODELE 1D 
-c=======================================================================
-
-      firstcall=.true.
-      lastcall=.false.
-
-      DO idt=1,ndt
-        IF (idt.eq.ndt-day_step-1) then       !test
-         lastcall=.true.
-         call solarlong(day*1.0,zls)
-         write(103,*) 'Ls=',zls*180./pi
-         write(103,*) 'Lat=', lati(1)*180./pi
-         write(103,*) 'Tau=', tauvis/700*psurf
-         write(103,*) 'RunEnd - Atmos. Temp. File'
-         write(103,*) 'RunEnd - Atmos. Temp. File'
-         write(104,*) 'Ls=',zls*180./pi
-         write(104,*) 'Lat=', lati(1)
-         write(104,*) 'Tau=', tauvis/700*psurf
-         write(104,*) 'RunEnd - Atmos. Temp. File'
-        ENDIF
-
-c    calcul du geopotentiel 
-c     ~~~~~~~~~~~~~~~~~~~~~
-
-        if(nonideal)then
-
-           DO ilayer=1,nlayer
-              call calc_cpp3d(cpp3D(1,ilayer),
-     $             rcp3D(1,ilayer),temp(ilayer),play(ilayer))
-           ENDDO
-
-           DO ilayer=1,nlayer
-              s(ilayer)=(aps(ilayer)/psurf+bps(ilayer))**rcp3D(1,ilayer)
-              h(ilayer)=cpp3D(1,ilayer)*temp(ilayer)/(pks*s(ilayer))
-           ENDDO
-
-        else
-           DO ilayer=1,nlayer
-              s(ilayer)=(aps(ilayer)/psurf+bps(ilayer))**rcp
-              h(ilayer)=cpp*temp(ilayer)/(pks*s(ilayer))
-           ENDDO
-        endif
-!      DO ilayer=1,nlayer
-!        s(ilayer)=(aps(ilayer)/psurf+bps(ilayer))**rcp
-!        h(ilayer)=cpp*temp(ilayer)/(pks*s(ilayer))
-!      ENDDO
-      phi(1)=pks*h(1)*(1.E+0-s(1))
-      DO ilayer=2,nlayer
-         phi(ilayer)=phi(ilayer-1)+
-     &               pks*(h(ilayer-1)+h(ilayer))*.5E+0
-     &                  *(s(ilayer-1)-s(ilayer))
-
-      ENDDO
-
-c       appel de la physique
-c       --------------------
-
-      CALL physiq (1,llm,nqmx,
-     ,     firstcall,lastcall,
-     ,     day,time,dtphys,
-     ,     plev,play,phi,
-     ,     u, v,temp, q,  
-     ,     w,
-C - sorties
-     s     du, dv, dtemp, dq,dpsurf,tracerdyn)
-
-
-c       evolution du vent : modele 1D
-c       -----------------------------
- 
-c       la physique calcule les derivees temporelles de u et v.
-c       on y rajoute betement un effet Coriolis.
-c
-c       DO ilayer=1,nlayer
-c          du(ilayer)=du(ilayer)+ptif*(v(ilayer)-grv)
-c          dv(ilayer)=dv(ilayer)+ptif*(-u(ilayer)+gru)
-c       ENDDO
-
-c       Pour certain test : pas de coriolis a l'equateur
-c       if(lati(1).eq.0.) then
-          DO ilayer=1,nlayer
-             du(ilayer)=du(ilayer)+ (gru-u(ilayer))/1.e4
-             dv(ilayer)=dv(ilayer)+ (grv-v(ilayer))/1.e4
-          ENDDO
-c       end if
-c      
-c
-c       Calcul du temps au pas de temps suivant
-c       ---------------------------------------
-        firstcall=.false.
-        time=time+dtphys/daysec
-        IF (time.gt.1.E+0) then
-            time=time-1.E+0
-            day=day+1
-        ENDIF
-
-c       calcul des vitesses et temperature au pas de temps suivant
-c       ----------------------------------------------------------
-
-        DO ilayer=1,nlayer
-           u(ilayer)=u(ilayer)+dtphys*du(ilayer)
-           v(ilayer)=v(ilayer)+dtphys*dv(ilayer)
-           temp(ilayer)=temp(ilayer)+dtphys*dtemp(ilayer)
-        ENDDO
-
-c       calcul des pressions au pas de temps suivant
-c       ----------------------------------------------------------
-
-           psurf=psurf+dtphys*dpsurf   ! evolution de la pression de surface
-           DO ilevel=1,nlevel
-             plev(ilevel)=ap(ilevel)+psurf*bp(ilevel)
-           ENDDO
-           DO ilayer=1,nlayer
-             play(ilayer)=aps(ilayer)+psurf*bps(ilayer)
-           ENDDO
-
-c       calcul traceur au pas de temps suivant
-c       --------------------------------------
-           
-           !print*,'dq in testphys1d=',dq*dtphys
-           !print*,'q in testphys1d=',q
-
-        DO iq = 1, nqmx
-          DO ilayer=1,nlayer
-             q(ilayer,iq)=q(ilayer,iq)+dtphys*dq(ilayer,iq)
-          ENDDO
-        END DO
-
-      ENDDO   ! fin de la boucle temporelle
-
-c    ========================================================
-c    GESTION DES SORTIE
-c    ========================================================
-
-c    fermeture pour conclure les sorties format grads dans "g1d.dat"
-c    et "g1d.ctl" (effectuee avec "writeg1d" a partir de "physiq.F"
-c    ou tout autre subroutine physique, y compris celle ci).
-
-
-! save temperature profile
-      if(saveprofile)then
-         OPEN(12,file='profile.out',form='formatted')
-         write(12,*) tsurf
-         DO ilayer=1,nlayermx
-	    write(12,*) temp(ilayer)
-         ENDDO
-         CLOSE(12)
-      endif
-
-      ! here we compute altitude CORRECTLY!!!
-
-!      print*,'zlay=',zlay/1000.
-!      rho = play(1)/(R*tsurf)
-!      zlay(1)=(plev(1)-plev(2))/(g*rho)
-!      do ilayer=2,nlayer
-!         rho  = play(ilayer)/(R*temp(ilayer))
-!         rho  = play(ilayer)/(R*230.0)
-!         dz = (plev(ilayer-1)-plev(ilayer))/(g*rho)
-!         zlay(ilayer)=zlay(ilayer-1)+dz
-!      enddo
-!      print*,'zlay=',zlay/1000.
-!      stop
-
-c        CALL endg1d(1,nlayer,zphi/(g*1000.),ndt)
-        CALL endg1d(1,nlayer,zlay/1000.,ndt)
-
-c    ========================================================
-      END
- 
-c***********************************************************************
-c***********************************************************************
-c     Subroutines Bidons utilise seulement en 3D, mais
-c     necessaire a la compilation de testphys1d en 1-D
-
-      subroutine gr_fi_dyn
-      RETURN
-      END
- 
-c***********************************************************************
-c***********************************************************************
-
-#include "../dyn3d/disvert.F"
Index: /trunk/LMDZ.GENERIC/libf/phystd/totalcloudfrac.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/totalcloudfrac.F90	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/totalcloudfrac.F90	(revision 253)
@@ -0,0 +1,70 @@
+      subroutine totalcloudfrac(rneb,totalrneb)
+
+      implicit none
+
+!==================================================================
+!     
+!     Purpose
+!     -------
+!     Calculates the total cloud fraction 
+!     
+!     Authors
+!     -------
+!     Adapted from the LMDTERRE code by B Charnay (2010)
+!     
+!==================================================================
+
+#include "dimensions.h"
+#include "dimphys.h"
+#include "comcstfi.h"
+#include "tracer.h"
+#include "fisice.h"
+#include "comgeomfi.h"
+#include "comdiurn.h"
+
+      real rneb(ngridmx,nlayermx)             ! cloud fraction     
+      real totalrneb(ngridmx)                 ! total cloud fraction 
+
+      integer recovery
+      parameter(recovery=1)
+
+! hypothesis behind recovery. value: 
+! 1 = random recovery
+! 2 = maximal recovery
+! 3 = minimal recovery
+
+
+!     Local variables
+      integer ig, l
+      real clear
+
+      do ig=1,ngridmx
+         totalrneb(ig) = 0.
+
+         if (recovery.eq.1) then
+            clear = (1.-rneb(ig,1))
+            do l=2,nlayermx       
+               clear = clear*(1.-rneb(ig,l))
+            enddo
+            totalrneb(ig) = 1.-clear
+
+         elseif (recovery.eq.2) then
+            totalrneb(ig) = rneb(ig,1)
+            do l=2,nlayermx       
+               totalrneb(ig) = max(rneb(ig,l),totalrneb(ig))
+            enddo
+            
+         elseif (recovery.eq.3) then
+            totalrneb(ig) = rneb(ig,1)
+            do l=2,nlayermx       
+               totalrneb(ig) = min(rneb(ig,l),totalrneb(ig))
+            enddo
+         endif                  ! (recovery=)
+         
+         totalrneb(ig) = min(1.,totalrneb(ig))
+         totalrneb(ig) = max(0.,totalrneb(ig))
+         
+      enddo                     ! (ig=)
+      
+      
+    end subroutine totalcloudfrac
Index: /trunk/LMDZ.GENERIC/libf/phystd/vdifc.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/vdifc.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/vdifc.F	(revision 253)
@@ -1,33 +1,36 @@
-      SUBROUTINE vdifc(ngrid,nlay,nq,ppopsk,
-     $                ptimestep,pcapcal,lecrit,
-     $                pplay,pplev,pzlay,pzlev,pz0,
-     $                pu,pv,ph,pq,ptsrf,pemis,pqsurf,
-     $                pdufi,pdvfi,pdhfi,pdqfi,pfluxsrf,
-     $                pdudif,pdvdif,pdhdif,pdtsrf,pq2,
-     $                pdqdif,pdqsdif)
-
-      use watercommon_h, only : RLVTT
+      subroutine vdifc(ngrid,nlay,nq,rnat,ppopsk,         
+     &     ptimestep,pcapcal,lecrit,                        
+     &     pplay,pplev,pzlay,pzlev,pz0,
+     &     pu,pv,ph,pq,ptsrf,pemis,pqsurf,
+     &     pdufi,pdvfi,pdhfi,pdqfi,pfluxsrf,
+     &     pdudif,pdvdif,pdhdif,pdtsrf,pq2,
+     &     pdqdif,pdqsdif)
+
+      use watercommon_h, only : RLVTT, To, RCPD, mx_eau_sol
 
       implicit none
 
-c=======================================================================
-c
-c   subject:
-c   --------
-c   Turbulent diffusion (mixing) for potential T, U, V and tracer
-c
-c   Shema implicite
-c   On commence par rajouter au variables x la tendance physique
-c   et on resoult en fait:
-c      x(t+1) =  x(t) + dt * (dx/dt)phys(t)  +  dt * (dx/dt)difv(t+1)
-c
-c   author:
-c   ------
-c      Hourdin/Forget/Fournier
-c=======================================================================
-
-c-----------------------------------------------------------------------
-c   declarations:
-c   -------------
+!==================================================================
+!     
+!     Purpose
+!     -------
+!     Turbulent diffusion (mixing) for pot. T, U, V and tracers
+!     
+!     Implicit scheme
+!     We start by adding to variables x the physical tendencies
+!     already computed. We resolve the equation:
+!
+!     x(t+1) =  x(t) + dt * (dx/dt)phys(t)  +  dt * (dx/dt)difv(t+1)
+!     
+!     Authors
+!     ------- 
+!     F. Hourdin, F. Forget, R. Fournier (199X)
+!     R. Wordsworth, B. Charnay (2010)
+!     
+!==================================================================
+
+!-----------------------------------------------------------------------
+!     declarations
+!     ------------
 
 #include "dimensions.h"
@@ -40,8 +43,7 @@
 
 #include "watercap.h"
-c
-c   arguments:
-c   ----------
-
+
+!     arguments
+!     ---------
       INTEGER ngrid,nlay
       REAL ptimestep
@@ -55,22 +57,23 @@
       REAL pdtsrf(ngrid),pcapcal(ngrid)
       REAL pq2(ngrid,nlay+1)
-
-c    Argument added for condensation:
-!      REAL co2ice (ngrid)
+      
+      integer rnat(ngrid)      
+
+!     Arguments added for condensation
       REAL ppopsk(ngrid,nlay)
       logical lecrit
       REAL pz0
 
-c    Traceurs :
+!     Tracers
+!     --------
       integer nq 
-      REAL pqsurf(ngrid,nq)
+      real pqsurf(ngrid,nq)
       real pq(ngrid,nlay,nq), pdqfi(ngrid,nlay,nq) 
       real pdqdif(ngrid,nlay,nq) 
       real pdqsdif(ngrid,nq) 
       
-c   local:
-c   ------
-
-      INTEGER ilev,ig,ilay,nlev
+!     local
+!     -----
+      integer ilev,ig,ilay,nlev
 
       REAL z4st,zdplanck(ngridmx)
@@ -86,62 +89,104 @@
       REAL zc(ngridmx,nlayermx),zd(ngridmx,nlayermx)
       REAL zcst1
-      REAL zu2
-
-      EXTERNAL SSUM,SCOPY
-      REAL SSUM
+      REAL zu2!, a
+      REAL zcq(ngridmx,nlayermx),zdq(ngridmx,nlayermx)
+      REAL evap(ngridmx)
+      REAL zcq0(ngridmx),zdq0(ngridmx)
+      REAL zx_alf1(ngridmx),zx_alf2(ngridmx)
+
       LOGICAL firstcall
       SAVE firstcall
 
-c     variable added for CO2 condensation:
-c     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
-      REAL hh , zhcond(ngridmx,nlayermx)
-      REAL latcond,tcond1mb
-      REAL acond,bcond
-      SAVE acond,bcond
-      DATA latcond,tcond1mb/5.9e5,136.27/
-
-c    Tracers :
-c    ~~~~~~~ 
+!     variables added for CO2 condensation
+!     ------------------------------------
+      REAL hh                   !, zhcond(ngridmx,nlayermx)
+!     REAL latcond,tcond1mb
+!     REAL acond,bcond
+!     SAVE acond,bcond
+!     DATA latcond,tcond1mb/5.9e5,136.27/
+
+!     Tracers
+!     -------
       INTEGER iq
       REAL zq(ngridmx,nlayermx,nqmx)
       REAL zq1temp(ngridmx)
-      REAL rho(ngridmx) ! near surface air density
+      REAL rho(ngridmx)         ! near-surface air density
       REAL qsat(ngridmx)
       DATA firstcall/.true./
       REAL kmixmin
 
-c    ** un petit test de coherence
-c       --------------------------
+!     Variables added for implicit latent heat inclusion
+!     --------------------------------------------------
+      real latconst, dqsat(ngridmx), qsat_temp1, qsat_temp2
+      real z1_Tdry(ngridmx), z2_Tdry(ngridmx)
+      real z1_T(ngridmx), z2_T(ngridmx)
+      real zb_T(ngridmx)
+      real zc_T(ngridmx,nlayermx)
+      real zd_T(ngridmx,nlayermx)
+      real lat1(ngridmx), lat2(ngridmx)
+      real surfh2otot
+      logical surffluxdiag
+      integer isub ! sub-loop for precision
+
+      integer ivap, iice ! also make liq for clarity on surface...
+      save ivap, iice
+
+      real, parameter :: sigma=5.67e-8
+      real, parameter :: karman=0.4
+      real cd0, roughratio
+
+      logical forceWC
+      real masse, Wtot, Wdiff
+
+      real dqsdif_total(ngrid) 
+      real zq0(ngrid) 
+
+      forceWC=.true.
+!      forceWC=.false.
+
+
+!     Coherence test
+!     --------------
 
       IF (firstcall) THEN
-         IF(ngrid.NE.ngridmx) THEN
-            PRINT*,'STOP dans vdifc'
-            PRINT*,'probleme de dimensions :'
-            PRINT*,'ngrid  =',ngrid
-            PRINT*,'ngridmx  =',ngridmx
-            STOP
-         ENDIF
-c        To compute: Tcond= 1./(bcond-acond*log(.0095*p)) (p in pascal)
-         bcond=1./tcond1mb
-         acond=r/latcond
-         PRINT*,'In vdifc: Tcond(P=1mb)=',tcond1mb,' Lcond=',latcond
-         PRINT*,'          acond,bcond',acond,bcond
-
-        firstcall=.false.
+!         IF(ngrid.NE.ngridmx) THEN
+!            PRINT*,'STOP dans vdifc'
+!            PRINT*,'probleme de dimensions :'
+!            PRINT*,'ngrid  =',ngrid
+!            PRINT*,'ngridmx  =',ngridmx
+!            STOP
+!         ENDIF
+!     To compute: Tcond= 1./(bcond-acond*log(.0095*p)) (p in pascal)
+!     bcond=1./tcond1mb
+!     acond=r/latcond
+!     PRINT*,'In vdifc: Tcond(P=1mb)=',tcond1mb,' Lcond=',latcond
+!     PRINT*,'          acond,bcond',acond,bcond
+
+         if(water)then
+!                iliq=igcm_h2o_vap
+                ivap=igcm_h2o_vap
+                iice=igcm_h2o_ice ! simply to make the code legible               
+                                  ! to be generalised later
+         endif
+
+         if(ngridmx.ne.1)then
+            if(nonideal)then
+               print*,'Nonideal doesnt work yet in 3D!!!'
+               call abort
+            endif
+         endif
+
+         firstcall=.false.
       ENDIF
 
-
-
-
-
-c-----------------------------------------------------------------------
-c    1. initialisation
-c    -----------------
+!-----------------------------------------------------------------------
+!     1. Initialisation
+!     -----------------
 
       nlev=nlay+1
 
-c    ** calcul de rho*dz et dt*rho/dz=dt*rho**2 g/dp
-c       avec rho=p/RT=p/ (R Theta) (p/ps)**kappa
-c       ----------------------------------------
+!     Calculate rho*dz and dt*rho/dz=dt*rho**2 g/dp
+!     with rho=p/RT=p/ (R Theta) (p/ps)**kappa
+!     ---------------------------------------------
 
       DO ilay=1,nlay
@@ -151,55 +196,23 @@
       ENDDO
 
-      zcst1=4.*g*ptimestep/(r*r)
+      zcst1=4.*g*ptimestep/(R*R)
       DO ilev=2,nlev-1
          DO ig=1,ngrid
             zb0(ig,ilev)=pplev(ig,ilev)*
-     s      (pplev(ig,1)/pplev(ig,ilev))**rcp /
-     s      (ph(ig,ilev-1)+ph(ig,ilev))
+     s           (pplev(ig,1)/pplev(ig,ilev))**rcp /
+     s           (ph(ig,ilev-1)+ph(ig,ilev))
             zb0(ig,ilev)=zcst1*zb0(ig,ilev)*zb0(ig,ilev)/
-     s      (pplay(ig,ilev-1)-pplay(ig,ilev))
-         ENDDO
-      ENDDO
-      DO ig=1,ngrid
-		 zb0(ig,1)=ptimestep*pplev(ig,1)/(r*ptsrf(ig))
-      ENDDO
-
-c    ** diagnostique pour l'initialisation
-c       ----------------------------------
-
-      IF(lecrit) THEN
-         ig=ngrid/2+1
-         PRINT*,'Pression (mbar) ,altitude (km),u,v,theta, rho dz'
-         DO ilay=1,nlay
-            WRITE(*,'(6f11.5)')
-     s      .01*pplay(ig,ilay),.001*pzlay(ig,ilay),
-     s      pu(ig,ilay),pv(ig,ilay),ph(ig,ilay),za(ig,ilay)
-         ENDDO
-         PRINT*,'Pression (mbar) ,altitude (km),zb'
-         DO ilev=1,nlay
-            WRITE(*,'(3f15.7)')
-     s      .01*pplev(ig,ilev),.001*pzlev(ig,ilev),
-     s      zb0(ig,ilev)
-         ENDDO
-      ENDIF
-
-c     Potential Condensation temperature:
-c     -----------------------------------
-
-c     if (callcond) then 
-c       DO ilev=1,nlay
-c         DO ig=1,ngrid
-c           zhcond(ig,ilev) =
-c    &  (1./(bcond-acond*log(.0095*pplay(ig,ilev))))/ppopsk(ig,ilev)
-c         END DO
-c       END DO
-c     else
-        call zerophys(ngrid*nlay,zhcond)
-c     end if
-
-
-c-----------------------------------------------------------------------
-c   2. ajout des tendances physiques
-c      -----------------------------
+     s           (pplay(ig,ilev-1)-pplay(ig,ilev))
+         ENDDO
+      ENDDO
+      DO ig=1,ngrid
+         zb0(ig,1)=ptimestep*pplev(ig,1)/(R*ptsrf(ig))
+      ENDDO
+
+      dqsdif_total(:)=0.0
+
+!-----------------------------------------------------------------------
+!     2. Add the physical tendencies computed so far
+!     ----------------------------------------------
 
       DO ilev=1,nlay
@@ -208,85 +221,71 @@
             zv(ig,ilev)=pv(ig,ilev)+pdvfi(ig,ilev)*ptimestep
             zh(ig,ilev)=ph(ig,ilev)+pdhfi(ig,ilev)*ptimestep
-            zh(ig,ilev)=max(zh(ig,ilev),zhcond(ig,ilev))
          ENDDO
       ENDDO
       if(tracer) then
-        DO iq =1, nq
-         DO ilev=1,nlay
-           DO ig=1,ngrid
-              zq(ig,ilev,iq)=pq(ig,ilev,iq)+pdqfi(ig,ilev,iq)*ptimestep
-           ENDDO
-         ENDDO
-        ENDDO
+         DO iq =1, nq
+            DO ilev=1,nlay
+               DO ig=1,ngrid
+                  zq(ig,ilev,iq)=pq(ig,ilev,iq) + 
+     &                 pdqfi(ig,ilev,iq)*ptimestep
+               ENDDO
+            ENDDO
+         ENDDO
       end if
 
-c-----------------------------------------------------------------------
-c   3. schema de turbulence
-c      --------------------
-
-c    ** source d'energie cinetique turbulente a la surface
-c       (condition aux limites du schema de diffusion turbulente
-c       dans la couche limite
-c       ---------------------
-
-      CALL vdif_cd( ngrid,nlay,pz0,g,pzlay,pu,pv,ptsrf,ph
-     &             ,zcdv_true,zcdh_true)
-      DO ig=1,ngrid
-        zu2=pu(ig,1)*pu(ig,1)+pv(ig,1)*pv(ig,1)
-        zcdv(ig)=zcdv_true(ig)*sqrt(zu2)
-        zcdh(ig)=zcdh_true(ig)*sqrt(zu2)
-      ENDDO
-
-c    ** schema de diffusion turbulente dans la couche limite
-c       ---------------------------------------------------- 
-
-        CALL vdif_kc(ptimestep,g,pzlev,pzlay
-     &              ,pu,pv,ph,zcdv_true
-     &              ,pq2,zkv,zkh)
-
-
-c    Adding eddy mixing to mimic 3D general circulation in 1D
-c    RW FF 2010
+!-----------------------------------------------------------------------
+!     3. Turbulence scheme
+!     --------------------
+!
+!     Source of turbulent kinetic energy at the surface
+!     ------------------------------------------------- 
+!     Formula is Cd_0 = (karman / log[1+z1/z0])^2
+
+      DO ig=1,ngrid
+         roughratio = 1.E+0 + pzlay(ig,1)/pz0
+         cd0 = karman/log(roughratio)
+         cd0 = cd0*cd0
+         zcdv_true(ig) = cd0
+         zcdh_true(ig) = cd0
+      ENDDO
+
+      DO ig=1,ngrid
+         zu2=pu(ig,1)*pu(ig,1)+pv(ig,1)*pv(ig,1)
+         zcdv(ig)=zcdv_true(ig)*sqrt(zu2)
+         zcdh(ig)=zcdh_true(ig)*sqrt(zu2)
+      ENDDO
+
+!     Turbulent diffusion coefficients in the boundary layer
+!     ------------------------------------------------------ 
+
+      call vdif_kc(ptimestep,g,pzlev,pzlay
+     &     ,pu,pv,ph,zcdv_true
+     &     ,pq2,zkv,zkh)
+
+!     Adding eddy mixing to mimic 3D general circulation in 1D
+!     R. Wordsworth & F. Forget (2010)
       if ((ngrid.eq.1)) then
-        kmixmin = 1.0e-2   ! minimum eddy mix coeff in 1D
-        do ilev=1,nlay
-          do ig=1,ngrid
-           zkh(ig,ilev) = max(kmixmin,zkh(ig,ilev))
-           zkv(ig,ilev) = max(kmixmin,zkv(ig,ilev))
-           !zkh(ig,ilev) = kmixmin
-           !zkv(ig,ilev) = kmixmin
-          end do
-        end do
+         kmixmin = 1.0e-2       ! minimum eddy mix coeff in 1D
+         do ilev=1,nlay
+            do ig=1,ngrid
+               !zkh(ig,ilev) = 1.0
+               zkh(ig,ilev) = max(kmixmin,zkh(ig,ilev))
+               zkv(ig,ilev) = max(kmixmin,zkv(ig,ilev))
+            end do
+         end do
       end if
 
-
-c    ** diagnostique pour le schema de turbulence
-c       -----------------------------------------
-
-      IF(lecrit) THEN
-         PRINT*
-         PRINT*,'Diagnostic for the vertical turbulent mixing'
-         PRINT*,'Cd for momentum and potential temperature'
-
-         PRINT*,zcdv(ngrid/2+1),zcdh(ngrid/2+1)
-         PRINT*,'Mixing coefficient for momentum and pot.temp.'
-         DO ilev=1,nlay
-            PRINT*,zkv(ngrid/2+1,ilev),zkh(ngrid/2+1,ilev)
-         ENDDO
-      ENDIF
-
-c-----------------------------------------------------------------------
-c   4. inversion pour l'implicite sur u
-c      --------------------------------
-
-c    ** l'equation est 
-c       u(t+1) =  u(t) + dt * {(du/dt)phys}(t)  +  dt * {(du/dt)difv}(t+1)
-c       avec
-c       /zu/ = u(t) + dt * {(du/dt)phys}(t)   (voir paragraphe 2.)
-c       et
-c       dt * {(du/dt)difv}(t+1) = dt * {(d/dz)[ Ku (du/dz) ]}(t+1)
-c       donc les entrees sont /zcdv/ pour la condition a la limite sol
-c       et /zkv/ = Ku
- 
+!-----------------------------------------------------------------------
+!     4. Implicit inversion of u
+!     --------------------------
+
+!     u(t+1) =  u(t) + dt * {(du/dt)phys}(t)  +  dt * {(du/dt)difv}(t+1)
+!     avec
+!     /zu/ = u(t) + dt * {(du/dt)phys}(t)   (voir paragraphe 2.)
+!     et
+!     dt * {(du/dt)difv}(t+1) = dt * {(d/dz)[ Ku (du/dz) ]}(t+1)
+!     donc les entrees sont /zcdv/ pour la condition a la limite sol
+!     et /zkv/ = Ku
+      
       CALL multipl((nlay-1)*ngrid,zkv(1,2),zb0(1,2),zb(1,2))
       CALL multipl(ngrid,zcdv,zb0,zb)
@@ -301,7 +300,7 @@
          DO ig=1,ngrid
             z1(ig)=1./(za(ig,ilay)+zb(ig,ilay)+
-     $         zb(ig,ilay+1)*(1.-zd(ig,ilay+1)))
+     $           zb(ig,ilay+1)*(1.-zd(ig,ilay+1)))
             zc(ig,ilay)=(za(ig,ilay)*zu(ig,ilay)+
-     $         zb(ig,ilay+1)*zc(ig,ilay+1))*z1(ig)
+     $           zb(ig,ilay+1)*zc(ig,ilay+1))*z1(ig)
             zd(ig,ilay)=zb(ig,ilay)*z1(ig)
          ENDDO
@@ -317,16 +316,15 @@
       ENDDO
 
-c-----------------------------------------------------------------------
-c   5. inversion pour l'implicite sur v
-c      --------------------------------
-
-c    ** l'equation est 
-c       v(t+1) =  v(t) + dt * {(dv/dt)phys}(t)  +  dt * {(dv/dt)difv}(t+1)
-c       avec
-c       /zv/ = v(t) + dt * {(dv/dt)phys}(t)   (voir paragraphe 2.)
-c       et
-c       dt * {(dv/dt)difv}(t+1) = dt * {(d/dz)[ Kv (dv/dz) ]}(t+1)
-c       donc les entrees sont /zcdv/ pour la condition a la limite sol
-c       et /zkv/ = Kv
+!-----------------------------------------------------------------------
+!     5. Implicit inversion of v
+!     --------------------------
+
+!     v(t+1) =  v(t) + dt * {(dv/dt)phys}(t)  +  dt * {(dv/dt)difv}(t+1)
+!     avec
+!     /zv/ = v(t) + dt * {(dv/dt)phys}(t)   (voir paragraphe 2.)
+!     et
+!     dt * {(dv/dt)difv}(t+1) = dt * {(d/dz)[ Kv (dv/dz) ]}(t+1)
+!     donc les entrees sont /zcdv/ pour la condition a la limite sol
+!     et /zkv/ = Kv
 
       DO ig=1,ngrid
@@ -339,7 +337,7 @@
          DO ig=1,ngrid
             z1(ig)=1./(za(ig,ilay)+zb(ig,ilay)+
-     $         zb(ig,ilay+1)*(1.-zd(ig,ilay+1)))
+     $           zb(ig,ilay+1)*(1.-zd(ig,ilay+1)))
             zc(ig,ilay)=(za(ig,ilay)*zv(ig,ilay)+
-     $         zb(ig,ilay+1)*zc(ig,ilay+1))*z1(ig)
+     $           zb(ig,ilay+1)*zc(ig,ilay+1))*z1(ig)
             zd(ig,ilay)=zb(ig,ilay)*z1(ig)
          ENDDO
@@ -355,18 +353,22 @@
       ENDDO
 
-c-----------------------------------------------------------------------
-c   6. inversion pour l'implicite sur h sans oublier le couplage
-c      avec le sol (conduction)
-c      ------------------------
-
-c    ** l'equation est 
-c       h(t+1) =  h(t) + dt * {(dh/dt)phys}(t)  +  dt * {(dh/dt)difv}(t+1)
-c       avec
-c       /zh/ = h(t) + dt * {(dh/dt)phys}(t)   (voir paragraphe 2.)
-c       et
-c       dt * {(dh/dt)difv}(t+1) = dt * {(d/dz)[ Kh (dh/dz) ]}(t+1)
-c       donc les entrees sont /zcdh/ pour la condition de raccord au sol
-c       et /zkh/ = Kh
-c       -------------
+!----------------------------------------------------------------------------
+!     6. Implicit inversion of h, not forgetting the coupling with the ground
+
+!     h(t+1) =  h(t) + dt * {(dh/dt)phys}(t)  +  dt * {(dh/dt)difv}(t+1)
+!     avec
+!     /zh/ = h(t) + dt * {(dh/dt)phys}(t)   (voir paragraphe 2.)
+!     et
+!     dt * {(dh/dt)difv}(t+1) = dt * {(d/dz)[ Kh (dh/dz) ]}(t+1)
+!     donc les entrees sont /zcdh/ pour la condition de raccord au sol
+!     et /zkh/ = Kh
+
+!     Using the wind modified by friction for lifting and sublimation
+!     ---------------------------------------------------------------
+         DO ig=1,ngrid
+            zu2      = zu(ig,1)*zu(ig,1)+zv(ig,1)*zv(ig,1)
+            zcdv(ig) = zcdv_true(ig)*sqrt(zu2)
+            zcdh(ig) = zcdh_true(ig)*sqrt(zu2)
+         ENDDO
 
       CALL multipl((nlay-1)*ngrid,zkh(1,2),zb0(1,2),zb(1,2))
@@ -379,244 +381,343 @@
       ENDDO
 
-      DO ilay=nlay-1,1,-1
+      DO ilay=nlay-1,2,-1
          DO ig=1,ngrid
             z1(ig)=1./(za(ig,ilay)+zb(ig,ilay)+
-     $         zb(ig,ilay+1)*(1.-zd(ig,ilay+1)))
+     &           zb(ig,ilay+1)*(1.-zd(ig,ilay+1)))
             zc(ig,ilay)=(za(ig,ilay)*zh(ig,ilay)+
-     $         zb(ig,ilay+1)*zc(ig,ilay+1))*z1(ig)
+     &           zb(ig,ilay+1)*zc(ig,ilay+1))*z1(ig)
             zd(ig,ilay)=zb(ig,ilay)*z1(ig)
          ENDDO
       ENDDO
 
-c    ** calcul de (d Planck / dT) a la temperature d'interface
-c       ------------------------------------------------------
-
-      z4st=4.*5.67e-8*ptimestep
+      DO ig=1,ngrid
+         z1(ig)=1./(za(ig,1)+zb(ig,1)+
+     &        zb(ig,2)*(1.-zd(ig,2)))
+         zc(ig,1)=(za(ig,1)*zh(ig,1)+
+     &        zb(ig,2)*zc(ig,2))*z1(ig)
+         zd(ig,1)=zb(ig,1)*z1(ig)
+      ENDDO
+
+!     Calculate (d Planck / dT) at the interface temperature
+!     ------------------------------------------------------
+
+      z4st=4.0*sigma*ptimestep
       DO ig=1,ngrid
          zdplanck(ig)=z4st*pemis(ig)*ptsrf(ig)*ptsrf(ig)*ptsrf(ig)
       ENDDO
 
-c    ** calcul de la temperature_d'interface et de sa tendance.
-c       on ecrit que la somme des flux est nulle a l'interface
-c       a t + \delta t,
-c       c'est a dire le flux radiatif a {t + \delta t}
-c       + le flux turbulent a {t + \delta t} 
-c            qui s'ecrit K (T1-Tsurf) avec T1 = d1 Tsurf + c1
-c            (notation K dt = /cpp*b/)        
-c       + le flux dans le sol a t
-c       + l'evolution du flux dans le sol lorsque la temperature d'interface
-c       passe de sa valeur a t a sa valeur a {t + \delta t}.
-c       ----------------------------------------------------
-
-      DO ig=1,ngrid
-         z1(ig)=pcapcal(ig)*ptsrf(ig)+cpp*zb(ig,1)*zc(ig,1)
-     s     +zdplanck(ig)*ptsrf(ig)+ pfluxsrf(ig)*ptimestep
-         z2(ig)= pcapcal(ig)+cpp*zb(ig,1)*(1.-zd(ig,1))+zdplanck(ig)
-         ztsrf2(ig)=z1(ig)/z2(ig)
-         pdtsrf(ig)=(ztsrf2(ig)-ptsrf(ig))/ptimestep
-
-c        Modif speciale CO2 condensation:
-c        tconds = 1./(bcond-acond*log(.0095*pplev(ig,1)))
-c        if ((callcond).and.
-c    &      ((co2ice(ig).ne.0).or.(ztsrf2(ig).lt.tconds)))then
-c           zh(ig,1)=zc(ig,1)+zd(ig,1)*tconds
-c        else
-            zh(ig,1)=zc(ig,1)+zd(ig,1)*ztsrf2(ig)
-c        end if
-      ENDDO
-
-c    ** et a partir de la temperature au sol on remonte 
-c       -----------------------------------------------
-
-      DO ilay=2,nlay
-         DO ig=1,ngrid
-            hh = max( zh(ig,ilay-1) , zhcond(ig,ilay-1) ) ! modif co2cond
-            zh(ig,ilay)=zc(ig,ilay)+zd(ig,ilay)*hh
-         ENDDO
-      ENDDO
-
-
-c-----------------------------------------------------------------------
-c   TRACERS
-c   -------
+!     Calculate temperature tendency at the interface (dry case)
+!     ----------------------------------------------------------
+!     Sum of fluxes at interface at time t + \delta t gives change in T:
+!       radiative fluxes
+!       turbulent convective (sensible) heat flux
+!       flux (if any) from subsurface
+
+      if(.not.water) then
+
+         DO ig=1,ngrid
+
+            z1(ig) = pcapcal(ig)*ptsrf(ig) + cpp*zb(ig,1)*zc(ig,1)
+     &           + zdplanck(ig)*ptsrf(ig) + pfluxsrf(ig)*ptimestep
+            z2(ig) = pcapcal(ig) + cpp*zb(ig,1)*(1.-zd(ig,1)) 
+     &           +zdplanck(ig)
+            ztsrf2(ig) = z1(ig) / z2(ig)
+            pdtsrf(ig) = (ztsrf2(ig) - ptsrf(ig))/ptimestep
+            zh(ig,1)   = zc(ig,1) + zd(ig,1)*ztsrf2(ig)
+         ENDDO
+
+!     Recalculate temperature to top of atmosphere, starting from ground
+!     ------------------------------------------------------------------
+
+         DO ilay=2,nlay
+            DO ig=1,ngrid
+               hh = zh(ig,ilay-1)
+               zh(ig,ilay)=zc(ig,ilay)+zd(ig,ilay)*hh
+            ENDDO
+         ENDDO
+
+      endif                     ! not water
+
+!-----------------------------------------------------------------------
+!     TRACERS (no vapour)
+!     -------
 
       if(tracer) then
 
-c     Using the wind modified by friction for lifting and  sublimation
-c     ----------------------------------------------------------------
-        DO ig=1,ngrid
-          zu2=zu(ig,1)*zu(ig,1)+zv(ig,1)*zv(ig,1)
-          zcdv(ig)=zcdv_true(ig)*sqrt(zu2)
-          zcdh(ig)=zcdh_true(ig)*sqrt(zu2)
-        ENDDO
-
-c       Calcul du flux vertical au bas de la premiere couche (dust) :
-c       -----------------------------------------------------------
-        do ig=1,ngridmx  
-          rho(ig) = zb0(ig,1) /ptimestep
-!          zb(ig,1) = 0.
-        end do
-
-        call zerophys(ngrid*nq,pdqsdif)
-
-c       OU calcul de la valeur de q a la surface (water)  :
-c       ----------------------------------------
-        if (water) then
-           !call watersat(ngridmx,ptsrf,pplev(1,1),qsat)
-           do ig=1,ngridmx  
-              call watersat_2(ptsrf(ig),pplev(ig,1),qsat(ig))
-           end do
-        end if
-
-c      Inversion pour l'implicite sur q 
-c       --------------------------------
-        do iq=1,nq 
-          CALL multipl((nlay-1)*ngrid,zkh(1,2),zb0(1,2),zb(1,2))
-
-          if ((water).and.(iq.eq.igcm_h2o_vap)) then 
-c            This line is required to account for turbulent transport 
-c            from surface (e.g. ice) to mid-layer of atmosphere:
-             CALL multipl(ngrid,zcdv,zb0,zb(1,1))
-             CALL multipl(ngrid,dryness,zb(1,1),zb(1,1)) 
-          else ! (re)-initialize zb(:,1)
-             zb(1:ngrid,1)=0
-          end if
-
-          DO ig=1,ngrid
-               z1(ig)=1./(za(ig,nlay)+zb(ig,nlay))
-               zc(ig,nlay)=za(ig,nlay)*zq(ig,nlay,iq)*z1(ig)
-               zd(ig,nlay)=zb(ig,nlay)*z1(ig)
-          ENDDO 
-  
-          DO ilay=nlay-1,2,-1
+!     Calculate vertical flux from the bottom to the first layer (dust)
+!     -----------------------------------------------------------------
+         do ig=1,ngridmx  
+            rho(ig) = zb0(ig,1) /ptimestep
+         end do
+
+         call zerophys(ngrid*nq,pdqsdif)
+
+!     Implicit inversion of q
+!     -----------------------
+         do iq=1,nq 
+
+            if (iq.ne.igcm_h2o_vap) then
+
                DO ig=1,ngrid
-                z1(ig)=1./(za(ig,ilay)+zb(ig,ilay)+
-     $           zb(ig,ilay+1)*(1.-zd(ig,ilay+1)))
-                zc(ig,ilay)=(za(ig,ilay)*zq(ig,ilay,iq)+
-     $           zb(ig,ilay+1)*zc(ig,ilay+1))*z1(ig)
-                zd(ig,ilay)=zb(ig,ilay)*z1(ig)
+                  z1(ig)=1./(za(ig,nlay)+zb(ig,nlay))
+                  zcq(ig,nlay)=za(ig,nlay)*zq(ig,nlay,iq)*z1(ig)
+                  zdq(ig,nlay)=zb(ig,nlay)*z1(ig)
+               ENDDO 
+            
+               DO ilay=nlay-1,2,-1
+                  DO ig=1,ngrid
+                     z1(ig)=1./(za(ig,ilay)+zb(ig,ilay)+
+     &                    zb(ig,ilay+1)*(1.-zdq(ig,ilay+1)))
+                     zcq(ig,ilay)=(za(ig,ilay)*zq(ig,ilay,iq)+
+     &                    zb(ig,ilay+1)*zcq(ig,ilay+1))*z1(ig)
+                     zdq(ig,ilay)=zb(ig,ilay)*z1(ig)
+                  ENDDO
                ENDDO
-          ENDDO
-
-          if (water.and.(iq.eq.igcm_h2o_ice)) then
-            ! special case for water ice tracer: do not include
-            ! h2o ice tracer from surface (which is set when handling
-            ! h2o vapour case (see further down).
-            DO ig=1,ngrid
-                z1(ig)=1./(za(ig,1)+zb(ig,1)+
-     $           zb(ig,2)*(1.-zd(ig,2)))
-                zc(ig,1)=(za(ig,1)*zq(ig,1,iq)+
-     $         zb(ig,2)*zc(ig,2)) *z1(ig)
-            ENDDO
-          else ! general case
-            DO ig=1,ngrid
-                z1(ig)=1./(za(ig,1)+zb(ig,1)+
-     $           zb(ig,2)*(1.-zd(ig,2)))
-                zc(ig,1)=(za(ig,1)*zq(ig,1,iq)+
-     $         zb(ig,2)*zc(ig,2) +
-     $        (-pdqsdif(ig,iq)) *ptimestep) *z1(ig)  !tracer flux from surface
-            ENDDO
-          endif ! of if (water.and.(iq.eq.igcm_h2o_ice))
-  
-          IF ((water).and.(iq.eq.igcm_h2o_vap)) then 
-c           Calculation for turbulent exchange with the surface (for ice)
-            DO ig=1,ngrid
-              zd(ig,1)=zb(ig,1)*z1(ig)
-              zq1temp(ig)=zc(ig,1)+ zd(ig,1)*qsat(ig)
-
-              pdqsdif(ig,igcm_h2o_ice)=rho(ig)*dryness(ig)*zcdv(ig)
-     &                       *(zq1temp(ig)-qsat(ig))
-c             write(*,*)'flux vers le sol=',pdqsdif(ig,nq)
-            END DO
-
-            DO ig=1,ngrid
-              if(.not.watercaptag(ig)) then
-                if ((-pdqsdif(ig,igcm_h2o_ice)*ptimestep)
-     &             .gt.pqsurf(ig,igcm_h2o_ice)) then
-c                 write(*,*)'on sublime plus que qsurf!'
-                  pdqsdif(ig,igcm_h2o_ice)=
-     &                         -pqsurf(ig,igcm_h2o_ice)/ptimestep
-c                 write(*,*)'flux vers le sol=',pdqsdif(ig,nq)
-                  z1(ig)=1./(za(ig,1)+ zb(ig,2)*(1.-zd(ig,2)))
-                  zc(ig,1)=(za(ig,1)*zq(ig,1,igcm_h2o_vap)+
-     $            zb(ig,2)*zc(ig,2) +
-     $            (-pdqsdif(ig,igcm_h2o_ice)) *ptimestep) *z1(ig)
-                  zq1temp(ig)=zc(ig,1)
-                endif   
-              endif ! if (.not.watercaptag(ig))
-c             Starting upward calculations for water :
-               zq(ig,1,igcm_h2o_vap)=zq1temp(ig)
-            ENDDO ! of DO ig=1,ngrid
-
-
-!            ! ADDED BY RW: Water latent heat effect 
-!     this doesnt work; causes instability. What do they do on earth?
-!            DO ig=1,ngrid
-!               pdtsrf(ig)= 
-!     &             pdtsrf(ig)+RLVTT*pdqsdif(ig,igcm_h2o_ice)/pcapcal(ig)
-!            ENDDO
-!            print*,'Surface latent heat release in vdifc'
-!            print*,'due to H2O NOT taken into account.'
-
-          ELSE
-c           Starting upward calculations for simple mixing of tracer (dust)
-            DO ig=1,ngrid
-               zq(ig,1,iq)=zc(ig,1)
-            ENDDO
-          END IF ! of IF ((water).and.(iq.eq.igcm_h2o_vap))
-
-          DO ilay=2,nlay
-             DO ig=1,ngrid
-                zq(ig,ilay,iq)=zc(ig,ilay)+zd(ig,ilay)*zq(ig,ilay-1,iq)
-             ENDDO
-          ENDDO
-        enddo ! of do iq=1,nq
-      end if ! of if(tracer)
-
-c-----------------------------------------------------------------------
-c   8. calcul final des tendances de la diffusion verticale
-c      ----------------------------------------------------
-
-      DO ilev = 1, nlay
-         DO ig=1,ngrid
-            pdudif(ig,ilev)=(    zu(ig,ilev)-
-     $      (pu(ig,ilev)+pdufi(ig,ilev)*ptimestep)    )/ptimestep
-            pdvdif(ig,ilev)=(    zv(ig,ilev)-
-     $      (pv(ig,ilev)+pdvfi(ig,ilev)*ptimestep)    )/ptimestep
-            hh = max(ph(ig,ilev)+pdhfi(ig,ilev)*ptimestep ,
-     $           zhcond(ig,ilev))        ! modif co2cond
+
+               if ((water).and.(iq.eq.iice)) then
+                  ! special case for water ice tracer: do not include
+                  ! h2o ice tracer from surface (which is set when handling
+                  ! h2o vapour case (see further down).
+                  ! zb(ig,1)=0 if iq ne ivap
+                  DO ig=1,ngrid
+                     z1(ig)=1./(za(ig,1)+
+     &                    zb(ig,2)*(1.-zdq(ig,2)))
+                     zcq(ig,1)=(za(ig,1)*zq(ig,1,iq)+
+     &                    zb(ig,2)*zcq(ig,2))*z1(ig)
+                  ENDDO
+               else             ! general case
+                  DO ig=1,ngrid
+                     z1(ig)=1./(za(ig,1)+
+     &                    zb(ig,2)*(1.-zdq(ig,2)))
+                     zcq(ig,1)=(za(ig,1)*zq(ig,1,iq)+
+     &                    zb(ig,2)*zcq(ig,2)
+     &                    +(-pdqsdif(ig,iq))*ptimestep)*z1(ig)
+                          ! tracer flux from surface
+                          ! currently pdqsdif always zero here,
+                          ! so last line is superfluous
+                  enddo
+               endif            ! of if (water.and.(iq.eq.igcm_h2o_ice))
+
+
+!     Starting upward calculations for simple tracer mixing (e.g., dust)
+               do ig=1,ngrid
+                  zq(ig,1,iq)=zcq(ig,1)
+               end do
+
+               do ilay=2,nlay
+                  do ig=1,ngrid
+                     zq(ig,ilay,iq)=zcq(ig,ilay)+
+     $                    zdq(ig,ilay)*zq(ig,ilay-1,iq)
+                  end do
+               end do
+
+            endif               ! if (iq.ne.igcm_h2o_vap)
+
+!     Calculate temperature tendency including latent heat term
+!     and assuming an infinite source of water on the ground
+!     ------------------------------------------------------------------
+
+            if (water.and.(iq.eq.igcm_h2o_vap)) then 
+            
+               ! compute evaporation efficiency
+               do ig = 1, ngrid
+                  if(rnat(ig).eq.1)then
+                     dryness(ig)=pqsurf(ig,ivap)+pqsurf(ig,iice) 
+                     dryness(ig)=MIN(1.,2*dryness(ig)/mx_eau_sol)
+                     dryness(ig)=MAX(0.,dryness(ig))
+                  endif
+               enddo
+
+               do ig=1,ngrid
+
+                ! Calculate the value of qsat at the surface (water)
+                call watersat(ptsrf(ig),pplev(ig,1),qsat(ig))
+                call watersat(ptsrf(ig)-0.0001,pplev(ig,1),qsat_temp1)
+                call watersat(ptsrf(ig)+0.0001,pplev(ig,1),qsat_temp2)
+                dqsat(ig)=(qsat_temp2-qsat_temp1)/0.0002
+                ! calculate dQsat / dT by finite differences
+                ! we cannot use the updated temperature value yet...
+ 
+               enddo
+
+! coefficients for q
+
+               do ig=1,ngrid
+                  z1(ig)=1./(za(ig,nlay)+zb(ig,nlay))
+                  zcq(ig,nlay)=za(ig,nlay)*zq(ig,nlay,iq)*z1(ig)
+                  zdq(ig,nlay)=zb(ig,nlay)*z1(ig)
+               enddo 
+            
+               do ilay=nlay-1,2,-1
+                  do ig=1,ngrid
+                     z1(ig)=1./(za(ig,ilay)+zb(ig,ilay)+
+     $                    zb(ig,ilay+1)*(1.-zdq(ig,ilay+1)))
+                     zcq(ig,ilay)=(za(ig,ilay)*zq(ig,ilay,iq)+
+     $                    zb(ig,ilay+1)*zcq(ig,ilay+1))*z1(ig)
+                     zdq(ig,ilay)=zb(ig,ilay)*z1(ig)
+                  enddo
+               enddo
+
+               do ig=1,ngrid
+                  z1(ig)=1./(za(ig,1)+zb(ig,1)*dryness(ig)+
+     $                 zb(ig,2)*(1.-zdq(ig,2)))
+                  zcq(ig,1)=(za(ig,1)*zq(ig,1,iq)+
+     $                 zb(ig,2)*zcq(ig,2))*z1(ig)
+                  zdq(ig,1)=dryness(ig)*zb(ig,1)*z1(ig)
+               enddo
+
+! calculation of h0 and h1
+               do ig=1,ngrid
+                  zdq0(ig) = dqsat(ig)
+                  zcq0(ig) = qsat(ig)-dqsat(ig)*ptsrf(ig)
+
+                  z1(ig) = pcapcal(ig)*ptsrf(ig) +cpp*zb(ig,1)*zc(ig,1)
+     &                 + zdplanck(ig)*ptsrf(ig) + pfluxsrf(ig)*ptimestep 
+     &                 +  zb(ig,1)*dryness(ig)*RLVTT*
+     &                 ((zdq(ig,1)-1.0)*zcq0(ig)+zcq(ig,1))
+
+                  z2(ig) = pcapcal(ig) + cpp*zb(ig,1)*(1.-zd(ig,1))
+     &                 +zdplanck(ig)
+     &                 +zb(ig,1)*dryness(ig)*RLVTT*zdq0(ig)*
+     &                 (1.0-zdq(ig,1))
+
+                  ztsrf2(ig) = z1(ig) / z2(ig)
+                  pdtsrf(ig) = (ztsrf2(ig) - ptsrf(ig))/ptimestep
+                  zh(ig,1)   = zc(ig,1) + zd(ig,1)*ztsrf2(ig)
+               enddo
+
+! calculation of qs and q1
+               do ig=1,ngrid
+                  zq0(ig)     = zcq0(ig)+zdq0(ig)*ztsrf2(ig)
+                  zq(ig,1,iq) = zcq(ig,1)+zdq(ig,1)*zq0(ig)
+               enddo
+
+! calculation of evaporation              
+               do ig=1,ngrid 
+                  evap(ig)= zb(ig,1)*dryness(ig)*(zq(ig,1,ivap)-zq0(ig))
+                  dqsdif_total(ig)=evap(ig)
+               enddo
+
+! recalculate temperature and q(vap) to top of atmosphere, starting from ground
+               do ilay=2,nlay
+                  do ig=1,ngrid
+                     zq(ig,ilay,iq)=zcq(ig,ilay)
+     &                    +zdq(ig,ilay)*zq(ig,ilay-1,iq)
+                     zh(ig,ilay)=zc(ig,ilay)+zd(ig,ilay)*zh(ig,ilay-1)
+                  end do
+               end do
+
+               do ig=1,ngrid
+
+!     --------------------------------------------------------------------------
+!     On the ocean, if T > 0 C then the vapour tendency must replace the ice one
+!     The surface vapour tracer is actually liquid. To make things difficult.
+
+                  if (rnat(ig).eq.0) then ! unfrozen ocean
+                     
+                     pdqsdif(ig,ivap)=dqsdif_total(ig)/ptimestep
+                     pdqsdif(ig,iice)=0.0
+
+
+                  elseif (rnat(ig).eq.1) then ! (continent)
+
+!     --------------------------------------------------------
+!     Now check if we've taken too much water from the surface
+!     This can only occur on the continent 
+
+!     If water is evaporating / subliming, we take it from ice before liquid
+!     -- is this valid??
+                     if(dqsdif_total(ig).lt.0)then
+                        pdqsdif(ig,iice)=dqsdif_total(ig)/ptimestep
+                        pdqsdif(ig,iice)=max(-pqsurf(ig,iice)/ptimestep
+     &                       ,pdqsdif(ig,iice))
+                     endif
+                     ! sublimation only greater than qsurf(ice)
+                     ! ----------------------------------------
+                     ! we just convert some liquid to vapour too
+                     ! if latent heats are the same, no big deal
+                     if (-dqsdif_total(ig).gt.pqsurf(ig,iice))then            
+                       pdqsdif(ig,iice) = -pqsurf(ig,iice)/ptimestep ! removes all the ice!
+                       pdqsdif(ig,ivap) = dqsdif_total(ig)/ptimestep
+     &                       - pdqsdif(ig,iice) ! take the remainder from the liquid instead
+                       pdqsdif(ig,ivap) = max(-pqsurf(ig,ivap)/ptimestep
+     &                       ,pdqsdif(ig,ivap))
+                    endif
+
+                 endif          ! if (rnat.ne.1)
+
+!     If water vapour is condensing, we must decide whether it forms ice or liquid.
+                 if(dqsdif_total(ig).gt.0)then ! a bug was here!
+                    if(ztsrf2(ig).gt.To)then
+                       pdqsdif(ig,iice)=0.0
+                       pdqsdif(ig,ivap)=dqsdif_total(ig)/ptimestep
+                    else
+                       pdqsdif(ig,iice)=dqsdif_total(ig)/ptimestep
+                       pdqsdif(ig,ivap)=0.0
+                    endif
+                 endif
+
+              end do            ! of DO ig=1,ngrid
+           endif                ! if (water et iq=ivap)
+        end do                  ! of do iq=1,nq
+      endif                     ! traceur
+
+
+!-----------------------------------------------------------------------
+!     8. Final calculation of the vertical diffusion tendencies
+!     -----------------------------------------------------------------
+
+      do ilev = 1, nlay
+         do ig=1,ngrid
+            pdudif(ig,ilev)=(zu(ig,ilev)-
+     &           (pu(ig,ilev)+pdufi(ig,ilev)*ptimestep))/ptimestep
+            pdvdif(ig,ilev)=(zv(ig,ilev)-
+     &           (pv(ig,ilev)+pdvfi(ig,ilev)*ptimestep))/ptimestep
+            hh = ph(ig,ilev)+pdhfi(ig,ilev)*ptimestep 
+
             pdhdif(ig,ilev)=( zh(ig,ilev)- hh )/ptimestep
-         ENDDO
-      ENDDO
-
-    
-      if (tracer) then 
-        DO iq = 1, nq
-          DO ilev = 1, nlay
-            DO ig=1,ngrid
-              pdqdif(ig,ilev,iq)=(zq(ig,ilev,iq)-
-     $      (pq(ig,ilev,iq) + pdqfi(ig,ilev,iq)*ptimestep))/ptimestep
-            ENDDO
-          ENDDO
-        ENDDO
-      end if
-
-c    ** diagnostique final 
-c       ------------------
-
-      IF(lecrit) THEN
-         PRINT*,'In vdif'
-         PRINT*,'Ts (t) and Ts (t+st)'
-         WRITE(*,'(a10,3a15)')
-     s   'theta(t)','theta(t+dt)','u(t)','u(t+dt)'
-         PRINT*,ptsrf(ngrid/2+1),ztsrf2(ngrid/2+1)
-         DO ilev=1,nlay
-            WRITE(*,'(4f15.7)')
-     s      ph(ngrid/2+1,ilev),zh(ngrid/2+1,ilev),
-     s      pu(ngrid/2+1,ilev),zu(ngrid/2+1,ilev)
-
-         ENDDO
-      ENDIF
-
-      RETURN
-      END
+         enddo
+      enddo
+      
+      if (tracer) then
+         do iq = 1, nq
+            do ilev = 1, nlay
+               do ig=1,ngrid
+                  pdqdif(ig,ilev,iq)=(zq(ig,ilev,iq)-
+     &           (pq(ig,ilev,iq)+pdqfi(ig,ilev,iq)*ptimestep))/
+     &           ptimestep
+               enddo
+            enddo
+         enddo
+
+         if(water.and.forceWC)then ! force water conservation in model
+                                   ! we calculate the difference and add it to the ground
+                                   ! this is ugly and should be improved in the future
+            do ig=1,ngrid
+               Wtot=0.0
+               do ilay=1,nlay
+                  masse = (pplev(ig,ilay) - pplev(ig,ilay+1))/g
+!                  Wtot=Wtot+masse*(zq(ig,ilay,iice)-
+!     &                 (pq(ig,ilay,iice)+pdqfi(ig,ilay,iice)*ptimestep))
+                  Wtot=Wtot+masse*(zq(ig,ilay,ivap)-
+     &                 (pq(ig,ilay,ivap)+pdqfi(ig,ilay,ivap)*ptimestep))
+               enddo
+               Wdiff=Wtot/ptimestep+pdqsdif(ig,ivap)+pdqsdif(ig,iice)
+
+               if(ztsrf2(ig).gt.To)then
+                  pdqsdif(ig,ivap)=pdqsdif(ig,ivap)-Wdiff
+               else
+                  pdqsdif(ig,iice)=pdqsdif(ig,iice)-Wdiff
+               endif
+            enddo
+
+         endif
+
+      endif 
+
+      if(water)then
+      call writediagfi(ngrid,'beta','Dryness coefficient',' ',2,dryness)
+      endif
+
+      return
+      end
Index: /trunk/LMDZ.GENERIC/libf/phystd/watercap.h
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/watercap.h	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/watercap.h	(revision 253)
@@ -1,4 +1,4 @@
-c-----------------------------------------------------------------------
-c INCLUDE 'watercap.h'
+!-----------------------------------------------------------------------
+! INCLUDE 'watercap.h'
 
       logical watercaptag(ngridmx)
Index: /trunk/LMDZ.GENERIC/libf/phystd/watercommon_h.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/watercommon_h.F90	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/watercommon_h.F90	(revision 253)
@@ -6,5 +6,15 @@
       real, parameter :: To = 273.16
       real, parameter :: mH2O = 18.01528   
-      real, parameter :: RLVTT = 2.5008E+6 ! Latent heat of sublimation (J kg-1) 
+
+      ! benjamin additions
+      real, parameter :: RLVTT = 2.257E+6 ! Latent heat of sublimation (J kg-1) 
+      real, parameter :: RLSTT = 2.257E+6 ! 2.591E+6 in reality ! Latent heat of sublimation (J kg-1)
+      !real, parameter :: RLVTT = 0.0 
+      !real, parameter :: RLSTT = 0.0
+
+      real, parameter :: RLFTT = 3.334E+5 ! Latent heat of fusion (J kg-1) 
+      !real, parameter :: RLFTT = 0.0 
+      real, parameter :: rhowater = 1.0E+3 ! mass of water (kg/m^3)
+      real, parameter :: mx_eau_sol = 150 ! mass of water (kg/m^2)
 
 !     This was the old Martian latent heat version:
Index: /trunk/LMDZ.GENERIC/libf/phystd/watersat.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/watersat.F90	(revision 253)
+++ /trunk/LMDZ.GENERIC/libf/phystd/watersat.F90	(revision 253)
@@ -0,0 +1,41 @@
+subroutine watersat(T,p,qsat)
+
+  use watercommon_h, only: To, epsi
+  implicit none
+
+!==================================================================
+!     Purpose
+!     -------
+!     Compute the water mass mixing ratio at saturation (kg/kg)
+!     for a given pressure (Pa) and temperature (K)
+!     A replacement for the old watersat.F in the Martian GCM.
+!     Based on FCTTRE.h in the LMDTERRE model.
+!
+!     Authors
+!     -------
+!     Robin Wordsworth (2010)
+!
+!==================================================================
+
+!   input
+  real T, p
+  
+!   output
+  real qsat
+
+! checked vs. NIST data 22/06/2010 by RW.
+! / by p gives partial pressure
+! x by epsi converts to mass mixing ratio
+
+  if (T.lt.To) then ! solid / vapour
+     qsat = 100.0 * epsi * 10**(2.07023 - 0.00320991             &
+          * T - 2484.896 / T + 3.56654 * alog10(T))
+  else                 ! liquid / vapour
+     qsat = 100.0 * epsi * 10**(23.8319 - 2948.964 / T - 5.028  &
+          * alog10(T) - 29810.16 * exp( -0.0699382 * T)  &
+          + 25.21935 * exp(-2999.924/T))
+  endif
+  qsat=qsat/p
+
+  return
+end subroutine watersat
Index: unk/LMDZ.GENERIC/libf/phystd/watersat_2.F90
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/watersat_2.F90	(revision 252)
+++ 	(revision )
@@ -1,39 +1,0 @@
-subroutine watersat_2(T,p,qsat)
-
-  use watercommon_h, only: T_coup, epsi
-  implicit none
-
-!==================================================================
-!     Purpose
-!     -------
-!     Compute the water mass mixing ratio at saturation (kg/kg)
-!     for a given pressure (Pa) and temperature (K)
-!     A replacement for the old watersat.F in the Martian GCM.
-!     Based on FCTTRE.h in the LMDTERRE model.
-!
-!     Authors
-!     -------
-!     Robin Wordsworth (2010)
-!
-!==================================================================
-
-!   input
-  real T, p
-  
-!   output
-  real qsat
-
-
-  if (T.lt.T_coup) then ! solid / vapour
-     qsat = 100.0 * epsi * 10**(2.07023 - 0.00320991             &
-          * T - 2484.896 / T + 3.56654 * alog10(T))
-  else                 ! liquid / vapour
-     qsat = 100.0 * epsi * 10**(23.8319 - 2948.964 / T - 5.028  &
-          * alog10(T) - 29810.16 * exp( -0.0699382 * T)  &
-          + 25.21935 * exp(-2999.924/T))
-  endif
-  qsat=qsat/p
-
-  return
-end subroutine watersat_2
-
Index: /trunk/LMDZ.GENERIC/libf/phystd/writediagfi.F
===================================================================
--- /trunk/LMDZ.GENERIC/libf/phystd/writediagfi.F	(revision 252)
+++ /trunk/LMDZ.GENERIC/libf/phystd/writediagfi.F	(revision 253)
@@ -6,5 +6,5 @@
 !  0d (pour un scalaire qui ne depend que du temps : ex : la longitude
 !  solaire)
-!  (ou encore 1d, dans le cas de testphys1d, pour sortir une colonne)
+!  (ou encore 1d, dans le cas de rcm1d, pour sortir une colonne)
 !  La periode d'ecriture est donnee par 
 !  "ecritphy " regle dans le fichier de controle de run :  run.def
@@ -149,5 +149,5 @@
 
       if (ngridmx.eq.1) then
-        ! in testphys1d, for the 1d version of the GCM, iphysiq and irythme
+        ! in rcm1d, for the 1d version of the GCM, iphysiq and irythme
         ! are undefined; so set them to 1
         iphysiq=1 
Index: /trunk/LMDZ.GENERIC/liste_des_sources_f77
===================================================================
--- /trunk/LMDZ.GENERIC/liste_des_sources_f77	(revision 252)
+++ /trunk/LMDZ.GENERIC/liste_des_sources_f77	(revision 253)
@@ -179,34 +179,37 @@
 libf/filtrez/jacobi.F
 libf/filtrez/parafilt.h
-libf/grid/fxyprim.h
 libf/grid/fxy_new.h
 libf/grid/fxy_reg.h
 libf/grid/fxy_sin.h
+libf/grid/fxyprim.h
 libf/grid/dimensions.h
 libf/grid/bands.h
 libf/phystd/aerave.F
+libf/phystd/aerave_new.F
 libf/phystd/blackl.F
-libf/phystd/physiq.F
-libf/phystd/callcorrk.F
-libf/phystd/tracer.h
 libf/phystd/callkeys.h
+libf/phystd/callsedim.F
 libf/phystd/comcstfi.h
-libf/phystd/cvmgp.F
 libf/phystd/comdiurn.h
 libf/phystd/comg1d.h
 libf/phystd/comgeomfi.h
-libf/phystd/solarlong.F
 libf/phystd/comsaison.h
+libf/phystd/comsoil.h
 libf/phystd/convadj.F
+libf/phystd/cpdet.F
+libf/phystd/cpdet.h
+libf/phystd/cvmgp.F
 libf/phystd/cvmgt.F
-libf/phystd/lagrange.F
 libf/phystd/datafile.h
 libf/phystd/datareadnc.F
 libf/phystd/dimphys.h
-libf/phystd/tabfi.F
+libf/phystd/dsolver.F
+libf/phystd/dtridgl.F
+libf/phystd/evap.F
 libf/phystd/fisice.h
-libf/phystd/optcv.F
-libf/phystd/phyetat0.F
-libf/phystd/planete.h
+libf/phystd/forceWCfn.F
+libf/phystd/gases.h
+libf/phystd/gfluxi.F
+libf/phystd/gfluxv.F
 libf/phystd/inifis.F
 libf/phystd/iniorbit.F
@@ -214,43 +217,41 @@
 libf/phystd/initracer.F
 libf/phystd/iniwrite.F
+libf/phystd/iniwrite_spec.F
+libf/phystd/interp_line.F
 libf/phystd/ismax.F
 libf/phystd/ismin.F
-libf/phystd/physdem1.F
+libf/phystd/lagrange.F
+libf/phystd/largescale.F
 libf/phystd/mucorr.F
 libf/phystd/mufract.F
 libf/phystd/multipl.F
+libf/phystd/newsedim.F
+libf/phystd/orbite.F
+libf/phystd/phyetat0.F
+libf/phystd/physdem1.F
+libf/phystd/planete.h
+libf/phystd/profile.F
+libf/phystd/rcm1d.F
+libf/phystd/scopyi.F
+libf/phystd/sfluxi.F
 libf/phystd/sfluxv.F
-libf/phystd/orbite.F
-libf/phystd/profile.F
-libf/phystd/scopyi.F
+libf/phystd/soil.F
+libf/phystd/soil_settings.F
+libf/phystd/statto.h
+libf/phystd/stelang.F
+libf/phystd/stellarlong.F
+libf/phystd/surface_nature.F
+libf/phystd/surfdat.h
 libf/phystd/surfini.F
+libf/phystd/tabfi.F
+libf/phystd/tpindex.F
+libf/phystd/tracer.h
 libf/phystd/vdifc.F
-libf/phystd/soil.F
-libf/phystd/solang.F
-libf/phystd/statto.h
-libf/phystd/surfdat.h
 libf/phystd/vdif_cd.F
 libf/phystd/vdif_kc.F
 libf/phystd/vlz_fi.F
 libf/phystd/watercap.h
-libf/phystd/comsoil.h
 libf/phystd/writediagfi.F
+libf/phystd/writediagspec.F
 libf/phystd/writeg1d.F
 libf/phystd/zerophys.F
-libf/phystd/callsedim.F
-libf/phystd/interp_line.F
-libf/phystd/soil_settings.F
-libf/phystd/sfluxi.F
-libf/phystd/tpindex.F
-libf/phystd/gfluxv.F
-libf/phystd/gfluxi.F
-libf/phystd/dsolver.F
-libf/phystd/dtridgl.F
-libf/phystd/co2snow.F
-libf/phystd/testphys1d.F
-libf/phystd/kastprof_fn.F
-libf/phystd/newsedim.F
-libf/phystd/aerave_new.F
-libf/phystd/iniwrite_spec.F
-libf/phystd/writediagspec.F
-libf/phystd/largescale2.F
Index: /trunk/LMDZ.GENERIC/liste_des_sources_f90
===================================================================
--- /trunk/LMDZ.GENERIC/liste_des_sources_f90	(revision 252)
+++ /trunk/LMDZ.GENERIC/liste_des_sources_f90	(revision 253)
@@ -3,27 +3,38 @@
 libf/bibio/ioipsl_stringop.F90
 libf/phystd/aeropacity.F90
+libf/phystd/aeroptproperties.F90
+libf/phystd/ave_stelspec.F90
+libf/phystd/calc_cpp3d.F90
+libf/phystd/calc_cpp_mugaz.F90
+libf/phystd/calc_rayleigh.F90
+libf/phystd/callcorrk.F90
+libf/phystd/condens_co2cloud.F90
+libf/phystd/def_var.F90
+libf/phystd/hydrol.F90
+libf/phystd/iniwritesoil.F90
+libf/phystd/interpolateH2H2.F90
+libf/phystd/kastprof_fn.F90
+libf/phystd/mkstat.F90
+libf/phystd/moistadj.F90
+libf/phystd/N2broadprof_fn.F90
+libf/phystd/newtrelax.F90
+libf/phystd/optci.F90
+libf/phystd/optcv.F90
+libf/phystd/physiq.F90
+libf/phystd/radcommon_h.F90
+libf/phystd/radinc_h.F90
+libf/phystd/rain.F90
+libf/phystd/setspi.F90
+libf/phystd/setspv.F90
+libf/phystd/simpleprof_fn.F90
+libf/phystd/stokes.F90
 libf/phystd/suaer_corrk.F90
-libf/phystd/radcommon_h.F90
-libf/phystd/condens_co2cloud.F90
 libf/phystd/sugas_corrk.F90
-libf/phystd/def_var.F90
-libf/phystd/rain.F90
-libf/phystd/radinc_h.F90
-libf/phystd/optci.F90
-libf/phystd/mkstat.F90
-libf/phystd/setspi.F90
-libf/phystd/aeroptproperties.F90
-libf/phystd/stokes.F90
-libf/phystd/setspv.F90
+libf/phystd/su_gases.F90
+libf/phystd/su_watercycle.F90
+libf/phystd/totalcloudfrac.F90
 libf/phystd/watercommon_h.F90
+libf/phystd/watersat.F90
+libf/phystd/watersat_grad.F90
+libf/phystd/writediagsoil.F90
 libf/phystd/wstats.F90
-libf/phystd/iniwritesoil.F90
-libf/phystd/writediagsoil.F90
-libf/phystd/su_watercycle.F90
-libf/phystd/aeroptpropertiesJBnew.F90
-libf/phystd/watersat_2.F90
-libf/phystd/moistadj.F90
-libf/phystd/watersat_grad.F90
-libf/phystd/ave_stelspec.F90
-libf/phystd/calc_rayleigh.F90
-libf/phystd/calc_cpp3d.F90
Index: /trunk/LMDZ.GENERIC/makefile
===================================================================
--- /trunk/LMDZ.GENERIC/makefile	(revision 252)
+++ /trunk/LMDZ.GENERIC/makefile	(revision 253)
@@ -7,9 +7,9 @@
 # Repertoires :
 
-GCM     = /u/rwlmd/LMDZ.GENERIC
+GCM     = /san/home/rdword/gcm/LMDZ.GENERIC
 MACHINE = sun4
 LIBF    = $(GCM)/libf
 LIBO    = $(LIBOGCM)/$(MACHINE)
-LOCAL_DIR=/d2/rwlmd/earthmars_test/earth/one_d
+LOCAL_DIR=/san/home/rdword/gcm/earlymars/0711/wet/1bar_hiVres
 BIBIO    = $(LIBF)/bibio
 FILTRE   = filtre
@@ -113,7 +113,7 @@
 $(LIBO)/libbibio.a :  $(LIBO)/libbibio.a(mxm.o)
 
+$(LIBO)/libbibio.a :  $(LIBO)/libbibio.a(mxv.o)
+
 $(LIBO)/libbibio.a :  $(LIBO)/libbibio.a(mxva.o)
-
-$(LIBO)/libbibio.a :  $(LIBO)/libbibio.a(mxv.o)
 
 $(LIBO)/libbibio.a :  $(LIBO)/libbibio.a(mywrite.o)
@@ -228,14 +228,14 @@
 	cd $(GCM)
 
+$(LIBO)/libbibio.a(mxv.o) : $(LIBF)/bibio/mxv.F
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/bibio/mxv.F ; \
+	$(AR) r $(LIBO)/libbibio.a mxv.o ; $(RM) mxv.o ; \
+	cd $(GCM)
+
 $(LIBO)/libbibio.a(mxva.o) : $(LIBF)/bibio/mxva.F
 	cd $(LOCAL_DIR); \
 	$(COMPILE) $(LIBF)/bibio/mxva.F ; \
 	$(AR) r $(LIBO)/libbibio.a mxva.o ; $(RM) mxva.o ; \
-	cd $(GCM)
-
-$(LIBO)/libbibio.a(mxv.o) : $(LIBF)/bibio/mxv.F
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/bibio/mxv.F ; \
-	$(AR) r $(LIBO)/libbibio.a mxv.o ; $(RM) mxv.o ; \
 	cd $(GCM)
 
@@ -345,8 +345,8 @@
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(addit.o)
 
+$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(adv_h2o.o)
+
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(advect.o)
 
-$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(adv_h2o.o)
-
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(amont.o)
 
@@ -355,8 +355,8 @@
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(bernoui.o)
 
+$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(caldyn.o)
+
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(caldyn0.o)
 
-$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(caldyn.o)
-
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(calfis.o)
 
@@ -383,16 +383,16 @@
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(diverg.o)
 
+$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(diverg_gam.o)
+
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(divergf.o)
 
-$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(diverg_gam.o)
-
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(divergst.o)
 
+$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(divgrad.o)
+
+$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(divgrad2.o)
+
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(divgrad22.o)
 
-$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(divgrad2.o)
-
-$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(divgrad.o)
-
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(dteta1.o)
 
@@ -429,36 +429,36 @@
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(geopot.o)
 
+$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(gr_dyn_fi.o)
+
+$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(gr_fi_dyn.o)
+
+$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(gr_int_dyn.o)
+
+$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(gr_u_scal.o)
+
+$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(gr_v_scal.o)
+
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(grad.o)
 
+$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(gradiv.o)
+
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(gradiv2.o)
 
-$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(gradiv.o)
-
-$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(gr_dyn_fi.o)
-
-$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(gr_fi_dyn.o)
-
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(grid_atob.o)
 
+$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(grid_noro.o)
+
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(grid_noro1.o)
 
-$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(grid_noro.o)
-
-$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(gr_int_dyn.o)
-
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(groupe.o)
 
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(groupeun.o)
 
-$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(gr_u_scal.o)
-
-$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(gr_v_scal.o)
-
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(heavyside.o)
 
+$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(ini_archive.o)
+
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(iniadvtrac.o)
 
-$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(ini_archive.o)
-
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(iniav.o)
 
@@ -489,8 +489,8 @@
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(laplacien_rotgam.o)
 
+$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(lect_start_archive.o)
+
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(lectflux.o)
 
-$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(lect_start_archive.o)
-
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(massbar.o)
 
@@ -525,15 +525,15 @@
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(rotat.o)
 
+$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(rotat_nfil.o)
+
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(rotatf.o)
 
-$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(rotat_nfil.o)
-
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(rotatst.o)
 
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(scal_wind.o)
 
+$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(sortvarc.o)
+
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(sortvarc0.o)
-
-$(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(sortvarc.o)
 
 $(LIBO)/libdyn3d.a :  $(LIBO)/libdyn3d.a(spline.o)
@@ -594,4 +594,14 @@
 	cd $(GCM)
 
+$(LIBO)/libdyn3d.a(adv_h2o.o) : $(LIBF)/dyn3d/adv_h2o.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/dyn3d/paramet.h \
+$(LIBF)/dyn3d/logic.h \
+$(LIBF)/dyn3d/comvert.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/dyn3d/adv_h2o.F ; \
+	$(AR) r $(LIBO)/libdyn3d.a adv_h2o.o ; $(RM) adv_h2o.o ; \
+	cd $(GCM)
+
 $(LIBO)/libdyn3d.a(advect.o) : $(LIBF)/dyn3d/advect.F \
 $(LIBF)/grid/dimensions.h \
@@ -607,5 +617,5 @@
 	cd $(GCM)
 
-$(LIBO)/libdyn3d.a(adv_h2o.o) : $(LIBF)/dyn3d/adv_h2o.F \
+$(LIBO)/libdyn3d.a(amont.o) : $(LIBF)/dyn3d/amont.F \
 $(LIBF)/grid/dimensions.h \
 $(LIBF)/dyn3d/paramet.h \
@@ -613,14 +623,4 @@
 $(LIBF)/dyn3d/comvert.h
 	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/adv_h2o.F ; \
-	$(AR) r $(LIBO)/libdyn3d.a adv_h2o.o ; $(RM) adv_h2o.o ; \
-	cd $(GCM)
-
-$(LIBO)/libdyn3d.a(amont.o) : $(LIBF)/dyn3d/amont.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/dyn3d/paramet.h \
-$(LIBF)/dyn3d/logic.h \
-$(LIBF)/dyn3d/comvert.h
-	cd $(LOCAL_DIR); \
 	$(COMPILE) $(LIBF)/dyn3d/amont.F ; \
 	$(AR) r $(LIBO)/libdyn3d.a amont.o ; $(RM) amont.o ; \
@@ -649,4 +649,15 @@
 	cd $(GCM)
 
+$(LIBO)/libdyn3d.a(caldyn.o) : $(LIBF)/dyn3d/caldyn.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/dyn3d/paramet.h \
+$(LIBF)/dyn3d/comconst.h \
+$(LIBF)/dyn3d/comvert.h \
+$(LIBF)/dyn3d/comgeom.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/dyn3d/caldyn.F ; \
+	$(AR) r $(LIBO)/libdyn3d.a caldyn.o ; $(RM) caldyn.o ; \
+	cd $(GCM)
+
 $(LIBO)/libdyn3d.a(caldyn0.o) : $(LIBF)/dyn3d/caldyn0.F \
 $(LIBF)/grid/dimensions.h \
@@ -658,15 +669,4 @@
 	$(COMPILE) $(LIBF)/dyn3d/caldyn0.F ; \
 	$(AR) r $(LIBO)/libdyn3d.a caldyn0.o ; $(RM) caldyn0.o ; \
-	cd $(GCM)
-
-$(LIBO)/libdyn3d.a(caldyn.o) : $(LIBF)/dyn3d/caldyn.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/dyn3d/paramet.h \
-$(LIBF)/dyn3d/comconst.h \
-$(LIBF)/dyn3d/comvert.h \
-$(LIBF)/dyn3d/comgeom.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/caldyn.F ; \
-	$(AR) r $(LIBO)/libdyn3d.a caldyn.o ; $(RM) caldyn.o ; \
 	cd $(GCM)
 
@@ -778,7 +778,9 @@
 $(LIBF)/dyn3d/comvert.h \
 $(LIBF)/dyn3d/comconst.h \
-$(LIBF)/dyn3d/logic.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/disvert.F ; \
+$(LIBF)/dyn3d/logic.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBO)/libbibio.a(ioipsl_getincom.o)
+	cd $(LOCAL_DIR); \
+	$(COMPILE90) $(LIBF)/dyn3d/disvert.F ; \
 	$(AR) r $(LIBO)/libdyn3d.a disvert.o ; $(RM) disvert.o ; \
 	cd $(GCM)
@@ -793,4 +795,13 @@
 	cd $(GCM)
 
+$(LIBO)/libdyn3d.a(diverg_gam.o) : $(LIBF)/dyn3d/diverg_gam.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/dyn3d/paramet.h \
+$(LIBF)/dyn3d/comgeom.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/dyn3d/diverg_gam.F ; \
+	$(AR) r $(LIBO)/libdyn3d.a diverg_gam.o ; $(RM) diverg_gam.o ; \
+	cd $(GCM)
+
 $(LIBO)/libdyn3d.a(divergf.o) : $(LIBF)/dyn3d/divergf.F \
 $(LIBF)/grid/dimensions.h \
@@ -802,13 +813,4 @@
 	cd $(GCM)
 
-$(LIBO)/libdyn3d.a(diverg_gam.o) : $(LIBF)/dyn3d/diverg_gam.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/dyn3d/paramet.h \
-$(LIBF)/dyn3d/comgeom.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/diverg_gam.F ; \
-	$(AR) r $(LIBO)/libdyn3d.a diverg_gam.o ; $(RM) diverg_gam.o ; \
-	cd $(GCM)
-
 $(LIBO)/libdyn3d.a(divergst.o) : $(LIBF)/dyn3d/divergst.F \
 $(LIBF)/grid/dimensions.h \
@@ -818,23 +820,4 @@
 	$(COMPILE) $(LIBF)/dyn3d/divergst.F ; \
 	$(AR) r $(LIBO)/libdyn3d.a divergst.o ; $(RM) divergst.o ; \
-	cd $(GCM)
-
-$(LIBO)/libdyn3d.a(divgrad22.o) : $(LIBF)/dyn3d/divgrad22.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/dyn3d/paramet.h \
-$(LIBF)/dyn3d/comdissipn.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/divgrad22.F ; \
-	$(AR) r $(LIBO)/libdyn3d.a divgrad22.o ; $(RM) divgrad22.o ; \
-	cd $(GCM)
-
-$(LIBO)/libdyn3d.a(divgrad2.o) : $(LIBF)/dyn3d/divgrad2.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/dyn3d/paramet.h \
-$(LIBF)/dyn3d/comgeom2.h \
-$(LIBF)/dyn3d/comdissipn.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/divgrad2.F ; \
-	$(AR) r $(LIBO)/libdyn3d.a divgrad2.o ; $(RM) divgrad2.o ; \
 	cd $(GCM)
 
@@ -848,4 +831,23 @@
 	$(COMPILE) $(LIBF)/dyn3d/divgrad.F ; \
 	$(AR) r $(LIBO)/libdyn3d.a divgrad.o ; $(RM) divgrad.o ; \
+	cd $(GCM)
+
+$(LIBO)/libdyn3d.a(divgrad2.o) : $(LIBF)/dyn3d/divgrad2.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/dyn3d/paramet.h \
+$(LIBF)/dyn3d/comgeom2.h \
+$(LIBF)/dyn3d/comdissipn.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/dyn3d/divgrad2.F ; \
+	$(AR) r $(LIBO)/libdyn3d.a divgrad2.o ; $(RM) divgrad2.o ; \
+	cd $(GCM)
+
+$(LIBO)/libdyn3d.a(divgrad22.o) : $(LIBF)/dyn3d/divgrad22.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/dyn3d/paramet.h \
+$(LIBF)/dyn3d/comdissipn.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/dyn3d/divgrad22.F ; \
+	$(AR) r $(LIBO)/libdyn3d.a divgrad22.o ; $(RM) divgrad22.o ; \
 	cd $(GCM)
 
@@ -1025,4 +1027,40 @@
 	cd $(GCM)
 
+$(LIBO)/libdyn3d.a(gr_dyn_fi.o) : $(LIBF)/dyn3d/gr_dyn_fi.F
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/dyn3d/gr_dyn_fi.F ; \
+	$(AR) r $(LIBO)/libdyn3d.a gr_dyn_fi.o ; $(RM) gr_dyn_fi.o ; \
+	cd $(GCM)
+
+$(LIBO)/libdyn3d.a(gr_fi_dyn.o) : $(LIBF)/dyn3d/gr_fi_dyn.F
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/dyn3d/gr_fi_dyn.F ; \
+	$(AR) r $(LIBO)/libdyn3d.a gr_fi_dyn.o ; $(RM) gr_fi_dyn.o ; \
+	cd $(GCM)
+
+$(LIBO)/libdyn3d.a(gr_int_dyn.o) : $(LIBF)/dyn3d/gr_int_dyn.F
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/dyn3d/gr_int_dyn.F ; \
+	$(AR) r $(LIBO)/libdyn3d.a gr_int_dyn.o ; $(RM) gr_int_dyn.o ; \
+	cd $(GCM)
+
+$(LIBO)/libdyn3d.a(gr_u_scal.o) : $(LIBF)/dyn3d/gr_u_scal.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/dyn3d/paramet.h \
+$(LIBF)/dyn3d/comgeom.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/dyn3d/gr_u_scal.F ; \
+	$(AR) r $(LIBO)/libdyn3d.a gr_u_scal.o ; $(RM) gr_u_scal.o ; \
+	cd $(GCM)
+
+$(LIBO)/libdyn3d.a(gr_v_scal.o) : $(LIBF)/dyn3d/gr_v_scal.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/dyn3d/paramet.h \
+$(LIBF)/dyn3d/comgeom.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/dyn3d/gr_v_scal.F ; \
+	$(AR) r $(LIBO)/libdyn3d.a gr_v_scal.o ; $(RM) gr_v_scal.o ; \
+	cd $(GCM)
+
 $(LIBO)/libdyn3d.a(grad.o) : $(LIBF)/dyn3d/grad.F \
 $(LIBF)/grid/dimensions.h \
@@ -1033,4 +1071,14 @@
 	cd $(GCM)
 
+$(LIBO)/libdyn3d.a(gradiv.o) : $(LIBF)/dyn3d/gradiv.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/dyn3d/paramet.h \
+$(LIBF)/dyn3d/comdissipn.h \
+$(LIBF)/dyn3d/logic.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/dyn3d/gradiv.F ; \
+	$(AR) r $(LIBO)/libdyn3d.a gradiv.o ; $(RM) gradiv.o ; \
+	cd $(GCM)
+
 $(LIBO)/libdyn3d.a(gradiv2.o) : $(LIBF)/dyn3d/gradiv2.F \
 $(LIBF)/grid/dimensions.h \
@@ -1043,26 +1091,4 @@
 	cd $(GCM)
 
-$(LIBO)/libdyn3d.a(gradiv.o) : $(LIBF)/dyn3d/gradiv.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/dyn3d/paramet.h \
-$(LIBF)/dyn3d/comdissipn.h \
-$(LIBF)/dyn3d/logic.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/gradiv.F ; \
-	$(AR) r $(LIBO)/libdyn3d.a gradiv.o ; $(RM) gradiv.o ; \
-	cd $(GCM)
-
-$(LIBO)/libdyn3d.a(gr_dyn_fi.o) : $(LIBF)/dyn3d/gr_dyn_fi.F
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/gr_dyn_fi.F ; \
-	$(AR) r $(LIBO)/libdyn3d.a gr_dyn_fi.o ; $(RM) gr_dyn_fi.o ; \
-	cd $(GCM)
-
-$(LIBO)/libdyn3d.a(gr_fi_dyn.o) : $(LIBF)/dyn3d/gr_fi_dyn.F
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/gr_fi_dyn.F ; \
-	$(AR) r $(LIBO)/libdyn3d.a gr_fi_dyn.o ; $(RM) gr_fi_dyn.o ; \
-	cd $(GCM)
-
 $(LIBO)/libdyn3d.a(grid_atob.o) : $(LIBF)/dyn3d/grid_atob.F
 	cd $(LOCAL_DIR); \
@@ -1071,4 +1097,11 @@
 	cd $(GCM)
 
+$(LIBO)/libdyn3d.a(grid_noro.o) : $(LIBF)/dyn3d/grid_noro.F \
+$(LIBF)/grid/dimensions.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/dyn3d/grid_noro.F ; \
+	$(AR) r $(LIBO)/libdyn3d.a grid_noro.o ; $(RM) grid_noro.o ; \
+	cd $(GCM)
+
 $(LIBO)/libdyn3d.a(grid_noro1.o) : $(LIBF)/dyn3d/grid_noro1.F \
 $(LIBF)/grid/dimensions.h \
@@ -1079,17 +1112,4 @@
 	cd $(GCM)
 
-$(LIBO)/libdyn3d.a(grid_noro.o) : $(LIBF)/dyn3d/grid_noro.F \
-$(LIBF)/grid/dimensions.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/grid_noro.F ; \
-	$(AR) r $(LIBO)/libdyn3d.a grid_noro.o ; $(RM) grid_noro.o ; \
-	cd $(GCM)
-
-$(LIBO)/libdyn3d.a(gr_int_dyn.o) : $(LIBF)/dyn3d/gr_int_dyn.F
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/gr_int_dyn.F ; \
-	$(AR) r $(LIBO)/libdyn3d.a gr_int_dyn.o ; $(RM) gr_int_dyn.o ; \
-	cd $(GCM)
-
 $(LIBO)/libdyn3d.a(groupe.o) : $(LIBF)/dyn3d/groupe.F \
 $(LIBF)/grid/dimensions.h \
@@ -1113,35 +1133,8 @@
 	cd $(GCM)
 
-$(LIBO)/libdyn3d.a(gr_u_scal.o) : $(LIBF)/dyn3d/gr_u_scal.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/dyn3d/paramet.h \
-$(LIBF)/dyn3d/comgeom.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/gr_u_scal.F ; \
-	$(AR) r $(LIBO)/libdyn3d.a gr_u_scal.o ; $(RM) gr_u_scal.o ; \
-	cd $(GCM)
-
-$(LIBO)/libdyn3d.a(gr_v_scal.o) : $(LIBF)/dyn3d/gr_v_scal.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/dyn3d/paramet.h \
-$(LIBF)/dyn3d/comgeom.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/gr_v_scal.F ; \
-	$(AR) r $(LIBO)/libdyn3d.a gr_v_scal.o ; $(RM) gr_v_scal.o ; \
-	cd $(GCM)
-
 $(LIBO)/libdyn3d.a(heavyside.o) : $(LIBF)/dyn3d/heavyside.F
 	cd $(LOCAL_DIR); \
 	$(COMPILE) $(LIBF)/dyn3d/heavyside.F ; \
 	$(AR) r $(LIBO)/libdyn3d.a heavyside.o ; $(RM) heavyside.o ; \
-	cd $(GCM)
-
-$(LIBO)/libdyn3d.a(iniadvtrac.o) : $(LIBF)/dyn3d/iniadvtrac.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/dyn3d/advtrac.h \
-$(LIBF)/dyn3d/control.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/iniadvtrac.F ; \
-	$(AR) r $(LIBO)/libdyn3d.a iniadvtrac.o ; $(RM) iniadvtrac.o ; \
 	cd $(GCM)
 
@@ -1165,4 +1158,13 @@
 	cd $(GCM)
 
+$(LIBO)/libdyn3d.a(iniadvtrac.o) : $(LIBF)/dyn3d/iniadvtrac.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/dyn3d/advtrac.h \
+$(LIBF)/dyn3d/control.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/dyn3d/iniadvtrac.F ; \
+	$(AR) r $(LIBO)/libdyn3d.a iniadvtrac.o ; $(RM) iniadvtrac.o ; \
+	cd $(GCM)
+
 $(LIBO)/libdyn3d.a(iniav.o) : $(LIBF)/dyn3d/iniav.F \
 $(LIBF)/grid/dimensions.h \
@@ -1292,16 +1294,4 @@
 	$(COMPILE) $(LIBF)/dyn3d/laplacien_rotgam.F ; \
 	$(AR) r $(LIBO)/libdyn3d.a laplacien_rotgam.o ; $(RM) laplacien_rotgam.o ; \
-	cd $(GCM)
-
-$(LIBO)/libdyn3d.a(lectflux.o) : $(LIBF)/dyn3d/lectflux.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/dyn3d/paramet.h \
-$(LIBF)/dyn3d/comvert.h \
-$(LIBF)/dyn3d/comconst.h \
-$(LIBF)/dyn3d/comgeom2.h \
-$(LIBF)/dyn3d/tracstoke.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/lectflux.F ; \
-	$(AR) r $(LIBO)/libdyn3d.a lectflux.o ; $(RM) lectflux.o ; \
 	cd $(GCM)
 
@@ -1329,4 +1319,16 @@
 	cd $(GCM)
 
+$(LIBO)/libdyn3d.a(lectflux.o) : $(LIBF)/dyn3d/lectflux.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/dyn3d/paramet.h \
+$(LIBF)/dyn3d/comvert.h \
+$(LIBF)/dyn3d/comconst.h \
+$(LIBF)/dyn3d/comgeom2.h \
+$(LIBF)/dyn3d/tracstoke.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/dyn3d/lectflux.F ; \
+	$(AR) r $(LIBO)/libdyn3d.a lectflux.o ; $(RM) lectflux.o ; \
+	cd $(GCM)
+
 $(LIBO)/libdyn3d.a(massbar.o) : $(LIBF)/dyn3d/massbar.F \
 $(LIBF)/grid/dimensions.h \
@@ -1469,4 +1471,13 @@
 	cd $(GCM)
 
+$(LIBO)/libdyn3d.a(rotat_nfil.o) : $(LIBF)/dyn3d/rotat_nfil.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/dyn3d/paramet.h \
+$(LIBF)/dyn3d/comgeom.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/dyn3d/rotat_nfil.F ; \
+	$(AR) r $(LIBO)/libdyn3d.a rotat_nfil.o ; $(RM) rotat_nfil.o ; \
+	cd $(GCM)
+
 $(LIBO)/libdyn3d.a(rotatf.o) : $(LIBF)/dyn3d/rotatf.F \
 $(LIBF)/grid/dimensions.h \
@@ -1478,13 +1489,4 @@
 	cd $(GCM)
 
-$(LIBO)/libdyn3d.a(rotat_nfil.o) : $(LIBF)/dyn3d/rotat_nfil.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/dyn3d/paramet.h \
-$(LIBF)/dyn3d/comgeom.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/rotat_nfil.F ; \
-	$(AR) r $(LIBO)/libdyn3d.a rotat_nfil.o ; $(RM) rotat_nfil.o ; \
-	cd $(GCM)
-
 $(LIBO)/libdyn3d.a(rotatst.o) : $(LIBF)/dyn3d/rotatst.F \
 $(LIBF)/grid/dimensions.h \
@@ -1504,5 +1506,5 @@
 	cd $(GCM)
 
-$(LIBO)/libdyn3d.a(sortvarc0.o) : $(LIBF)/dyn3d/sortvarc0.F \
+$(LIBO)/libdyn3d.a(sortvarc.o) : $(LIBF)/dyn3d/sortvarc.F \
 $(LIBF)/grid/dimensions.h \
 $(LIBF)/dyn3d/paramet.h \
@@ -1514,9 +1516,9 @@
 $(LIBF)/dyn3d/temps.h
 	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/sortvarc0.F ; \
-	$(AR) r $(LIBO)/libdyn3d.a sortvarc0.o ; $(RM) sortvarc0.o ; \
-	cd $(GCM)
-
-$(LIBO)/libdyn3d.a(sortvarc.o) : $(LIBF)/dyn3d/sortvarc.F \
+	$(COMPILE) $(LIBF)/dyn3d/sortvarc.F ; \
+	$(AR) r $(LIBO)/libdyn3d.a sortvarc.o ; $(RM) sortvarc.o ; \
+	cd $(GCM)
+
+$(LIBO)/libdyn3d.a(sortvarc0.o) : $(LIBF)/dyn3d/sortvarc0.F \
 $(LIBF)/grid/dimensions.h \
 $(LIBF)/dyn3d/paramet.h \
@@ -1528,6 +1530,6 @@
 $(LIBF)/dyn3d/temps.h
 	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/dyn3d/sortvarc.F ; \
-	$(AR) r $(LIBO)/libdyn3d.a sortvarc.o ; $(RM) sortvarc.o ; \
+	$(COMPILE) $(LIBF)/dyn3d/sortvarc0.F ; \
+	$(AR) r $(LIBO)/libdyn3d.a sortvarc0.o ; $(RM) sortvarc0.o ; \
 	cd $(GCM)
 
@@ -1793,130 +1795,146 @@
 $(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(blackl.o)
 
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(callsedim.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(convadj.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(cpdet.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(cvmgp.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(cvmgt.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(datareadnc.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(dsolver.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(dtridgl.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(evap.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(forceWCfn.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(gfluxi.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(gfluxv.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(inifis.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(iniorbit.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(inistats.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(initracer.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(iniwrite.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(iniwrite_spec.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(interp_line.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(ismax.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(ismin.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(lagrange.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(largescale.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(mucorr.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(mufract.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(multipl.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(newsedim.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(orbite.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(phyetat0.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(physdem1.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(profile.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(rcm1d.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(scopyi.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(sfluxi.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(sfluxv.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(soil.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(soil_settings.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(stelang.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(stellarlong.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(surface_nature.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(surfini.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(tabfi.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(tpindex.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(vdif_cd.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(vdif_kc.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(vdifc.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(vlz_fi.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(writediagfi.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(writediagspec.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(writeg1d.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(zerophys.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(N2broadprof_fn.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(aeropacity.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(aeroptproperties.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(ave_stelspec.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(calc_cpp3d.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(calc_cpp_mugaz.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(calc_rayleigh.o)
+
 $(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(callcorrk.o)
 
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(callsedim.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(co2snow.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(convadj.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(cvmgp.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(cvmgt.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(datareadnc.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(dsolver.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(dtridgl.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(gfluxi.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(gfluxv.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(inifis.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(iniorbit.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(inistats.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(initracer.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(iniwrite.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(iniwrite_spec.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(interp_line.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(ismax.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(ismin.o)
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(condens_co2cloud.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(def_var.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(hydrol.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(iniwritesoil.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(interpolateH2H2.o)
 
 $(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(kastprof_fn.o)
 
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(lagrange.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(largescale2.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(mucorr.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(mufract.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(multipl.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(newsedim.o)
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(mkstat.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(moistadj.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(newtrelax.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(optci.o)
 
 $(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(optcv.o)
 
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(orbite.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(phyetat0.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(physdem1.o)
-
 $(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(physiq.o)
 
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(profile.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(scopyi.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(sfluxi.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(sfluxv.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(soil.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(soil_settings.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(solang.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(solarlong.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(surfini.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(tabfi.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(tpindex.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(vdif_cd.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(vdifc.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(vdif_kc.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(vlz_fi.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(writediagfi.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(writediagspec.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(writeg1d.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(zerophys.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(aeropacity.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(aeroptproperties.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(aeroptpropertiesJBnew.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(ave_stelspec.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(calc_cpp3d.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(calc_rayleigh.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(condens_co2cloud.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(def_var.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(iniwritesoil.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(mkstat.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(moistadj.o)
-
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(optci.o)
-
 $(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(radcommon_h.o)
 
@@ -1929,15 +1947,21 @@
 $(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(setspv.o)
 
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(simpleprof_fn.o)
+
 $(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(stokes.o)
 
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(su_gases.o)
+
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(su_watercycle.o)
+
 $(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(suaer_corrk.o)
 
 $(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(sugas_corrk.o)
 
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(su_watercycle.o)
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(totalcloudfrac.o)
 
 $(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(watercommon_h.o)
 
-$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(watersat_2.o)
+$(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(watersat.o)
 
 $(LIBO)/libphystd.a :  $(LIBO)/libphystd.a(watersat_grad.o)
@@ -1970,18 +1994,4 @@
 	cd $(GCM)
 
-$(LIBO)/libphystd.a(callcorrk.o) : $(LIBF)/phystd/callcorrk.F \
-$(LIBF)/phystd/dimphys.h \
-$(LIBF)/phystd/datafile.h \
-$(LIBF)/phystd/comcstfi.h \
-$(LIBF)/phystd/callkeys.h \
-$(LIBF)/phystd/tracer.h \
-$(LIBO)/libphystd.a(radinc_h.o) \
-$(LIBO)/libphystd.a(radcommon_h.o) \
-$(LIBO)/libbibio.a(ioipsl_getincom.o)
-	cd $(LOCAL_DIR); \
-	$(COMPILE90) $(LIBF)/phystd/callcorrk.F ; \
-	$(AR) r $(LIBO)/libphystd.a callcorrk.o ; $(RM) callcorrk.o ; \
-	cd $(GCM)
-
 $(LIBO)/libphystd.a(callsedim.o) : $(LIBF)/phystd/callsedim.F \
 $(LIBF)/grid/dimensions.h \
@@ -1996,15 +2006,4 @@
 	cd $(GCM)
 
-$(LIBO)/libphystd.a(co2snow.o) : $(LIBF)/phystd/co2snow.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h \
-$(LIBF)/phystd/comcstfi.h \
-$(LIBF)/phystd/surfdat.h \
-$(LIBF)/phystd/callkeys.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/co2snow.F ; \
-	$(AR) r $(LIBO)/libphystd.a co2snow.o ; $(RM) co2snow.o ; \
-	cd $(GCM)
-
 $(LIBO)/libphystd.a(convadj.o) : $(LIBF)/phystd/convadj.F \
 $(LIBF)/grid/dimensions.h \
@@ -2016,4 +2015,14 @@
 	$(COMPILE) $(LIBF)/phystd/convadj.F ; \
 	$(AR) r $(LIBO)/libphystd.a convadj.o ; $(RM) convadj.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(cpdet.o) : $(LIBF)/phystd/cpdet.F \
+$(LIBF)/phystd/cpdet.h \
+$(LIBF)/phystd/cpdet.h \
+$(LIBF)/phystd/cpdet.h \
+$(LIBF)/phystd/cpdet.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/cpdet.F ; \
+	$(AR) r $(LIBO)/libphystd.a cpdet.o ; $(RM) cpdet.o ; \
 	cd $(GCM)
 
@@ -2055,4 +2064,25 @@
 	cd $(GCM)
 
+$(LIBO)/libphystd.a(evap.o) : $(LIBF)/phystd/evap.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/tracer.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBO)/libphystd.a(watercommon_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPILE90) $(LIBF)/phystd/evap.F ; \
+	$(AR) r $(LIBO)/libphystd.a evap.o ; $(RM) evap.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(forceWCfn.o) : $(LIBF)/phystd/forceWCfn.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/tracer.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/forceWCfn.F ; \
+	$(AR) r $(LIBO)/libphystd.a forceWCfn.o ; $(RM) forceWCfn.o ; \
+	cd $(GCM)
+
 $(LIBO)/libphystd.a(gfluxi.o) : $(LIBF)/phystd/gfluxi.F \
 $(LIBF)/phystd/comcstfi.h \
@@ -2081,4 +2111,5 @@
 $(LIBF)/phystd/callkeys.h \
 $(LIBF)/phystd/surfdat.h \
+$(LIBO)/libphystd.a(radinc_h.o) \
 $(LIBO)/libbibio.a(ioipsl_getincom.o)
 	cd $(LOCAL_DIR); \
@@ -2178,13 +2209,4 @@
 	cd $(GCM)
 
-$(LIBO)/libphystd.a(kastprof_fn.o) : $(LIBF)/phystd/kastprof_fn.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h \
-$(LIBF)/phystd/comcstfi.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/kastprof_fn.F ; \
-	$(AR) r $(LIBO)/libphystd.a kastprof_fn.o ; $(RM) kastprof_fn.o ; \
-	cd $(GCM)
-
 $(LIBO)/libphystd.a(lagrange.o) : $(LIBF)/phystd/lagrange.F
 	cd $(LOCAL_DIR); \
@@ -2193,5 +2215,5 @@
 	cd $(GCM)
 
-$(LIBO)/libphystd.a(largescale2.o) : $(LIBF)/phystd/largescale2.F \
+$(LIBO)/libphystd.a(largescale.o) : $(LIBF)/phystd/largescale.F \
 $(LIBF)/grid/dimensions.h \
 $(LIBF)/phystd/dimphys.h \
@@ -2202,6 +2224,6 @@
 $(LIBO)/libphystd.a(watercommon_h.o)
 	cd $(LOCAL_DIR); \
-	$(COMPILE90) $(LIBF)/phystd/largescale2.F ; \
-	$(AR) r $(LIBO)/libphystd.a largescale2.o ; $(RM) largescale2.o ; \
+	$(COMPILE90) $(LIBF)/phystd/largescale.F ; \
+	$(AR) r $(LIBO)/libphystd.a largescale.o ; $(RM) largescale.o ; \
 	cd $(GCM)
 
@@ -2231,13 +2253,4 @@
 	$(COMPILE) $(LIBF)/phystd/newsedim.F ; \
 	$(AR) r $(LIBO)/libphystd.a newsedim.o ; $(RM) newsedim.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(optcv.o) : $(LIBF)/phystd/optcv.F \
-$(LIBF)/phystd/comcstfi.h \
-$(LIBO)/libphystd.a(radinc_h.o) \
-$(LIBO)/libphystd.a(radcommon_h.o)
-	cd $(LOCAL_DIR); \
-	$(COMPILE90) $(LIBF)/phystd/optcv.F ; \
-	$(AR) r $(LIBO)/libphystd.a optcv.o ; $(RM) optcv.o ; \
 	cd $(GCM)
 
@@ -2289,5 +2302,433 @@
 	cd $(GCM)
 
-$(LIBO)/libphystd.a(physiq.o) : $(LIBF)/phystd/physiq.F \
+$(LIBO)/libphystd.a(profile.o) : $(LIBF)/phystd/profile.F \
+$(LIBO)/libbibio.a(ioipsl_getincom.o)
+	cd $(LOCAL_DIR); \
+	$(COMPILE90) $(LIBF)/phystd/profile.F ; \
+	$(AR) r $(LIBO)/libphystd.a profile.o ; $(RM) profile.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(rcm1d.o) : $(LIBF)/phystd/rcm1d.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/comgeomfi.h \
+$(LIBF)/phystd/surfdat.h \
+$(LIBF)/phystd/comsoil.h \
+$(LIBF)/phystd/comdiurn.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/planete.h \
+$(LIBF)/phystd/comsaison.h \
+$(LIBF)/dyn3d/control.h \
+$(LIBF)/dyn3d/comvert.h \
+$(LIBF)/phystd/comg1d.h \
+$(LIBF)/phystd/watercap.h \
+$(LIBF)/phystd/fisice.h \
+$(LIBF)/dyn3d/logic.h \
+$(LIBF)/dyn3d/advtrac.h \
+$(LIBO)/libphystd.a(radcommon_h.o) \
+$(LIBO)/libbibio.a(ioipsl_getincom.o)
+	cd $(LOCAL_DIR); \
+	$(COMPILE90) $(LIBF)/phystd/rcm1d.F ; \
+	$(AR) r $(LIBO)/libphystd.a rcm1d.o ; $(RM) rcm1d.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(scopyi.o) : $(LIBF)/phystd/scopyi.F
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/scopyi.F ; \
+	$(AR) r $(LIBO)/libphystd.a scopyi.o ; $(RM) scopyi.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(sfluxi.o) : $(LIBF)/phystd/sfluxi.F \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBO)/libphystd.a(radinc_h.o) \
+$(LIBO)/libphystd.a(radcommon_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPILE90) $(LIBF)/phystd/sfluxi.F ; \
+	$(AR) r $(LIBO)/libphystd.a sfluxi.o ; $(RM) sfluxi.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(sfluxv.o) : $(LIBF)/phystd/sfluxv.F \
+$(LIBO)/libphystd.a(radinc_h.o) \
+$(LIBO)/libphystd.a(radcommon_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPILE90) $(LIBF)/phystd/sfluxv.F ; \
+	$(AR) r $(LIBO)/libphystd.a sfluxv.o ; $(RM) sfluxv.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(soil.o) : $(LIBF)/phystd/soil.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/comsoil.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/soil.F ; \
+	$(AR) r $(LIBO)/libphystd.a soil.o ; $(RM) soil.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(soil_settings.o) : $(LIBF)/phystd/soil_settings.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/comsoil.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/soil_settings.F ; \
+	$(AR) r $(LIBO)/libphystd.a soil_settings.o ; $(RM) soil_settings.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(stelang.o) : $(LIBF)/phystd/stelang.F
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/stelang.F ; \
+	$(AR) r $(LIBO)/libphystd.a stelang.o ; $(RM) stelang.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(stellarlong.o) : $(LIBF)/phystd/stellarlong.F \
+$(LIBF)/phystd/planete.h \
+$(LIBF)/phystd/comcstfi.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/stellarlong.F ; \
+	$(AR) r $(LIBO)/libphystd.a stellarlong.o ; $(RM) stellarlong.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(surface_nature.o) : $(LIBF)/phystd/surface_nature.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBF)/phystd/tracer.h \
+$(LIBF)/phystd/fisice.h \
+$(LIBF)/phystd/comgeomfi.h \
+$(LIBF)/phystd/surfdat.h \
+$(LIBF)/phystd/comsoil.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/surface_nature.F ; \
+	$(AR) r $(LIBO)/libphystd.a surface_nature.o ; $(RM) surface_nature.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(surfini.o) : $(LIBF)/phystd/surfini.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/surfdat.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBF)/phystd/tracer.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/surfini.F ; \
+	$(AR) r $(LIBO)/libphystd.a surfini.o ; $(RM) surfini.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(tabfi.o) : $(LIBF)/phystd/tabfi.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/comgeomfi.h \
+$(LIBF)/phystd/planete.h \
+$(LIBF)/phystd/surfdat.h \
+$(LIBF)/phystd/comsoil.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBO)/libbibio.a(ioipsl_getincom.o) \
+$(LIBO)/libphystd.a(radcommon_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPILE90) $(LIBF)/phystd/tabfi.F ; \
+	$(AR) r $(LIBO)/libphystd.a tabfi.o ; $(RM) tabfi.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(tpindex.o) : $(LIBF)/phystd/tpindex.F \
+$(LIBO)/libphystd.a(radinc_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPILE90) $(LIBF)/phystd/tpindex.F ; \
+	$(AR) r $(LIBO)/libphystd.a tpindex.o ; $(RM) tpindex.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(vdif_cd.o) : $(LIBF)/phystd/vdif_cd.F
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/vdif_cd.F ; \
+	$(AR) r $(LIBO)/libphystd.a vdif_cd.o ; $(RM) vdif_cd.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(vdif_kc.o) : $(LIBF)/phystd/vdif_kc.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/vdif_kc.F ; \
+	$(AR) r $(LIBO)/libphystd.a vdif_kc.o ; $(RM) vdif_kc.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(vdifc.o) : $(LIBF)/phystd/vdifc.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBF)/phystd/surfdat.h \
+$(LIBF)/phystd/comgeomfi.h \
+$(LIBF)/phystd/tracer.h \
+$(LIBF)/phystd/watercap.h \
+$(LIBO)/libphystd.a(watercommon_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPILE90) $(LIBF)/phystd/vdifc.F ; \
+	$(AR) r $(LIBO)/libphystd.a vdifc.o ; $(RM) vdifc.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(vlz_fi.o) : $(LIBF)/phystd/vlz_fi.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/vlz_fi.F ; \
+	$(AR) r $(LIBO)/libphystd.a vlz_fi.o ; $(RM) vlz_fi.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(writediagfi.o) : $(LIBF)/phystd/writediagfi.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/dyn3d/paramet.h \
+$(LIBF)/dyn3d/control.h \
+$(LIBF)/dyn3d/comvert.h \
+$(LIBF)/dyn3d/comgeom.h \
+$(LIBF)/dyn3d/description.h \
+$(LIBF)/dyn3d/temps.h \
+$(LIBF)/phystd/surfdat.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/writediagfi.F ; \
+	$(AR) r $(LIBO)/libphystd.a writediagfi.o ; $(RM) writediagfi.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(writediagspec.o) : $(LIBF)/phystd/writediagspec.F \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/dyn3d/paramet.h \
+$(LIBF)/dyn3d/control.h \
+$(LIBF)/dyn3d/comvert.h \
+$(LIBF)/dyn3d/comgeom.h \
+$(LIBF)/dyn3d/description.h \
+$(LIBF)/dyn3d/temps.h \
+$(LIBF)/phystd/surfdat.h \
+$(LIBO)/libphystd.a(radinc_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPILE90) $(LIBF)/phystd/writediagspec.F ; \
+	$(AR) r $(LIBO)/libphystd.a writediagspec.o ; $(RM) writediagspec.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(writeg1d.o) : $(LIBF)/phystd/writeg1d.F \
+$(LIBF)/phystd/comg1d.h \
+$(LIBF)/phystd/comg1d.h \
+$(LIBF)/phystd/comcstfi.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/writeg1d.F ; \
+	$(AR) r $(LIBO)/libphystd.a writeg1d.o ; $(RM) writeg1d.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(zerophys.o) : $(LIBF)/phystd/zerophys.F
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/zerophys.F ; \
+	$(AR) r $(LIBO)/libphystd.a zerophys.o ; $(RM) zerophys.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(N2broadprof_fn.o) : $(LIBF)/phystd/N2broadprof_fn.F90 \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/callkeys.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/N2broadprof_fn.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a N2broadprof_fn.o ; $(RM) N2broadprof_fn.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(aeropacity.o) : $(LIBF)/phystd/aeropacity.F90 \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/comgeomfi.h \
+$(LIBF)/phystd/tracer.h \
+$(LIBO)/libphystd.a(radinc_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPTRU90) $(LIBF)/phystd/aeropacity.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a aeropacity.o ; $(RM) aeropacity.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(aeroptproperties.o) : $(LIBF)/phystd/aeroptproperties.F90 \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBO)/libphystd.a(radinc_h.o) \
+$(LIBO)/libphystd.a(radcommon_h.o) \
+$(LIBO)/libphystd.a(radcommon_h.o) \
+$(LIBO)/libphystd.a(radcommon_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPTRU90) $(LIBF)/phystd/aeroptproperties.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a aeroptproperties.o ; $(RM) aeroptproperties.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(ave_stelspec.o) : $(LIBF)/phystd/ave_stelspec.F90 \
+$(LIBF)/phystd/datafile.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBO)/libphystd.a(radinc_h.o) \
+$(LIBO)/libphystd.a(radcommon_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPTRU90) $(LIBF)/phystd/ave_stelspec.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a ave_stelspec.o ; $(RM) ave_stelspec.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(calc_cpp3d.o) : $(LIBF)/phystd/calc_cpp3d.F90 \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBF)/phystd/cpdet.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/calc_cpp3d.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a calc_cpp3d.o ; $(RM) calc_cpp3d.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(calc_cpp_mugaz.o) : $(LIBF)/phystd/calc_cpp_mugaz.F90 \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBF)/phystd/gases.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/calc_cpp_mugaz.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a calc_cpp_mugaz.o ; $(RM) calc_cpp_mugaz.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(calc_rayleigh.o) : $(LIBF)/phystd/calc_rayleigh.F90 \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBF)/phystd/gases.h \
+$(LIBO)/libphystd.a(radinc_h.o) \
+$(LIBO)/libphystd.a(radcommon_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPTRU90) $(LIBF)/phystd/calc_rayleigh.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a calc_rayleigh.o ; $(RM) calc_rayleigh.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(callcorrk.o) : $(LIBF)/phystd/callcorrk.F90 \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/datafile.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBF)/phystd/tracer.h \
+$(LIBO)/libphystd.a(radinc_h.o) \
+$(LIBO)/libphystd.a(radcommon_h.o) \
+$(LIBO)/libphystd.a(watercommon_h.o) \
+$(LIBO)/libbibio.a(ioipsl_getincom.o)
+	cd $(LOCAL_DIR); \
+	$(COMPTRU90) $(LIBF)/phystd/callcorrk.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a callcorrk.o ; $(RM) callcorrk.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(condens_co2cloud.o) : $(LIBF)/phystd/condens_co2cloud.F90 \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/surfdat.h \
+$(LIBF)/phystd/comgeomfi.h \
+$(LIBF)/dyn3d/comvert.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBF)/phystd/tracer.h \
+$(LIBF)/phystd/gases.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBO)/libphystd.a(radinc_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPTRU90) $(LIBF)/phystd/condens_co2cloud.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a condens_co2cloud.o ; $(RM) condens_co2cloud.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(def_var.o) : $(LIBF)/phystd/def_var.F90
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/def_var.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a def_var.o ; $(RM) def_var.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(hydrol.o) : $(LIBF)/phystd/hydrol.F90 \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBF)/phystd/tracer.h \
+$(LIBF)/phystd/fisice.h \
+$(LIBF)/phystd/comgeomfi.h \
+$(LIBF)/phystd/comdiurn.h \
+$(LIBF)/phystd/surfdat.h \
+$(LIBO)/libphystd.a(watercommon_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPTRU90) $(LIBF)/phystd/hydrol.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a hydrol.o ; $(RM) hydrol.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(iniwritesoil.o) : $(LIBF)/phystd/iniwritesoil.F90 \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/dyn3d/paramet.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/dyn3d/comgeom.h \
+$(LIBF)/phystd/comsoil.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/iniwritesoil.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a iniwritesoil.o ; $(RM) iniwritesoil.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(interpolateH2H2.o) : $(LIBF)/phystd/interpolateH2H2.F90 \
+$(LIBF)/phystd/datafile.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/interpolateH2H2.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a interpolateH2H2.o ; $(RM) interpolateH2H2.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(kastprof_fn.o) : $(LIBF)/phystd/kastprof_fn.F90 \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/callkeys.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/kastprof_fn.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a kastprof_fn.o ; $(RM) kastprof_fn.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(mkstat.o) : $(LIBF)/phystd/mkstat.F90 \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/statto.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/mkstat.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a mkstat.o ; $(RM) mkstat.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(moistadj.o) : $(LIBF)/phystd/moistadj.F90 \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/tracer.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBO)/libphystd.a(watercommon_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPTRU90) $(LIBF)/phystd/moistadj.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a moistadj.o ; $(RM) moistadj.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(newtrelax.o) : $(LIBF)/phystd/newtrelax.F90 \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/callkeys.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/newtrelax.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a newtrelax.o ; $(RM) newtrelax.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(optci.o) : $(LIBF)/phystd/optci.F90 \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBF)/phystd/gases.h \
+$(LIBO)/libphystd.a(radinc_h.o) \
+$(LIBO)/libphystd.a(radcommon_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPTRU90) $(LIBF)/phystd/optci.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a optci.o ; $(RM) optci.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(optcv.o) : $(LIBF)/phystd/optcv.F90 \
+$(LIBF)/phystd/callkeys.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/gases.h \
+$(LIBO)/libphystd.a(radinc_h.o) \
+$(LIBO)/libphystd.a(radcommon_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPTRU90) $(LIBF)/phystd/optcv.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a optcv.o ; $(RM) optcv.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(physiq.o) : $(LIBF)/phystd/physiq.F90 \
 $(LIBF)/grid/dimensions.h \
 $(LIBF)/phystd/dimphys.h \
@@ -2304,366 +2745,73 @@
 $(LIBF)/phystd/tracer.h \
 $(LIBF)/phystd/watercap.h \
-$(LIBF)/phystd/fisice.h \
+$(LIBO)/libphystd.a(radinc_h.o) \
+$(LIBO)/libphystd.a(watercommon_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPTRU90) $(LIBF)/phystd/physiq.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a physiq.o ; $(RM) physiq.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(radcommon_h.o) : $(LIBF)/phystd/radcommon_h.F90 \
 $(LIBO)/libphystd.a(radinc_h.o)
 	cd $(LOCAL_DIR); \
-	$(COMPILE90) $(LIBF)/phystd/physiq.F ; \
-	$(AR) r $(LIBO)/libphystd.a physiq.o ; $(RM) physiq.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(profile.o) : $(LIBF)/phystd/profile.F \
-$(LIBO)/libbibio.a(ioipsl_getincom.o)
-	cd $(LOCAL_DIR); \
-	$(COMPILE90) $(LIBF)/phystd/profile.F ; \
-	$(AR) r $(LIBO)/libphystd.a profile.o ; $(RM) profile.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(scopyi.o) : $(LIBF)/phystd/scopyi.F
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/scopyi.F ; \
-	$(AR) r $(LIBO)/libphystd.a scopyi.o ; $(RM) scopyi.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(sfluxi.o) : $(LIBF)/phystd/sfluxi.F \
-$(LIBF)/phystd/comcstfi.h \
-$(LIBO)/libphystd.a(radinc_h.o) \
-$(LIBO)/libphystd.a(radcommon_h.o)
-	cd $(LOCAL_DIR); \
-	$(COMPILE90) $(LIBF)/phystd/sfluxi.F ; \
-	$(AR) r $(LIBO)/libphystd.a sfluxi.o ; $(RM) sfluxi.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(sfluxv.o) : $(LIBF)/phystd/sfluxv.F \
-$(LIBO)/libphystd.a(radinc_h.o) \
-$(LIBO)/libphystd.a(radcommon_h.o)
-	cd $(LOCAL_DIR); \
-	$(COMPILE90) $(LIBF)/phystd/sfluxv.F ; \
-	$(AR) r $(LIBO)/libphystd.a sfluxv.o ; $(RM) sfluxv.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(soil.o) : $(LIBF)/phystd/soil.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h \
-$(LIBF)/phystd/comsoil.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/soil.F ; \
-	$(AR) r $(LIBO)/libphystd.a soil.o ; $(RM) soil.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(soil_settings.o) : $(LIBF)/phystd/soil_settings.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h \
-$(LIBF)/phystd/comsoil.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/soil_settings.F ; \
-	$(AR) r $(LIBO)/libphystd.a soil_settings.o ; $(RM) soil_settings.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(solang.o) : $(LIBF)/phystd/solang.F
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/solang.F ; \
-	$(AR) r $(LIBO)/libphystd.a solang.o ; $(RM) solang.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(solarlong.o) : $(LIBF)/phystd/solarlong.F \
-$(LIBF)/phystd/planete.h \
-$(LIBF)/phystd/comcstfi.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/solarlong.F ; \
-	$(AR) r $(LIBO)/libphystd.a solarlong.o ; $(RM) solarlong.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(surfini.o) : $(LIBF)/phystd/surfini.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h \
-$(LIBF)/phystd/surfdat.h \
-$(LIBF)/phystd/callkeys.h \
-$(LIBF)/phystd/tracer.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/surfini.F ; \
-	$(AR) r $(LIBO)/libphystd.a surfini.o ; $(RM) surfini.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(tabfi.o) : $(LIBF)/phystd/tabfi.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h \
-$(LIBF)/phystd/comcstfi.h \
-$(LIBF)/phystd/comgeomfi.h \
-$(LIBF)/phystd/planete.h \
-$(LIBF)/phystd/surfdat.h \
-$(LIBF)/phystd/comsoil.h \
-$(LIBF)/phystd/callkeys.h \
-$(LIBO)/libbibio.a(ioipsl_getincom.o) \
-$(LIBO)/libphystd.a(radcommon_h.o)
-	cd $(LOCAL_DIR); \
-	$(COMPILE90) $(LIBF)/phystd/tabfi.F ; \
-	$(AR) r $(LIBO)/libphystd.a tabfi.o ; $(RM) tabfi.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(tpindex.o) : $(LIBF)/phystd/tpindex.F \
-$(LIBO)/libphystd.a(radinc_h.o)
-	cd $(LOCAL_DIR); \
-	$(COMPILE90) $(LIBF)/phystd/tpindex.F ; \
-	$(AR) r $(LIBO)/libphystd.a tpindex.o ; $(RM) tpindex.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(vdif_cd.o) : $(LIBF)/phystd/vdif_cd.F
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/vdif_cd.F ; \
-	$(AR) r $(LIBO)/libphystd.a vdif_cd.o ; $(RM) vdif_cd.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(vdifc.o) : $(LIBF)/phystd/vdifc.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h \
-$(LIBF)/phystd/comcstfi.h \
-$(LIBF)/phystd/callkeys.h \
-$(LIBF)/phystd/surfdat.h \
-$(LIBF)/phystd/comgeomfi.h \
+	$(COMPTRU90) $(LIBF)/phystd/radcommon_h.F90 ; \
+	mv $(MOD_LOC_DIR)/radcommon_h.$(MOD_SUFFIX) $(LIBO)/radcommon_h.$(MOD_SUFFIX) ; \
+	$(AR) r $(LIBO)/libphystd.a radcommon_h.o ; $(RM) radcommon_h.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(radinc_h.o) : $(LIBF)/phystd/radinc_h.F90 \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/grid/bands.h
+	cd $(LOCAL_DIR); \
+	$(COMPTRU90) $(LIBF)/phystd/radinc_h.F90 ; \
+	mv $(MOD_LOC_DIR)/radinc_h.$(MOD_SUFFIX) $(LIBO)/radinc_h.$(MOD_SUFFIX) ; \
+	$(AR) r $(LIBO)/libphystd.a radinc_h.o ; $(RM) radinc_h.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(rain.o) : $(LIBF)/phystd/rain.F90 \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
 $(LIBF)/phystd/tracer.h \
-$(LIBF)/phystd/watercap.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/callkeys.h \
 $(LIBO)/libphystd.a(watercommon_h.o)
 	cd $(LOCAL_DIR); \
-	$(COMPILE90) $(LIBF)/phystd/vdifc.F ; \
-	$(AR) r $(LIBO)/libphystd.a vdifc.o ; $(RM) vdifc.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(vdif_kc.o) : $(LIBF)/phystd/vdif_kc.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/vdif_kc.F ; \
-	$(AR) r $(LIBO)/libphystd.a vdif_kc.o ; $(RM) vdif_kc.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(vlz_fi.o) : $(LIBF)/phystd/vlz_fi.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/vlz_fi.F ; \
-	$(AR) r $(LIBO)/libphystd.a vlz_fi.o ; $(RM) vlz_fi.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(writediagfi.o) : $(LIBF)/phystd/writediagfi.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h \
-$(LIBF)/dyn3d/paramet.h \
-$(LIBF)/dyn3d/control.h \
-$(LIBF)/dyn3d/comvert.h \
-$(LIBF)/dyn3d/comgeom.h \
-$(LIBF)/dyn3d/description.h \
-$(LIBF)/dyn3d/temps.h \
-$(LIBF)/phystd/surfdat.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/writediagfi.F ; \
-	$(AR) r $(LIBO)/libphystd.a writediagfi.o ; $(RM) writediagfi.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(writediagspec.o) : $(LIBF)/phystd/writediagspec.F \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h \
-$(LIBF)/dyn3d/paramet.h \
-$(LIBF)/dyn3d/control.h \
-$(LIBF)/dyn3d/comvert.h \
-$(LIBF)/dyn3d/comgeom.h \
-$(LIBF)/dyn3d/description.h \
-$(LIBF)/dyn3d/temps.h \
-$(LIBF)/phystd/surfdat.h \
-$(LIBO)/libphystd.a(radinc_h.o)
-	cd $(LOCAL_DIR); \
-	$(COMPILE90) $(LIBF)/phystd/writediagspec.F ; \
-	$(AR) r $(LIBO)/libphystd.a writediagspec.o ; $(RM) writediagspec.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(writeg1d.o) : $(LIBF)/phystd/writeg1d.F \
-$(LIBF)/phystd/comg1d.h \
-$(LIBF)/phystd/comg1d.h \
-$(LIBF)/phystd/comcstfi.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/writeg1d.F ; \
-	$(AR) r $(LIBO)/libphystd.a writeg1d.o ; $(RM) writeg1d.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(zerophys.o) : $(LIBF)/phystd/zerophys.F
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/zerophys.F ; \
-	$(AR) r $(LIBO)/libphystd.a zerophys.o ; $(RM) zerophys.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(aeropacity.o) : $(LIBF)/phystd/aeropacity.F90 \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h \
-$(LIBF)/phystd/callkeys.h \
-$(LIBF)/phystd/comcstfi.h \
-$(LIBF)/phystd/comgeomfi.h \
-$(LIBF)/phystd/tracer.h \
-$(LIBO)/libphystd.a(radinc_h.o)
-	cd $(LOCAL_DIR); \
-	$(COMPTRU90) $(LIBF)/phystd/aeropacity.F90 ; \
-	$(AR) r $(LIBO)/libphystd.a aeropacity.o ; $(RM) aeropacity.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(aeroptproperties.o) : $(LIBF)/phystd/aeroptproperties.F90 \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h \
-$(LIBF)/phystd/callkeys.h \
-$(LIBO)/libphystd.a(radinc_h.o) \
-$(LIBO)/libphystd.a(radcommon_h.o) \
-$(LIBO)/libphystd.a(radcommon_h.o)
-	cd $(LOCAL_DIR); \
-	$(COMPTRU90) $(LIBF)/phystd/aeroptproperties.F90 ; \
-	$(AR) r $(LIBO)/libphystd.a aeroptproperties.o ; $(RM) aeroptproperties.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(aeroptpropertiesJBnew.o) : $(LIBF)/phystd/aeroptpropertiesJBnew.F90 \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h \
-$(LIBF)/phystd/callkeys.h \
-$(LIBO)/libphystd.a(radinc_h.o) \
-$(LIBO)/libphystd.a(radcommon_h.o) \
-$(LIBO)/libphystd.a(radcommon_h.o) \
-$(LIBO)/libphystd.a(radcommon_h.o)
-	cd $(LOCAL_DIR); \
-	$(COMPTRU90) $(LIBF)/phystd/aeroptpropertiesJBnew.F90 ; \
-	$(AR) r $(LIBO)/libphystd.a aeroptpropertiesJBnew.o ; $(RM) aeroptpropertiesJBnew.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(ave_stelspec.o) : $(LIBF)/phystd/ave_stelspec.F90 \
+	$(COMPTRU90) $(LIBF)/phystd/rain.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a rain.o ; $(RM) rain.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(setspi.o) : $(LIBF)/phystd/setspi.F90 \
+$(LIBF)/phystd/callkeys.h \
+$(LIBF)/phystd/comcstfi.h \
 $(LIBF)/phystd/datafile.h \
 $(LIBO)/libphystd.a(radinc_h.o) \
 $(LIBO)/libphystd.a(radcommon_h.o)
 	cd $(LOCAL_DIR); \
-	$(COMPTRU90) $(LIBF)/phystd/ave_stelspec.F90 ; \
-	$(AR) r $(LIBO)/libphystd.a ave_stelspec.o ; $(RM) ave_stelspec.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(calc_cpp3d.o) : $(LIBF)/phystd/calc_cpp3d.F90 \
-$(LIBF)/phystd/comcstfi.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/calc_cpp3d.F90 ; \
-	$(AR) r $(LIBO)/libphystd.a calc_cpp3d.o ; $(RM) calc_cpp3d.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(calc_rayleigh.o) : $(LIBF)/phystd/calc_rayleigh.F90 \
-$(LIBF)/phystd/comcstfi.h \
-$(LIBO)/libphystd.a(radinc_h.o) \
-$(LIBO)/libphystd.a(radcommon_h.o)
-	cd $(LOCAL_DIR); \
-	$(COMPTRU90) $(LIBF)/phystd/calc_rayleigh.F90 ; \
-	$(AR) r $(LIBO)/libphystd.a calc_rayleigh.o ; $(RM) calc_rayleigh.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(condens_co2cloud.o) : $(LIBF)/phystd/condens_co2cloud.F90 \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h \
-$(LIBF)/phystd/comcstfi.h \
-$(LIBF)/phystd/surfdat.h \
-$(LIBF)/phystd/comgeomfi.h \
-$(LIBF)/dyn3d/comvert.h \
-$(LIBF)/phystd/callkeys.h \
-$(LIBF)/phystd/tracer.h \
-$(LIBO)/libphystd.a(radinc_h.o)
-	cd $(LOCAL_DIR); \
-	$(COMPTRU90) $(LIBF)/phystd/condens_co2cloud.F90 ; \
-	$(AR) r $(LIBO)/libphystd.a condens_co2cloud.o ; $(RM) condens_co2cloud.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(def_var.o) : $(LIBF)/phystd/def_var.F90
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/def_var.F90 ; \
-	$(AR) r $(LIBO)/libphystd.a def_var.o ; $(RM) def_var.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(iniwritesoil.o) : $(LIBF)/phystd/iniwritesoil.F90 \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h \
-$(LIBF)/dyn3d/paramet.h \
-$(LIBF)/phystd/comcstfi.h \
-$(LIBF)/dyn3d/comgeom.h \
-$(LIBF)/phystd/comsoil.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/iniwritesoil.F90 ; \
-	$(AR) r $(LIBO)/libphystd.a iniwritesoil.o ; $(RM) iniwritesoil.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(mkstat.o) : $(LIBF)/phystd/mkstat.F90 \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/statto.h
-	cd $(LOCAL_DIR); \
-	$(COMPILE) $(LIBF)/phystd/mkstat.F90 ; \
-	$(AR) r $(LIBO)/libphystd.a mkstat.o ; $(RM) mkstat.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(moistadj.o) : $(LIBF)/phystd/moistadj.F90 \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h \
-$(LIBF)/phystd/tracer.h \
-$(LIBF)/phystd/comcstfi.h \
-$(LIBO)/libphystd.a(watercommon_h.o)
-	cd $(LOCAL_DIR); \
-	$(COMPTRU90) $(LIBF)/phystd/moistadj.F90 ; \
-	$(AR) r $(LIBO)/libphystd.a moistadj.o ; $(RM) moistadj.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(optci.o) : $(LIBF)/phystd/optci.F90 \
-$(LIBF)/phystd/comcstfi.h \
-$(LIBF)/phystd/callkeys.h \
-$(LIBO)/libphystd.a(radinc_h.o) \
-$(LIBO)/libphystd.a(radcommon_h.o)
-	cd $(LOCAL_DIR); \
-	$(COMPTRU90) $(LIBF)/phystd/optci.F90 ; \
-	$(AR) r $(LIBO)/libphystd.a optci.o ; $(RM) optci.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(radcommon_h.o) : $(LIBF)/phystd/radcommon_h.F90 \
-$(LIBO)/libphystd.a(radinc_h.o)
-	cd $(LOCAL_DIR); \
-	$(COMPTRU90) $(LIBF)/phystd/radcommon_h.F90 ; \
-	mv $(MOD_LOC_DIR)/radcommon_h.$(MOD_SUFFIX) $(LIBO)/radcommon_h.$(MOD_SUFFIX) ; \
-	$(AR) r $(LIBO)/libphystd.a radcommon_h.o ; $(RM) radcommon_h.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(radinc_h.o) : $(LIBF)/phystd/radinc_h.F90 \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/grid/bands.h
-	cd $(LOCAL_DIR); \
-	$(COMPTRU90) $(LIBF)/phystd/radinc_h.F90 ; \
-	mv $(MOD_LOC_DIR)/radinc_h.$(MOD_SUFFIX) $(LIBO)/radinc_h.$(MOD_SUFFIX) ; \
-	$(AR) r $(LIBO)/libphystd.a radinc_h.o ; $(RM) radinc_h.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(rain.o) : $(LIBF)/phystd/rain.F90 \
-$(LIBF)/grid/dimensions.h \
-$(LIBF)/phystd/dimphys.h \
-$(LIBF)/phystd/tracer.h \
-$(LIBF)/phystd/comcstfi.h \
-$(LIBF)/phystd/callkeys.h \
-$(LIBO)/libphystd.a(watercommon_h.o)
-	cd $(LOCAL_DIR); \
-	$(COMPTRU90) $(LIBF)/phystd/rain.F90 ; \
-	$(AR) r $(LIBO)/libphystd.a rain.o ; $(RM) rain.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(setspi.o) : $(LIBF)/phystd/setspi.F90 \
-$(LIBF)/phystd/callkeys.h \
-$(LIBF)/phystd/comcstfi.h \
+	$(COMPTRU90) $(LIBF)/phystd/setspi.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a setspi.o ; $(RM) setspi.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(setspv.o) : $(LIBF)/phystd/setspv.F90 \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/callkeys.h \
 $(LIBF)/phystd/datafile.h \
 $(LIBO)/libphystd.a(radinc_h.o) \
 $(LIBO)/libphystd.a(radcommon_h.o)
 	cd $(LOCAL_DIR); \
-	$(COMPTRU90) $(LIBF)/phystd/setspi.F90 ; \
-	$(AR) r $(LIBO)/libphystd.a setspi.o ; $(RM) setspi.o ; \
-	cd $(GCM)
-
-$(LIBO)/libphystd.a(setspv.o) : $(LIBF)/phystd/setspv.F90 \
-$(LIBF)/phystd/comcstfi.h \
-$(LIBF)/phystd/callkeys.h \
-$(LIBF)/phystd/datafile.h \
-$(LIBO)/libphystd.a(radinc_h.o) \
-$(LIBO)/libphystd.a(radcommon_h.o)
-	cd $(LOCAL_DIR); \
 	$(COMPTRU90) $(LIBF)/phystd/setspv.F90 ; \
 	$(AR) r $(LIBO)/libphystd.a setspv.o ; $(RM) setspv.o ; \
 	cd $(GCM)
 
+$(LIBO)/libphystd.a(simpleprof_fn.o) : $(LIBF)/phystd/simpleprof_fn.F90 \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/callkeys.h \
+$(LIBO)/libphystd.a(radcommon_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPTRU90) $(LIBF)/phystd/simpleprof_fn.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a simpleprof_fn.o ; $(RM) simpleprof_fn.o ; \
+	cd $(GCM)
+
 $(LIBO)/libphystd.a(stokes.o) : $(LIBF)/phystd/stokes.F90 \
 $(LIBF)/phystd/comcstfi.h
@@ -2671,4 +2819,18 @@
 	$(COMPILE) $(LIBF)/phystd/stokes.F90 ; \
 	$(AR) r $(LIBO)/libphystd.a stokes.o ; $(RM) stokes.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(su_gases.o) : $(LIBF)/phystd/su_gases.F90
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/su_gases.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a su_gases.o ; $(RM) su_gases.o ; \
+	cd $(GCM)
+
+$(LIBO)/libphystd.a(su_watercycle.o) : $(LIBF)/phystd/su_watercycle.F90 \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBO)/libphystd.a(watercommon_h.o)
+	cd $(LOCAL_DIR); \
+	$(COMPTRU90) $(LIBF)/phystd/su_watercycle.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a su_watercycle.o ; $(RM) su_watercycle.o ; \
 	cd $(GCM)
 
@@ -2689,4 +2851,5 @@
 $(LIBF)/phystd/datafile.h \
 $(LIBF)/phystd/callkeys.h \
+$(LIBF)/phystd/gases.h \
 $(LIBO)/libphystd.a(radinc_h.o) \
 $(LIBO)/libphystd.a(radcommon_h.o) \
@@ -2699,10 +2862,15 @@
 	cd $(GCM)
 
-$(LIBO)/libphystd.a(su_watercycle.o) : $(LIBF)/phystd/su_watercycle.F90 \
-$(LIBF)/phystd/comcstfi.h \
-$(LIBO)/libphystd.a(watercommon_h.o)
-	cd $(LOCAL_DIR); \
-	$(COMPTRU90) $(LIBF)/phystd/su_watercycle.F90 ; \
-	$(AR) r $(LIBO)/libphystd.a su_watercycle.o ; $(RM) su_watercycle.o ; \
+$(LIBO)/libphystd.a(totalcloudfrac.o) : $(LIBF)/phystd/totalcloudfrac.F90 \
+$(LIBF)/grid/dimensions.h \
+$(LIBF)/phystd/dimphys.h \
+$(LIBF)/phystd/comcstfi.h \
+$(LIBF)/phystd/tracer.h \
+$(LIBF)/phystd/fisice.h \
+$(LIBF)/phystd/comgeomfi.h \
+$(LIBF)/phystd/comdiurn.h
+	cd $(LOCAL_DIR); \
+	$(COMPILE) $(LIBF)/phystd/totalcloudfrac.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a totalcloudfrac.o ; $(RM) totalcloudfrac.o ; \
 	cd $(GCM)
 
@@ -2714,9 +2882,9 @@
 	cd $(GCM)
 
-$(LIBO)/libphystd.a(watersat_2.o) : $(LIBF)/phystd/watersat_2.F90 \
+$(LIBO)/libphystd.a(watersat.o) : $(LIBF)/phystd/watersat.F90 \
 $(LIBO)/libphystd.a(watercommon_h.o)
 	cd $(LOCAL_DIR); \
-	$(COMPTRU90) $(LIBF)/phystd/watersat_2.F90 ; \
-	$(AR) r $(LIBO)/libphystd.a watersat_2.o ; $(RM) watersat_2.o ; \
+	$(COMPTRU90) $(LIBF)/phystd/watersat.F90 ; \
+	$(AR) r $(LIBO)/libphystd.a watersat.o ; $(RM) watersat.o ; \
 	cd $(GCM)
 
Index: /trunk/LMDZ.GENERIC/makegcm
===================================================================
--- /trunk/LMDZ.GENERIC/makegcm	(revision 252)
+++ /trunk/LMDZ.GENERIC/makegcm	(revision 253)
@@ -18,20 +18,9 @@
 ########################################################################
 
-###### VERSION LMDZ.3.3
-# set LMDGCM=$HOME/LMDZ.3.3
-#
-
 #### If you want you can set environment variables here
-#setenv LMDGCM /d5/emlmd/test_universal/v0.4/LMDZ.UCM
+#setenv LMDGCM "/san/home/rdword/gcm/LMDZ.GENERIC"
 #setenv LIBOGCM $LMDGCM/libo
-#if ( `uname -m` == "x86_64" ) then
-## 64 bit machines
-#  setenv NCDFLIB /donnees/emlmd/netcdf64-4.0.1_pgi/lib
-#  setenv NCDFINC /donnees/emlmd/netcdf64-4.0.1_pgi/include
-#else
-#  setenv NCDFLIB /donnees/emlmd/netcdf-4.0.1_pgi/lib
-#  setenv NCDFINC /donnees/emlmd/netcdf-4.0.1_pgi/include
-#endif
-
+setenv NCDFLIB /usr/local/lib
+setenv NCDFINC /usr/local/include
 ####
 
@@ -181,11 +170,9 @@
 else if $DEC then
 else if $LINUX then
-   set optim90=" -fast"
-   set optimtru90=" -fast -c -Mfree "
-#   set opt_link=" -Mfree -L/usr/local/pgi/linux86/lib -lpgf90 -lpgftnrtl -lpghpf -lpghpf2 -L$NCDFLIB -lnetcdf -Wl,-Bstatic "
-# Ehouarn: there is no /usr/local/pgi/linux86/lib, but it doesn't matter
-#          also changed -Wl,-Bstatic to -Bstatic
-   set opt_link=" -Mfree -lpgf90 -lpgftnrtl -lpghpf -lpghpf2 -L$NCDFLIB -lnetcdf -Bstatic "
-   set mod_loc_dir=$localdir
+   #NB: on gnome -O3 ==> NaNs ...
+   set optim=" -O2 -ip -mkl=sequential -align common "
+   set optim90=" -O2 -ip -mkl=sequential -align common "
+   set optimtru90=" -O2 -ip -mkl=sequential -align common "
+   set mod_loc_dir=$LIBOGCM
    set mod_suffix=mod
 else if $NEC then
@@ -337,9 +324,9 @@
 ########################################################################
 
-    case -d:
+    case -d
         set dim=$2 ; shift ; shift ; goto top
                         
     case -O:
-        set optim90="$2" ; set optimtru90="$2" ; shift ; shift ; goto top
+        set optim90="$2" ; set optim="$2" ; set optimtru90="$2" ; shift ; shift ; goto top
 
      case -p
@@ -380,6 +367,7 @@
            set optim90="$optim90"" -G1 "
         else if $LINUX then
-           set optim90="-g -Mbounds "
-           set optimtrue90="-g -Mbounds -Mfree"
+	   set optim=" -g -no-ftz -traceback -ftrapuv -fp-stack-check -check"
+           set optim90=" -g -no-ftz -traceback -ftrapuv -fp-stack-check -check"
+           set optimtru90=" -g -no-ftz -traceback -ftrapuv -fp-stack-check -check"
         else 
            echo "pas d option debug predefinie pour cette machine"
@@ -393,4 +381,5 @@
    endsw
 endif
+
 
 echo "apres les opts dim $dim"
@@ -425,4 +414,5 @@
 #subtilites sur le nom de la librairie
 ########################################################################
+
 
 \rm tmp ; touch tmp
@@ -548,5 +538,4 @@
 
 # Build the appropriate 'bands.h' file
-cd dimension
 makbands $bands
 # echo contents of bands.h to standard output
@@ -657,4 +646,5 @@
 ########################################################################
 
+
 echo PHYSIQUE $phys
 echo dynamique $dyn $dimension
@@ -674,6 +664,9 @@
    set f90=f90
 else if $LINUX then
-   set f77=pgf90
-   set f90=pgf90
+   set f77=ifort
+   set f90=ifort
+   set opt_link=" -L$LIBOGCM -L$NCDFLIB -lnetcdf "
+#   set f77=pgf90
+#   set f90=pgf90
 else if $SUN then
    set f77=f90
@@ -769,4 +762,5 @@
  set optimtru90=" $optimtru90 -I$libo "
 else if $LINUX then
+ set optim="$optim -module $libo"
  set optim90="$optim90 -module $libo"
  set optimtru90="$optimtru90 -module $libo"
@@ -788,7 +782,8 @@
 cd $localdir
 
+
 echo $make -f $LMDGCM/makefile \
 OPTION_DEP="$opt_dep" OPTION_LINK="$opt_link" \
-OPTIM="$optim90" \
+OPTIM="$optim" \
 OPTIM90="$optim90" \
 OPTIMTRU90="$optimtru90" \
@@ -815,5 +810,5 @@
 $make -f $LMDGCM/makefile \
 OPTION_DEP="$opt_dep" OPTION_LINK="$opt_link" \
-OPTIM="$optim90" \
+OPTIM="$optim" \
 OPTIM90="$optim90" \
 OPTIMTRU90="$optimtru90" \
Index: /trunk/LMDZ.GENERIC/makegcm_gfortran
===================================================================
--- /trunk/LMDZ.GENERIC/makegcm_gfortran	(revision 253)
+++ /trunk/LMDZ.GENERIC/makegcm_gfortran	(revision 253)
@@ -0,0 +1,847 @@
+#!/bin/csh -f
+# $Header: /users/lmdz/cvsroot/LMDZ.3.3/makegcm,v 1.21 2001/07/04 08:41:44 lmdz Exp $
+#set verbose echo
+########################################################################
+# options par defaut pour la commande make
+########################################################################
+set dim="64x48x32"
+set physique=std
+set phys="PHYS=$physique"
+set include='-I$(LIBF)/grid -I$(LIBF)/bibio -I.'
+set ntrac = 1
+set filtre=filtrez
+set grille=reg
+set dyntype="dyn"
+set bands="32x36"
+########################################################################
+# path a changer contenant les sources et les objets du modele
+########################################################################
+
+#### If you want you can set environment variables here
+#setenv LMDGCM "/san/home/rdword/gcm/LMDZ.GENERIC"
+#setenv LIBOGCM $LMDGCM/libo
+setenv NCDFLIB /home/rdword/netcdf/lib
+setenv NCDFINC /home/rdword/netcdf/include
+####
+
+setenv localdir "`pwd`"
+set MODIPSL=0
+echo $localdir | grep modipsl >& /dev/null
+if ( ! $status ) then
+  set MODIPSL=1
+  setenv LMDGCM $localdir
+  cd ../..
+  setenv LIBOGCM "`pwd`/lib"
+  cd $localdir
+  if ( `hostname` == rhodes ) then
+    set NCDFINC=`grep sxnec ../../util/AA_make.gdef| grep NCDF_INC|sed -e "s/^.* =//"`
+    set NCDFLIB=`grep sxnec ../../util/AA_make.gdef| grep NCDF_LIB|sed -e 's/^.* =//'`
+  else
+    if ( `hostname` == nymphea0 ) then
+      set NCDFINC=`grep fjvpp ../../util/AA_make.gdef| grep NCDF_INC|sed -e "s/^.* =//"`
+      set NCDFLIB=`grep fjvpp ../../util/AA_make.gdef| grep NCDF_LIB|sed -e 's/^.* =//'`
+    else
+      echo 'Probleme de definition des variables NCDFINC et NCDFLIB'
+    endif 
+  endif 
+else
+  if ( ! $?LMDGCM ) then
+    echo You must initialize the variable LMDGCM in your environnement
+    echo for instance: "setenv LMDGCM /usr/myself/supergcm" in .cshrc
+    exit
+  endif
+  if ( ! $?LIBOGCM ) then
+    set LIBOGCM=$LMDGCM/libo
+  endif
+  if ( ! $?NCDFLIB ) then
+    echo You must initialize the variable NCDFLIB in your environnement
+    echo for instance: "setenv NCDFLIB /usr/myself/netcdf" in .cshrc
+    exit
+  endif
+  if ( ! $?NCDFINC ) then
+    echo You must initialize the variable NCDFINC in your environnement
+    echo for instance: "setenv NCDFINC /usr/myself/netcdf" in .cshrc
+    exit
+  endif
+endif
+set model=$LMDGCM
+set libo=$LIBOGCM
+
+########################################################################
+#  Les differentes platformes reconnues
+########################################################################
+
+set HP=0
+set IBM=0
+set SUN=0
+set VPP=0
+set CRAY=0
+set DEC=0
+set LINUX=0
+set NEC=0
+set XNEC=0
+if ( `uname` == HP-UX ) then
+   set machine=HP
+   set HP=1
+else if (`uname` == UNIX_System_V ) then
+   set machine=VPP
+   set VPP=1
+else if (`uname` == SunOS ) then
+   set machine=SUN
+   set SUN=1
+else if ( `uname` == AIX ) then
+   set machine=IBM
+   set IBM=1
+else if ( `uname` == OSF1 ) then
+   set machine=ALPHA
+   set DEC=1
+else if ( `uname` == Linux ) then
+   set machine=LINUX
+   set LINUX=1
+else if ( `hostname` == atlas || `hostname` == axis  || `hostname` == etoile ) then
+   set machine=CRAY
+   set CRAY=1
+else if ( `uname` == SUPER-UX ) then
+   set machine=NEC
+   set NEC=1
+else if ( `hostname` == rhodes) then
+   set machine=XNEC
+   set XNEC=1
+else if ( `uname` == CYGWIN_NT-6.1-WOW64) then
+   set machine=LINUX
+   set LINUX=1
+else
+   echo Vous travaillez sur une machine non prevue par le reglement
+   exit
+endif
+
+# create $libo directory if it doesn't exist
+if ( ! -d $libo )  then
+   mkdir $libo
+endif
+
+if $VPP then
+set netcdf=netcdf_v
+else 
+set netcdf=netcdf
+endif
+########################################################################
+#  Quelques initialisations de variables du shell.
+########################################################################
+
+set dyn=
+set opt_link=""
+set adjnt=""
+set opt_dep=""
+
+set optim90=""
+set oplink=""
+
+########################################################################
+#  Optimisations par defaut suivant les machines
+########################################################################
+
+echo "Optimisations par defaut suivant les machines"
+set libf=$model/libf
+#setenv localdir "LOCAL_DIR=`pwd`"
+#setenv localdir "`pwd`"
+cd $model
+if $CRAY then
+   set optim90="-Wp'-P' -DCRAY "'-p$(LIBO) -eiv '
+   set oplink="-Wl'-DSTACK=128 -f indef' -L$NCDFLIB -lnetcdf "
+   set mod_loc_dir=" "
+   set mod_suffix=" "
+else if $SUN then
+   set optim90=" -fast"
+   set optimtru90=" -fast -free"
+   set opt_link="-L$NCDFLIB -lnetcdf"
+   set mod_loc_dir=$localdir
+   set mod_suffix=mod
+else if $HP then
+else if $IBM then
+else if $VPP then
+   set optim90="$optim -X9 -w"
+   if $COUPLE then
+     set opt_link="-Wg,-c $IOIPSLDIR/liboasis2.4_mpi2.a /usr/lang/mpi2/lib64/libmpi.a /usr/lang/mpi2/lib64/libmp.a /usr/local/lib/lib64/libnetcdf_cc.a -L$IOIPSLDIR -lioipsl"
+     set oplink="-Wl,-t,-P,-dy "
+   else
+     set opt_link="-Wg,-c /usr/local/lib/lib64/libnetcdf_cc.a -L$IOIPSLDIR -lioipsl"
+     set oplink="-Wl,-t,-dy "
+   endif
+   set mod_loc_dir=$IOIPSLDIR
+   set mod_suffix=mod
+else if $DEC then
+else if $LINUX then
+
+# Ehouarn 'gfortran' compiler
+   set optim="-O3 -funroll-loops "
+   set optim90="-O3 -funroll-loops "
+   set optimtru90="-O3 -funroll-loops "
+   set opt_link=" -L$NCDFLIB -lnetcdf -lnetcdff "
+
+   #NB: on gnome -O3 ==> NaNs ...
+   #set optim=" -O2 -ip -mkl=sequential -align common "
+   #set optim90=" -O2 -ip -mkl=sequential -align common "
+   #set optimtru90=" -O2 -ip -mkl=sequential -align common "
+
+   set mod_loc_dir="./"
+   set mod_suffix=mod
+else if $NEC then
+   set optim90=' -clear -C hopt -float0 -ew -P static -Wf,"-pvctl fullmsg noassume "'
+   set optimtru90=' -clear -f4 -C hopt -float0 -ew -P static -Wf,"-pvctl fullmsg noassume "'
+###   set opt_link=" -C hopt -float0 -ew -P static -L$IOIPSLDIR -lioipsl  -L/u/rech/psl/rpsl003/IOIPSL -lnetcdf_i8r8_v "
+   set opt_link=" -C hopt -float0 -ew -P static -L/SX/usr/local/lib  -lnetcdf_i8r8 "
+   set mod_loc_dir="."
+   set mod_suffix="mod"
+else if $XNEC then
+   set optim90=' -clear -R5 -C vopt -float0 -ew -P static -Wf,"-pvctl loopcnt=40000 fullmsg noassume "'
+   set optimtru90=' -clear -R5 -f4 -C vopt -float0 -ew -P static -Wf,"-pvctl loopcnt=40000 fullmsg noassume "'
+   if $MODIPSL then
+     if $COUPLE then
+       set opt_link="-L$IOIPSLDIR -lsxioipsl -loasis2.4_mpi2 -float0 -ew -P static -I$NCDFINC $NCDFLIB "
+     else
+       set opt_link="-L$IOIPSLDIR -lsxioipsl -float0 -ew -P static -I$NCDFINC $NCDFLIB "
+     endif
+     set mod_loc_dir="./"
+   else
+     set opt_link=" -C hopt -float0 -ew -P static -I$NCDFINC -L/SX/usr/local/lib -lnetcdf_i8r8"
+     set mod_loc_dir="."
+   endif
+   set mod_suffix="mod"
+
+endif
+
+set nomlib=${machine}_gfortran
+
+# Impose distinct name for 64 bit Linux machines (to avoid mixing 32 and 64)
+if (`uname` == Linux && `uname -m` == "x86_64") then
+  set nomlib=${machine}64_gfortran
+endif
+
+########################################################################
+# lecture des options de mymake
+########################################################################
+
+top:
+if ($#argv > 0) then
+    switch ($1:q)
+
+    case -h:
+
+########################################################################
+# Manuel en ligne
+########################################################################
+more <<eod
+
+
+makegcm [Options] prog
+
+
+
+
+Par default, la commande makegcm:
+---------------------------------
+
+1. compile une serie de sous programmes se trouvant dans des sous-repertoires
+de $LMDGCM/libf.
+Les sous programmes sont ensuite stokes sur dans des librairies FORTRAN
+sur $LIBOGCM.
+
+2. Ensuite, makegcm compile le programme prog.f se trouvant par default sur
+$LMDGCM/libf/dyn3d et effectue le lien avec l ensemble des librairies.
+
+La variable '$LMDGCM' doit etre initialisee dans votre .cshrc ou en dur
+dans la comande makegcm.
+
+La commande makegcm est faite pour permettre de gerer en parallele des
+versions differentes du modele, compilees avec des options de compilation
+et des dimensions differentes sans avoir a chaque fois a recompiler tout
+le modele.
+
+Les librairies FORTRAN sont stoquees sur le directory $LIBOGCM.
+
+
+OPTIONS:
+--------
+
+Les options suivantes peuvent etre definies soit par defaut en editant le
+"script" makegcm, soit en interactif:
+
+-d imxjmxlm  ou im, jm, et lm sont resp. le nombre de longitudes, latitudes
+             et couches verticales. 
+
+-t ntrac   selectionne le nombre de traceur advectes par la dynamique.
+           Dans les versions courantes du modele terrestre on a par exemple
+           ntrac=2 pour l'eau vapeur et liquide
+
+             L'effet des options -d et -t est d'ecraser le fichier 
+             $LMDGCM/libf/grid/dimensions.h
+             qui contient sous forme de 4 PARAMETER FORTRAN les 3 dimensions
+             de la grille horizontale im, jm, lm plus le nombre de traceurs
+             advectes passivement par la dynamique ntrac, par un nouveu fichier
+             $LMDGCM/libf/grid/dimension/dimensions.im.jm.lm.tntrac
+             Si ce fichier n'existe pas encore, il est cree par le script
+             $LMDGCM/libf/grid/dimension/makdim
+
+-p PHYS    pour selectionner le jeu de parametrisations physiques avec
+           lequel on veut compiler le modele.
+           Le modele sera alors compile en prenant les sources des
+           parametrisations physiques dans le repertoire:
+            $LMDGCM/libf/phyPHYS
+
+-g grille  selectionne le type de grille qu'on veut utiliser.
+           L'effet de cette option est d'ecraser le fichier
+           $LMDGCM/libf/grid/fxyprim.h
+           avec le fichier
+           $LMDGCM/libf/grid/fxy_grille.h
+           grille peut prendre les valeurs:
+           1. reg pour la grille reguliere
+           2. sin pour avoir des points equidistants en sinus de la latitude
+           3. new pour pouvoir zoomer sur une partie du globe
+
+-O "optimisation fortran" ou les optimisations fortran sont les options de la
+            commande f77
+
+-include path
+           Dans le cas ou on a dans des sous programmes des fichiers 
+           #include (cpp) qui se trouve sur des repertoires non references
+           par defaut
+
+-adjnt     Pour compiler la l'adjoint du code dynamique
+
+-olddyn    To compile GCM with "old dynamics"
+
+-filtre  filtre
+           Pour choisir le filtre en longitude dans les regions polaires.
+           "filtre" correspond au nom d'un repertoire se trouvant sur
+           $LMDGCM/libf. Le filtre standard du modele est "filtrez" qui peut
+           etre utilise aussi bien pour une grille reguliere que pour une 
+           grille zoomee en longitude.
+
+-link "-Ldir1 -lfile1 -Ldir2 -lfile2 ..."
+          Pour rajouter un lien avec les librairies FORTRAN
+          libfile1.a, libfile2.a ... se trouvant respectivement sur les
+          repertoires dir1, dir2 ...
+          Si dirn est un repertoire dont le chemin est automatique (comme
+          par exemple /usr/lib ...) il n'est pas besoin de specifier -Ldirn.
+
+Auteur: Frederic Hourdin  (hourdin@lmd.jussieu.fr)
+eod
+exit
+
+########################################################################
+# Lecture des differentes options
+########################################################################
+
+    case -d
+        set dim=$2 ; shift ; shift ; goto top
+                        
+    case -O:
+        set optim90="$2" ; set optim="$2" ; set optimtru90="$2" ; shift ; shift ; goto top
+
+     case -p
+        set physique="$2" ; set phys="PHYS=$physique" ; shift ; shift ; goto top
+
+     case -g
+        set grille="$2" ; shift ; shift ; goto top
+
+    case -b
+        set bands=$2 ; shift ; shift ; goto top
+           
+     case -t
+        set ntrac=$2 ; shift ; shift ; goto top
+
+     case -include
+        set include="$include -I$2" ; shift ; shift ; goto top
+
+     case -adjnt
+        set opt_dep="$opt_dep adjnt" ; set adjnt="-ladjnt -ldyn3d "
+
+     case -olddyn
+        set dyntype="olddyn" ; shift; goto top
+
+     case -filtre
+        set filtre=$2 ; shift ; shift ; goto top
+
+     case -link
+        set opt_link="$opt_link $2" ; shift ; shift ; goto top
+
+     case -debug
+        if $HP then
+           set optim90=" -g "
+        else if $SUN then
+           setenv PARALLEL 4
+           set optim90=" -g -C "
+           set optimtru90=" -g -C "
+        else if $CRAY then
+           set optim90="$optim90"" -G1 "
+        else if $LINUX then
+
+           ## for gfortran
+           set optim="-g -finit-real=-inf -finit-integer=-999999 -Wall -fbacktrace -fbounds-check -ffpe-trap=invalid,zero,overflow"
+           set optim90="-g -finit-real=-inf -finit-integer=-999999 -Wall -fbacktrace -fbounds-check -ffpe-trap=invalid,zero,overflow"
+           set optimtru90="-g -finit-real=-inf -finit-integer=-999999 -Wall -fbacktrace -fbounds-check -ffpe-trap=invalid,zero,overflow"
+
+        else 
+           echo "pas d option debug predefinie pour cette machine"
+           exit
+        endif
+        shift ; goto top
+
+     default
+        set code="$1" ; shift ; goto top
+
+   endsw
+endif
+
+
+echo "apres les opts dim $dim"
+
+########################################################################
+# cas special sans physique
+########################################################################
+if ( "$physique" == 'nophys' ) then
+   set phys="L_PHY= LIBPHY="
+endif
+
+########################################################################
+# choix du nombre de traceur par defaut si il n'a pas ete choisi,
+# suivant la physique
+########################################################################
+
+if ( $ntrac == 0  ) then
+    if ( "$physique" == 'nophys' ) then
+        set ntrac=1
+    else if ( "$physique" == 'lmd' ) then
+        set ntrac=2
+    else if ( "$physique" == 'lmd_test_li' ) then
+        set ntrac=2
+    else if ( "$physique" == 'ec' ) then
+        set ntrac=1
+    else
+        set ntrac = 1
+    endif
+endif
+
+########################################################################
+#subtilites sur le nom de la librairie
+########################################################################
+
+
+\rm tmp ; touch tmp
+\rm tmp90 ; touch tmp90
+foreach i ( $optim90 )
+   echo $i | sed -e 's/\"//g' -e "s/\'//g" -e 's/-//g' -e 's/://g' -e 's/=//g' -e 's/%//g' >> tmp
+end
+set suf=
+foreach i ( `sort tmp | uniq ` )
+   set suf=$suf$i
+end
+if ( ! $IBM ) then
+   set nomlib="$nomlib$suf"
+endif
+if ( $DEC ) then
+   set nomlib=DEC
+endif
+
+# dimension
+echo "dimension avant sed $dim"
+if ( $IBM ) then
+   set dim=`echo $dim | sed -en 's/[^0-9]/ /g'`
+   set dim_=`echo $dim | sed -en 's/[^0-9]/_/g'`
+else if ( $SUN || $XNEC ) then
+   set dim=`echo $dim | sed -e 's/[^0-9]/ /g'` 
+   set dim_=`echo $dim | sed -e 's/[^0-9]/_/g'`
+else
+     set dim=`echo $dim | sed -e 's/[^0-9]/ /g'`
+     set dim_=`echo $dim | sed -e 's/[^0-9]/_/g'`
+endif
+
+# bands
+echo "bands avant sed $bands"
+if ( $IBM ) then
+   set bands=`echo $bands | sed -en 's/[^0-9]/ /g'`
+   set bands_=`echo $bands | sed -en 's/[^0-9]/_/g'`
+else if ( $SUN || $XNEC ) then
+   set bands=`echo $bands | sed -e 's/[^0-9]/ /g'` 
+   set bands_=`echo $bands | sed -e 's/[^0-9]/_/g'`
+else
+     set bands=`echo $bands | sed -e 's/[^0-9]/ /g'`
+     set bands_=`echo $bands | sed -e 's/[^0-9]/_/g'`
+endif
+
+
+# build final name of libraries directory:
+if ( "$dyntype" == "olddyn" ) then
+  set nomlib=${nomlib}_${dim_}_t${ntrac}_${grille}_olddyn
+else
+  set nomlib=${nomlib}_${dim_}_t${ntrac}_${grille}
+endif
+
+# Append number of bands to nomlib (new for universal model)
+set nomlib=${nomlib}_${bands_}
+
+# Append 'physique' type, if it is not mars, to nomlib
+if ( "$physique" != "mars" ) then
+  set nomlib=${nomlib}_${physique}
+endif
+
+## M-A-F nomlib trop long sur CRAY pour ar
+if ( $CRAY ) then
+    set nomlib=F90_${dim_}_t${ntrac}
+endif
+if ( $NEC || $XNEC ) then
+    set nomlib=F90_${dim_}_t${ntrac}
+endif
+
+echo "calcul de la dimension"
+set dimc=`echo $dim | wc -w`
+
+if ( "$dimc" == "2" ) then
+  set include="$include "'-I$(LIBF)/dyn2d '
+  set dimh=$dim
+else
+  if ( "$dyntype" == "olddyn" ) then
+    set include="$include "'-I$(LIBF)/olddyn3d '
+  else
+    set include="$include "'-I$(LIBF)/dyn3d '
+  endif
+  set dimh=`echo $dim | awk ' { print $1 "." $2 } '`
+endif
+echo "dimc is $dimc"
+
+########################################################################
+# path pour les #include
+########################################################################
+
+set include="$include -I$NCDFINC "
+echo $include
+
+########################################################################
+# Gestion des dimensions du modele.
+# on cree ou remplace le fichier des dimensions/nombre de traceur
+########################################################################
+
+cd $libf/grid
+if ( -f dimensions.h ) then
+  echo "WARNING: you are already compiling the model somewhere else"
+  echo "Wait until the first compilation is finished before starting."
+  echo "If you are sure that you are not compiling elsewhere, you can"
+  echo "type [yes] to continue."
+  echo "Do you want to continue?"
+  if ( $< == "yes" ) then
+    #remove old dimensions.h file
+    \rm $libf/grid/dimensions.h
+    \rm $libf/grid/bands.h
+  else
+    exit
+  endif
+endif
+
+# Build the appropriate 'dimensions.h' file
+cd dimension
+./makdim $ntrac $dim
+# echo contents of dimensions.h to standard output
+cat $libf/grid/dimensions.h
+
+# Build the appropriate 'bands.h' file
+./makbands $bands
+# echo contents of bands.h to standard output
+cat $libf/grid/bands.h
+
+cd $LMDGCM
+# set path to objects directory
+set libo=$libo/$nomlib
+# create objects directory, if it doesn't exist
+if ( ! -d $libo )  then
+   mkdir $libo
+   cd $model
+endif
+
+########################################################################
+# Differentes dynamiques (3d, 2d, 1d)
+########################################################################
+
+set dimension=`echo $dim | wc -w`
+echo dimension $dimension dim $dim
+if ( $dimension == 1 ) then
+  echo pas de dynamique
+  set dyn="L_DYN= DYN= L_FILTRE= DIRMAIN=phy$physique "
+endif
+endif
+
+cd $model
+if ( $dimension == 3 ) then
+  cd libf/grid
+  \rm fxyprim.h
+  cp -p fxy_${grille}.h fxyprim.h
+endif
+
+######################################################################
+#   Traitement special pour le nouveau rayonnement de Laurent Li.
+######################################################################
+#if ( -f $libf/phy$physique/raddim.h ) then
+#  if ( -f $libf/phy$physique/raddim.$dimh.h ) then
+#    \rm $libf/phy$physique/raddim.h
+#    cp -p $libf/phy$physique/raddim.$dimh.h $libf/phy$physique/raddim.h
+#    echo $libf/phy$physique/raddim.$dimh.h 
+#    cat $libf/phy$physique/raddim.$dimh.h 
+#    cat $libf/phy$physique/raddim.h
+#  else
+#    echo On peut diminuer la taille de l executable en creant
+#    echo le fichier $libf/phy$physique/raddim.$dimh.h
+#    \cp -p $libf/phy$physique/raddim.defaut.h $libf/phy$physique/raddim.h
+#  endif
+#endif
+
+######################################################################
+# Gestion du filtre qui n'existe qu'en 3d.
+######################################################################
+
+# set filtre to 'oldfiltrez' if using -olddyn option
+if ( "$dyntype" == "olddyn" ) then
+  set filtre="oldfiltrez"
+endif
+
+if ( `expr $dimc \> 2` == 1 ) then
+   set filtre="FILTRE=$filtre"
+else
+   set filtre="FILTRE= L_FILTRE= "
+endif
+echo "MACRO FILTRE $filtre"
+
+echo "dimc $dimc"
+
+########################################################################
+#  Avant de lancer le make, on recree le makefile si necessaire
+########################################################################
+# c'est a dire dans 3 cas:
+# 1. si la liste des fichiers .F et .h a ete modifiee depuis la
+#    derniere creation du makefile
+# 2. si le fichier contenant cette liste "liste_des_sources"
+#    n'existe pas.
+# 3. Si le makefile n'existe pas.
+########################################################################
+
+cd $model
+find libf -name '*.[Fh]' -print >! tmp77
+#find libf -name '*.[Fh]' -exec egrep -i " *use *ioipsl" {} \; -print >! tmp90
+find libf -name '*.[Fh]90' -print >> tmp90
+
+if (    `diff tmp77 liste_des_sources_f77 | wc -w` \
+     || `diff tmp90 liste_des_sources_f90 | wc -w` \
+     || ! -f makefile \
+     || ! -f liste_des_sources_f90 \
+     || ! -f liste_des_sources_f77 ) then
+        echo "les fichiers suivants ont ete crees ou detruits"
+        echo "ou les fichiers suivants sont passes ou ne sont plus en Fortran 90"
+        diff liste_des_sources_f77 tmp77
+        diff liste_des_sources_f90 tmp90
+        \cp tmp77 liste_des_sources_f77
+        \cp tmp90 liste_des_sources_f90
+        echo "Remaking the makefile!"
+        if ("$dyntype" == "olddyn") then
+          ./create_make_gcm olddyn3d grid bibio phy$physique >! tmp
+        else
+          ./create_make_gcm dyn3d grid bibio phy$physique >! tmp
+        endif
+        \mv tmp makefile
+        echo "New makefile created."
+endif
+
+########################################################################
+#  Execution de la comande make
+########################################################################
+
+
+echo PHYSIQUE $phys
+echo dynamique $dyn $dimension
+echo OPTIM90="$optim90" $filtre LIBO=$libo $dyn PHYS=$phys DIM=$dimc PROG=$code
+echo PATH pour les fichiers INCLUDE $include
+echo OPLINK="$oplink"
+
+if $HP then
+   set f77='fort77 +OP'
+   set f90='jensaisrien'
+   set opt_link="$opt_link -lm"
+else  if $VPP then
+   set f77=frt
+   set f90=$f77
+else if $CRAY then
+   set f77=f90
+   set f90=f90
+else if $LINUX then
+   set f77=gfortran
+   set f90=gfortran
+   set opt_link=" -L$LIBOGCM -L$NCDFLIB -lnetcdff -lnetcdf "
+else if $SUN then
+   set f77=f90
+   set f90=f90
+else if $NEC then
+   set f77=f90
+   set f90=f90
+else if $XNEC then
+   set f77=sxmpif90
+   set f90=sxmpif90
+else
+   set f77=f77
+   set f90=f90
+endif
+
+cd $model
+
+if $VPP then
+  set make="gmake RANLIB=ls"
+else if $CRAY then
+  set make="make RANLIB=ls"
+else if $NEC then
+  set make="make RANLIB=ls"
+else if $LINUX then
+  set make="make -k RANLIB=ranlib"
+else if $XNEC then
+  set make="/usr/local/bin/gmake RANLIB=ls"
+  set make="/usr/freeware/bin/gmake RANLIB=ls"
+else
+  set make="make RANLIB=ranlib"
+endif
+
+
+
+#
+# les deux test suivants sont "temporaires" pour pallier des "faiblesses" du 
+# compilateur fortran Sun: f90: SC4.0 11 Sep 1995 FORTRAN 90 1.1
+#
+#if ($code == 'create_limit' && $SUN) then
+#   set link=f77
+#   set opt_link="-L$NCDFLIB -lnetcdf"
+#endif
+
+#if ($code == 'create_etat0' && $SUN) then
+#   if ( ! -f $libo/libdyn3d.a ) then
+#     echo "Priere de compiler gcm en premier pour des raisons d'optimisation"
+#     \rm $libf/grid/dimensions.h
+#     exit
+#   endif
+#   set optim90=" -dalign -fixed "
+#   set opt_link="-L$IOIPSLDIR -lioipsl  -L$NCDFLIB -lnetcdf"
+#   set link="$f90 $optim90"
+#   touch $LMDGCM/libf/dyn3d/startvar.F
+#   touch $LMDGCM/libf/dyn3d/etat0_netcdf.F
+#endif
+
+#
+# Encore un test temporaire: probleme de compilation sur VPP
+# l'optimisation de startvar se passe mal
+#
+#if ($code == 'create_etat0' && $VPP) then
+#   if ( ! -f $libo/libdyn3d.a ) then
+#     echo "Priere de compiler gcm en premier pour des raisons d'optimisation"
+#     \rm $libf/grid/dimensions.h                                             
+#     exit                       
+#   endif
+#   set optim90="$optim90"" -X9 -w"
+#   set opt_link="-L$NCDFLIB -lnetcdf"
+#   touch $LMDGCM/libf/dyn3d/startvar.F
+#   touch $LMDGCM/libf/dyn3d/etat0_netcdf.F
+#endif
+
+#
+# etat0_netcdf a besoin d'info de la physique
+# A revoir
+set include="$include"" -I$libf/phy$physique"
+
+
+#################################################################
+# Execution de la comande make... ENFIN!
+#################################################################
+
+if $VPP then
+  set optim90=" $optim90 -Am -M$libo"
+  set optimtru90="$optim90"
+else if $SUN then
+ set optim90=" $optim90 -M$libo"
+ set optimtru90=" $optimtru90 "
+else if $NEC then
+ set optim90=" $optim90 -I$libo "
+else if $XNEC then
+ set optim90=" $optim90 -I$libo "
+ set optimtru90=" $optimtru90 -I$libo "
+else if $LINUX then
+# set optim="$optim -module $libo"
+# set optim90="$optim90 -module $libo"
+# set optimtru90="$optimtru90 -module $libo"
+# Ehouarn: remove set mod_loc_dir def below; mod_loc_dir=$localdir (set above)
+# set mod_loc_dir=$libo
+
+# Ehouarn : adapt to gfortran
+ set optim="$optim -I${libo}"
+ set optim90="$optim90 -I${libo}"
+ set optimtru90="$optimtru90 -ffree-form -I${libo}"
+
+endif
+
+set link="$f90 $optim90"
+
+set ar=ar
+
+if $XNEC then
+  set link="sxld $opt_link"
+  set link="$f90 "
+#  set ar=sxar
+endif
+
+
+cd $localdir
+
+
+echo $make -f $LMDGCM/makefile \
+OPTION_DEP="$opt_dep" OPTION_LINK="$opt_link" \
+OPTIM="$optim" \
+OPTIM90="$optim90" \
+OPTIMTRU90="$optimtru90" \
+INCLUDE="$include" \
+$filtre \
+LIBO=$libo \
+$dyn \
+$phys \
+DIM=$dimc \
+DYNTYPE="$dyntype" \
+L_ADJNT="$adjnt" \
+LOCAL_DIR="$localdir"  \
+F77="$f77" \
+F90="$f90" \
+OPLINK="$oplink" \
+LINK="$link" \
+GCM="$LMDGCM" \
+MOD_LOC_DIR=$mod_loc_dir \
+MOD_SUFFIX=$mod_suffix \
+AR=$ar \
+PROG=$code
+
+
+$make -f $LMDGCM/makefile \
+OPTION_DEP="$opt_dep" OPTION_LINK="$opt_link" \
+OPTIM="$optim" \
+OPTIM90="$optim90" \
+OPTIMTRU90="$optimtru90" \
+INCLUDE="$include" \
+$filtre \
+LIBO=$libo \
+$dyn \
+$phys \
+DIM=$dimc \
+DYNTYPE="$dyntype" \
+L_ADJNT="$adjnt" \
+LOCAL_DIR="$localdir"  \
+F77="$f77" \
+F90="$f90" \
+OPLINK="$oplink" \
+LINK="$link" \
+GCM="$LMDGCM" \
+MOD_LOC_DIR=$mod_loc_dir \
+MOD_SUFFIX=$mod_suffix \
+AR=$ar \
+PROG=$code
+
+\rm $libf/grid/dimensions.h
+\rm $libf/grid/bands.h
Index: /trunk/LMDZ.GENERIC/makegcm_ifort
===================================================================
--- /trunk/LMDZ.GENERIC/makegcm_ifort	(revision 252)
+++ /trunk/LMDZ.GENERIC/makegcm_ifort	(revision 253)
@@ -13,5 +13,5 @@
 set grille=reg
 set dyntype="dyn"
-set bands="8x7"
+set bands="32x36"
 ########################################################################
 # path a changer contenant les sources et les objets du modele
@@ -324,10 +324,9 @@
 ########################################################################
 
-    case -d:
+    case -d
         set dim=$2 ; shift ; shift ; goto top
                         
     case -O:
-#        set optim90="$2" ; set optimtru90="$2" ; shift ; shift ; goto top
-        set optim90="$2" ; optim="$2" ; optimtru90="$2" ; shift ; shift ; goto top
+        set optim90="$2" ; set optim="$2" ; set optimtru90="$2" ; shift ; shift ; goto top
 
      case -p
@@ -368,7 +367,7 @@
            set optim90="$optim90"" -G1 "
         else if $LINUX then
-	   set optim=" -g -no-ftz -traceback -ftrapuv -fp-stack-check "
-           set optim90=" -g -no-ftz -traceback -ftrapuv -fp-stack-check "
-           set optimtru90=" -g -no-ftz -traceback -ftrapuv -fp-stack-check "
+	   set optim=" -g -no-ftz -traceback -ftrapuv -fp-stack-check -check"
+           set optim90=" -g -no-ftz -traceback -ftrapuv -fp-stack-check -check"
+           set optimtru90=" -g -no-ftz -traceback -ftrapuv -fp-stack-check -check"
         else 
            echo "pas d option debug predefinie pour cette machine"
@@ -382,4 +381,5 @@
    endsw
 endif
+
 
 echo "apres les opts dim $dim"
@@ -414,4 +414,5 @@
 #subtilites sur le nom de la librairie
 ########################################################################
+
 
 \rm tmp ; touch tmp
@@ -644,4 +645,5 @@
 #  Execution de la comande make
 ########################################################################
+
 
 echo PHYSIQUE $phys
@@ -780,4 +782,5 @@
 cd $localdir
 
+
 echo $make -f $LMDGCM/makefile \
 OPTION_DEP="$opt_dep" OPTION_LINK="$opt_link" \
Index: /trunk/LMDZ.GENERIC/makegcm_pgf90
===================================================================
--- /trunk/LMDZ.GENERIC/makegcm_pgf90	(revision 252)
+++ /trunk/LMDZ.GENERIC/makegcm_pgf90	(revision 253)
@@ -6,5 +6,5 @@
 ########################################################################
 set dim="64x48x32"
-set physique=mars
+set physique=std
 set phys="PHYS=$physique"
 set include='-I$(LIBF)/grid -I$(LIBF)/bibio -I.'
@@ -13,23 +13,22 @@
 set grille=reg
 set dyntype="dyn"
+set bands="32x36"
 ########################################################################
 # path a changer contenant les sources et les objets du modele
 ########################################################################
 
-###### VERSION LMDZ.3.3
-# set LMDGCM=$HOME/LMDZ.3.3
-#
-
 #### If you want you can set environment variables here
-#setenv LMDGCM /d5/emlmd/test_universal/LMDZ.UCM.v0.2
+#setenv LMDGCM "/san/home/rdword/gcm/LMDZ.GENERIC"
 #setenv LIBOGCM $LMDGCM/libo
-#if ( `uname -m` == "x86_64" ) then
-## 64 bit machines
-#  setenv NCDFLIB /donnees/emlmd/netcdf64-4.0.1_pgi/lib
-#  setenv NCDFINC /donnees/emlmd/netcdf64-4.0.1_pgi/include
-#else
-#  setenv NCDFLIB /distrib/local/netcdf/pgi_32bits/lib
-#  setenv NCDFINC /distrib/local/netcdf/pgi_32bits/include
-#endif
+#setenv NCDFLIB /usr/local/lib
+#setenv NCDFINC /usr/local/include
+if ( `uname -m` == "x86_64" ) then
+# 64 bit machines
+  setenv NCDFLIB /donnees/emlmd/netcdf64-4.0.1_pgi/lib
+  setenv NCDFINC /donnees/emlmd/netcdf64-4.0.1_pgi/include
+else
+  setenv NCDFLIB /donnees/emlmd/netcdf-4.0.1_pgi/lib
+  setenv NCDFINC /donnees/emlmd/netcdf-4.0.1_pgi/include
+endif
 ####
 
@@ -179,12 +178,17 @@
 else if $DEC then
 else if $LINUX then
-   set optim90=" -fast"
-   set optimtru90=" -fast -c -Mfree "
-#   set opt_link=" -Mfree -L/usr/local/pgi/linux86/lib -lpgf90 -lpgftnrtl -lpghpf -lpghpf2 -L$NCDFLIB -lnetcdf -Wl,-Bstatic "
-# Ehouarn: there is no /usr/local/pgi/linux86/lib, but it doesn't matter
-#          also changed -Wl,-Bstatic to -Bstatic
-   set opt_link=" -Mfree -lpgf90 -lpgftnrtl -lpghpf -lpghpf2 -L$NCDFLIB -lnetcdf -Bstatic "
+   set optim=" -O2 -Munroll -Mcache_align "
+   set optim90=" -O2 -Munroll -Mcache_align "
+   set optimtru90=" -O2 -Munroll -Mcache_align "
+   set opt_link=" -L$NCDFLIB -lnetcdf"
    set mod_loc_dir=$localdir
    set mod_suffix=mod
+# Ehouarn 'ifort' compiler
+#   #NB: on gnome -O3 ==> NaNs ...
+#   set optim=" -O2 -ip -mkl=sequential -align common "
+#   set optim90=" -O2 -ip -mkl=sequential -align common "
+#   set optimtru90=" -O2 -ip -mkl=sequential -align common "
+#   set mod_loc_dir=$LIBOGCM
+#   set mod_suffix=mod
 else if $NEC then
    set optim90=' -clear -C hopt -float0 -ew -P static -Wf,"-pvctl fullmsg noassume "'
@@ -335,9 +339,9 @@
 ########################################################################
 
-    case -d:
+    case -d
         set dim=$2 ; shift ; shift ; goto top
                         
     case -O:
-        set optim90="$2" ; shift ; shift ; goto top
+        set optim90="$2" ; set optim="$2" ; set optimtru90="$2" ; shift ; shift ; goto top
 
      case -p
@@ -347,4 +351,7 @@
         set grille="$2" ; shift ; shift ; goto top
 
+    case -b
+        set bands=$2 ; shift ; shift ; goto top
+           
      case -t
         set ntrac=$2 ; shift ; shift ; goto top
@@ -375,5 +382,10 @@
            set optim90="$optim90"" -G1 "
         else if $LINUX then
-           set optim90="-g -Mbounds "
+           set optim="-g -Mbounds -Kieee -Ktrap=fp -traceback"
+           set optim90="-g -Mbounds -Kieee -Ktrap=fp -traceback"
+           set optimtru90="-g -Mbounds -Kieee -Ktrap=fp -traceback"
+#	   set optim=" -g -no-ftz -traceback -ftrapuv -fp-stack-check "
+#           set optim90=" -g -no-ftz -traceback -ftrapuv -fp-stack-check "
+#           set optimtru90=" -g -no-ftz -traceback -ftrapuv -fp-stack-check "
         else 
            echo "pas d option debug predefinie pour cette machine"
@@ -387,4 +399,5 @@
    endsw
 endif
+
 
 echo "apres les opts dim $dim"
@@ -420,4 +433,5 @@
 ########################################################################
 
+
 \rm tmp ; touch tmp
 \rm tmp90 ; touch tmp90
@@ -437,5 +451,4 @@
 
 # dimension
-
 echo "dimension avant sed $dim"
 if ( $IBM ) then
@@ -446,9 +459,21 @@
    set dim_=`echo $dim | sed -e 's/[^0-9]/_/g'`
 else
-#   set dim=`echo $dim | sed -n -e 's/[^0-9]/ /gp'`
-#   set dim_=`echo $dim | sed -n -e 's/[^0-9]/_/gp'`
      set dim=`echo $dim | sed -e 's/[^0-9]/ /g'`
      set dim_=`echo $dim | sed -e 's/[^0-9]/_/g'`
 endif
+
+# bands
+echo "bands avant sed $bands"
+if ( $IBM ) then
+   set bands=`echo $bands | sed -en 's/[^0-9]/ /g'`
+   set bands_=`echo $bands | sed -en 's/[^0-9]/_/g'`
+else if ( $SUN || $XNEC ) then
+   set bands=`echo $bands | sed -e 's/[^0-9]/ /g'` 
+   set bands_=`echo $bands | sed -e 's/[^0-9]/_/g'`
+else
+     set bands=`echo $bands | sed -e 's/[^0-9]/ /g'`
+     set bands_=`echo $bands | sed -e 's/[^0-9]/_/g'`
+endif
+
 
 # build final name of libraries directory:
@@ -458,4 +483,7 @@
   set nomlib=${nomlib}_${dim_}_t${ntrac}_${grille}
 endif
+
+# Append number of bands to nomlib (new for universal model)
+set nomlib=${nomlib}_${bands_}
 
 # Append 'physique' type, if it is not mars, to nomlib
@@ -502,12 +530,18 @@
 cd $libf/grid
 if ( -f dimensions.h ) then
-  echo "ATTENTION: vous etes sans doute en train de compiler le modele par ailleurs"
-  echo "Attendez que la premiere compilation soit terminee pour relancer la suivante."
-  echo "Si vous etes sur que vous ne compilez pas le modele par ailleurs,"
-  echo "vous pouvez continuer en repondant oui."
-  echo "Voulez-vous vraiment continuer?"
-  if ( $< == "oui" ) then
+  echo "WARNING: you are already compiling the model somewhere else"
+  echo "Wait until the first compilation is finished before starting."
+  echo "If you are sure that you are not compiling elsewhere, you can"
+  echo "type [yes] to continue."
+  echo "Do you want to continue?"
+#  echo "ATTENTION: vous etes sans doute en train de compiler le modele par ailleurs"
+#  echo "Attendez que la premiere compilation soit terminee pour relancer la suivante."
+#  echo "Si vous etes sur que vous ne compilez pas le modele par ailleurs,"
+#  echo "vous pouvez continuer en repondant oui."
+#  echo "Voulez-vous vraiment continuer?"
+  if ( $< == "yes" ) then
     #remove old dimensions.h file
     \rm $libf/grid/dimensions.h
+    \rm $libf/grid/bands.h
   else
     exit
@@ -520,4 +554,9 @@
 # echo contents of dimensions.h to standard output
 cat $libf/grid/dimensions.h
+
+# Build the appropriate 'bands.h' file
+makbands $bands
+# echo contents of bands.h to standard output
+cat $libf/grid/bands.h
 
 cd $LMDGCM
@@ -552,18 +591,17 @@
 #   Traitement special pour le nouveau rayonnement de Laurent Li.
 ######################################################################
-
-if ( -f $libf/phy$physique/raddim.h ) then
-  if ( -f $libf/phy$physique/raddim.$dimh.h ) then
-    \rm $libf/phy$physique/raddim.h
-    cp -p $libf/phy$physique/raddim.$dimh.h $libf/phy$physique/raddim.h
-    echo $libf/phy$physique/raddim.$dimh.h 
-    cat $libf/phy$physique/raddim.$dimh.h 
-    cat $libf/phy$physique/raddim.h
-  else
-    echo On peut diminuer la taille de l executable en creant
-    echo le fichier $libf/phy$physique/raddim.$dimh.h
-    \cp -p $libf/phy$physique/raddim.defaut.h $libf/phy$physique/raddim.h
-  endif
-endif
+#if ( -f $libf/phy$physique/raddim.h ) then
+#  if ( -f $libf/phy$physique/raddim.$dimh.h ) then
+#    \rm $libf/phy$physique/raddim.h
+#    cp -p $libf/phy$physique/raddim.$dimh.h $libf/phy$physique/raddim.h
+#    echo $libf/phy$physique/raddim.$dimh.h 
+#    cat $libf/phy$physique/raddim.$dimh.h 
+#    cat $libf/phy$physique/raddim.h
+#  else
+#    echo On peut diminuer la taille de l executable en creant
+#    echo le fichier $libf/phy$physique/raddim.$dimh.h
+#    \cp -p $libf/phy$physique/raddim.defaut.h $libf/phy$physique/raddim.h
+#  endif
+#endif
 
 ######################################################################
@@ -612,5 +650,5 @@
         \cp tmp77 liste_des_sources_f77
         \cp tmp90 liste_des_sources_f90
-        echo "On recree le makefile"
+        echo "Remaking the makefile!"
         if ("$dyntype" == "olddyn") then
           ./create_make_gcm olddyn3d grid bibio phy$physique >! tmp
@@ -619,5 +657,5 @@
         endif
         \mv tmp makefile
-        echo "Nouveau makefile cree."
+        echo "New makefile created."
 endif
 
@@ -625,4 +663,5 @@
 #  Execution de la comande make
 ########################################################################
+
 
 echo PHYSIQUE $phys
@@ -643,4 +682,7 @@
    set f90=f90
 else if $LINUX then
+#   set f77=ifort
+#   set f90=ifort
+#   set opt_link=" -L$LIBOGCM -L$NCDFLIB -lnetcdf "
    set f77=pgf90
    set f90=pgf90
@@ -704,15 +746,15 @@
 # l'optimisation de startvar se passe mal
 #
-if ($code == 'create_etat0' && $VPP) then
-   if ( ! -f $libo/libdyn3d.a ) then
-     echo "Priere de compiler gcm en premier pour des raisons d'optimisation"
-     \rm $libf/grid/dimensions.h                                             
-     exit                       
-   endif
-   set optim90="$optim90"" -X9 -w"
-   set opt_link="-L$NCDFLIB -lnetcdf"
-   touch $LMDGCM/libf/dyn3d/startvar.F
-   touch $LMDGCM/libf/dyn3d/etat0_netcdf.F
-endif
+#if ($code == 'create_etat0' && $VPP) then
+#   if ( ! -f $libo/libdyn3d.a ) then
+#     echo "Priere de compiler gcm en premier pour des raisons d'optimisation"
+#     \rm $libf/grid/dimensions.h                                             
+#     exit                       
+#   endif
+#   set optim90="$optim90"" -X9 -w"
+#   set opt_link="-L$NCDFLIB -lnetcdf"
+#   touch $LMDGCM/libf/dyn3d/startvar.F
+#   touch $LMDGCM/libf/dyn3d/etat0_netcdf.F
+#endif
 
 #
@@ -738,4 +780,8 @@
  set optimtru90=" $optimtru90 -I$libo "
 else if $LINUX then
+# set optim="$optim -I${libo}"
+# set optim90="$optim90 -I${libo}"
+# set optimtru90="$optimtru90 -ffree-form -I${libo}"
+ set optim="$optim -module $libo"
  set optim90="$optim90 -module $libo"
  set optimtru90="$optimtru90 -module $libo"
@@ -757,6 +803,8 @@
 cd $localdir
 
+
 echo $make -f $LMDGCM/makefile \
 OPTION_DEP="$opt_dep" OPTION_LINK="$opt_link" \
+OPTIM="$optim" \
 OPTIM90="$optim90" \
 OPTIMTRU90="$optimtru90" \
@@ -783,4 +831,5 @@
 $make -f $LMDGCM/makefile \
 OPTION_DEP="$opt_dep" OPTION_LINK="$opt_link" \
+OPTIM="$optim" \
 OPTIM90="$optim90" \
 OPTIMTRU90="$optimtru90" \
@@ -805,2 +854,3 @@
 
 \rm $libf/grid/dimensions.h
+\rm $libf/grid/bands.h
Index: /trunk/LMDZ.GENERIC/tmp
===================================================================
--- /trunk/LMDZ.GENERIC/tmp	(revision 252)
+++ /trunk/LMDZ.GENERIC/tmp	(revision 253)
@@ -1,1 +1,5 @@
-fast
+O2
+ip
+mklsequential
+align
+common
Index: /trunk/LMDZ.GENERIC/tmp77
===================================================================
--- /trunk/LMDZ.GENERIC/tmp77	(revision 252)
+++ /trunk/LMDZ.GENERIC/tmp77	(revision 253)
@@ -179,34 +179,37 @@
 libf/filtrez/jacobi.F
 libf/filtrez/parafilt.h
-libf/grid/fxyprim.h
 libf/grid/fxy_new.h
 libf/grid/fxy_reg.h
 libf/grid/fxy_sin.h
+libf/grid/fxyprim.h
 libf/grid/dimensions.h
 libf/grid/bands.h
 libf/phystd/aerave.F
+libf/phystd/aerave_new.F
 libf/phystd/blackl.F
-libf/phystd/physiq.F
-libf/phystd/callcorrk.F
-libf/phystd/tracer.h
 libf/phystd/callkeys.h
+libf/phystd/callsedim.F
 libf/phystd/comcstfi.h
-libf/phystd/cvmgp.F
 libf/phystd/comdiurn.h
 libf/phystd/comg1d.h
 libf/phystd/comgeomfi.h
-libf/phystd/solarlong.F
 libf/phystd/comsaison.h
+libf/phystd/comsoil.h
 libf/phystd/convadj.F
+libf/phystd/cpdet.F
+libf/phystd/cpdet.h
+libf/phystd/cvmgp.F
 libf/phystd/cvmgt.F
-libf/phystd/lagrange.F
 libf/phystd/datafile.h
 libf/phystd/datareadnc.F
 libf/phystd/dimphys.h
-libf/phystd/tabfi.F
+libf/phystd/dsolver.F
+libf/phystd/dtridgl.F
+libf/phystd/evap.F
 libf/phystd/fisice.h
-libf/phystd/optcv.F
-libf/phystd/phyetat0.F
-libf/phystd/planete.h
+libf/phystd/forceWCfn.F
+libf/phystd/gases.h
+libf/phystd/gfluxi.F
+libf/phystd/gfluxv.F
 libf/phystd/inifis.F
 libf/phystd/iniorbit.F
@@ -214,43 +217,41 @@
 libf/phystd/initracer.F
 libf/phystd/iniwrite.F
+libf/phystd/iniwrite_spec.F
+libf/phystd/interp_line.F
 libf/phystd/ismax.F
 libf/phystd/ismin.F
-libf/phystd/physdem1.F
+libf/phystd/lagrange.F
+libf/phystd/largescale.F
 libf/phystd/mucorr.F
 libf/phystd/mufract.F
 libf/phystd/multipl.F
+libf/phystd/newsedim.F
+libf/phystd/orbite.F
+libf/phystd/phyetat0.F
+libf/phystd/physdem1.F
+libf/phystd/planete.h
+libf/phystd/profile.F
+libf/phystd/rcm1d.F
+libf/phystd/scopyi.F
+libf/phystd/sfluxi.F
 libf/phystd/sfluxv.F
-libf/phystd/orbite.F
-libf/phystd/profile.F
-libf/phystd/scopyi.F
+libf/phystd/soil.F
+libf/phystd/soil_settings.F
+libf/phystd/statto.h
+libf/phystd/stelang.F
+libf/phystd/stellarlong.F
+libf/phystd/surface_nature.F
+libf/phystd/surfdat.h
 libf/phystd/surfini.F
+libf/phystd/tabfi.F
+libf/phystd/tpindex.F
+libf/phystd/tracer.h
 libf/phystd/vdifc.F
-libf/phystd/soil.F
-libf/phystd/solang.F
-libf/phystd/statto.h
-libf/phystd/surfdat.h
 libf/phystd/vdif_cd.F
 libf/phystd/vdif_kc.F
 libf/phystd/vlz_fi.F
 libf/phystd/watercap.h
-libf/phystd/comsoil.h
 libf/phystd/writediagfi.F
+libf/phystd/writediagspec.F
 libf/phystd/writeg1d.F
 libf/phystd/zerophys.F
-libf/phystd/callsedim.F
-libf/phystd/interp_line.F
-libf/phystd/soil_settings.F
-libf/phystd/sfluxi.F
-libf/phystd/tpindex.F
-libf/phystd/gfluxv.F
-libf/phystd/gfluxi.F
-libf/phystd/dsolver.F
-libf/phystd/dtridgl.F
-libf/phystd/co2snow.F
-libf/phystd/testphys1d.F
-libf/phystd/kastprof_fn.F
-libf/phystd/newsedim.F
-libf/phystd/aerave_new.F
-libf/phystd/iniwrite_spec.F
-libf/phystd/writediagspec.F
-libf/phystd/largescale2.F
Index: /trunk/LMDZ.GENERIC/tmp90
===================================================================
--- /trunk/LMDZ.GENERIC/tmp90	(revision 252)
+++ /trunk/LMDZ.GENERIC/tmp90	(revision 253)
@@ -3,27 +3,38 @@
 libf/bibio/ioipsl_stringop.F90
 libf/phystd/aeropacity.F90
+libf/phystd/aeroptproperties.F90
+libf/phystd/ave_stelspec.F90
+libf/phystd/calc_cpp3d.F90
+libf/phystd/calc_cpp_mugaz.F90
+libf/phystd/calc_rayleigh.F90
+libf/phystd/callcorrk.F90
+libf/phystd/condens_co2cloud.F90
+libf/phystd/def_var.F90
+libf/phystd/hydrol.F90
+libf/phystd/iniwritesoil.F90
+libf/phystd/interpolateH2H2.F90
+libf/phystd/kastprof_fn.F90
+libf/phystd/mkstat.F90
+libf/phystd/moistadj.F90
+libf/phystd/N2broadprof_fn.F90
+libf/phystd/newtrelax.F90
+libf/phystd/optci.F90
+libf/phystd/optcv.F90
+libf/phystd/physiq.F90
+libf/phystd/radcommon_h.F90
+libf/phystd/radinc_h.F90
+libf/phystd/rain.F90
+libf/phystd/setspi.F90
+libf/phystd/setspv.F90
+libf/phystd/simpleprof_fn.F90
+libf/phystd/stokes.F90
 libf/phystd/suaer_corrk.F90
-libf/phystd/radcommon_h.F90
-libf/phystd/condens_co2cloud.F90
 libf/phystd/sugas_corrk.F90
-libf/phystd/def_var.F90
-libf/phystd/rain.F90
-libf/phystd/radinc_h.F90
-libf/phystd/optci.F90
-libf/phystd/mkstat.F90
-libf/phystd/setspi.F90
-libf/phystd/aeroptproperties.F90
-libf/phystd/stokes.F90
-libf/phystd/setspv.F90
+libf/phystd/su_gases.F90
+libf/phystd/su_watercycle.F90
+libf/phystd/totalcloudfrac.F90
 libf/phystd/watercommon_h.F90
+libf/phystd/watersat.F90
+libf/phystd/watersat_grad.F90
+libf/phystd/writediagsoil.F90
 libf/phystd/wstats.F90
-libf/phystd/iniwritesoil.F90
-libf/phystd/writediagsoil.F90
-libf/phystd/su_watercycle.F90
-libf/phystd/aeroptpropertiesJBnew.F90
-libf/phystd/watersat_2.F90
-libf/phystd/moistadj.F90
-libf/phystd/watersat_grad.F90
-libf/phystd/ave_stelspec.F90
-libf/phystd/calc_rayleigh.F90
-libf/phystd/calc_cpp3d.F90
Index: /trunk/LMDZ.GENERIC/utilities/clean_bad_run
===================================================================
--- /trunk/LMDZ.GENERIC/utilities/clean_bad_run	(revision 253)
+++ /trunk/LMDZ.GENERIC/utilities/clean_bad_run	(revision 253)
@@ -0,0 +1,33 @@
+#!/bin/bash
+
+mv start_archive.nc ../
+rm -f gcm_*
+rm -f fort*
+rm -f g1d.dat
+rm -f g1d.ctl
+rm -f exe_planet
+rm -f lruns?
+rm -f lrun*
+rm -f olr.txt
+rm -f olr?.txt
+rm -f start.nc
+rm -f start*.nc
+rm -f startfi.nc
+rm -f startfi*.nc
+rm -f stats*.nc
+rm -f diagfi.nc
+rm -f diagfi*.nc
+rm -f diagspec.nc
+rm -f diagspec*.nc
+rm -f *.out
+rm -f num_run
+rm -f num_run.crash
+rm -f gcm_3D.*
+rm -f rcm_1D.*
+rm -f *~
+rm -rf files_out
+rm -f profile*.out
+mv ../start_archive.nc .
+
+
+exit 0
Index: /trunk/LMDZ.GENERIC/utilities/co2_cont.for
===================================================================
--- /trunk/LMDZ.GENERIC/utilities/co2_cont.for	(revision 253)
+++ /trunk/LMDZ.GENERIC/utilities/co2_cont.for	(revision 253)
@@ -0,0 +1,346 @@
+c     This program computes RT CIA spectra of CO2 at low density limit 
+C     at temperatures between 200 and 800K.
+C     
+C     ============================================================================
+C     Copyright (C) 1997   Marcin Gruszka 
+C     ============================================================================
+C     
+C     Copyright Notice:
+C     You may use this program for your scientific applications,
+C     but please do not	distribute it yourself.
+C     Direct all your inquires to the  author: e-mail aborysow@stella.nbi.dk
+C     Final request: If you publish  your work which benefited from this
+C     program, please acknowledge using this program and quote 
+C     the original paper describing the procedure:
+C     M. Gruszka and A. Borysow,
+C     Roto-translational collision-induced absorption of CO2
+C     for the Atmosphere of Venus at Frequencies from 0 to 250 cm$^{-1}$
+C     and at temperature from 200K to 800K,
+C     Icarus, vol. 129, pp. 172-177, (1997). 
+
+C     
+C     The paper (Icarus) describing this computer model, is based on  original paper by
+C     M. Gruszka and A. Borysow,
+C     "Computer Simulation of the Far Infrared Collision-induced absorption spectra 
+C     of gaseous CO2", Mol. Phys., vol. 93, pp. 1007-1016, 1998. 
+C     ============================================================================
+C     
+C     NOTE: The program gives data at spacing corresponding to
+c     Freq(max)-Freq(min)/(npoint-1),
+c     Since reasons are unknown (author's secret), it is recommended to
+c     request one more point that neccesary and get the right freq. step
+c     ==================================================================
+
+c     
+c     The following input parametres are required (*):
+c     ------------------------------------------------
+c     (*) some input parameters are Fortran REAL numbers
+c     and should be entered with a decimal point,
+c     not like INTEGER!
+c     
+c     1. Temperature: (in K) (REAL)
+c     -the model is restricted to the temperature range from
+c     200 K to 800 K.
+c     
+c     2. Frequency limits: (in cm^-1) (REAL,REAL)
+c     -the model has been designed to reproduce the MD and the
+c     experimental data up to 250 cm^-1. There is no restriction
+c     on requesting a higher value, but the accuracy may decrease 
+c     significantly.
+c     
+c     3. Number of points in the output file: (less than Npmx) (INTEGER)
+c     -the frequency grid is controled by the number of points
+c     in the output file.
+c     (i.e. if the upper limit = 250.0 and the number of points = 50.0,
+c     the spectrum will be computed every 5 cm^-1 )
+c     
+c     4. The output in automaticaly directed to output.dat file.
+c     
+c     STRUCTURE OF THE PROGRAM:
+c     -------------------------------------------------------------- 
+c     The MAIN program consists of three modules:
+c     
+c     1. getdat - provides the user interface, 
+c     in this subroutine the Temperature, Frequency Limits and
+c     the number of points are read from the keyboard.
+c     
+c     2. getspc - the main subroutine, where the spectrum is computed.
+c     The three input parameters (temp, range and n; all REAL numbers)
+c     are transmited by value and the absorption coefficient abcoef(..) 
+c     is returned. The default lenght of abcoef(..) is Npmx and if 
+c     n < Npmx, the empty places are set to 0. If a denser grid is
+c     required please change the n appropriaetly in the data declaration
+c     of the MAIN program and inside the getspc.
+c     
+c     3. putdat - generates the output file.
+c     The frequency (in cm^-1) and 
+c     the absorption coefficient (in cm^-1 amagat^-2) are written
+c     to the 'output.dat' file in the followinf format:
+c     format(f10.3,e20.7)
+c     
+c===========================================================================
+c     
+c     
+c     ---------------------------------------------------------------------------------------------------------------
+c     2008/10/15
+c     
+c     Modifications of the code by V. Eymet as follows:
+c     + only the "getspc" routine remains
+c     + inputs: temp (temperature in K), wn (wavenumber in cm^-1); output: abcoef (absorption coefficient, in cm^-1 amagat^-2)
+c     ---------------------------------------------------------------------------------------------------------------
+c
+c
+c
+c     ---------------------------------------------------------------------------------------------------------------
+c     2009/2/28
+c     
+c     Modifications of the code by R. Wordsworth as follows:
+c     + "baranov" routine added to calculate CIA dimer spectrum between 1100 and 1600 cm^-1
+c     + this uses recorded data rather than an analytical function, so bilinear interpolation is needed
+c     + inputs and outputs are identical to those of getspc
+c     ---------------------------------------------------------------------------------------------------------------
+
+
+
+      subroutine getspc(temp,wn,abcoef) ! computes the spectrum
+      implicit none
+      real*8 temp               !temperature
+      real*8 wn        !wavenumber
+      real*8 abcoef       !absorption coefficient
+c     -------------------------------------------------------
+c     The A, B and C parameters as given in the paper:
+      integer ndeg
+      parameter (ndeg=3)
+      real*8 ah(ndeg),bh(ndeg),at(ndeg),bt(ndeg),gam(ndeg)
+c     tau^{L}_{1}:
+      data ah /0.1586914382D+13,-0.9344296879D+01,0.6943966881D+00/
+c     tau^{L}_{2}:
+      data bh /0.1285676961D-12,0.9420973263D+01,-0.7855988401D+00/
+c     tau^{H}_{1}:
+      data at /0.3312598766D-09,0.7285659464D+01,-0.6732642658D+00/
+c     tau^{H}_{2}:
+      data bt /0.1960966173D+09,-0.6834613750D+01,0.5516825232D+00/
+c     gamma_{1}:
+      data gam /0.1059151675D+17,-0.1048630307D+02, 0.7321430968D+00/
+c     **************************************************************
+c     The S - shape function parameters:
+      real*8 w1,w2
+      data w1,w2 /50.0d0, 100.0d0/
+c     --------------------------------------------------------------
+c     local variables:
+c     ----------------------------------
+      real*8 incrmt
+      integer p1,p2,n
+      real*8 a1,b1,a2,b2,gamma
+      real*8 bc1,bc2,bcbc
+      real*8 scon,mtot,spunit,gm0con
+      real*8 icm, frq, lntemp
+      real*8 xk1,x1,x2
+      external xk1
+      incrmt=250.0D+0
+      n=1
+      p1=idint(dnint(w1/incrmt))
+      p2=idint(dnint(w2/incrmt))
+      lntemp=dlog(temp)
+      a1=1.0d0/(ah(1)*dexp(ah(2)*lntemp+ah(3)*lntemp*lntemp))
+      b1=bh(1)*dexp(bh(2)*lntemp+bh(3)*lntemp*lntemp)
+      a2=1.0d0/(at(1)*dexp(at(2)*lntemp+at(3)*lntemp*lntemp))
+      b2=bt(1)*dexp(bt(2)*lntemp+bt(3)*lntemp*lntemp)
+      gamma=gam(1)*dexp(gam(2)*lntemp+gam(3)*lntemp*lntemp)
+      icm=0.1885d0
+      frq=wn
+      x1=b1*dsqrt(a1*a1+icm*icm*frq*frq)
+      bc1=dexp(a1*b1)*a1*XK1(x1)/(a1*a1+icm*icm*frq*frq)
+      x2=b2*dsqrt(a2*a2+icm*icm*frq*frq)
+      bc2=dexp(a2*b2)*a2*XK1(x2)/(a2*a2+icm*icm*frq*frq)
+      if (p1.ge.1) then
+         bcbc=bc1
+      else if (p2.lt.1) then
+         bcbc=bc2
+      else
+         bcbc=dexp( (1.0d0-dble(1-p1)/dble(p2-p1))*dlog(bc1)+
+     &        dble(1-p1)/dble(p2-p1)*dlog(bc2) )
+      endif
+      spunit=1.296917d55
+      gm0con=1.259009d-6
+      scon=spunit/temp
+      mtot=gm0con*temp*gamma*1.0d-56
+      frq=wn
+      abcoef=scon*mtot*bcbc*frq*frq
+      return
+      end
+c     
+c     
+      FUNCTION XK1(X)
+C     MODIFIED BESSEL FUNCTION K1(X) TIMES X
+C     PRECISION IS BETTER THAN 2.2e-7 EVERYWHERE.
+C     ABRAMOWITZ AND S,TEGUN, P.379; TABLES P.417.
+      implicit double precision (a-h,o-z)
+!      IF(X-2.) 10,10,20
+      IF(X-2..le.0.0)then
+! 10   T=(X/3.75)**2
+      T=(X/3.75)**2
+      FI1=X*((((((.00032411*T+.00301532)*T+.02658733)*T+.15084934)
+     1     *T+.51498869)*T+.87890594)*T+.5)
+      T=(X/2.)**2
+      P=(((((-.00004686*T-.00110404)*T-.01919402)*T-.18156897)*T-
+     1     .67278579)*T+.15443144)*T+1.
+      XK1=X*dLOG(X/2)*FI1+P
+!      RETURN
+      else
+! 20   T=2./X
+      T=2./X
+      P=(((((-.00068245*T+.00325614)*T-.00780353)*T+.01504268)*T-
+     1     .03655620)*T+.23498619)*T+1.25331414
+      X=dMIN1(X,330.d0)
+      XK1=dSQRT(X)*dEXP(-X)*P
+      endif
+      RETURN
+      END
+
+
+
+
+c     ----------------------------------------------------------------------------------------------
+c     Added by RDW for inclusion of Baranov (2004) data
+      subroutine baranov(temp,wn,abcoef)
+      ! computes the dimer spectrum
+
+      implicit none
+      real*8 temp               !temperature
+      real*8 wn                 !wavenumber
+      real*8 abcoef             !absorption coefficient
+
+      integer nS,nT
+!      parameter(nS=1713)
+      parameter(nS=3000)
+      parameter(nT=9)
+
+      real*8 wn_arr(nS)
+      real*8 temp_arr(nT)
+      real*8 dim_arr(nS,nT)
+
+      integer pop
+      logical firstcall
+
+      save wn_arr, temp_arr, dim_arr
+
+      character*100 dt_file
+      integer strlen,ios
+      character*100 label
+      label='subroutine baranov'
+
+      dt_file='/san/home/rdword/kspectrum/line_data/CO2_dimer_data_NEW'
+!      dt_file='./data/CO2_dimer_data'
+      open(33,file=dt_file(1:strlen(dt_file)),
+     &     form='unformatted',
+     &     status='old',iostat=ios)
+      if (ios.ne.0) then        ! file not found
+         write(*,*) 'Error from ',label(1:strlen(label)),' :'
+         write(*,*) 'Data file could not be found:'
+         write(*,*) dt_file(1:strlen(dt_file))
+         stop
+      else
+         read(33) wn_arr
+         read(33) temp_arr
+         read(33) dim_arr
+      endif
+      close(33)
+
+
+!	print*,wn_arr(1)!
+!	print*,wn_arr(3000)
+!	print*,temp_arr
+!	print*,dim_arr(1500,1)
+!	stop
+
+
+      call bilinear(wn_arr,temp_arr,nS,nT,dim_arr,wn,temp,abcoef)
+
+ 111  continue
+      return
+      end
+c     ----------------------------------------------------------------------------------------------
+
+c     ----------------------------------------------------------------------------------------------
+c     Added by RDW for inclusion of Baranov (2004) data
+      subroutine bilinear(x_arr,y_arr,nX,nY,f2d_arr,x,y,f)
+
+      implicit none
+
+      integer nX,nY,i,j,a,b
+
+      real*8 x,y,x1,x2,y1,y2
+      real*8 f,f11,f12,f21,f22,fA,fB
+      real*8 x_arr(nX)
+      real*8 y_arr(nY)
+      real*8 f2d_arr(nX,nY)
+      
+      integer strlen
+      character*100 label
+      label='subroutine bilinear'
+
+c     1st check we're within the wavenumber range
+      if ((x.lt.x_arr(2)).or.(x.gt.x_arr(nX-2))) then
+         f=0.0D+0
+c     print*,'x=',x,x_Arr(2),x_arr(nX-2)
+c     stop('Outside CIA dimer wavenumber range!\n')
+         goto 112
+      else
+         
+c     in the x (wavenumber) direction 1st
+         i=1
+ 10      if (i.lt.(nX+1)) then ! what passes for a 'while' loop in this sorry language...
+            if (x_arr(i).gt.x) then
+               x1=x_arr(i-1)
+               x2=x_arr(i)
+               a=i-1
+               i=9999
+            endif
+            i=i+1
+            goto 10
+         endif
+      endif
+      
+      if ((y.lt.y_arr(1)).or.(y.gt.y_arr(nY))) then
+         write(*,*) 'Error from ',label(1:strlen(label)),' :'
+         write(*,*) 'Outside CIA dimer temperature range!'
+         if(y.lt.y_arr(1))then
+            y=y_arr(1)+0.01
+         endif
+         if(y.gt.y_arr(nY))then
+            y=y_arr(nY)-0.01
+         endif
+!         stop
+      else
+c     in the y (temperature) direction 2nd
+         j=1
+ 20      if (j.lt.(nY+1)) then
+            if (y_arr(j).gt.y) then
+               y1=y_arr(j-1)
+               y2=y_arr(j)
+               b=j-1
+               j=9999
+            endif
+            j=j+1
+            goto 20
+         endif
+      endif
+      
+      f11=f2d_arr(a,b)
+      f21=f2d_arr(a+1,b)
+      f12=f2d_arr(a,b+1)
+      f22=f2d_arr(a+1,b+1)
+      
+c     1st in x-direction
+      fA=f11*(x2-x)/(x2-x1)+f21*(x-x1)/(x2-x1)
+      fB=f12*(x2-x)/(x2-x1)+f22*(x-x1)/(x2-x1)
+      
+c     then in y-direction
+      f=fA*(y2-y)/(y2-y1)+fB*(y-y1)/(y2-y1)
+      
+ 112  continue
+      return
+      end
+c     ----------------------------------------------------------------------------------------------
+      
Index: /trunk/LMDZ.GENERIC/utilities/compile
===================================================================
--- /trunk/LMDZ.GENERIC/utilities/compile	(revision 253)
+++ /trunk/LMDZ.GENERIC/utilities/compile	(revision 253)
@@ -0,0 +1,11 @@
+#!/bin/bash
+#gfortran -c -g -fbounds-check generate_kmatrix.F90 strlen.for
+
+gfortran -c generate_kmatrix.F90 co2_cont.for strlen.for
+gfortran -o generate_kmatrix.exe generate_kmatrix.o co2_cont.o strlen.o
+
+gfortran -c make_composition_gen.for strlen.for
+gfortran -o make_composition_gen.exe make_composition_gen.o strlen.o
+
+rm -f *o
+rm -f *~
Index: /trunk/LMDZ.GENERIC/utilities/formats.inc
===================================================================
--- /trunk/LMDZ.GENERIC/utilities/formats.inc	(revision 253)
+++ /trunk/LMDZ.GENERIC/utilities/formats.inc	(revision 253)
@@ -0,0 +1,42 @@
+ 10   format(a)
+ 11   format(I1)
+ 12   format(I2)
+ 13   format(I3)
+ 14   format(I4)
+ 15   format(I5)
+ 16   format(I6)
+ 17   format(I7)
+ 18   format(I8)
+ 19   format(I9)
+ 110   format(I10)
+ 20   format(a23,I3,I3)
+ 21   format(a1)
+ 22   format(i3,a1,a10)
+ 30   format(a30,i3)
+ 31   format(a18,i3)
+ 32   format(a22,i3,a1,i3)
+ 33   format(a23,i3,a1,i3)
+ 34   format(a21,i3)
+ 35   format(a36,i3)
+ 36   format(a3,e17.9,a9,i4)
+   37   format(I1,I9,a100)
+   38   format(I9,a100)
+   39   format(a30,i3)
+   40  format(a,f9.3,a,f9.3,a)
+   41 format(a,f9.3,a)
+   42 format(a,I3,a,I3,a,I3,a)
+   43 format(a,I3,a)
+   44 format(I2,a)
+   45 format(I2,a,I2,a)
+   46 format(I2,a,I2,a,I2,a)
+   47 format(I2,a,I2,a,I2,a,I2,a)
+ 50   format(1000e17.9)
+ 51   format(I3,1000e17.9)
+ 52   format(1000e23.15)
+ 60   format(I2,I1,F12.6,2E10.3,2F5.4,F10.4,F4.2,F8.6,! &
+     &       4A15,6I1,6I2,A1,2F7.1)
+ 62   format(i12,F13.5,F14.4,i5,E14.6)
+ 63   format(I2)
+ 70   format(I2,I1,F12.6,1P2E10.3,0P2F5.4,F10.4,F4.2,F8.6,! &
+     &       2I3,2A9,3I1,3I2)
+ 80   format(I2,I1,F12.6)
Index: /trunk/LMDZ.GENERIC/utilities/generate_kmatrix.F90
===================================================================
--- /trunk/LMDZ.GENERIC/utilities/generate_kmatrix.F90	(revision 253)
+++ /trunk/LMDZ.GENERIC/utilities/generate_kmatrix.F90	(revision 253)
@@ -0,0 +1,461 @@
+      program generate_kmatrix
+      implicit none
+
+!     -------------------------------------------------------------
+!     Purpose: to read hires spectra and produce kdistribution data
+!     Authour: Robin Wordsworth (2010)
+!     -------------------------------------------------------------
+
+      integer nmolec,mol
+      integer i,j,k,im
+      integer Nb
+
+      character*4 fname
+      character*32 fnum
+
+      integer iT, iP, iQ, Nlevs
+
+      double precision nuT, sigT, kT
+
+      integer Nq
+      parameter (Nq=16) ! we choose this here
+
+      integer Nmax
+      parameter (Nmax=1000) ! maximum number of levels
+
+      integer Nmol_max
+      parameter (Nmol_max=10) ! maximum number of radiatively active species
+
+      integer Nkmax
+      ! large array = slow calculation... this makes a huge difference
+      !parameter (Nkmax=50000) ! works for IR, 27 bands
+      !parameter (Nkmax=100000) ! works for IR, 27 bands
+      !parameter (Nkmax=140000) ! works for IR, 32 bands
+      !parameter (Nkmax=250000) ! works for VI, 36 bands
+      parameter (Nkmax=400000) ! works for IR, 8 bands
+      !parameter (Nkmax=400000) ! works for VI, 12 bands
+      !parameter (Nkmax=200000) ! works for IR, 30 bands
+
+      integer NbMAX
+      parameter (NbMAX=100)
+
+      integer Ngres
+      parameter (Ngres=200)
+
+      character*10 molec_names(1:Nmol_max)
+      double precision T(1:Nmax), P(1:Nmax), Q(1:Nmax)
+
+
+      double precision pi
+      parameter (pi=3.14159265)
+      double precision x
+      double precision y(1:Nq+2)
+
+      double precision nu_min(1:NbMAX) ! make allocatable?
+      double precision nu_max(1:NbMAX)
+
+      integer quad, band
+
+      double precision ktemp(1:Nq)
+      double precision w(1:Nq), gw(1:Nq)
+
+      double precision, allocatable :: kdist_temp(:)
+      double precision, allocatable :: kdist(:,:,:,:,:)
+
+      double precision nuband(1:Nkmax), kband(1:Nkmax), nuwband(1:Nkmax) ! better static I think
+      double precision nuwbtot
+
+      double precision gfine(1:Ngres)      
+      double precision klevs(1:Ngres)
+      double precision addline(1:Nkmax)
+
+      double precision kmax, kmin, lkmax, lkmin, dlogK, klev
+      integer ic, ib, ig, ik1, ik2
+
+      integer filerr
+      logical filexi
+
+      logical addCIA
+      integer iCO2
+      double precision k1,k2,kCIA,amg,Pp
+
+      real truemean, distmean, etot
+      
+
+      addCIA=.false.
+
+      print*,'Creating the GCM correlated-k data...'
+      print*,' '
+
+      !--------------------------------------------------------
+      ! load temperature, pressure, mixing ratio data
+      open(9,file='T.dat')
+      read(9,*) iT
+      do i=1,iT
+         read(9,*) T(i)
+      enddo
+      close(9)
+
+      open(10,file='p.dat')
+      read(10,*) iP
+      do i=1,iP
+         read(10,*) P(i)
+         P(i)=10.**P(i)  ! note we keep P in millibars for the conversion later
+      enddo
+      close(10)
+
+      open(11,file='Q.dat')
+      read(11,*) nmolec
+      do mol=1,nmolec
+         read(11,*) molec_names(mol)
+      enddo
+      read(11,*) iQ
+      do i=1,iQ
+         read(11,*) Q(i)
+      enddo
+      close(11)
+
+      Nlevs=iT*iP*iQ ! total number of layers
+
+      print*,'Temperature layers:  ',iT
+      print*,'Pressure layers:     ',iP
+      print*,'Mixing ratio layers: ',iQ
+      print*,'Total:               ',Nlevs
+
+
+      if(addCIA)then
+
+         if(nmolec.gt.2)then
+            print*,'I cant deal with this situation yet'
+            call abort
+         endif
+
+         iCO2=0
+         do mol=1,nmolec
+            if(molec_names(mol).eq.'CO2')then
+               iCO2=mol
+            endif
+         enddo
+
+         !if(iCO2.eq.1)then
+         print*,' '
+         print*,'--- Adding CO2 CIA ---'
+         !else
+         !   print*,'Warning, not CO2+H2O mixture, need CO2 mixing ratio'
+         !   call abort
+         !endif
+      endif
+
+      !--------------------------------------------------------
+      ! load spectral data
+      open(12,file='narrowbands.in')
+      read(12,*) Nb
+
+      do band=1,Nb
+         read(12,*) nu_min(band),nu_max(band)
+      enddo
+      close(12)
+
+      print*,' '
+      print*,'Number of spectral bands: ',Nb
+
+      print*,'Band limits:'
+      do band=1,Nb
+         print*,band,'-->',nu_min(band),nu_max(band),' cm^-1'
+      end do
+
+      !--------------------------------------------------------
+      ! create g-space data
+      do quad=0,Nq+1
+         x=dble(quad)/dble(Nq+2)
+         !y(quad+1)=sin(pi*x)*exp(-5*x)
+         !y(quad+1)=sin(pi*x)*exp(-9*x)  ! CO2_H2Ovar 38x36
+         y(quad+1)=sin(pi*x)*exp(-12*x)
+         !y(quad+1)=sin(pi*x)*exp(-15*x) ! CO2_CH4
+      enddo
+
+      do quad=1,Nq
+         w(quad)=y(quad+1)
+      enddo
+      w=w/sum(w)
+
+      print*,' '
+      print*,'Number of g-space intervals: ',Nq
+
+      print*,'g-space weighting:'
+      do quad=1,Nq
+         print*,quad,'-->',w(quad)
+      end do
+
+      ! write g-space data
+      open(14,file='g.dat')
+      write(14,*) Nq+1
+
+      do quad=1,Nq
+         write(14,*) w(quad)
+      enddo
+      write(14,*) 0.0
+      close(14)
+
+      ! cumulative sum for g-vector
+      gw(1)=w(1)
+      do quad=2,Nq
+         gw(quad)=gw(quad-1)+w(quad)
+      enddo
+
+      ! allocate 5D matrices
+      allocate(kdist_temp(Nq))
+      allocate(kdist(iT,iP,iQ,Nb,Nq+1))
+
+
+      nuT=0.0
+      do i=1,iQ
+         do j=1,iP
+
+
+            if(addCIA.and.(iCO2.eq.1))then 
+               Pp=P(j)*(1.0-Q(i))
+            else
+               Pp=P(j)*Q(i)
+            endif
+            !if(addCIA) Pp=P(j)*(1.0-Q(i))
+
+
+            do k=1,iT             
+               im = (i-1)*iP*iT + (j-1)*iT + k
+
+               !-----------------------------------------------
+               ! open kspectrum file
+               write(fnum,*) im
+               if(im<10)then
+                   fname='k00'//trim(adjustl(fnum))
+               elseif(im<100)then
+                   fname='k0'//trim(adjustl(fnum))
+               else
+                   fname='k'//trim(adjustl(fnum))
+               endif
+
+               ! check that the file exists
+               inquire(FILE='hires_spectrum/'//fname,EXIST=filexi)
+               if(.not.filexi) then
+                  write(*,*)'The file ',fname(1:LEN_TRIM(fname))
+                  write(*,*)'was not found in the folder hires_spectrum, exiting.'
+                  call abort
+               endif
+
+               print*,'Opening file ',fname(1:LEN_TRIM(fname))
+               open(17,file='hires_spectrum/'//fname)
+
+               nuT=0.0
+               do band=1,Nb
+               print*,'Band ---> ',band
+
+                  !--------------------------------------------
+                  ! write kdata to temporary band arrays
+                  ! and find max / min k-values in band
+                  do while (nuT.lt.nu_min(band))
+                      read(17,*,IOSTAT=filerr) nuT, sigT, kT
+                   ! ideally need to catch all errors here (ask Ehouarn)
+                      if(filerr.lt.0)then
+                         print*,    &
+                             'nu_min greater than highest value in file'
+                         print*,'IOSTAT=',filerr
+                         print*,'nu_min=',nu_min(band)
+                         print*,'nu_endoffile=',nuT
+                         call abort
+                      endif
+                  enddo
+
+                  ic=1
+                  kmin=kT
+                  kmax=kT
+                  nuband(:)=0
+                  kband(:)=0
+
+                  do while (nuT.lt.nu_max(band))
+
+                      nuband(ic)=nuT
+                      kband(ic)=kT
+
+                      ! insert CIA option here
+                      if(addCIA)then
+
+                         k1=0.0
+                         k2=0.0
+                         if(nuT.lt.500.0) call getspc(T(k),nuT,k1)
+                         if((nuT.gt.1000.0).and.(nuT.lt.1800.0)) call baranov(T(k),nuT,k2)
+                         ! cm^-1.amagat^2
+
+                         amg=273.15D+0/T(k)*(Pp/1013.25) ! amagats of CO2
+
+                         kCIA=(k1+k2)*1.0D+2*amg**2.0D+0 ! m^-1
+                         kband(ic)=kband(ic)+kCIA
+                   	 kT=kband(ic)
+
+                         !kband(ic)=kCIA
+			 !kT=kCIA
+			 !if(nuband(ic).gt.1250.0)then
+			 !	print*,'P=',P(i)
+			 !	print*,'T=',T(k)
+		         !	print*,'amg=',amg
+			 !	print*,'nu=',nuband(ic)
+                         !       print*,'k1=',k1
+                         !       print*,'k2=',k2
+                         !       print*,'kCIA=',kCIA
+		  	 !	call abort
+                         !endif
+
+                      endif
+
+                      if(kT.lt.kmin)then
+                        kmin=kT
+                      endif
+                      if(kT.gt.kmax)then ! bug corrected!
+                        kmax=kT
+                      endif
+
+                      read(17,*,IOSTAT=filerr) nuT, sigT, kT
+                      if(filerr.lt.0)then
+                         print*,    &
+                             'nu_max greater than highest value in file'
+                         print*,'IOSTAT=',filerr
+                         print*,'nu_max=',nu_max(band)
+                         print*,'nu_endoffile=',nuT
+                         call abort
+                      endif
+
+
+                      ic=ic+1
+                      
+                      if(ic.gt.Nkmax)then
+                         print*,'Spectral resolution too low for these bands, exiting!'
+                         print*,'Increase Nkmax in generate_kmatrix.F90.'
+                         call abort
+                      endif
+
+                  enddo
+                  nuband(ic)=nuT
+                  kband(ic)=kT
+
+                  if(kmax.le.0.0)then
+                  !if(kmax.le.1.0e-15)then
+                     print*,'kmax=',kmax
+                     print*,'Setting values to zero in this band.'
+                     kdist(k,j,i,band,1:(Nq+1))=0.0
+                  else
+
+                  if(kmin.lt.1e-30)then
+                     kmin=1.0e-30
+                  endif
+
+                  !--------------------------------------------
+                  ! calculate delta nu values
+                  nuwband(:)=0.0
+                  do ib=2,(ic-1)
+                      nuwband(ib)=(nuband(ib+1)-nuband(ib-1))/2
+                  enddo
+                  nuwband(1)=nuwband(2)
+                  nuwband(ic)=nuwband(ic-1) ! causes tiny boundary error; whatever
+                  nuwbtot=sum(nuwband)
+
+                  lkmax=log10(kmax)
+                  lkmin=log10(kmin)
+                  
+                  dlogK=(lkmax-lkmin)/(Ngres-1)                 
+
+                  !--------------------------------------------
+                  ! calculate the g function
+                  gfine(:)=0.0
+                  do ig=1,Ngres
+                    klev=lkmin + dble(ig)*dlogK
+                    klev=10**klev
+                    klevs(ig)=klev
+
+                    addline(:)=0
+                    do ib=1,ic
+                        if(kband(ib).lt.klev)then
+                           addline(ib)=1.0
+                        endif
+                    enddo
+                    gfine(ig)=sum(addline(:)*nuwband(:))/nuwbtot
+
+                  enddo
+                  print*,'gnorm    = ',gfine(Ngres)
+
+                  !--------------------------------------------
+                  ! invert the g function
+                  ik1=1
+                  ik2=1
+                  kdist_temp(:)=0.0
+                  do quad=1,Nq
+                    
+                    ik2=ik1
+
+                    gfind: do while (gfine(ik2).lt.gw(quad))
+                       ik2=ik2+1
+                       if(ik2.gt.Ngres)then
+                          print*,'g-inversion overflow...'
+                          ik2=Ngres
+                          exit gfind
+                       endif
+                    enddo gfind
+
+                    !if(ik2.gt.Ngres)then ! avoid out-of-bounds on final step
+                    !   ik2=Ngres
+                    !endif
+
+
+                     if(.not.(ik1.ge.ik2))then ! this could probably be improved
+                        !kdist_temp(quad)=sum(klevs(ik1:ik2))/(ik2-ik1) ! a bug was here!
+                        kdist_temp(quad)=sum(klevs(ik1:ik2))/(ik2+1-ik1)
+
+
+                     elseif(quad.ne.1)then
+                        kdist_temp(quad)=kdist_temp(quad-1)
+                     else
+                        kdist_temp(quad)=kmin
+                     endif
+
+                     !-----------------------------------------
+                     ! assign to 5D matrix and convert to cm^2 / molecule
+                     kdist(k,j,i,band,quad)=1.3807e-21 *               &
+                                kdist_temp(quad) * T(k)/P(j)
+
+                     ik1=ik2
+                  enddo ! g-space
+                  kdist(k,j,i,band,Nq+1)=0.0
+
+                  truemean = sum(kband(1:ic)*nuwband(1:ic))/sum(nuwband(1:ic))
+                  distmean = sum(kdist_temp(:)*w(:))/sum(w)
+                  etot     = 100*abs(truemean-distmean)/(distmean+truemean)
+                  print*,'truemean = ',truemean
+                  print*,'distmean = ',distmean
+                  !print*,'kdisttemp = ',kdist_temp(Nq)
+                  !print*,'kdistmax  = ',kmax
+                  print*,'etot (%) = ',etot
+                  !print*,'w  = ',w
+
+                  endif ! if kmax .le. 0.0 
+
+               enddo ! bands
+
+            enddo
+         enddo
+      enddo
+
+      !--------------------------------------------------------
+      ! save data and clean up
+      close(17)
+      open(14,file='corrk_gcm.dat',form='formatted')
+      write(14,*) kdist
+      close(14)
+      print*,' '
+      print*,'Correlated-k data saved in corrk_gcm.dat'
+      print*,' '
+      print*,'Now you must change the values of L_NTREF etc. in radinc_h.F90 (if necessary)'
+      print*,'and the variable "corrkdata" in callphys.def'
+
+      deallocate(kdist_temp)
+      deallocate(kdist)
+
+    end program generate_kmatrix
Index: /trunk/LMDZ.GENERIC/utilities/make_composition_gen.for
===================================================================
--- /trunk/LMDZ.GENERIC/utilities/make_composition_gen.for	(revision 253)
+++ /trunk/LMDZ.GENERIC/utilities/make_composition_gen.for	(revision 253)
@@ -0,0 +1,161 @@
+      program make_composition_gen
+      implicit none
+
+!     -------------------------------------------------------------   
+!     Purpose: to create "composition.in" file readable by kspectrum
+!     Authour: Robin Wordsworth (2010)
+!     -------------------------------------------------------------
+
+      include 'max.inc'
+      include 'formats.inc'
+      integer strlen,nmolec,nlev_mf,mol,imf,ind,indf
+      integer i,j,k,im,m
+      integer nb,na,ne
+      double precision alt(1:Nmax)
+      double precision pres(1:Nmax)
+      double precision temp(1:Nmax)
+
+      double precision P_mf(1:Nmax)
+      double precision x(1:Nmax,1:Nmol_max)
+      double precision xlev(1:Nmol_max)
+      double precision xconst(1:Nmol_max)
+      character*100 composition_file,model_file
+      character*100 planet_descriptor
+      character*200 string
+      character*20 s
+      character*10 molec_names(1:Nmol_max),molname
+      character*1 spch
+
+      integer iP, iT, iQ
+      double precision P(1:Nmax), T(1:Nmax), Q(1:Nmax)
+
+      spch=' '
+
+      print*,'Name of atmosphere / planet:'
+      read*,planet_descriptor
+
+      composition_file='./composition.in'
+
+!     ! nmolec=2 ! total number of molecules
+
+      ! load temperature, pressure, mixing ratio data
+      open(9,file='T.dat')
+      read(9,*) iT
+      do i=1,iT
+         read(9,*) T(i)
+      enddo
+      close(9)
+
+      open(10,file='p.dat')
+      read(10,*) iP
+      do i=1,iP
+         read(10,*) P(i)
+         P(i)=10.**P(i)/1013.25
+      enddo
+      close(10)
+
+      open(11,file='Q.dat')
+      read(11,*) nmolec
+
+      print*,'nmolec=',nmolec
+
+      do mol=1,nmolec
+         read(11,*) molec_names(mol)
+      enddo
+      read(11,*) iQ
+      do i=1,iQ
+         read(11,*) Q(i)
+      enddo
+      close(11)
+
+      m=iP*iT*iQ ! total number of layers
+
+      print*,'Temperature layers:  ',iT
+      print*,'Pressure layers:     ',iP
+      print*,'Mixing ratio layers: ',iQ
+      print*,'Total:               ',m
+
+      do mol=1,nmolec-1
+         print*,'Please enter vmr of ',molec_names(mol)
+         read(*,*) xconst(mol)
+      end do
+
+     
+      do i=1,iQ
+         do j=1,iP              
+            do k=1,iT
+
+               im = (i-1)*iP*iT + (j-1)*iT + k
+
+               alt(im)=0.D0
+               pres(im)=P(j)
+               temp(im)=T(k)
+
+               do mol=1,nmolec-1
+                  x(im,mol)=xconst(mol)*(1.0-Q(i))
+               enddo
+               x(im,nmolec)=Q(i)
+
+            enddo
+         enddo
+      enddo
+
+      open(12,file=composition_file(1:strlen(composition_file)))
+      string='Atmospheric composition input '
+      string=string(1:strlen(string))//' data file for planet:'
+      string=string(1:strlen(string))//' '//
+
+     &     planet_descriptor(1:strlen(planet_descriptor))
+      write(12,'(a)') string(1:strlen(string))
+      write(12,39) 'Number of atmospheric levels: ',m
+      write(12,34) 'Number of molecules: ',nmolec
+      write(12,*) 
+      string='      z (km)     /    P (atm)     /     T (K) *'
+
+
+      do mol=1,nmolec
+
+         molname=molec_names(mol)
+
+         nb=5
+         if (strlen(molname).eq.1) then
+            na=7
+         else if (strlen(molname).eq.2) then
+            na=6
+         else if (strlen(molname).eq.3) then
+            na=5
+         endif
+         s='*'
+         do ne=1,nb
+            s=s(1:strlen(s)-1)//spch//'*'
+         enddo
+         s=s(1:strlen(s)-1)//'/*'
+         do ne=1,na
+            s=s(1:strlen(s)-1)//spch//'*'
+         enddo
+         
+         string=string(1:strlen(string)-1)
+     &        //s(1:strlen(s)-1)
+     &        //'x['
+     &        //molname(1:strlen(molname))
+     &        //']*'
+      enddo
+      write(12,*) string(1:strlen(string)-1)
+
+      do im=1,m
+
+         do mol=1,nmolec
+            xlev(mol)=x(im,mol)
+         enddo                  ! mol
+
+         write(12,50) alt(im),pres(im),temp(im),(xlev(mol),mol=1,nmolec)
+
+      enddo
+
+      write(12,*) 
+      close(12)
+
+      write(*,*) 'Output file successfully generated:'
+      write(*,*) composition_file(1:strlen(composition_file))
+      
+      end
Index: /trunk/LMDZ.GENERIC/utilities/max.inc
===================================================================
--- /trunk/LMDZ.GENERIC/utilities/max.inc	(revision 253)
+++ /trunk/LMDZ.GENERIC/utilities/max.inc	(revision 253)
@@ -0,0 +1,23 @@
+          integer Nline_mx,Nmol_max,Niso_max,Nbmx,Nkmx,Nmax,Nlpnb_mx
+	    integer Nxtab_mx,Nacc_mx,Nmax_tab,Nytab_mx,Nktab_mx
+	    integer nfiles_mx,Nproc_mx,Nchunk_mx,Nc_mx,Nmax_vt,Nppc_max
+	    integer Nti_mx
+          parameter(Nline_mx=2000000)
+          parameter(Nmol_max=42)
+          parameter(Niso_max=15)
+	  parameter(Nbmx=10000)
+	  parameter(Nkmx=100000)
+	  parameter(Nmax=2000)
+	  parameter(Nlpnb_mx=500000)
+	  parameter(Nxtab_mx=100000)
+	  parameter(Nacc_mx=1000)
+	  parameter(Nmax_tab=1000000)
+	    parameter(Nytab_mx=210)
+	    parameter(Nktab_mx=1000000)
+	    parameter(nfiles_mx=100)
+	    parameter(Nproc_mx=1000)
+	    parameter(Nchunk_mx=1000)
+	    parameter(Nc_mx=9)
+	    parameter(Nmax_vt=1000000)
+	    parameter(Nppc_max=10000)
+	    parameter(Nti_mx=100000)
Index: /trunk/LMDZ.GENERIC/utilities/postkspectrum
===================================================================
--- /trunk/LMDZ.GENERIC/utilities/postkspectrum	(revision 253)
+++ /trunk/LMDZ.GENERIC/utilities/postkspectrum	(revision 253)
@@ -0,0 +1,47 @@
+#!/bin/bash
+
+DWORK_DIR=/san/home/rdword/corrk_data/therm_test2
+KSPEC_DIR=/san/home/rdword/kspectrum/kspec_1
+BANDS_DIR=32x36
+
+### if hires_spectrum don't exist then create it, copy data from kspectrum
+DIRCHECK=hires_spectrum
+cd $DWORK_DIR/
+if [ -d $DIRCHECK ]; then
+    echo -en "Directory hires_spectrum already exists.\n"
+else
+    echo -en "Copying kspectrum data to its new home...\n"
+    cd $DWORK_DIR
+    mkdir hires_spectrum
+
+    mv $KSPEC_DIR/results/k* hires_spectrum/
+    cp $KSPEC_DIR/results/calculation_info.txt hires_spectrum/
+    cp $KSPEC_DIR/*in hires_spectrum/
+    cp $KSPEC_DIR/data/composition.in hires_spectrum/
+
+    # removing contents of 'optimizations' folder
+    rm -rf $KSPEC_DIR/optimizations
+    mkdir $KSPEC_DIR/optimizations
+
+    chmod 444 hires_spectrum/*
+fi
+
+cp ~/utilities/run_kmatrix .
+
+echo -en "\nNow you must submit the parallel job (>> llsubmit run_kmatrix)\n"
+
+exit 0
+
+#cp ~/utilities/generate_kmatrix.exe .
+### make kmatrix in the infrared and save it in a GCM-friendly format
+#cp $BANDS_DIR/narrowbands_IR.in narrowbands.in
+#generate_kmatrix.exe
+#mv corrk_gcm.dat $BANDS_DIR/corrk_gcm_IR.dat 
+#rm narrowbands.in
+### make kmatrix in the visible and save it in a GCM-friendly format
+#cp $BANDS_DIR/narrowbands_VI.in narrowbands.in
+#generate_kmatrix.exe
+#mv corrk_gcm.dat $BANDS_DIR/corrk_gcm_VI.dat 
+#rm narrowbands.in
+#rm generate_kmatrix.exe
+#exit 0
Index: /trunk/LMDZ.GENERIC/utilities/prekspectrum
===================================================================
--- /trunk/LMDZ.GENERIC/utilities/prekspectrum	(revision 253)
+++ /trunk/LMDZ.GENERIC/utilities/prekspectrum	(revision 253)
@@ -0,0 +1,26 @@
+#!/bin/bash
+
+DWORK_DIR=/san/home/rdword/corrk_data/therm_test2
+KSPEC_DIR=/san/home/rdword/kspectrum/kspec_1
+
+cd $DWORK_DIR
+
+# test for presence of k* in kspec results directory
+FILECHECK=$KSPEC_DIR/results/k001
+if [ -f $FILECHECK ]; then
+    echo -en "There is already k-data in the kspec directory "
+    echo -en $KSPEC_DIR
+    echo -en ", delete or move it before starting!\n"
+    exit 1
+fi
+
+#make_composition_gen.exe
+cp composition.in $KSPEC_DIR/data/
+
+echo -en "kspectrum working directory is:\n"
+echo -en $KSPEC_DIR
+echo -en "\nNow you must submit the parallel job (>> llsubmit run_kspec)\n"
+
+cd $KSPEC_DIR
+
+exit 0
Index: /trunk/LMDZ.GENERIC/utilities/run_kmatrix
===================================================================
--- /trunk/LMDZ.GENERIC/utilities/run_kmatrix	(revision 253)
+++ /trunk/LMDZ.GENERIC/utilities/run_kmatrix	(revision 253)
@@ -0,0 +1,28 @@
+# @ job_name=kmatrix
+# @ output = $(job_name).$(jobid)
+# @ error = $(output)
+# @ job_type = serial
+# @ class = B
+# @ queue
+
+BANDS_DIR=32x36
+
+cp ~/utilities/generate_kmatrix.exe .
+
+## make kmatrix in the infrared and save it in a GCM-friendly format
+cp $BANDS_DIR/narrowbands_IR.in narrowbands.in
+generate_kmatrix.exe #> log.out
+mv corrk_gcm.dat $BANDS_DIR/corrk_gcm_IR.dat 
+mv log.out $BANDS_DIR/logIR.out 
+rm narrowbands.in
+
+## make kmatrix in the visible and save it in a GCM-friendly format
+cp $BANDS_DIR/narrowbands_VI.in narrowbands.in
+generate_kmatrix.exe > log.out
+mv corrk_gcm.dat $BANDS_DIR/corrk_gcm_VI.dat 
+mv log.out $BANDS_DIR/logVI.out 
+rm narrowbands.in
+
+rm generate_kmatrix.exe
+
+exit 0
Index: /trunk/LMDZ.GENERIC/utilities/startrestart
===================================================================
--- /trunk/LMDZ.GENERIC/utilities/startrestart	(revision 253)
+++ /trunk/LMDZ.GENERIC/utilities/startrestart	(revision 253)
@@ -0,0 +1,6 @@
+#!/bin/bash
+
+mv -f restart.nc start.nc
+mv -f restartfi.nc startfi.nc
+
+exit 0
Index: /trunk/LMDZ.GENERIC/utilities/startrestart0
===================================================================
--- /trunk/LMDZ.GENERIC/utilities/startrestart0	(revision 253)
+++ /trunk/LMDZ.GENERIC/utilities/startrestart0	(revision 253)
@@ -0,0 +1,6 @@
+#!/bin/bash
+
+mv -f restart.nc start0.nc
+mv -f restartfi.nc startfi0.nc
+
+exit 0
Index: /trunk/LMDZ.GENERIC/utilities/strlen.for
===================================================================
--- /trunk/LMDZ.GENERIC/utilities/strlen.for	(revision 253)
+++ /trunk/LMDZ.GENERIC/utilities/strlen.for	(revision 253)
@@ -0,0 +1,10 @@
+      integer function strlen(st)
+      integer i
+      character st*(*)
+      i=len(st)
+      do while (st(i:i).eq.' ')
+         i=i-1
+      enddo
+      strlen=i
+      return
+      end
