diff --git a/.travis.yml b/.travis.yml
index 2f51ab7adc2766858e3019cd18ab902e1b066dee..0ba7a965f8558c2d82adb2e1fa4ff31dfc4419d1 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -50,4 +50,4 @@ install:
 script:
     - ./.travis_build.sh
     - sudo dpkg -i ../moose*.deb 
-    - python -c 'import moose;print(moose.version());print(moose.__file__)'
+    - /usr/bin/python -c 'import moose;print(moose.version());print(moose.__file__)'
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 531cac20dfa9a354490c1c7eb83d68e5e1ae455c..7695dd440d2d2885ec221a0bb44f43bae613f86f 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -109,8 +109,8 @@ if(WITH_GUI)
 endif()
 
 
-
-install(DIRECTORY ${PYMOOSE_INSTALL_DIR}/usr/
+# NOTE: leading / is important other whole path will be installed.
+install(DIRECTORY ${PYMOOSE_INSTALL_DIR}/
     DESTINATION ${CMAKE_INSTALL_PREFIX}
     CONFIGURATIONS Release
     PATTERN ".git" EXCLUDE
diff --git a/README.md b/README.md
index e3ccdefd2418ac04f3e36484554a38b0127f0ebf..a451b4f0537abac186e0645a7a21bb8c287e7d68 100644
--- a/README.md
+++ b/README.md
@@ -48,7 +48,7 @@ models.  Several additional rdesigneur tutorials have been implemented.
 
 # Installing
 
-See the file  [NSTALL.md](INSTALL.md).
+See the file  [INSTALL.md](INSTALL.md).
 
 # AUTHORS
 
diff --git a/docs/images/ex2.1_vclamp_a.png b/docs/images/ex2.1_vclamp_a.png
new file mode 100644
index 0000000000000000000000000000000000000000..bfb68c12d83563c3bd8b6f0ea281b713479fe94e
Binary files /dev/null and b/docs/images/ex2.1_vclamp_a.png differ
diff --git a/docs/images/ex2.1_vclamp_b.png b/docs/images/ex2.1_vclamp_b.png
new file mode 100644
index 0000000000000000000000000000000000000000..234dd59f6e3d74e8c35343af9e7c36df6a7ff421
Binary files /dev/null and b/docs/images/ex2.1_vclamp_b.png differ
diff --git a/docs/images/ex3.1_squid_vclamp.png b/docs/images/ex3.1_squid_vclamp.png
new file mode 100644
index 0000000000000000000000000000000000000000..0748b411e3b149792eac238e6860b0c13253f4c6
Binary files /dev/null and b/docs/images/ex3.1_squid_vclamp.png differ
diff --git a/docs/images/ex3.2_axon_propagating_AP.png b/docs/images/ex3.2_axon_propagating_AP.png
new file mode 100644
index 0000000000000000000000000000000000000000..649c380249e1bf7cc9586086ee0fe44d1ec251bc
Binary files /dev/null and b/docs/images/ex3.2_axon_propagating_AP.png differ
diff --git a/docs/images/ex3.3_AP_collision.png b/docs/images/ex3.3_AP_collision.png
new file mode 100644
index 0000000000000000000000000000000000000000..2c7b6ef81c20fbd756c51cc6b3de00a267c37a58
Binary files /dev/null and b/docs/images/ex3.3_AP_collision.png differ
diff --git a/docs/images/ex4.0_scaledSoma.png b/docs/images/ex4.0_scaledSoma.png
new file mode 100644
index 0000000000000000000000000000000000000000..1d5f861af2ce95d3195dc54564bdf4090366ee38
Binary files /dev/null and b/docs/images/ex4.0_scaledSoma.png differ
diff --git a/docs/images/ex4.1_ballAndStick.png b/docs/images/ex4.1_ballAndStick.png
new file mode 100644
index 0000000000000000000000000000000000000000..dcd4fb64bd6e8dac13322b1aa738b3792ef381ed
Binary files /dev/null and b/docs/images/ex4.1_ballAndStick.png differ
diff --git a/docs/images/ex4.2_sine_stim.png b/docs/images/ex4.2_sine_stim.png
new file mode 100644
index 0000000000000000000000000000000000000000..f592f8f3b70fb9fc1e211a5309624ace913c11d4
Binary files /dev/null and b/docs/images/ex4.2_sine_stim.png differ
diff --git a/docs/images/ex4.2_spiking.png b/docs/images/ex4.2_spiking.png
new file mode 100644
index 0000000000000000000000000000000000000000..33b3ab4aec5b97e1823c974250d33b0db3708060
Binary files /dev/null and b/docs/images/ex4.2_spiking.png differ
diff --git a/docs/images/ex5.0_random_syn_input.png b/docs/images/ex5.0_random_syn_input.png
new file mode 100644
index 0000000000000000000000000000000000000000..e7ef4c2683fd6764c60fbaae18a63be35e8b8520
Binary files /dev/null and b/docs/images/ex5.0_random_syn_input.png differ
diff --git a/docs/images/ex5.1_periodic_syn_input.png b/docs/images/ex5.1_periodic_syn_input.png
new file mode 100644
index 0000000000000000000000000000000000000000..e9503c3395615bf15e0306a2e0240f102c72c103
Binary files /dev/null and b/docs/images/ex5.1_periodic_syn_input.png differ
diff --git a/docs/images/ex7.0_spatial_chem_osc.png b/docs/images/ex7.0_spatial_chem_osc.png
new file mode 100644
index 0000000000000000000000000000000000000000..66927b396a5b500f602d81b86527e6cf4899b45b
Binary files /dev/null and b/docs/images/ex7.0_spatial_chem_osc.png differ
diff --git a/docs/images/ex7.1_diffusive_gradient.png b/docs/images/ex7.1_diffusive_gradient.png
new file mode 100644
index 0000000000000000000000000000000000000000..3ebb5c1dc63e78ca8017fa266fe5ca1516a6cc9c
Binary files /dev/null and b/docs/images/ex7.1_diffusive_gradient.png differ
diff --git a/docs/images/ex7.2_CICR_static.png b/docs/images/ex7.2_CICR_static.png
new file mode 100644
index 0000000000000000000000000000000000000000..fd52abf2ac0908c23035040d65b81c282547ed0c
Binary files /dev/null and b/docs/images/ex7.2_CICR_static.png differ
diff --git a/docs/images/ex7.2_CICR_wave_lastFrame.png b/docs/images/ex7.2_CICR_wave_lastFrame.png
new file mode 100644
index 0000000000000000000000000000000000000000..fa84f6a81e48790bd5dbe4cae5696944205eca91
Binary files /dev/null and b/docs/images/ex7.2_CICR_wave_lastFrame.png differ
diff --git a/docs/images/ex7.3_1.png b/docs/images/ex7.3_1.png
new file mode 100644
index 0000000000000000000000000000000000000000..1bccd999aa6df1cfbb89356fc53b39a37da77705
Binary files /dev/null and b/docs/images/ex7.3_1.png differ
diff --git a/docs/images/ex7.3_2.png b/docs/images/ex7.3_2.png
new file mode 100644
index 0000000000000000000000000000000000000000..87a77969a70009884a060b987cc982a67626b1de
Binary files /dev/null and b/docs/images/ex7.3_2.png differ
diff --git a/docs/images/ex7.3_3.png b/docs/images/ex7.3_3.png
new file mode 100644
index 0000000000000000000000000000000000000000..978f8e257eb28256f70ffb867c3e5ea5b8f13c34
Binary files /dev/null and b/docs/images/ex7.3_3.png differ
diff --git a/docs/images/ex7.3_4.png b/docs/images/ex7.3_4.png
new file mode 100644
index 0000000000000000000000000000000000000000..282db44db7933c94e575e56383a13c68066652aa
Binary files /dev/null and b/docs/images/ex7.3_4.png differ
diff --git a/docs/images/ex7.3_5.png b/docs/images/ex7.3_5.png
new file mode 100644
index 0000000000000000000000000000000000000000..66f25cfba2b1dac8dba71b6e71016809456af9aa
Binary files /dev/null and b/docs/images/ex7.3_5.png differ
diff --git a/docs/images/ex7.3_6.png b/docs/images/ex7.3_6.png
new file mode 100644
index 0000000000000000000000000000000000000000..75e29d1cc94c3a0b1108c6483bc6586e8b57ba37
Binary files /dev/null and b/docs/images/ex7.3_6.png differ
diff --git a/docs/images/ex7.4_travelling_osc.png b/docs/images/ex7.4_travelling_osc.png
new file mode 100644
index 0000000000000000000000000000000000000000..47cc7f407e80d122d105b20d3ddc57419bd3f615
Binary files /dev/null and b/docs/images/ex7.4_travelling_osc.png differ
diff --git a/docs/images/ex7.5_a.png b/docs/images/ex7.5_a.png
new file mode 100644
index 0000000000000000000000000000000000000000..100ba1984d076812d30237ee6f93fca07f8b86d5
Binary files /dev/null and b/docs/images/ex7.5_a.png differ
diff --git a/docs/images/ex7.5_a_later.png b/docs/images/ex7.5_a_later.png
new file mode 100644
index 0000000000000000000000000000000000000000..7a18c73c86946ed60879a20263fdc3759d75e5f1
Binary files /dev/null and b/docs/images/ex7.5_a_later.png differ
diff --git a/docs/images/ex7.5_b.png b/docs/images/ex7.5_b.png
new file mode 100644
index 0000000000000000000000000000000000000000..228cb498af756501231d25a9f0b2ebe6dab503e5
Binary files /dev/null and b/docs/images/ex7.5_b.png differ
diff --git a/docs/images/ex7.5_s.png b/docs/images/ex7.5_s.png
new file mode 100644
index 0000000000000000000000000000000000000000..f29c4fed86c1043aeedc8fe42cee622d11424e3b
Binary files /dev/null and b/docs/images/ex7.5_s.png differ
diff --git a/docs/images/ex8.0_multiscale_Ca.png b/docs/images/ex8.0_multiscale_Ca.png
new file mode 100644
index 0000000000000000000000000000000000000000..eacdebe336fed7174a2ba1204e66a56cdd0e8a86
Binary files /dev/null and b/docs/images/ex8.0_multiscale_Ca.png differ
diff --git a/docs/images/ex8.0_multiscale_KA_conc.png b/docs/images/ex8.0_multiscale_KA_conc.png
new file mode 100644
index 0000000000000000000000000000000000000000..d396c781a9fe59be7c293c649d758d2a5cb2bbcc
Binary files /dev/null and b/docs/images/ex8.0_multiscale_KA_conc.png differ
diff --git a/docs/images/ex8.0_multiscale_cell_spiking.png b/docs/images/ex8.0_multiscale_cell_spiking.png
new file mode 100644
index 0000000000000000000000000000000000000000..27cb4cf92fea542c5b82cce696dd41c304407575
Binary files /dev/null and b/docs/images/ex8.0_multiscale_cell_spiking.png differ
diff --git a/docs/images/ex8.0_multiscale_currInj.png b/docs/images/ex8.0_multiscale_currInj.png
new file mode 100644
index 0000000000000000000000000000000000000000..6701d6425a2923a0d9dbb74e0aa7ce8a41e3e1f8
Binary files /dev/null and b/docs/images/ex8.0_multiscale_currInj.png differ
diff --git a/docs/images/ex8.1_ER_Ca.png b/docs/images/ex8.1_ER_Ca.png
new file mode 100644
index 0000000000000000000000000000000000000000..f2c06c0ca9c971be5bd7028a8da47766bd2b0f32
Binary files /dev/null and b/docs/images/ex8.1_ER_Ca.png differ
diff --git a/docs/images/ex8.1_dend_Ca.png b/docs/images/ex8.1_dend_Ca.png
new file mode 100644
index 0000000000000000000000000000000000000000..c305fcc3c311c1001d244fd82dcba52012486c3d
Binary files /dev/null and b/docs/images/ex8.1_dend_Ca.png differ
diff --git a/docs/images/ex8.2_Ca_dend.png b/docs/images/ex8.2_Ca_dend.png
new file mode 100644
index 0000000000000000000000000000000000000000..079abb90ccd16410a7fb66ec87e3f43e3710e18c
Binary files /dev/null and b/docs/images/ex8.2_Ca_dend.png differ
diff --git a/docs/images/ex8.2_Ca_spine.png b/docs/images/ex8.2_Ca_spine.png
new file mode 100644
index 0000000000000000000000000000000000000000..fca5539669053deb7a91af5c04ce826bc5a122eb
Binary files /dev/null and b/docs/images/ex8.2_Ca_spine.png differ
diff --git a/docs/images/ex8.2_Vm.png b/docs/images/ex8.2_Vm.png
new file mode 100644
index 0000000000000000000000000000000000000000..97abd1b9f74a0de685f8943ebd7a71666cd6e044
Binary files /dev/null and b/docs/images/ex8.2_Vm.png differ
diff --git a/docs/images/ex8.2_active_CaMKII.png b/docs/images/ex8.2_active_CaMKII.png
new file mode 100644
index 0000000000000000000000000000000000000000..4a22f8766fbf25e3ee9e19a1c259d6a4356966ab
Binary files /dev/null and b/docs/images/ex8.2_active_CaMKII.png differ
diff --git a/docs/images/ex8.3_CaMKII_spine.png b/docs/images/ex8.3_CaMKII_spine.png
new file mode 100644
index 0000000000000000000000000000000000000000..ba132db6374787848d89f720dca84d4678af98d5
Binary files /dev/null and b/docs/images/ex8.3_CaMKII_spine.png differ
diff --git a/docs/images/ex8.3_Vm.png b/docs/images/ex8.3_Vm.png
new file mode 100644
index 0000000000000000000000000000000000000000..cead72861c9f7a67c2e8aed44ae3bf8222f343c1
Binary files /dev/null and b/docs/images/ex8.3_Vm.png differ
diff --git a/docs/images/ex8.3_chan_p.png b/docs/images/ex8.3_chan_p.png
new file mode 100644
index 0000000000000000000000000000000000000000..092a508d683496207eed9e6c6c0368c425c5667a
Binary files /dev/null and b/docs/images/ex8.3_chan_p.png differ
diff --git a/docs/images/ex8.3_gluR.png b/docs/images/ex8.3_gluR.png
new file mode 100644
index 0000000000000000000000000000000000000000..f2a0da86489987a18799a80ff0ea45404f20cb1a
Binary files /dev/null and b/docs/images/ex8.3_gluR.png differ
diff --git a/docs/images/ex9.0_passive_cell_morpho.png b/docs/images/ex9.0_passive_cell_morpho.png
new file mode 100644
index 0000000000000000000000000000000000000000..0d00e176ffc1d9591b0ee3de560aaa982bb46735
Binary files /dev/null and b/docs/images/ex9.0_passive_cell_morpho.png differ
diff --git a/docs/source/conf.py b/docs/source/conf.py
index 4bd3770f99af1e814c6f891139a6ba8542dbb47a..43a10e7d8b472fa41b4fe9a57d1c353495244ef2 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -27,13 +27,13 @@ conf_dir_ = os.path.dirname( __file__ )
 # If extensions (or modules to document with autodoc) are in another directory,
 # add these directories to sys.path here. If the directory is relative to the
 # documentation root, use os.path.abspath to make it absolute, like shown here.
-sys.path.insert(0, os.path.abspath('../python'))
-sys.path.append(os.path.abspath('../../moose-examples/snippets'))
-sys.path.append(os.path.abspath('../../moose-examples/tutorials/ChemicalOscillators'))
-sys.path.append(os.path.abspath('../../moose-examples/tutorials/ChemicalBistables'))
-sys.path.append(os.path.abspath('../../moose-examples/tutorials/ExcInhNet'))
-sys.path.append(os.path.abspath('../../moose-examples/neuroml/lobster_pyloric'))
-sys.path.append(os.path.abspath('../../moose-examples/tutorials/ExcInhNetCaPlasticity'))
+sys.path.insert(0, os.path.abspath('/home/harsha/MOOSE/FullMoose/moose-core/python'))
+sys.path.append(os.path.abspath('/home/harsha/MOOSE/moose-examples-july/snippets'))
+sys.path.append(os.path.abspath('/home/harsha/MOOSE/moose-examples-july/tutorials/ChemicalOscillators'))
+sys.path.append(os.path.abspath('/home/harsha/MOOSE/moose-examples-july/tutorials/ChemicalBistables'))
+sys.path.append(os.path.abspath('/home/harsha/MOOSE/moose-examples-july/tutorials/ExcInhNet'))
+sys.path.append(os.path.abspath('/home/harsha/MOOSE/moose-examples-july/neuroml/lobster_pyloric'))
+sys.path.append(os.path.abspath('/home/harsha/MOOSE/moose-examples-july/tutorials/ExcInhNetCaPlasticity'))
 sys.path.append(os.path.join(conf_dir_, 'Extensions') )
 
 # -- General configuration -----------------------------------------------------
@@ -301,6 +301,6 @@ exclude_patterns = ['/docs/source/user/py/references/*.rst']
 import subprocess, os
 read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True'
 
-if not read_the_docs_build:
-    subprocess.call('cd doxygen; echo HELLO......................; doxygen Doxyfile', shell=True)
+#if not read_the_docs_build:
+#    subprocess.call('cd doxygen; echo HELLO......................; doxygen Doxyfile', shell=True)
 
diff --git a/docs/source/index.rst b/docs/source/index.rst
index 55a9f2f5dd2ad707f20bdc31bb1d2c895ca76e27..1f5c7c4e62c1cea3bb2573a6635510916cdb6042 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -9,6 +9,7 @@
    /install/index_install
    /user/py/quickstart/index_qs
    /user/py/cookbook/index_ckbk
+   /user/py/rdesigneur/index_rd
    /user/py/tutorials/index_tut
    /user/py/graphics/index_graphics
    /user/py/references/index_ref
diff --git a/docs/source/install/install.rst b/docs/source/install/install.rst
index 4e6ca5d3a3f32334125b3d76c7a41be9e7ba790b..82265fb508d7783ad31754676665803fea8e7d58 100644
--- a/docs/source/install/install.rst
+++ b/docs/source/install/install.rst
@@ -1,8 +1,11 @@
 Use pre-built packages
 -----------------------
 
-If you need only `python` interface, you can install it using `pip`. This is the easiest
-way to install Python interface.
+pip
+^^^^
+
+If you only need `python` interface, use `pip`. This is the easiest way to install Python interface.
+This solution has been tested for Linux and MacOSX.
 ::
      pip install pymoose 
 
@@ -27,10 +30,14 @@ Mac OSX
 
 MacOSX support for moose-gui is not complete yet. However, the python-scripting interface can be installed on OSX using ``homebrew``
 ::
-
     $ brew tap BhallaLab/moose
     $ brew install moose
 
+Or alternatively, via pip 
+::
+    $ pip install pymoose --user 
+    
+
 Docker Images
 ^^^^^^^^^^^^^^
 
diff --git a/docs/source/user/py/cookbook/Rd.rst b/docs/source/user/py/cookbook/Rd.rst
deleted file mode 100644
index 625b8bc819cf5b695210c854050e7630d60c6ff0..0000000000000000000000000000000000000000
--- a/docs/source/user/py/cookbook/Rd.rst
+++ /dev/null
@@ -1,1186 +0,0 @@
-**Rdesigneur: Building multiscale models**
-==========================================
-
-.. Upi Bhalla
-
-.. Aug 26 2016.
-
-.. --------------
-
-Contents
---------
-
-.. contents::
-   :depth: 3
-
-Introduction
-------------
-
-**Rdesigneur** (Reaction Diffusion and Electrical SIGnaling in NEURons)
-is an interface to the multiscale modeling capabilities in MOOSE. It is
-designed to build models incorporating biochemical signaling pathways in
-dendrites and spines, coupled to electrical events in neurons.
-Rdesigneur assembles models from predefined parts: it delegates the
-details to specialized model definition formats. Rdesigneur combines one
-or more of the following cell parts to build models:
-
--  Neuronal morphology
--  Dendritic spines
--  Ion channels
--  Reaction systems
-
-Rdesigneur's main role is to specify how these are put together,
-including assigning parameters to do so. Rdesigneur also helps with
-setting up the simulation input and output.
-
-Quick Start
------------
-
-Here we provide a few use cases, building up from a minimal model to a
-reasonably complete multiscale model spanning chemical and electrical
-signaling.
-
-Bare Rdesigneur: single passive compartment
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-If we don't provide any arguments at all to the Rdesigneur, it makes a
-model with a single passive electrical compartment in the MOOSE path
-``/model/elec/soma``. Here is how to do this:
-
-::
-
-    import moose
-    import rdesigneur as rd
-    rdes = rd.rdesigneur()
-    rdes.buildModel()
-
-To confirm that it has made a compartment with some default values we
-can add a line:
-
-::
-
-    moose.showfields( rdes.soma )
-
-This should produce the output:
-
-::
-
-    [ /model[0]/elec[0]/soma[0] ]
-    diameter         = 0.0005
-    fieldIndex       = 0
-    Ra               = 7639437.26841
-    y0               = 0.0
-    Rm               = 424413.177334
-    index            = 0
-    numData          = 1
-    inject           = 0.0
-    initVm           = -0.065
-    Em               = -0.0544
-    y                = 0.0
-    numField         = 1
-    path             = /model[0]/elec[0]/soma[0]
-    dt               = 0.0
-    tick             = -2
-    z0               = 0.0
-    name             = soma
-    Cm               = 7.85398163398e-09
-    x0               = 0.0
-    Vm               = -0.06
-    className        = ZombieCompartment
-    idValue          = 465
-    length           = 0.0005
-    Im               = 1.3194689277e-08
-    x                = 0.0005
-    z                = 0.0
-
-Simulate and display current pulse to soma
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-A more useful script would run and display the model. Rdesigneur can
-help with the stimulus and the plotting. This simulation has the same
-passive compartment, and current is injected as the simulation runs.
-This script displays the membrane potential of the soma as it charges
-and discharges.
-
-::
-
-    import moose
-    import rdesigneur as rd
-    rdes = rd.rdesigneur(
-        stimList = [['soma', '1', '.', 'inject', '(t>0.1 && t<0.2) * 2e-8']],
-        plotList = [['soma', '1', '.', 'Vm', 'Soma membrane potential']],
-    )
-    rdes.buildModel()
-    moose.reinit()
-    moose.start( 0.3 )
-    rdes.display()
-
-The *stimList* defines a stimulus. Each entry has five arguments:
-
-::
-
-    `[region_in_cell, region_expression, moose_object, parameter, expression_string]`
-
--  ``region_in_cell`` specifies the objects to stimulate. Here it is
-   just the soma.
--  ``region_expression`` specifies a geometry based calculation to
-   decide whether to apply the stimulus. The value must be >0 for the
-   stimulus to be present. Here it is just 1. ``moose_object`` specifies
-   the simulation object to operate upon during the stimulus. Here the
-   ``.`` means that it is the soma itself. In other models it might be a
-   channel on the soma, or a synapse, and so on.
--  ``parameter`` specifies the simulation parameter on the moose object
-   that the stimulus will modify. Here it is the injection current to
-   the soma compartment.
--  ``expression_string`` calculates the value of the parameter,
-   typically as a function of time. Here we use the function
-   ``(t>0.1 && t<0.2) * 2e-8`` which evaluates as 2e-8 between the times
-   of 0.1 and 0.2 seconds.
-
-To summarise this, the *stimList* here means *inject a current of 20nA
-to the soma between the times of 0.1 and 0.2 s*.
-
-The *plotList* defines what to plot. It has a similar set of arguments:
-
-::
-
-    `[region_in_cell, region_expression, moose_object, parameter, title_of_plot]`
-
-These mean the same thing as for the stimList except for the title of
-the plot.
-
-The *rdes.display()* function causes the plots to be displayed.
-
-.. figure:: ../../../../images/rdes2_passive_squid.png
-   :alt: Plot for current input to passive compartment
-
-   Plot for current input to passive compartment
-
-When we run this we see an initial depolarization as the soma settles
-from its initial -65 mV to a resting Em = -54.4 mV. These are the
-original HH values, see the example above. At t = 0.1 seconds there is
-another depolarization due to the current injection, and at t = 0.2
-seconds this goes back to the resting potential.
-
-HH Squid model in a single compartment
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Here we put the Hodgkin-Huxley squid model channels into a passive
-compartment. The HH channels are predefined as prototype channels for
-Rdesigneur,
-
-::
-
-    import moose
-    import pylab
-    import rdesigneur as rd
-    rdes = rd.rdesigneur(
-        chanProto = [['make_HH_Na()', 'Na'], ['make_HH_K()', 'K']],
-        chanDistrib = [
-            ['Na', 'soma', 'Gbar', '1200' ],
-            ['K', 'soma', 'Gbar', '360' ]],
-        stimList = [['soma', '1', '.', 'inject', '(t>0.1 && t<0.2) * 1e-8' ]],
-        plotList = [['soma', '1', '.', 'Vm', 'Membrane potential']]
-    )
-
-    rdes.buildModel()
-    moose.reinit()
-    moose.start( 0.3 )
-    rdes.display()
-
-Here we introduce two new model specification lines:
-
--  **chanProto**: This specifies which ion channels will be used in the
-   model. Each entry here has two fields: the source of the channel
-   definition, and (optionally) the name of the channel. In this example
-   we specify two channels, an Na and a K channel using the original
-   Hodgkin-Huxley parameters. As the source of the channel definition we
-   use the name of the Python function that builds the channel. The
-   *make\_HH\_Na()* and *make\_HH\_K()* functions are predefined but we
-   can also specify our own functions for making prototypes. We could
-   also have specified the channel prototype using the name of a channel
-   definition file in ChannelML (a subset of NeuroML) format.
--  **chanDistrib**: This specifies *where* the channels should be placed
-   over the geometry of the cell. Each entry in the chanDistrib list
-   specifies the distribution of parameters for one channel using four
-   entries:
-
-   ``[object_name, region_in_cell, parameter, expression_string]``
-
-   In this case the job is almost trivial, since we just have a single
-   compartment named *soma*. So the line
-
-   ``['Na', 'soma', 'Gbar', '1200' ]``
-
-   means *Put the Na channel in the soma, and set its maximal
-   conductance density (Gbar) to 1200 Siemens/m^2*.
-
-As before we apply a somatic current pulse. Since we now have HH
-channels in the model, this generates action potentials.
-
-.. figure:: ../../../../images/rdes3_squid.png
-   :alt: Plot for HH squid simulation
-
-   Plot for HH squid simulation
-
-HH Squid model in an axon
-~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Here we put the Hodgkin-Huxley squid model into a long compartment that
-is subdivided into many segments, so that we can watch action potentials
-propagate. Most of this example is boilerplate code to build a spiral
-axon. There is a short *rdesigneur* segment that takes the spiral axon
-prototype and populates it with channels, and sets up the display. Later
-examples will show you how to read morphology files to specify the
-neuronal geometry.
-
-::
-
-    import numpy as np
-    import moose
-    import pylab
-    import rdesigneur as rd
-
-    numAxonSegments = 200
-    comptLen = 10e-6
-    comptDia = 1e-6
-    RM = 1.0
-    RA = 10.0
-    CM = 0.01
-
-    def makeAxonProto():
-            axon = moose.Neuron( '/library/axon' )
-            prev = rd.buildCompt( axon, 'soma', RM = RM, RA = RA, CM = CM, dia = 10e-6, x=0, dx=comptLen)
-            theta = 0
-            x = comptLen
-            y = 0.0
-
-            for i in range( numAxonSegments ):
-                dx = comptLen * np.cos( theta )
-                dy = comptLen * np.sin( theta )
-                r = np.sqrt( x * x + y * y )
-                theta += comptLen / r
-                compt = rd.buildCompt( axon, 'axon' + str(i), RM = RM, RA = RA, CM = CM, x = x, y = y, dx = dx, dy = dy, dia = comptDia )
-                moose.connect( prev, 'axial', compt, 'raxial' )
-                prev = compt
-                x += dx
-                y += dy
-            
-            return axon
-
-    moose.Neutral( '/library' )
-    makeAxonProto()
-
-    rdes = rd.rdesigneur(
-            chanProto = [['make_HH_Na()', 'Na'], ['make_HH_K()', 'K']],
-            cellProto = [['elec','axon']],
-            chanDistrib = [
-                ['Na', '#', 'Gbar', '1200' ],
-                ['K', '#', 'Gbar', '360' ]],
-            stimList = [['soma', '1', '.', 'inject', '(t>0.01 && t<0.2) * 2e-11' ]],
-            plotList = [['soma', '1', '.', 'Vm', 'Membrane potential']],
-            moogList = [['#', '1', '.', 'Vm', 'Vm (mV)']]
-            )
-
-    rdes.buildModel()
-    moose.reinit()
-
-    rdes.displayMoogli( 0.00005, 0.05, 0.0 )
-
-.. figure:: ../../../../images/rdes3.1_axon.png
-   :alt: Axon with propagating action potential
-
-   Axon with propagating action potential
-
-Note how we explicitly create the prototype axon on '/library', and then
-specify it using the *cellProto* line in the rdesigneur. The moogList
-specifies the 3-D display. See below for how to set up and use these
-displays.
-
-HH Squid model in a myelinated axon
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-This is a curious cross-species chimera model, where we embed the HH
-equations into a myelinated example model. As for the regular axon
-above, most of the example is boilerplate setup code. Note how we
-restrict the HH channels to the nodes of Ranvier using a conditional
-test for the diameter of the axon segment.
-
-::
-
-    import numpy as np
-    import moose
-    import pylab
-    import rdesigneur as rd
-
-    numAxonSegments = 405
-    nodeSpacing = 100
-    comptLen = 10e-6
-    comptDia = 2e-6 # 2x usual
-    RM = 100.0 # 10x usual
-    RA = 5.0
-    CM = 0.001 # 0.1x usual
-
-    nodeDia = 1e-6
-    nodeRM = 1.0
-    nodeCM = 0.01
-
-    def makeAxonProto():
-        axon = moose.Neuron( '/library/axon' )
-        x = 0.0
-        y = 0.0
-        prev = rd.buildCompt( axon, 'soma', RM = RM, RA = RA, CM = CM, dia = 10e-6, x=0, dx=comptLen)
-        theta = 0
-        x = comptLen
-
-        for i in range( numAxonSegments ):
-            r = comptLen
-            dx = comptLen * np.cos( theta )
-            dy = comptLen * np.sin( theta )
-            r = np.sqrt( x * x + y * y )
-            theta += comptLen / r
-            if i % nodeSpacing == 0:
-                compt = rd.buildCompt( axon, 'axon' + str(i), RM = nodeRM, RA = RA, CM = nodeCM, x = x, y = y, dx = dx, dy = dy, dia = nodeDia )
-            else:
-                compt = rd.buildCompt( axon, 'axon' + str(i), RM = RM, RA = RA, CM = CM, x = x, y = y, dx = dx, dy = dy, dia = comptDia )
-            moose.connect( prev, 'axial', compt, 'raxial' )
-            prev = compt
-            x += dx
-            y += dy
-        
-        return axon
-
-    moose.Neutral( '/library' )
-    makeAxonProto()
-
-    rdes = rd.rdesigneur(
-        chanProto = [['make_HH_Na()', 'Na'], ['make_HH_K()', 'K']],
-        cellProto = [['elec','axon']],
-        chanDistrib = [
-            ['Na', '#', 'Gbar', '12000 * (dia < 1.5e-6)' ],
-            ['K', '#', 'Gbar', '3600 * (dia < 1.5e-6)' ]],
-        stimList = [['soma', '1', '.', 'inject', '(t>0.01 && t<0.2) * 1e-10' ]],
-        plotList = [['soma,axon100,axon200,axon300,axon400', '1', '.', 'Vm', 'Membrane potential']],
-        moogList = [['#', '1', '.', 'Vm', 'Vm (mV)']]
-    )
-
-    rdes.buildModel()
-
-    for i in moose.wildcardFind( "/model/elec/#/Na" ):
-        print i.parent.name, i.Gbar
-
-    moose.reinit()
-
-    rdes.displayMoogli( 0.00005, 0.05, 0.0 )
-
-When you run the example, keep an eye out for a few things:
-
--  **saltatory conduction:** This is the way the action potential jumps
-   from one node of Ranvier to the next. Between the nodes it is just
-   passive propagation.
--  **Failure to propagate:** Observe that the second and fourth action
-   potentials fails to trigger propagation along the axon. Here we have
-   specially tuned the model properties so that this happens. With a
-   larger RA of 10.0, the model will be more reliable.
--  **Speed:** Compare the propagation speed with the previous,
-   unmyelinated axon. Note that the current model is larger!
-
-.. figure:: ../../../../images/rdes3.2_myelinated_axon.png
-   :alt: Myelinated axon with propagating action potential
-
-   Myelinated axon with propagating action potential
-
-Reaction system in a single compartment
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Here we use the compartment as a place in which to embed a chemical
-model. The chemical oscillator model is predefined in the rdesigneur
-prototypes.
-
-::
-
-    import moose
-    import pylab
-    import rdesigneur as rd
-    rdes = rd.rdesigneur(
-            turnOffElec = True,
-            diffusionLength = 1e-3, # Default diffusion length is 2 microns
-            chemProto = [['makeChemOscillator()', 'osc']],
-            chemDistrib = [['osc', 'soma', 'install', '1' ]],
-            plotList = [['soma', '1', 'dend/a', 'conc', 'a Conc'],
-                ['soma', '1', 'dend/b', 'conc', 'b Conc']]
-    )
-    rdes.buildModel()
-    b = moose.element( '/model/chem/dend/b' )
-    b.concInit *= 5
-    moose.reinit()
-    moose.start( 200 )
-
-    rdes.display()
-
-In this special case we set the turnOffElec flag to True, so that
-Rdesigneur only sets up chemical and not electrical calculations. This
-makes the calculations much faster, since we disable electrical
-calculations and delink chemical calculations from them.
-
-We also have a line which sets the ``diffusionLength`` to 1 mm, so that
-it is bigger than the 0.5 mm squid axon segment in the default
-compartment. If you don't do this the system will subdivide the
-compartment into the default 2 micron voxels for the purposes of putting
-in a reaction-diffusion system. We discuss this case below.
-
-Note how the *plotList* is done here. To remind you, each entry has five
-arguments
-
-::
-
-    [region_in_cell, region_expression, moose_object, parameter, title_of_plot]
-
-The change from the earlier usage is that the ``moose_object`` now
-refers to a chemical entity, in this example the molecule *dend/a*. The
-simulator builds a default chemical compartment named *dend* to hold the
-reactions defined in the *chemProto*. What we do in this plot is to
-select molecule *a* sitting in *dend*, and plot its concentration. Then
-we do this again for molecule *b*.
-
-After the model is built, we add a couple of lines to change the initial
-concentration of the molecular pool *b*. Note its full path within
-MOOSE: */model/chem/dend/b*. It is scaled up 5x to give rise to slowly
-decaying oscillations.
-
-.. figure:: ../../../../images/rdes4_osc.png
-   :alt: Plot for single-compartment reaction simulation
-
-   Plot for single-compartment reaction simulation
-
-Reaction-diffusion system
-~~~~~~~~~~~~~~~~~~~~~~~~~
-
-In order to see what a reaction-diffusion system looks like, delete the
-``diffusionLength`` expression in the previous example and add a couple
-of lines to set up 3-D graphics for the reaction-diffusion product:
-
-::
-
-    import moose
-    import pylab
-    import rdesigneur as rd
-    rdes = rd.rdesigneur(
-            turnOffElec = True,
-            chemProto = [['makeChemOscillator()', 'osc']],
-            chemDistrib = [['osc', 'soma', 'install', '1' ]],
-            plotList = [['soma', '1', 'dend/a', 'conc', 'Concentration of a'],
-                ['soma', '1', 'dend/b', 'conc', 'Concentration of b']],
-            moogList = [['soma', '1', 'dend/a', 'conc', 'a Conc', 0, 360 ]]
-    )
-
-    rdes.buildModel()
-    bv = moose.vec( '/model/chem/dend/b' )
-    bv[0].concInit *= 2
-    bv[-1].concInit *= 2
-    moose.reinit()
-
-    rdes.displayMoogli( 1, 400, 0.001 )
-
-This is the line we deleted.
-
-::
-
-        diffusionLength = 1e-3,
-
-With this change we permit *rdesigneur* to use the default diffusion
-length of 2 microns. The 500-micron axon segment is now subdivided into
-250 voxels, each of which has a reaction system and diffusing molecules.
-To make it more picturesque, we have added a line after the plotList, to
-display the outcome in 3-D:
-
-::
-
-    moogList = [['soma', '1', 'dend/a', 'conc', 'a Conc', 0, 360 ]]
-
-This line says: take the model compartments defined by ``soma`` as the
-region to display, do so throughout the the geometry (the ``1``
-signifies this), and over this range find the chemical entity defined by
-``dend/a``. For each ``a`` molecule, find the ``conc`` and dsiplay it.
-There are two optional arguments, ``0`` and ``360``, which specify the
-low and high value of the displayed variable.
-
-In order to initially break the symmetry of the system, we change the
-initial concentration of molecule b at each end of the cylinder:
-
-::
-
-    bv[0].concInit *= 2
-    bv[-1].concInit *= 2
-
-If we didn't do this the entire system would go through a few cycles of
-decaying oscillation and then reach a boring, spatially uniform, steady
-state. Try putting an initial symmetry break elsewhere to see what
-happens.
-
-To display the concenctration changes in the 3-D soma as the simulation
-runs, we use the line
-
-::
-
-    `rdes.displayMoogli( 1, 400, 0.001 )`
-
-The arguments mean: *displayMoogli( frametime, runtime, rotation )*
-Here,
-
-::
-
-    frametime = time by which simulation advances between display updates
-    runtime = Total simulated time
-    rotation = angle by which display rotates in each frame, in radians.
-
-When we run this, we first get a 3-D display with the oscillating
-reaction-diffusion system making its way inward from the two ends. After
-the simulation ends the plots for all compartments for the whole run
-come up.
-
-.. figure:: ../../../../images/rdes5_reacdiff.png
-   :alt: Display for oscillatory reaction-diffusion simulation
-
-   Display for oscillatory reaction-diffusion simulation
-
-Primer on using the 3-D MOOGLI display
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Here is a short primer on the 3-D display controls.
-
--  *Roll, pitch, and yaw*: Use the letters *r*, *p*, and *y*. To rotate
-   backwards, use capitals.
--  *Zoom out and in*: Use the *,* and *.* keys, or their upper-case
-   equivalents, *<* and *>*. Easier to remember if you think in terms of
-   the upper-case.
--  *Left/right/up/down*: Arrow keys.
--  *Quit*: control-q or control-w.
--  You can also use the mouse or trackpad to control most of the above.
--  By default rdesigneur gives Moogli a small rotation each frame. It is
-   the *rotation* argument in the line:
-
-   ``displayMoogli( frametime, runtime, rotation )``
-
-These controls operate over and above this rotation, but the rotation
-continues. If you set the rotation to zero you can, with a suitable
-flick of the mouse, get the image to rotate in any direction you choose
-as long as the window is updating.
-
-Make a toy multiscale model with electrical and chemical signaling.
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Now we put together chemical and electrical models. In this toy model we
-have an HH-squid type single compartment electrical model, cohabiting
-with a chemical oscillator. The chemical oscillator regulates K+ channel
-amounts, and the average membrane potential regulates the amounts of a
-reactant in the chemical oscillator. This is a recipe for some strange
-firing patterns.
-
-::
-
-    import moose
-    import pylab
-    import rdesigneur as rd
-    rdes = rd.rdesigneur(
-            # We want just one compartment so we set diffusion length to be
-            # bigger than the 0.5 mm HH axon compartment default. 
-                diffusionLength = 1e-3,
-                chanProto = [['make_HH_Na()', 'Na'], ['make_HH_K()', 'K']],
-                chanDistrib = [
-                    ['Na', 'soma', 'Gbar', '1200' ],
-                    ['K', 'soma', 'Gbar', '360' ]],
-            chemProto = [['makeChemOscillator()', 'osc']],
-            chemDistrib = [['osc', 'soma', 'install', '1' ]],
-            # These adaptor parameters give interesting-looking but
-            # not particularly physiological behaviour.
-            adaptorList = [
-                [ 'dend/a', 'conc', 'Na', 'modulation', 1, -5.0 ],
-                [ 'dend/b', 'conc', 'K', 'modulation', 1, -0.2],
-                [ 'dend/b', 'conc', '.', 'inject', -1.0e-7, 4e-7 ],
-                [ '.', 'Vm', 'dend/s', 'conc', 2.5, 20.0 ]
-            ],
-            plotList = [['soma', '1', 'dend/a', 'conc', 'a Conc'],
-                ['soma', '1', 'dend/b', 'conc', 'b Conc'],
-                ['soma', '1', 'dend/s', 'conc', 's Conc'],
-                ['soma', '1', 'Na', 'Gk', 'Na Gk'],
-                ['soma', '1', '.', 'Vm', 'Membrane potential']
-        ]
-    )
-
-    rdes.buildModel()
-    moose.reinit()
-    moose.start( 250 ) # Takes a few seconds to run this.
-
-    rdes.display()
-
-We've already modeled the HH squid model and the oscillator
-individually, and you should recognize the parts of those models above.
-The new section that makes this work the *adaptorList* which specifies
-how the electrical and chemical parts talk to each other. This entirely
-fictional set of interactions goes like this:
-
-::
-
-    [ 'dend/a', 'conc', 'Na', 'modulation', 1, -5.0 ]
-
--  *dend/a*: The originating variable comes from the 'a' pool on the
-   'dend' compartment.
-
-   *conc*: This is the originating variable name on the 'a' pool.
-
-   *Na*: This is the target variable
-
-   *modulation*: scale the Gbar of Na up and down. Use 'modulation'
-   rather than direct assignment of Gbar since Gbar is different for
-   each differently-sized compartment.
-
-   *1*: This is the initial offset
-
-   *-5.0*: This is the scaling from the input to the parameter updated
-   in the simulation.
-
-A similar set of adaptor entries couple the molecule *dend/b* to the K
-channel, *dend/b* again to the current injection into the soma, and the
-membrane potential to the concentration of *dend/s*.
-
-.. figure:: ../../../../images/rdes6_multiscale.png
-   :alt: Plot for toy multiscale model
-
-   Plot for toy multiscale model
-
-Morphology: Load .swc morphology file and view it
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Here we build a passive model using a morphology file in the .swc file
-format (as used by NeuroMorpho.org). The morphology file is predefined
-for Rdesigneur and resides in the directory ``./cells``. We apply a
-somatic current pulse, and view the somatic membrane potential in a
-plot, as before. To make things interesting we display the morphology in
-3-D upon which we represent the membrane potential as colors.
-
-::
-
-    import moose
-    import rdesigneur as rd
-    rdes = rd.rdesigneur(
-        cellProto = [['./cells/h10.CNG.swc', 'elec']],
-        stimList = [['soma', '1', '.', 'inject', 't * 25e-9' ]], 
-        plotList = [['#', '1', '.', 'Vm', 'Membrane potential'],
-            ['#', '1', 'Ca_conc', 'Ca', 'Ca conc (uM)']],
-        moogList = [['#', '1', '.', 'Vm', 'Soma potential']]
-    )
-
-    rdes.buildModel()
-
-    moose.reinit()
-    rdes.displayMoogli( 0.0002, 0.1 )
-
-Here the new concept is the cellProto line, which loads in the specified
-cell model:
-
-::
-
-    `[ filename, cellname ]`
-
-The system recognizes the filename extension and builds a model from the
-swc file. It uses the cellname **elec** in this example.
-
-We use a similar line as in the reaction-diffusion example, to build up
-a Moogli display of the cell model:
-
-::
-
-    `moogList = [['#', '1', '.', 'Vm', 'Soma potential']]`
-
-Here we have:
-
-::
-
-    *#*: the path to use for selecting the compartments to display. 
-    This wildcard means use all compartments.
-    *1*: The expression to use for the compartments. Again, `1` means use
-    all of them.
-    *.*: Which object in the compartment to display. Here we are using the
-    compartment itself, so it is just a dot.
-    *Vm*: Field to display
-    *Soma potential*: Title for display.
-
-.. figure:: ../../../../images/rdes7_passive.png
-   :alt: 3-D display for passive neuron
-
-   3-D display for passive neuron
-
-Build an active neuron model by putting channels into a morphology file
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-We load in a morphology file and distribute voltage-gated ion channels
-over the neuron. Here the voltage-gated channels are obtained from a
-number of channelML files, located in the ``./channels`` subdirectory.
-Since we have a spatially extended neuron, we need to specify the
-spatial distribution of channel densities too.
-
-::
-
-    import moose
-    import rdesigneur as rd
-    rdes = rd.rdesigneur(
-        chanProto = [
-            ['./chans/hd.xml'],
-            ['./chans/kap.xml'],
-            ['./chans/kad.xml'],
-            ['./chans/kdr.xml'],
-            ['./chans/na3.xml'],
-            ['./chans/nax.xml'],
-            ['./chans/CaConc.xml'],
-            ['./chans/Ca.xml']
-        ],
-        cellProto = [['./cells/h10.CNG.swc', 'elec']],
-        chanDistrib = [ \
-            ["hd", "#dend#,#apical#", "Gbar", "50e-2*(1+(p*3e4))" ],
-            ["kdr", "#", "Gbar", "p < 50e-6 ? 500 : 100" ],
-            ["na3", "#soma#,#dend#,#apical#", "Gbar", "850" ],
-            ["nax", "#soma#,#axon#", "Gbar", "1250" ],
-            ["kap", "#axon#,#soma#", "Gbar", "300" ],
-            ["kap", "#dend#,#apical#", "Gbar",
-                "300*(H(100-p*1e6)) * (1+(p*1e4))" ],
-            ["Ca_conc", "#", "tau", "0.0133" ],
-            ["kad", "#soma#,#dend#,#apical#", "Gbar", "50" ],
-            ["Ca", "#", "Gbar", "50" ]
-        ],
-        stimList = [['soma', '1', '.', 'inject', '(t>0.02) * 1e-9' ]],
-        plotList = [['#', '1', '.', 'Vm', 'Membrane potential'],
-                ['#', '1', 'Ca_conc', 'Ca', 'Ca conc (uM)']],
-        moogList = [['#', '1', 'Ca_conc', 'Ca', 'Calcium conc (uM)', 0, 120],
-            ['#', '1', '.', 'Vm', 'Soma potential']]
-    )
-
-    rdes.buildModel()
-
-    moose.reinit()
-    rdes.displayMoogli( 0.0002, 0.052 )
-
-Here we make more extensive use of two concepts which we've already seen
-from the single compartment squid model:
-
-1. *chanProto*: This defines numerous channels, each of which is of the
-   form:
-
-   ``[ filename ]``
-
-   or
-
-   ``[ filename, channelname ]``
-
-If the *channelname* is not specified the system uses the last part of
-the channel name, before the filetype suffix.
-
-2. *chanDistrib*: This defines the spatial distribution of each channel
-   type. Each line is of a form that should be familiar now:
-
-   ``[channelname, region_in_cell, parameter, expression_string]``
-
--  The *channelname* is the name of the prototype from *chanproto*. This
-   is usually an ion channel, but in the example above you can also see
-   a calcium concentration pool defined.
--  The *region\_in\_cell* is typically defined using wildcards, so that
-   it generalizes to any cell morphology. For example, the plain
-   wildcard ``#`` means to consider all cell compartments. The wildcard
-   ``#dend#`` means to consider all compartments with the string
-   ``dend`` somewhere in the name. Wildcards can be comma-separated, so
-   ``#soma#,#dend#`` means consider all compartments with either soma or
-   dend in their name. The naming in MOOSE is defined by the model file.
-   Importantly, in **.swc** files MOOSE generates names that respect the
-   classification of compartments into axon, soma, dendrite, and apical
-   dendrite compartments respectively. SWC files generate compartment
-   names such as:
-
-   ::
-
-       soma_<number>
-       dend_<number>
-       apical_<number>
-       axon_<number>
-
-where the number is automatically assigned by the reader. In order to
-select all dendritic compartments, for example, one would use *"#dend#"*
-where the *"#"* acts as a wildcard to accept any string. - The
-*parameter* is usually Gbar, the channel conductance density in *S/m^2*.
-If *Gbar* is zero or less, then the system economizes by not
-incorporating this channel mechanism in this part of the cell.
-Similarly, for calcium pools, if the *tau* is below zero then the
-calcium pool object is simply not inserted into this part of the cell. -
-The *expression\_string* defines the value of the parameter, such as
-Gbar. This is typically a function of position in the cell. The
-expression evaluator knows about several parameters of cell geometry.
-All units are in metres:
-
--  *x*, *y* and *z* coordinates.
--  *g*, the geometrical distance from the soma
--  *p*, the path length from the soma, measured along the dendrites.
--  *dia*, the diameter of the dendrite.
--  *L*, The electrotonic length from the soma (no units).
-
-Along with these geometrical arguments, we make liberal use of the
-Heaviside function H(x) to set up the channel distributions. The
-expression evaluator also knows about pretty much all common algebraic,
-trignometric, and logarithmic functions, should you wish to use these.
-
-Also note the two Moogli displays. The first is the calcium
-concentration. The second is the membrane potential in each compartment.
-Easy!
-
-.. figure:: ../../../../images/rdes8_active.png
-   :alt: 3-D display for active neuron
-
-   3-D display for active neuron
-
-Build a spiny neuron from a morphology file and put active channels in it.
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-This model is one step elaborated from the previous one, in that we now
-also have dendritic spines. MOOSE lets one decorate a bare neuronal
-morphology file with dendritic spines, specifying various geometric
-parameters of their location. As before, we use an swc file for the
-morphology, and the same ion channels and distribution.
-
-::
-
-    import moose
-    import pylab
-    import rdesigneur as rd
-    rdes = rd.rdesigneur(
-        chanProto = [
-            ['./chans/hd.xml'],
-            ['./chans/kap.xml'],
-            ['./chans/kad.xml'],
-            ['./chans/kdr.xml'],
-            ['./chans/na3.xml'],
-            ['./chans/nax.xml'],
-            ['./chans/CaConc.xml'],
-            ['./chans/Ca.xml']
-        ],
-        cellProto = [['./cells/h10.CNG.swc', 'elec']],
-        spineProto = [['makeActiveSpine()', 'spine']],
-        chanDistrib = [
-            ["hd", "#dend#,#apical#", "Gbar", "50e-2*(1+(p*3e4))" ],
-            ["kdr", "#", "Gbar", "p < 50e-6 ? 500 : 100" ],
-            ["na3", "#soma#,#dend#,#apical#", "Gbar", "850" ],
-            ["nax", "#soma#,#axon#", "Gbar", "1250" ],
-            ["kap", "#axon#,#soma#", "Gbar", "300" ],
-            ["kap", "#dend#,#apical#", "Gbar",
-                "300*(H(100-p*1e6)) * (1+(p*1e4))" ],
-            ["Ca_conc", "#", "tau", "0.0133" ],
-            ["kad", "#soma#,#dend#,#apical#", "Gbar", "50" ],
-            ["Ca", "#", "Gbar", "50" ]
-        ],
-        spineDistrib = [['spine', '#dend#,#apical#', '20e-6', '1e-6']],
-        stimList = [['soma', '1', '.', 'inject', '(t>0.02) * 1e-9' ]],
-        plotList = [['#', '1', '.', 'Vm', 'Membrane potential'],
-                ['#', '1', 'Ca_conc', 'Ca', 'Ca conc (uM)']],
-        moogList = [['#', '1', 'Ca_conc', 'Ca', 'Calcium conc (uM)', 0, 120],
-            ['#', '1', '.', 'Vm', 'Soma potential']]
-    )
-
-    rdes.buildModel()
-
-    moose.reinit()
-    rdes.displayMoogli( 0.0002, 0.023 )
-
-Spines are set up in a familiar way: we first define one (or more)
-prototype spines, and then distribute these around the cell. Here is the
-prototype string:
-
-::
-
-        [spine_proto, spinename]
-
-*spineProto*: This is typically a function. One can define one's own,
-but there are several predefined ones in rdesigneur. All these define a
-spine with the following parameters:
-
--  head diameter 0.5 microns
--  head length 0.5 microns
--  shaft length 1 micron
--  shaft diameter of 0.2 microns
--  RM = 1.0 ohm-metre square
--  RA = 1.0 ohm-meter
--  CM = 0.01 Farads per square metre.
-
-Here are the predefined spine prototypes:
-
--  *makePassiveSpine()*: This just makes a passive spine with the
-   default parameters
--  *makeExcSpine()*: This makes a spine with NMDA and glu receptors, and
-   also a calcium pool. The NMDA channel feeds the Ca pool.
--  *makeActiveSpine()*: This adds a Ca channel to the exc\_spine. and
-   also a calcium pool.
-
-The spine distributions are specified in a familiar way for the first
-few arguments, and then there are multiple (optional) spine-specific
-parameters:
-
-*[spinename, region\_in\_cell, spacing, spacing\_distrib, size,
-size\_distrib, angle, angle\_distrib ]*
-
-Only the first two arguments are mandatory.
-
--  *spinename*: The prototype name
--  *region\_in\_cell*: Usual wildcard specification of names of
-   compartments in which to put the spines.
--  *spacing*: Math expression to define spacing between spines. In the
-   current implementation this evaluates to
-   ``1/probability_of_spine_per_unit_length``. Defaults to 10 microns.
-   Thus, there is a 10% probability of a spine insertion in every
-   micron. This evaluation method has the drawback that it is possible
-   to space spines rather too close to each other. If spacing is zero or
-   less, no spines are inserted.
--  *spacing\_distrib*: Math expression for distribution of spacing. In
-   the current implementation, this specifies the interval at which the
-   system samples from the spacing probability above. Defaults to 1
-   micron.
--  *size*: Linear scale factor for size of spine. All dimensions are
-   scaled by this factor. The default spine head here is 0.5 microns in
-   diameter and length. If the scale factor were to be 2, the volume
-   would be 8 times as large. Defaults to 1.0.
--  *size\_distrib*: Range for size of spine. A random number R is
-   computed in the range 0 to 1, and the final size used is
-   ``size + (R - 0.5) * size_distrib``. Defaults to 0.5
--  *angle*: This specifies the initial angle at which the spine sticks
-   out of the dendrite. If all angles were zero, they would all point
-   away from the soma. Defaults to 0 radians.
--  *angle\_distrib*: Specifies a random number to add to the initial
-   angle. Defaults to 2 PI radians, so the spines come out in any
-   direction.
-
-One may well ask why we are not using a Python dictionary to handle all
-these parameters. Short answer is: terseness. Longer answer is that the
-rdesigneur format is itself meant to be an intermediate form for an
-eventual high-level, possibly XML-based multiscale modeling format.
-
-.. figure:: ../../../../images/rdes9_spiny_active.png
-   :alt: 3-D display for spiny active neuron
-
-   3-D display for spiny active neuron
-
-Put a spine on a cylindrical compartment, give it synaptic input, and watch Ca diffuse.
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Calcium enters spines during strong synaptic input, how far does it
-spread along the dendrites? This model is simple conceptually but
-illustrates several things:
-
--  Setting up random (Poisson) synaptic input to one or more spines
--  Setting up a reaction-diffusion system (Ca) coupled to an electrical
-   system (Ca influx through channels). This uses a separate chemical
-   definition script. One can replace this with more elaborate chemical
-   schemes simply by changing the name of the script.
--  User definitions of prototypes (the soma in this example).
--  Assigning random number seeds.
--  The difference between electrical and chemical length scales. For
-   numerical reasons, the discretization of reaction-diffusion systems
-   into voxels normally happens on a smaller length scale (microns) than
-   for electrical systems (tens to hundreds of microns). In this example
-   there is just one electrical compartment, but 50 chemical
-   subdivisions.
-
-Most of the script is setting up the input and the prototypes.
-Rdesigneur is compact, as usual. First, the headers and parameter list:
-
-::
-
-    import moose
-    import numpy as np
-    import rdesigneur as rd
-
-    params = { 
-        'diffusionLength':1.0e-6,  # Diffusion characteristic length, used as voxel length too.
-        'dendDiameter': 1e-6,  # Diameter of section of dendrite in model
-        'dendLength': 50e-6,   # Length of section of dendrite in model
-        'spineSpacing': 30e-6,   # mean spacing between spines.
-        'diffConstCa':20.0e-12,  # Diffusion constant of Ca, m^2/sec
-        'spineFreq': 1,  # Frequencey of input to spines
-        'gluWeight': 100,  # Weight for glutamate receptor
-        'nmdaWeight': 100, # weight for NMDA receptor
-        'chemModel':'spineCa_diffn.g',  # Chem model definition.
-        'RA': 1.0,        # Axial resistivity of compartment, ohms.metre
-        'RM': 1.0,        # membrane resistivity of compartment, ohms.metre^2
-        'CM': 0.01,       # Specific capacitance of membrane, Farads/metre^2
-        'runtime': 3,      # Simulation run time, sec.
-    }
-
-Then, we define the prototypes for the soma compartment and the CaConc
-object that handles conversion of calcium current into calcium
-concentration:
-
-::
-
-    def makePassiveSoma( name, length, diameter ):
-        elecid = moose.Neuron( '/library/' + name )
-        dend = moose.Compartment( elecid.path + '/soma' )
-        dend.diameter = diameter
-        dend.length = length
-        dend.Ra = params['RA'] * length * 4.0 / (diameter * diameter * np.pi)
-        dend.Rm = params['RM'] / (length * diameter * np.pi)
-        dend.Cm = params['CM'] * length * diameter * np.pi
-        dend.x = length
-        return elecid
-
-    def makeCaConc( name ):
-        conc = moose.CaConc( '/library/' + name )
-        conc.tau = 0.0133333
-        conc.B = 17.402e12 # Conversion from Amps to milliMolar for soma
-        conc.Ca_base = 0.0 
-
-Then, we define the stimulus including the poisson spike generator:
-
-::
-
-    def attachStimulus():
-        numSpine = len( moose.wildcardFind( '/model/elec/head#' ) ) 
-        spikeInput = moose.RandSpike( '/model/elec/spineInput', numSpine )
-        spikeVec = spikeInput.vec
-        spikeVec.rate = params['spineFreq']
-
-        j = 0 
-        for i in moose.wildcardFind( '/model/elec/head#' ):
-            sh = moose.element( i.path + '/glu/sh' )
-            sh.numSynapses = 1 
-            sh.synapse[0].weight = params['gluWeight']
-            moose.connect( spikeVec[j], 'spikeOut', sh.synapse[0], 'addSpike')
-            sh = moose.element( i.path + '/NMDA/sh' )
-            sh.numSynapses = 1 
-            sh.synapse[0].weight = params['nmdaWeight']
-            moose.connect( spikeVec[j], 'spikeOut', sh.synapse[0], 'addSpike')
-            j += 1
-
-Having specified the framework for the model, here is the actual
-rdesigneur setup:
-
-::
-
-    moose.seed( 123 ) # One seed for the layout
-    library = moose.Neutral( '/library' )
-    makePassiveSoma( 'cell', params['dendLength'], params['dendDiameter'] )
-    makeCaConc( 'Ca_conc' )
-
-    rdes = rd.rdesigneur(
-        chemPlotDt = 0.02,
-        diffusionLength = params['diffusionLength'],
-        spineProto = [['makeExcSpine()', 'spine']],
-        spineDistrib = [['spine', '#', str( params['spineSpacing'] ),'1e-7']],
-        chanDistrib = [["Ca_conc", "#", "tau", "0.0133", "thick","0.1e-6"]],
-        cellProto = [['cell', 'elec']],
-        chemProto = [['../chem/' + params['chemModel'], 'chem']],
-        chemDistrib = [['chem', '#soma#', 'install', '1' ]],
-        plotList = [
-            ['soma', '1', '.', 'Vm', 'soma Vm'],
-            ['soma', '1', 'dend/DEND/Ca', 'conc', '[dend Ca]'],
-            ['#head#', '1', 'spine/Ca', 'conc', '[Spine Ca]'],
-            ['#head#', '1', 'psd/Ca', 'conc', '[PSD Ca]'],
-        ],
-        moogList = [['#', '1', 'dend/DEND/Ca', 'conc', 'dend Ca', 0, 0.5]],
-        adaptorList = [
-            [ 'Ca_conc', 'Ca', 'psd/Ca_input', 'concInit', 2e-6, 0.1 ],
-            [ 'Ca_conc', 'Ca','dend/DEND/Ca_input','concInit',2e-6,0.001],
-        ]
-    )
-    for ca in moose.wildcardFind( '/library/##/Ca' ):
-        ca.diffConst = params['diffConstCa']
-    rdes.buildModel()
-    attachStimulus()
-    moose.reinit()
-    moose.seed( 3 ) # Another seed because the reinit does a reseed.
-    rdes.displayMoogli( 0.01, params['runtime'], 0.0 )
-
-You will additionally need to copy over the chemical models for the
-calcium. These reside in the moose-examples/genesis directory. The
-simple model ``spineCa_diffn.g`` has calcium in spine PSD, spine head,
-and dendrite pools, with reactions for controlling input from the
-*Ca\_conc* object.
-
-With this done you can run the script and watch calcium spreading from
-the location of the spine. There are three pulses of calcium, the first
-being quite weak.
-
-.. figure:: ../../../../images/rdes10_CaSpread.png
-   :alt: Calcium influx from spine in middle of cylindrical compartment, spreading into the dendrite and then axially in both directions.
-
-   Calcium influx from spine in middle of cylindrical compartment, spreading into the dendrite and then axially in both directions.
-
-Once the simulation completes you'll also see a number of plots, so that
-you can figure out what the calcium influx was doing. Here, we have a
-single spine so there is just one trace for it. We have 50 chemical
-voxels along the dendrite, so there are 50 traces for the chemical
-time-course.
-
-.. figure:: ../../../../images/rdes10_CaTimecourse.png
-   :alt: Time-course of Calcium buildup in spine and dendrite.
-
-   Time-course of Calcium buildup in spine and dendrite.
-
-Note the explicit assignment of random seeds using
-``moose.seed( 123 )``. By default, MOOSE generates a reasonably random
-seed using system information. Here, however, we want to be sure that
-the simulation always gives the same result. So we explicitly set the
-seed to a known number. Note also that we set the seed at two places:
-First, before setup, so that we ensure that the spines are going to come
-in the same number and place each time. Second, after ``moose.reinit()``
-to make sure that the same pseudo-random sequence of synaptic input and
-chemical stochastic calculations happens each run.
-
-Note also that this is run using stochastic methods for the chemical
-calculations. This is the default. One can alter this using the
-following line in rdesigneur:
-
-::
-
-        useGssa = False
-
-As an exercise for the user, we also have a plug-in replaceable model
-for Ca influx, this one having a lot of calmodulin to act as a buffer.
-Replace the original line in the params dictionary as follows:
-
-::
-
-        'chemModel':'spineCa_diffn.g'
-
-with
-
-::
-
-        'chemModel':'spineCa_CaM_diffn.g'
-
-The resultant model has reduced free Ca++ buildup.
-
-Some other interesting things to try are:
-
--  Increase the diffusion constant for calcium. You might expect that
-   this would lead to faster flow of Ca from the spine to the dendrite,
-   and hence a higher peak in the dendrite. Try it and see.
--  Change the diameter of the dendrite.
-
-.. Build a spiny neuron from a morphology file and put a reaction-diffusion system in it.
-.. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-.. Rdesigneur is specially designed to take reaction systems with a
-   dendrite, a spine head, and a spine PSD compartment, and embed these
-   systems into neuronal morphologies. This example shows how this is done.
-
-   The dendritic molecules diffuse along the dendrite in the region
-   specified by the *chemDistrib* keyword. In this case they are placed on
-    all apical and basal dendrites, but only at distances over 500 microns
-   from the soma. The spine head and PSD reaction systems are inserted only
-   into spines within this same *chemDistrib* zone. Diffusion coupling
-   between dendrite, and each spine head and PSD is also set up. It takes a
-   predefined chemical model file for Rdesigneur, which resides in the
-   ``./chem`` subdirectory. As in an earlier example, we turn off the
-   electrical calculations here as they are not needed. Here we plot out
-   the number of receptors on every single spine as a function of time.
-
-   (Documentation still to come here)
-
-.. Make a full multiscale model with complex spiny morphology and electrical and chemical signaling.
-.. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-.. (Documentation still to come here)
diff --git a/docs/source/user/py/cookbook/multiscale.rst b/docs/source/user/py/cookbook/multiscale.rst
index d751d3e4bb807f031020ba03fd4d4dd99854e20f..799ee8045213ca6c3f1d28300b74bb4ec888fd46 100644
--- a/docs/source/user/py/cookbook/multiscale.rst
+++ b/docs/source/user/py/cookbook/multiscale.rst
@@ -6,8 +6,6 @@ MultiScale Modeling
    :maxdepth: 2
 
    multi_sim_eg
-   Rd
-   multi_rdes
    
 
 
diff --git a/docs/source/user/py/rdesigneur/index_rd.rst b/docs/source/user/py/rdesigneur/index_rd.rst
new file mode 100644
index 0000000000000000000000000000000000000000..a729cb8b0a2f2a9d357f566bd8821085078f7571
--- /dev/null
+++ b/docs/source/user/py/rdesigneur/index_rd.rst
@@ -0,0 +1,13 @@
+.. MOOSE documentation master file, created by
+   sphinx-quickstart on Tue Jul  31 19:05:47 2018.
+   You can adapt this file completely to your liking, but it should at least
+   contain the root `toctree` directive.
+
+Rdesignuer
+===========
+
+.. toctree::
+   :maxdepth: 2
+
+   rdes
+   multi_rdes
diff --git a/docs/source/user/py/cookbook/multi_rdes.rst b/docs/source/user/py/rdesigneur/multi_rdes.rst
similarity index 98%
rename from docs/source/user/py/cookbook/multi_rdes.rst
rename to docs/source/user/py/rdesigneur/multi_rdes.rst
index 2015743a75e5e827cd0b40b1a46f40c9a4024f9b..d240f1b1cbb2412ab0d9331eff0ccb4f25d136c7 100644
--- a/docs/source/user/py/cookbook/multi_rdes.rst
+++ b/docs/source/user/py/rdesigneur/multi_rdes.rst
@@ -1,5 +1,5 @@
 ************************
-More Rdesigneur Examples
+Rdesigneur Examples
 ************************
 
 .. hidden-code-block:: reStructuredText
diff --git a/docs/source/user/py/rdesigneur/rdes.rst b/docs/source/user/py/rdesigneur/rdes.rst
new file mode 100644
index 0000000000000000000000000000000000000000..0927770023960cd502cfc01748bddf6786bf481c
--- /dev/null
+++ b/docs/source/user/py/rdesigneur/rdes.rst
@@ -0,0 +1,3297 @@
+**Rdesigneur: Building multiscale models**
+==========================================
+
+.. Upi Bhalla
+
+.. Aug 26 2016. Updated August 2018
+
+.. --------------
+
+Contents
+--------
+
+.. contents::
+   :depth: 3
+
+Introduction
+------------
+
+**Rdesigneur** (Reaction Diffusion and Electrical SIGnaling in NEURons)
+is an interface to the multiscale modeling capabilities in MOOSE. It is
+designed to build models incorporating biochemical signaling pathways in
+dendrites and spines, coupled to electrical events in neurons.
+Rdesigneur assembles models from predefined parts: it delegates the
+details to specialized model definition formats. Rdesigneur combines one
+or more of the following cell parts to build models:
+
+-  Neuronal morphology
+-  Dendritic spines
+-  Ion channels
+-  Reaction systems
+-  Adaptors that couple between these for multiscale models
+
+It also folds in simulation input and output
+
+-  Time-series stimuli for molecular concentration change and reaction rates 
+-  Current and voltage clamp 
+-  Synaptic input.
+-  Time-series plots
+-  File dumps
+-  3-D neuronal graphics
+
+Rdesigneur's main role is to specify how these are put together,
+including assigning parameters for the model. Using Rdesigneur one can compactly
+and quickly put together quite complex multiscale models.
+
+Rdesigneur examples
+-------------------
+
+Here we provide a few use cases, building up from a minimal model to a
+reasonably complete multiscale model spanning chemical and electrical
+signaling. The files for these examples are also available in
+``moose-examples/tutorials/Rdesigneur``, and the file names are mentioned
+as we go along.
+
+.. _`building rdesigneur without arguments`:
+
+Bare Rdesigneur: single passive compartment
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex1_minimalModel.py*
+
+If we don't provide any arguments at all to the Rdesigneur, it makes a
+model with a single passive electrical compartment in the MOOSE path
+``/model/elec/soma``. Here is how to do this:
+
+::
+
+    import moose
+    import rdesigneur as rd
+    rdes = rd.rdesigneur()
+    rdes.buildModel()
+
+To confirm that it has made a compartment with some default values we
+can add a line:
+
+::
+
+    moose.showfields( rdes.soma )
+
+This should produce the output:
+
+::
+
+    [ /model[0]/elec[0]/soma[0] ]
+    diameter         = 0.0005
+    fieldIndex       = 0
+    Ra               = 7639437.26841
+    y0               = 0.0
+    Rm               = 424413.177334
+    index            = 0
+    numData          = 1
+    inject           = 0.0
+    initVm           = -0.065
+    Em               = -0.0544
+    y                = 0.0
+    numField         = 1
+    path             = /model[0]/elec[0]/soma[0]
+    dt               = 0.0
+    tick             = -2
+    z0               = 0.0
+    name             = soma
+    Cm               = 7.85398163398e-09
+    x0               = 0.0
+    Vm               = -0.06
+    className        = ZombieCompartment
+    idValue          = 465
+    length           = 0.0005
+    Im               = 1.3194689277e-08
+    x                = 0.0005
+    z                = 0.0
+
+Simulate and display current pulse to soma
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex2.0_currentPulse.py*
+
+A more useful script would run and display the model. Rdesigneur can
+help with the stimulus and the plotting. This simulation has the same
+passive compartment, and current is injected as the simulation runs.
+This script displays the membrane potential of the soma as it charges
+and discharges.
+
+::
+
+    import moose
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+        stimList = [['soma', '1', '.', 'inject', '(t>0.1 && t<0.2) * 2e-8']],
+        plotList = [['soma', '1', '.', 'Vm', 'Soma membrane potential']],
+    )
+    rdes.buildModel()
+    moose.reinit()
+    moose.start( 0.3 )
+    rdes.display()
+
+The *stimList* defines a stimulus. Each entry has five arguments:
+
+::
+
+    `[region_in_cell, region_expression, moose_object, parameter, expression_string]`
+
+-  ``region_in_cell`` specifies the objects to stimulate. Here it is
+   just the soma.
+-  ``region_expression`` specifies a geometry based calculation to
+   decide whether to apply the stimulus. The value must be >0 for the
+   stimulus to be present. Here it is just 1. ``moose_object`` specifies
+   the simulation object to operate upon during the stimulus. Here the
+   ``.`` means that it is the soma itself. In other models it might be a
+   channel on the soma, or a synapse, and so on.
+-  ``parameter`` specifies the simulation parameter on the moose object
+   that the stimulus will modify. Here it is the injection current to
+   the soma compartment.
+-  ``expression_string`` calculates the value of the parameter,
+   typically as a function of time. Here we use the function
+   ``(t>0.1 && t<0.2) * 2e-8`` which evaluates as 2e-8 between the times
+   of 0.1 and 0.2 seconds.
+
+To summarise this, the *stimList* here means *inject a current of 20nA
+to the soma between the times of 0.1 and 0.2 s*.
+
+The *plotList* defines what to plot. It has a similar set of arguments:
+
+::
+
+    `[region_in_cell, region_expression, moose_object, parameter, title_of_plot]`
+
+These mean the same thing as for the stimList except for the title of
+the plot.
+
+The *rdes.display()* function causes the plots to be displayed.
+
+.. figure:: ../../../../images/rdes2_passive_squid.png
+   :alt: Plot for current input to passive compartment
+
+   Plot for current input to passive compartment
+
+When we run this we see an initial depolarization as the soma settles
+from its initial -65 mV to a resting Em = -54.4 mV. These are the
+original HH values, see the example above. At t = 0.1 seconds there is
+another depolarization due to the current injection, and at t = 0.2
+seconds this goes back to the resting potential.
+
+Simulate and display voltage clamp stimulus to soma
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex2.1_vclamp.py*
+
+This model introduces the voltage clamp stimulus on a passive compartment.
+As before, we add a few lines to define the stimulus and plot.
+This script displays both the membrane potential, and the holding current 
+of the voltage clamp circuit as
+it charges and discharges the passive compartment model. 
+
+::
+
+    import moose
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+        stimList = [['soma', '1', '.', 'vclamp', '-0.065 + (t>0.1 && t<0.2) * 0.02' ]],
+        plotList = [
+            ['soma', '1', '.', 'Vm', 'Soma membrane potential'],
+            ['soma', '1', 'vclamp', 'current', 'Soma holding current'],
+        ]
+    )
+    rdes.buildModel()
+    moose.reinit()
+    moose.start( 0.3 )
+    rdes.display()
+
+Here the *stimList* line tells the system to deliver a voltage clamp (vclamp)
+on the soma, starting at -65 mV and jumping up by 20 mV between 0.1 and 0.2 
+seconds. The *plotList* now includes two entries, and will generate two plots.
+The first is for plotting the soma membrane potential, just to be sure that
+the voltage clamp is doing its job. 
+
+.. figure:: ../../../../images/ex2.1_vclamp_a.png
+   :alt: Plot for membrane potential in voltage clamp
+
+   Plot for membrane potential in voltage clamp
+
+The second graph plots the holding current.  Note the capacitive transients.
+
+.. figure:: ../../../../images/ex2.1_vclamp_b.png
+   :alt: Plot for holding current for voltage clamp
+
+   Plot for holding current for voltage clamp
+
+HH Squid model in a single compartment
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex3.0_squid_currentPulse.py*
+
+Here we put the Hodgkin-Huxley squid model channels into a passive
+compartment. The HH channels are predefined as prototype channels for
+Rdesigneur,
+
+::
+
+    import moose
+    import pylab
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+        chanProto = [['make_HH_Na()', 'Na'], ['make_HH_K()', 'K']],
+        chanDistrib = [
+            ['Na', 'soma', 'Gbar', '1200' ],
+            ['K', 'soma', 'Gbar', '360' ]],
+        stimList = [['soma', '1', '.', 'inject', '(t>0.1 && t<0.2) * 1e-8' ]],
+        plotList = [['soma', '1', '.', 'Vm', 'Membrane potential']]
+    )
+
+    rdes.buildModel()
+    moose.reinit()
+    moose.start( 0.3 )
+    rdes.display()
+
+Here we introduce two new model specification lines:
+
+-  **chanProto**: This specifies which ion channels will be used in the
+   model. Each entry here has two fields: the source of the channel
+   definition, and (optionally) the name of the channel. In this example
+   we specify two channels, an Na and a K channel using the original
+   Hodgkin-Huxley parameters. As the source of the channel definition we
+   use the name of the Python function that builds the channel. The
+   *make\_HH\_Na()* and *make\_HH\_K()* functions are predefined but we
+   can also specify our own functions for making prototypes. We could
+   also have specified the channel prototype using the name of a channel
+   definition file in ChannelML (a subset of NeuroML) format.
+-  **chanDistrib**: This specifies *where* the channels should be placed
+   over the geometry of the cell. Each entry in the chanDistrib list
+   specifies the distribution of parameters for one channel using four
+   entries:
+
+   ``[object_name, region_in_cell, parameter, expression_string]``
+
+   In this case the job is almost trivial, since we just have a single
+   compartment named *soma*. So the line
+
+   ``['Na', 'soma', 'Gbar', '1200' ]``
+
+   means *Put the Na channel in the soma, and set its maximal
+   conductance density (Gbar) to 1200 Siemens/m^2*.
+
+As before we apply a somatic current pulse. Since we now have HH
+channels in the model, this generates action potentials.
+
+.. figure:: ../../../../images/rdes3_squid.png
+   :alt: Plot for HH squid simulation
+
+   Plot for HH squid simulation
+
+There are several interesting things to do with the model by varying stimulus
+parameters:
+
+        -  Change injection current.
+        -  Put in a protocol to get rebound action potential.
+        -  Put in a current ramp, and run it for a different duration
+        -  Put in a frequency chirp, and see how the squid model is tuned
+           to a certain frequency range.
+        -  Modify channel or passive parameters. See if it still fires.
+        -  Try the frequency chirp on the cell with parameters changed. Does 
+           the tuning change?
+
+
+HH Squid model with voltage clamp
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex3.1_squid_vclamp.py*
+
+This is the same squid model, but now we add a voltage clamp to the squid
+and monitor the holding current. This stimulus line is identical to ex2.1.
+
+::
+
+    import moose
+    import pylab
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+        chanProto = [['make_HH_Na()', 'Na'], ['make_HH_K()', 'K']],
+        chanDistrib = [
+            ['Na', 'soma', 'Gbar', '1200' ],
+            ['K', 'soma', 'Gbar', '360' ]],
+        stimList = [['soma', '1', '.', 'vclamp', '-0.065 + (t>0.1 && t<0.2) * 0.02' ]],
+        plotList = [
+            ['soma', '1', '.', 'Vm', 'Membrane potential'],
+            ['soma', '1', 'vclamp', 'current', 'Soma holding current']
+        ]
+    )
+    rdes.buildModel()
+    moose.reinit()
+    moose.start( 0.3 )
+    rdes.display()
+
+Here we see the classic HH current response, a downward brief deflection due to
+the Na channel, and a slower upward sustained current due to the K delayed
+rectifier.
+
+.. figure:: ../../../../images/ex3.1_squid_vclamp.png
+   :alt: Plot for HH squid voltage clamp pulse.
+
+   Plot for HH squid voltage clamp pulse.
+
+Here are some suggestions for further exploration:
+
+        - Monitor individual channel currents through additional plots.
+        - Convert this into a voltage clamp series. Easiest way to do this is
+          to complete the rdes.BuildModel, then delete the Function object
+          on the */model/elec/soma/vclamp*. Now you can simply set the 'command'
+          field of the vclamp in a for loop, going from -ve to +ve voltages.
+          Remember, SI units. You may wish to capture the plot vectors each
+          cycle. The plot vectors are accessed by something like
+
+        ``moose.element( '/model/graphs/plot1' ).vector``
+
+
+HH Squid model in an axon
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex3.2_squid_axon_propgn.py*
+
+Here we put the Hodgkin-Huxley squid model into a long compartment that
+is subdivided into many segments, so that we can watch action potentials
+propagate. Most of this example is boilerplate code to build a spiral
+axon. There is a short *rdesigneur* segment that takes the spiral axon
+prototype and populates it with channels, and sets up the display. Later
+examples will show you how to read morphology files to specify the
+neuronal geometry.
+
+::
+
+    import numpy as np
+    import moose
+    import pylab
+    import rdesigneur as rd
+
+    numAxonSegments = 200
+    comptLen = 10e-6
+    comptDia = 1e-6
+    RM = 1.0
+    RA = 10.0
+    CM = 0.01
+
+    def makeAxonProto():
+            axon = moose.Neuron( '/library/axon' )
+            prev = rd.buildCompt( axon, 'soma', RM = RM, RA = RA, CM = CM, dia = 10e-6, x=0, dx=comptLen)
+            theta = 0
+            x = comptLen
+            y = 0.0
+
+            for i in range( numAxonSegments ):
+                dx = comptLen * np.cos( theta )
+                dy = comptLen * np.sin( theta )
+                r = np.sqrt( x * x + y * y )
+                theta += comptLen / r
+                compt = rd.buildCompt( axon, 'axon' + str(i), RM = RM, RA = RA, CM = CM, x = x, y = y, dx = dx, dy = dy, dia = comptDia )
+                moose.connect( prev, 'axial', compt, 'raxial' )
+                prev = compt
+                x += dx
+                y += dy
+            
+            return axon
+
+    moose.Neutral( '/library' )
+    makeAxonProto()
+
+    rdes = rd.rdesigneur(
+            chanProto = [['make_HH_Na()', 'Na'], ['make_HH_K()', 'K']],
+            cellProto = [['elec','axon']],
+            chanDistrib = [
+                ['Na', '#', 'Gbar', '1200' ],
+                ['K', '#', 'Gbar', '360' ]],
+            stimList = [['soma', '1', '.', 'inject', '(t>0.01 && t<0.2) * 2e-11' ]],
+            plotList = [['soma', '1', '.', 'Vm', 'Membrane potential']],
+            moogList = [['#', '1', '.', 'Vm', 'Vm (mV)']]
+            )
+
+    rdes.buildModel()
+    moose.reinit()
+
+    rdes.displayMoogli( 0.00005, 0.05, 0.0 )
+
+.. figure:: ../../../../images/ex3.2_axon_propagating_AP.png
+   :alt: Axon with propagating action potential
+
+   Axon with propagating action potential
+
+Note how we explicitly create the prototype axon on '/library', and then
+specify it using the *cellProto* line in the rdesigneur. The moogList
+specifies the 3-D display. See below for how to set up and use these
+displays.
+
+Action potential collision in HH Squid axon model
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex3.3_AP_collision.py*
+
+This is identical to the previous example, except that now we deliver current
+injection at at two points, the soma and a point along the axon. The modified
+stimulus line is:
+
+::
+
+        ...
+        stimList = [['soma', '1', '.', 'inject', '(t>0.01 && t<0.2) * 2e-11' ],
+        ['axon100', '1', '.', 'inject', '(t>0.01 && t<0.2) * 3e-11' ]],
+        ...
+
+Watch how the AP is triggered bidirectionally from the stimulus point on the
+100th segment of the axon, and observe what happens when two action potentials 
+bump into each other.
+
+.. figure:: ../../../../images/ex3.3_AP_collision.png
+   :alt: Colliding action potentials
+
+   Colliding action potentials
+
+
+
+HH Squid model in a myelinated axon
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex3.4_myelinated_axon.py*
+
+This is a curious cross-species chimera model, where we embed the HH
+equations into a myelinated example model. As for the regular axon
+above, most of the example is boilerplate setup code. Note how we
+restrict the HH channels to the nodes of Ranvier using a conditional
+test for the diameter of the axon segment.
+
+::
+
+    import numpy as np
+    import moose
+    import pylab
+    import rdesigneur as rd
+
+    numAxonSegments = 405
+    nodeSpacing = 100
+    comptLen = 10e-6
+    comptDia = 2e-6 # 2x usual
+    RM = 100.0 # 10x usual
+    RA = 5.0
+    CM = 0.001 # 0.1x usual
+
+    nodeDia = 1e-6
+    nodeRM = 1.0
+    nodeCM = 0.01
+
+    def makeAxonProto():
+        axon = moose.Neuron( '/library/axon' )
+        x = 0.0
+        y = 0.0
+        prev = rd.buildCompt( axon, 'soma', RM = RM, RA = RA, CM = CM, dia = 10e-6, x=0, dx=comptLen)
+        theta = 0
+        x = comptLen
+
+        for i in range( numAxonSegments ):
+            r = comptLen
+            dx = comptLen * np.cos( theta )
+            dy = comptLen * np.sin( theta )
+            r = np.sqrt( x * x + y * y )
+            theta += comptLen / r
+            if i % nodeSpacing == 0:
+                compt = rd.buildCompt( axon, 'axon' + str(i), RM = nodeRM, RA = RA, CM = nodeCM, x = x, y = y, dx = dx, dy = dy, dia = nodeDia )
+            else:
+                compt = rd.buildCompt( axon, 'axon' + str(i), RM = RM, RA = RA, CM = CM, x = x, y = y, dx = dx, dy = dy, dia = comptDia )
+            moose.connect( prev, 'axial', compt, 'raxial' )
+            prev = compt
+            x += dx
+            y += dy
+        
+        return axon
+
+    moose.Neutral( '/library' )
+    makeAxonProto()
+
+    rdes = rd.rdesigneur(
+        chanProto = [['make_HH_Na()', 'Na'], ['make_HH_K()', 'K']],
+        cellProto = [['elec','axon']],
+        chanDistrib = [
+            ['Na', '#', 'Gbar', '12000 * (dia < 1.5e-6)' ],
+            ['K', '#', 'Gbar', '3600 * (dia < 1.5e-6)' ]],
+        stimList = [['soma', '1', '.', 'inject', '(t>0.01 && t<0.2) * 1e-10' ]],
+        plotList = [['soma,axon100,axon200,axon300,axon400', '1', '.', 'Vm', 'Membrane potential']],
+        moogList = [['#', '1', '.', 'Vm', 'Vm (mV)']]
+    )
+
+    rdes.buildModel()
+
+    for i in moose.wildcardFind( "/model/elec/#/Na" ):
+        print i.parent.name, i.Gbar
+
+    moose.reinit()
+
+    rdes.displayMoogli( 0.00005, 0.05, 0.0 )
+
+When you run the example, keep an eye out for a few things:
+
+-  **saltatory conduction:** This is the way the action potential jumps
+   from one node of Ranvier to the next. Between the nodes it is just
+   passive propagation.
+-  **Failure to propagate:** Observe that the second and fourth action
+   potentials fails to trigger propagation along the axon. Here we have
+   specially tuned the model properties so that this happens. With a
+   larger RA of 10.0, the model will be more reliable.
+-  **Speed:** Compare the propagation speed with the previous,
+   unmyelinated axon. Note that the current model is larger!
+
+.. figure:: ../../../../images/rdes3.2_myelinated_axon.png
+   :alt: Myelinated axon with propagating action potential
+
+   Myelinated axon with propagating action potential
+
+Alternate (non-squid) way to define soma
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex4.0_scaledSoma.py*
+
+The default HH-squid axon is not a very convincing soma. Rdesigneur offers a
+somewhat more general way to define the soma in the  cell prototype line.
+
+::
+
+    import moose
+    import pylab
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+        # cellProto syntax: ['somaProto', 'name', dia, length]
+        cellProto = [['somaProto', 'soma', 20e-6, 200e-6]],
+        chanProto = [['make_HH_Na()', 'Na'], ['make_HH_K()', 'K']],
+        chanDistrib = [
+            ['Na', 'soma', 'Gbar', '1200' ],
+            ['K', 'soma', 'Gbar', '360' ]],
+        stimList = [['soma', '1', '.', 'inject', '(t>0.01 && t<0.05) * 1e-9' ]],
+        plotList = [['soma', '1', '.', 'Vm', 'Membrane potential']],
+        moogList = [['#', '1', '.', 'Vm', 'Vm (mV)']]
+    )
+    
+    rdes.buildModel()
+    soma = moose.element( '/model/elec/soma' )
+    print( 'Soma dia = {}, length = {}'.format( soma.diameter, soma.length ) )
+    moose.reinit()
+    
+    rdes.displayMoogli( 0.0005, 0.06, 0.0 )
+
+Here the crucial line is the *cellProto* line. There are four arguments here:
+
+        ``['somaProto', 'name', dia, length]``
+
+        - The first argument tells the system to use a prototype soma, that is 
+          a single cylindrical compartment. 
+        - The second argument is the name to give the cell.
+        - The third argument is the diameter. Note that this is a double, 
+          not a string.
+        - The fourth argument is the length of the cylinder that makes up the 
+          soma. This too is a double, not a string.
+          The cylinder is oriented along the x axis, with one end at (0,0,0)
+          and the other end at (length, 0, 0).
+
+This is what the soma looks like:
+
+.. figure:: ../../../../images/ex4.0_scaledSoma.png
+   :alt: Image of soma.
+
+   Image of soma.
+
+It a somewhat elongated soma, being a cylinder 10 times as long as it is wide. 
+
+Ball-and-stick model of a neuron
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex4.1_ballAndStick.py*
+
+A somewhat more electrically reasonable model of a neuron has a soma and a
+single dendrite, which can itself be subdivided into segments so that it
+can exhibit voltage gradients, have channel and receptor distributions, 
+and so on. This is accomplished in *rdesigneur* using a variant of the
+cellProto syntax.
+
+::
+
+    import moose
+    import pylab
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+        # cellProto syntax: ['ballAndStick', 'name', somaDia, somaLength, dendDia, dendLength, numDendSegments ]
+        # The numerical arguments are all optional
+        cellProto = [['ballAndStick', 'soma', 20e-6, 20e-6, 4e-6, 500e-6, 10]],
+        chanProto = [['make_HH_Na()', 'Na'], ['make_HH_K()', 'K']],
+        chanDistrib = [
+            ['Na', 'soma', 'Gbar', '1200' ],
+            ['K', 'soma', 'Gbar', '360' ],
+            ['Na', 'dend#', 'Gbar', '400' ],
+            ['K', 'dend#', 'Gbar', '120' ]
+            ],
+        stimList = [['soma', '1', '.', 'inject', '(t>0.01 && t<0.05) * 1e-9' ]],
+        plotList = [['soma', '1', '.', 'Vm', 'Membrane potential']],
+        moogList = [['#', '1', '.', 'Vm', 'Vm (mV)']]
+    )
+    rdes.buildModel()
+    soma = moose.element( '/model/elec/soma' )
+    moose.reinit()
+    rdes.displayMoogli( 0.0005, 0.06, 0.0 )
+
+As before, the *cellProto* line plays a key role. Here, because we have a long
+dendrite, we have a few more numerical arguments. All of the numerical 
+arguments are optional.
+
+    ``['ballAndStick', 'name', somaDia, somaLength, dendDia, dendLength, numDendSegments ]``
+
+        - The first argument specifies a ballAndStick model: soma + dendrite.
+          The length of the dendrite is along the x axis. The soma is a single
+          segment, the dendrite can be more than one.
+        - The second argument is the name to give the cell.
+        - Arg 3 is the soma diameter, as a double.
+        - Arg 4 is the length of the soma, as a double.
+        - Arg 5 is the diameter of the dendrite, as a double.
+        - Arg 6 is the length of the dendrite, as a double.
+        - Arg 7 is the number of segments into which the dendrite should be 
+          divided. This is a positive integer greater than 0.
+        
+This is what the ball-and-stick cell looks like:
+
+.. figure:: ../../../../images/ex4.1_ballAndStick.png
+   :alt: Image of ball and stick cell.
+
+   Image of ball and stick cell.
+
+In this version of the 3-D display, the soma is displayed as a bit blocky
+rather than round.
+Note that we have populated the dendrite with Na and K channels and it has
+10 segments, so it supports action potential propagation. The snapshot 
+illustrates this.
+
+Here are some things to try:
+
+        - Change the length of the dendrite
+        - Change the number of segments. Explore what it does to accuracy. How
+          will you know that you have an accurate model?
+
+Benchmarking simulation speed
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex4.2_ballAndStickSpeed.py*
+
+The ball-and-stick model gives us an opportunity to check out your system
+and how computation scales with model size. While we're at it we'll deliver
+a sine-wave stimulus just to see how it can be done. The test model is
+very similar to the previous one, ex4.1:
+
+::
+
+    import moose
+    import pylab
+    import rdesigneur as rd
+    import time
+    rdes = rd.rdesigneur(
+        cellProto = [['ballAndStick', 'soma', 20e-6, 20e-6, 4e-6, 500e-6, 10]],
+        chanProto = [['make_HH_Na()', 'Na'], ['make_HH_K()', 'K']],
+        chanDistrib = [
+            ['Na', 'soma', 'Gbar', '1200' ],
+            ['K', 'soma', 'Gbar', '360' ],
+            ['Na', 'dend#', 'Gbar', '400' ],
+            ['K', 'dend#', 'Gbar', '120' ]
+        ],
+        stimList = [['soma', '1', '.', 'inject', '(1+cos(t/10))*(t>31.4 && t<94) * 0
+    .2e-9' ]],
+        plotList = [
+            ['soma', '1', '.', 'Vm', 'Membrane potential'],
+            ['soma', '1', '.', 'inject', 'Stimulus current']
+        ],
+    )
+    rdes.buildModel()
+    runtime = 100
+    moose.reinit()
+    t0= time.time()
+    moose.start( runtime )
+    print "Real time to run {} simulated seconds = {} seconds".format( runtime, time
+    .time() - t0 )
+    
+    rdes.display()
+
+While the real point of this simulation is to check speed, it does illustrate
+how to deliver a stimulus shaped like a sine wave:
+
+.. figure:: ../../../../images/ex4.2_sine_stim.png
+   :alt: Sine-wave shaped stimulus.
+
+   Sine-wave shaped stimulus.
+
+We can see that the cell has a peculiar response to this. Not surprising, as
+the cell uses HH channels which are not good at rate coding.
+
+.. figure:: ../../../../images/ex4.2_spiking.png
+   :alt: Spiking response to sine-wave shaped stimulus.
+
+   Spiking response to sine-wave shaped stimulus.
+
+As a reference point, on a fast 2018 laptop this benchmark runs in 5.4 seconds.
+Some more things to try for benchmarking:
+
+    - How slow does it get if you turn on the 3-D moogli display?
+    - Is it costlier to run 2 compartments for 1000 seconds, or
+      200 compartments for 10 seconds?
+
+Synaptic stimulus: random (Possion)
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex5.0_random_syn_input.py*
+
+In this example we introduce synaptic inputs: both the receptor channels
+and a means for stimulating the channels. We do this in a passive model.
+
+::
+
+    import moose
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+        cellProto = [['somaProto', 'soma', 20e-6, 200e-6]],
+        chanProto = [['make_glu()', 'glu']],
+        chanDistrib = [['glu', 'soma', 'Gbar', '1' ]],
+        stimList = [['soma', '0.5', 'glu', 'randsyn', '50' ]],
+        # Deliver stimulus to glu synapse on soma, at mean 50 Hz Poisson.
+        plotList = [['soma', '1', '.', 'Vm', 'Soma membrane potential']]
+    )
+    rdes.buildModel()
+    moose.reinit()
+    moose.start( 0.3 )
+    rdes.display()
+
+Most of the rdesigneur setup uses familiar syntax.
+
+Novelty 1: we use the default built-in glutamate receptor model, in chanProto.
+We just put it in the soma at a max conductance of 1 Siemen/sq metre.
+
+Novelty 2: We specify a new kind of stimulus in the stimList:
+
+        ``['soma', '0.5', 'glu', 'randsyn', '50' ]``
+
+Most of this is similar to previous stimLists.
+
+        - arg0: 'soma': the named compartments in the cell to populate with 
+          the *glu* receptor
+        - arg1: '0.5': Tell the system to use a uniform synaptic weight of 0.5.
+          This argument could be a more complicated expression incorporating
+          spatial arguments. Here it is just uniform.
+        - arg2: 'glu': Which receptor to stimulate
+        - arg3: 'randsyn': Apply random (Poisson) synaptic input.
+        - arg4: '50': Mean firing rate of the Poisson input. Note that this last
+          argument could be a function of time and hence is quite versatile.
+
+As the model has no voltage-gated channels, we do not see spiking.
+
+.. figure:: ../../../../images/ex5.0_random_syn_input.png
+   :alt: Random synaptic input with a Poisson distribution.
+   
+   Random synaptic input with a Poisson distribution.
+
+Things to try: Vary the rate and the weight of the synaptic input.
+
+Synaptic stimulus: periodic
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex5.1_periodic_syn_input.py*
+
+This is almost identical to 5.0, except that the input is now perfectly
+periodic. The one change is of an argument in the stimList to say
+``periodicsyn`` rather than ``randsyn``.
+
+::
+
+    import moose
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+        cellProto = [['somaProto', 'soma', 20e-6, 200e-6]],
+        chanProto = [['make_glu()', 'glu']],
+        chanDistrib = [['glu', 'soma', 'Gbar', '1' ]],
+    
+        # Deliver stimulus to glu synapse on soma, periodically at 50 Hz.
+        stimList = [['soma', '0.5', 'glu', 'periodicsyn', '50' ]],
+        plotList = [['soma', '1', '.', 'Vm', 'Soma membrane potential']]
+    )
+    rdes.buildModel()
+    moose.reinit()
+    moose.start( 0.3 )
+    rdes.display()
+
+As designed, we get periodically firing synaptic input.
+
+.. figure:: ../../../../images/ex5.1_periodic_syn_input.png
+   :alt: Periodic synaptic input
+   
+   Periodic synaptic input
+
+
+Reaction system in a single compartment
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex6_chem_osc.py*
+
+Here we use the compartment as a place in which to embed a chemical
+model. The chemical oscillator model is predefined in the rdesigneur
+prototypes. Its general form is:
+
+::
+
+    s ---a---> a  // s goes to a, catalyzed by a.
+    s ---a---> b  // s goes to b, catalyzed by a.
+    a ---b---> s  // a goes to s, catalyzed by b.
+    b -------> s  // b is degraded irreversibly to s
+
+Here is the script:
+
+::
+
+    import moose
+    import pylab
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+            turnOffElec = True,
+            diffusionLength = 1e-3, # Default diffusion length is 2 microns
+            chemProto = [['makeChemOscillator()', 'osc']],
+            chemDistrib = [['osc', 'soma', 'install', '1' ]],
+            plotList = [['soma', '1', 'dend/a', 'conc', 'a Conc'],
+                ['soma', '1', 'dend/b', 'conc', 'b Conc']]
+    )
+    rdes.buildModel()
+    b = moose.element( '/model/chem/dend/b' )
+    b.concInit *= 5
+    moose.reinit()
+    moose.start( 200 )
+
+    rdes.display()
+
+In this special case we set the turnOffElec flag to True, so that
+Rdesigneur only sets up chemical and not electrical calculations. This
+makes the calculations much faster, since we disable electrical
+calculations and delink chemical calculations from them.
+
+We also have a line which sets the ``diffusionLength`` to 1 mm, so that
+it is bigger than the 0.5 mm squid axon segment in the default
+compartment. If you don't do this the system will subdivide the
+compartment into the default 2 micron voxels for the purposes of putting
+in a reaction-diffusion system. We discuss this case below.
+
+Note how the *plotList* is done here. To remind you, each entry has five
+arguments
+
+::
+
+    [region_in_cell, region_expression, moose_object, parameter, title_of_plot]
+
+The change from the earlier usage is that the ``moose_object`` now
+refers to a chemical entity, in this example the molecule *dend/a*. The
+simulator builds a default chemical compartment named *dend* to hold the
+reactions defined in the *chemProto*. What we do in this plot is to
+select molecule *a* sitting in *dend*, and plot its concentration. Then
+we do this again for molecule *b*.
+
+After the model is built, we add a couple of lines to change the initial
+concentration of the molecular pool *b*. Note its full path within
+MOOSE: */model/chem/dend/b*. It is scaled up 5x to give rise to slowly
+decaying oscillations.
+
+.. figure:: ../../../../images/rdes4_osc.png
+   :alt: Plot for single-compartment reaction simulation
+
+   Plot for single-compartment reaction simulation
+
+Reaction-diffusion system
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex7.0_spatial_chem_osc.py*
+
+In order to see what a reaction-diffusion system looks like, we assign the
+``diffusionLength`` expression in the previous example to a much shorter
+length, and add a couple of lines to set up 3-D graphics for the 
+reaction-diffusion product:
+
+::
+
+    import moose
+    import pylab
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+            turnOffElec = True,
+            #This subdivides the length of the soma into 2 micron voxels
+            diffusionLength = 2e-6,
+            chemProto = [['makeChemOscillator()', 'osc']],
+            chemDistrib = [['osc', 'soma', 'install', '1' ]],
+            plotList = [['soma', '1', 'dend/a', 'conc', 'Concentration of a'],
+                ['soma', '1', 'dend/b', 'conc', 'Concentration of b']],
+            moogList = [['soma', '1', 'dend/a', 'conc', 'a Conc', 0, 360 ]]
+    )
+
+    rdes.buildModel()
+    bv = moose.vec( '/model/chem/dend/b' )
+    bv[0].concInit *= 2
+    bv[-1].concInit *= 2
+    moose.reinit()
+
+    rdes.displayMoogli( 1, 400, rotation = 0, azim = np.pi/2, elev = 0.0 )
+
+This is the new value for diffusion length.
+
+::
+
+        diffusionLength = 2e-3,
+
+With this change we tell *rdesigneur* to use the diffusion length of 2 microns.
+This happens to be the default too. The 500-micron axon segment is now 
+subdivided into 250 voxels, each of which has a reaction system and 
+diffusing molecules.
+To make it more picturesque, we have added a line after the plotList, to
+display the outcome in 3-D:
+
+::
+
+    moogList = [['soma', '1', 'dend/a', 'conc', 'a Conc', 0, 360 ]]
+
+This line says: take the model compartments defined by ``soma`` as the
+region to display, do so throughout the the geometry (the ``1``
+signifies this), and over this range find the chemical entity defined by
+``dend/a``. For each ``a`` molecule, find the ``conc`` and dsiplay it.
+There are two optional arguments, ``0`` and ``360``, which specify the
+low and high value of the displayed variable.
+
+In order to initially break the symmetry of the system, we change the
+initial concentration of molecule b at each end of the cylinder:
+
+::
+
+    bv[0].concInit *= 2
+    bv[-1].concInit *= 2
+
+If we didn't do this the entire system would go through a few cycles of
+decaying oscillation and then reach a boring, spatially uniform, steady
+state. Try putting an initial symmetry break elsewhere to see what
+happens.
+
+To display the concenctration changes in the 3-D soma as the simulation
+runs, we use the line
+
+::
+
+    rdes.displayMoogli( 1, 400, rotation = 0, azim = np.pi/2, elev = 0.0 )
+
+The arguments mean: *displayMoogli( frametime, runtime, rotation, azimuth, elevation )*
+Here,
+
+::
+
+    frametime = time by which simulation advances between display updates
+    runtime = Total simulated time
+    rotation = angle by which display rotates in each frame, in radians.
+    azimuth = Azimuth angle of view point, in radians
+    elevation = elevation angle of view point, in radians
+
+When we run this, we first get a 3-D display with the oscillating
+reaction-diffusion system making its way inward from the two ends. After
+the simulation ends the plots for all compartments for the whole run
+come up.
+
+.. figure:: ../../../../images/rdes5_reacdiff.png
+   :alt: Display for oscillatory reaction-diffusion simulation
+
+   Display for oscillatory reaction-diffusion simulation
+
+For those who would rather use the much simpler matplotlib 3-D display option,
+this is what the same simulation looks like:
+
+.. figure:: ../../../../images/ex7.0_spatial_chem_osc.png
+   :alt: Display for oscillatory reac-diff simulation using matplotlib
+
+   Display for oscillatory reac-diff simulation using matplotlib
+
+
+.. _`moogli primer`:
+
+Primer on using the 3-D MOOGLI display
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+There are two variants of the MOOGLI display. The first, named Moogli,
+uses OpenGL and OpenSceneGraph. It is fast to display, slow to load, and
+difficult to compile. It produces much better looking 3-D graphics.
+The second is a fallback interface using mplot3d, which is a library of 
+Matplotlib and so should be generally available. It is slower to display,
+faster to load, but needs no special compilation. It uses stick graphics
+and though it conveys much the same information, isn't as nice to look at
+as the original Moogli. Its controls are more or less the same but less 
+smooth than the original Moogli.
+
+Here is a short primer on the 3-D display controls.
+
+-  *Roll, pitch, and yaw*: Use the letters *r*, *p*, and *y*. To rotate
+   backwards, use capitals.
+-  *Zoom out and in*: Use the *,* and *.* keys, or their upper-case
+   equivalents, *<* and *>*. Easier to remember if you think in terms of
+   the upper-case.
+-  *Left/right/up/down*: Arrow keys.
+-  *Quit*: control-q or control-w.
+-  You can also use the mouse or trackpad to control most of the above.
+-  By default rdesigneur gives Moogli a small rotation each frame. It is
+   the *rotation* argument in the line:
+
+   ``displayMoogli( frametime, runtime, rotation )``
+
+These controls operate over and above this rotation, but the rotation
+continues. If you set the rotation to zero you can, with a suitable
+flick of the mouse, get the image to rotate in any direction you choose
+as long as the window is updating.
+
+Diffusion of a single molecule
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex7.1_diffusive_gradient.py*
+
+This is simply a test model to confirm that simple diffusion happens as
+expected. While the model is just that of a single pool, we spend a few lines
+taking snapshots of the spatial profile of this pool.
+
+::
+
+    import moose
+    import pylab
+    import re
+    import rdesigneur as rd
+    import matplotlib.pyplot as plt
+    import numpy as np
+    
+    moose.Neutral( '/library' )
+    moose.Neutral( '/library/diffn' )
+    moose.CubeMesh( '/library/diffn/dend' )
+    A = moose.Pool( '/library/diffn/dend/A' )
+    A.diffConst = 1e-10
+    
+    rdes = rd.rdesigneur(
+        turnOffElec = True,
+        diffusionLength = 1e-6,
+        chemProto = [['diffn', 'diffn']],
+        chemDistrib = [['diffn', 'soma', 'install', '1' ]],
+        moogList = [
+                ['soma', '1', 'dend/A', 'conc', 'A Conc', 0, 360 ]
+        ]
+    )
+    rdes.buildModel()
+    
+    rdes.displayMoogli( 1, 2, rotation = 0, azim = -np.pi/2, elev = 0.0, block = False )
+    av = moose.vec( '/model/chem/dend/A' )
+    for i in range(10):
+        av[i].concInit = 1
+    moose.reinit()
+    plist = []
+    for i in range( 20 ):
+        plist.append( av.conc[:200] )
+        moose.start( 2 )
+    fig = plt.figure( figsize = ( 10, 12 ) )
+    plist = np.array( plist ).T
+    plt.plot( range( 0, 200 ), plist )
+    plt.xlabel( "position ( microns )" )
+    plt.ylabel( "concentration ( mM )" )
+    plt.show( block = True )
+    
+    
+Here are the snapshots, overlaid in a single plot:
+
+.. figure:: ../../../../images/ex7.1_diffusive_gradient.png
+   :alt: Display of how a molecule A spreads through the inter
+
+   Display for simple time-series of spread of a diffusing molecule 
+   using matplotlib
+
+Calcium-induced calcium release
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. _`models of calcium-induced calcium release`:
+
+*ex7.2_CICR.py*
+
+This is a somewhat more complex reaction-diffusion system, involving calcium
+release from intracellular stores that propagates in a wave of activity along
+a dendrite. This example demonstrates the use of endo compartments.
+
+Endo-compartments, as the name suggests, represent compartments that sit 
+within other cellular compartments. If the surround compartment is subdivided 
+into N voxels, so is the endo- compartment. The rdesigneur system looks at the
+provided model, and if there are 2 compartments and the *addEndoChemCompt* flag
+is True, then the chemistry contained in the smaller of the two compartments is 
+positioned in an endo compartment surrounded by the first compartment.
+Here we use the endo-compartment to represent the endoplasmic reticulum sitting
+inside the dendrite. 
+
+In the chemical model, we also introduce a new MOOSE class,
+ConcChan. These act as membrane pores whose permeability scales with 
+number of channels in the open state. The IP3 receptor in this model is 
+implemented as a ConcChan which opens due to binding to IP3 and Calcium.
+This leads to the release of more calcium from the ER, and this feedback
+loop develops into a propagating-wave oscillation.
+
+::
+
+    import moose
+    import pylab
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+        turnOffElec = True,
+        chemDt = 0.005,
+        chemPlotDt = 0.02,
+        diffusionLength = 1e-6,
+        useGssa = False,
+        addSomaChemCompt = False,
+        addEndoChemCompt = True,
+        # cellProto syntax: ['somaProto', 'name', dia, length]
+        cellProto = [['somaProto', 'soma', 2e-6, 10e-6]],
+        chemProto = [['./chem/CICRwithConcChan.g', 'chem']],
+        chemDistrib = [['chem', 'soma', 'install', '1' ]],
+        plotList = [
+            ['soma', '1', 'dend/CaCyt', 'conc', 'Dendritic Ca'],
+            ['soma', '1', 'dend/CaCyt', 'conc', 'Dendritic Ca', 'wave'],
+            ['soma', '1', 'dend_endo/CaER', 'conc', 'ER Ca'],
+            ['soma', '1', 'dend/ActIP3R', 'conc', 'active IP3R'],
+        ],
+    )
+    rdes.buildModel()
+    IP3 = moose.element( '/model/chem/dend/IP3' )
+    IP3.vec.concInit = 0.004
+    IP3.vec[0].concInit = 0.02
+    moose.reinit()
+    moose.start( 40 )
+    rdes.display()
+
+Note how the dendritic calcium is displayed both as a time-series plot and
+as a wave plot, which presents the time-evolution of the calcium as a function
+of position in successive image frames.
+
+.. figure:: ../../../../images/ex7.2_CICR_static.png
+    :alt: Time-series plot of dendritic calcium. Different colors represent
+        different voxels in the dendrite.
+
+    Time-series plot of dendritic calcium. Different colors represent
+    different voxels in the dendrite.
+
+.. figure:: ../../../../images/ex7.2_CICR_wave_lastFrame.png
+
+    Place holder for time-evolving movie of dendritic calcium as a function of
+    position along the dendrite.
+
+
+Intracellular transport
+~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex7.3_simple_transport.py*
+
+This illustrates how intracellular transport works in MOOSE. We have a 
+an elongated soma in which molecules start out at the left and are transported
+to the right. Note that they spread out as they go along,
+This is because the transport is implemented as drift-diffusion, in which a 
+fraction of the molecules move to the next location each timestep. The 
+equation is
+
+        ``flux = motorConst * conc / spacing``
+
+for a uniform cylinder. MOOSE applies suitable scaling terms if the neuronal
+geometry is non-uniform.
+
+::
+
+    import moose
+    import numpy as np
+    import pylab
+    import rdesigneur as rd
+    
+    moose.Neutral( '/library' )
+    moose.Neutral( '/library/transp' )
+    moose.CubeMesh( '/library/transp/dend' )
+    A = moose.Pool( '/library/transp/dend/A' )
+    A.diffConst = 0 
+    A.motorConst = 1e-6     # Metres/sec
+    
+    rdes = rd.rdesigneur(
+        turnOffElec = True,
+        #This subdivides the length of the soma into 0.5 micron voxels
+        diffusionLength = 0.5e-6, 
+        cellProto = [['somaProto', 'soma', 2e-6, 50e-6]],
+        chemProto = [['transp', 'transp']],
+        chemDistrib = [['transp', 'soma', 'install', '1' ]], 
+        plotList = [ 
+            ['soma', '1', 'dend/A', 'conc', 'Concentration of A'],
+            ['soma', '1', 'dend/A', 'conc', 'Concentration of A', 'wave'],
+        ],  
+        moogList = [['soma', '1', 'dend/A', 'conc', 'A Conc', 0, 20 ]]
+    )
+    rdes.buildModel()
+    moose.element( '/model/chem/dend/A[0]' ).concInit = 0.1 
+    moose.reinit()
+    rdes.displayMoogli( 1, 80, rotation = 0, azim = -np.pi/2, elev = 0.0 )
+
+In this example we explicitly create the single-molecule reaction system,
+and assign a motorConst of 1 micron/sec to the molecule A. We start off with 
+all the molecules in a single voxel on the left of the cylinder, and then
+watch the molecules move.
+Once the molecules reach the end of the cylindrical soma, they have nowhere
+further to go so they pile up.
+
+.. figure:: ../../../../images/ex7.3_1.png
+    :alt: Transport frame 1.
+.. figure:: ../../../../images/ex7.3_2.png
+    :alt: Transport frame 2.
+.. figure:: ../../../../images/ex7.3_3.png
+    :alt: Transport frame 3.
+.. figure:: ../../../../images/ex7.3_4.png
+    :alt: Transport frame 4.
+.. figure:: ../../../../images/ex7.3_5.png
+    :alt: Transport frame 5.
+.. figure:: ../../../../images/ex7.3_6.png
+    :alt: Transport frame 6.
+
+    Frames at increasing intervals from the transport simulation showing 
+    spreading and piling up of the molecule at the right end of the cylinder.
+
+Suggestions:
+
+    - Play with different motor rates.
+    - The motor constant sign detemines the direction of transport. See
+      what happens if you get it going in the opposite direction.
+    - Consider how you could avoid the buildup in the last voxel.
+    - Consider how to achieve a nice exponential falloff over a
+      much longer range than possible with diffusion.
+
+Travelling oscillator
+~~~~~~~~~~~~~~~~~~~~~
+
+*ex7.4_travelling_osc.py*
+
+Here we put a chemical oscillator into a cylinder, and activate motor transport
+in one of the molecules. The oscillatory zone slowly moves to the right, with 
+an amplification in the last compartment due to end-effects.
+
+::
+
+    import moose
+    import numpy as np
+    import pylab
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+        turnOffElec = True,
+        diffusionLength = 2e-6,
+        chemProto = [['makeChemOscillator()', 'osc']],
+        chemDistrib = [['osc', 'soma', 'install', '1' ]],
+        plotList = [
+            ['soma', '1', 'dend/a', 'conc', 'Concentration of a'],
+            ['soma', '1', 'dend/b', 'conc', 'Concentration of b'],
+            ['soma', '1', 'dend/a', 'conc', 'Concentration of a', 'wave'],
+        ],
+        moogList = [['soma', '1', 'dend/a', 'conc', 'a Conc', 0, 360 ]]
+    )
+    a = moose.element( '/library/osc/kinetics/a' )
+    b = moose.element( '/library/osc/kinetics/b' )
+    s = moose.element( '/library/osc/kinetics/s' )
+    a.diffConst = 0
+    b.diffConst = 0
+    a.motorConst = 1e-6
+    
+    rdes.buildModel()
+    moose.reinit()
+    
+    rdes.displayMoogli( 1, 400, rotation = 0, azim = -np.pi/2, elev = 0.0 )
+
+.. figure:: ../../../../images/ex7.4_travelling_osc.png
+    :alt: Travelling Oscillator
+
+    Snapshot of travelling oscillator waveform at t = 198.
+
+Suggestions:
+
+    - What happens if all molecules undergo transport?
+    - What happens if b is transported opposite to a?
+    - What happens if there is also diffusion?
+
+Bidirectional transport
+~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex7.5_bidirectional_transport.py*
+
+This is almost identical to ex7.4, except that we implement bidirectional
+transport. Molecule a goes from left to right, and b and s go from 
+right to left. Here we see that the system builds up with large oscillations
+in the middle as the molecules converge, then the peaks collapse when 
+the molecules go away.
+
+::
+
+    import moose
+    import numpy as np
+    import pylab
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+        turnOffElec = True,
+        diffusionLength = 2e-6, 
+        numWaveFrames = 50, 
+        chemProto = [['makeChemOscillator()', 'osc']],
+        chemDistrib = [['osc', 'soma', 'install', '1' ]], 
+        plotList = [ 
+            ['soma', '1', 'dend/a', 'conc', 'Concentration of a', 'wave', 0, 1800],
+            ['soma', '1', 'dend/b', 'conc', 'Concentration of b', 'wave', 0, 500],
+            ['soma', '1', 'dend/s', 'conc', 'Concentration of s', 'wave', 0, 1200],
+        ],
+        moogList = [['soma', '1', 'dend/a', 'conc', 'a Conc', 0, 600 ]]
+    )
+    a = moose.element( '/library/osc/kinetics/a' )
+    b = moose.element( '/library/osc/kinetics/b' )
+    s = moose.element( '/library/osc/kinetics/s' )
+    a.diffConst = 0
+    b.diffConst = 0
+    a.motorConst = 2e-6
+    b.motorConst = -2e-6
+    s.motorConst = -2e-6
+    
+    rdes.buildModel()
+    moose.reinit()
+    
+    rdes.displayMoogli( 1, 250, rotation = 0, azim = -np.pi/2, elev = 0.0 )
+    
+.. figure:: ../../../../images/ex7.5_a.png
+    :alt: Travelling Oscillator molecule a
+
+.. figure:: ../../../../images/ex7.5_b.png
+    :alt: Travelling Oscillator molecule b
+
+.. figure:: ../../../../images/ex7.5_s.png
+    :alt: Travelling Oscillator molecule 
+
+Above we see *a*, *b*, *s* at a point where the transport has collected the 
+molecules toward the middle of the cylinder, so the oscillations are large. 
+Below we see molecule *a* later, when it has gone past the *b* and *s* pools
+and so the reaction system is depleted and does not oscillate.
+
+.. figure:: ../../../../images/ex7.5_a_later.png
+    :alt: Travelling Oscillator molecule a later.
+
+
+
+Multiscale models: single compartment
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex8.0_multiscale_KA_phosph.py*
+
+The next few examples are for the multiscale modeling that is the main purpose
+of rdesigneur and MOOSE as a whole. These are 'toy' examples in that the
+chemical and electrical signaling is simplified, but they exhibit dynamics
+that are of real interest.
+
+The first example is of a bistable system where the feedback loop comprises of
+
+`calcium influx -> chemical activity -> channel modulation -> electrical activity -> calcium influx.`
+
+Calcium enters through voltage gated calcium channels, leads to enzyme 
+activation and phosphorylation of a KA channel, which depolarizes the cell,
+so it spikes more, so more calcium enters.
+
+::
+    
+    import moose
+    import pylab
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+        elecDt = 50e-6,
+        chemDt = 0.002,
+        chemPlotDt = 0.002,
+        # cellProto syntax: ['somaProto', 'name', dia, length]
+        cellProto = [['somaProto', 'soma', 12e-6, 12e-6]],
+        chemProto = [['./chem/chanPhosphByCaMKII.g', 'chem']],
+        chanProto = [
+            ['make_Na()', 'Na'], 
+            ['make_K_DR()', 'K_DR'], 
+            ['make_K_A()', 'K_A' ],
+            ['make_Ca()', 'Ca' ],
+            ['make_Ca_conc()', 'Ca_conc' ]
+        ],
+        # Some changes to the default passive properties of the cell.
+        passiveDistrib = [['.', 'soma', 'CM', '0.03', 'Em', '-0.06']],
+        chemDistrib = [['chem', 'soma', 'install', '1' ]],
+        chanDistrib = [
+            ['Na', 'soma', 'Gbar', '300' ],
+            ['K_DR', 'soma', 'Gbar', '250' ],
+            ['K_A', 'soma', 'Gbar', '200' ],
+            ['Ca_conc', 'soma', 'tau', '0.0333' ],
+            ['Ca', 'soma', 'Gbar', '40' ]
+        ],
+        adaptorList = [
+            [ 'dend/chan', 'conc', 'K_A', 'modulation', 0.0, 70 ],
+            [ 'Ca_conc', 'Ca', 'dend/Ca', 'conc', 0.00008, 2 ]
+        ],
+        # Give a + pulse from 5 to 7s, and a - pulse from 20 to 21.
+        stimList = [['soma', '1', '.', 'inject', '((t>5 && t<7) - (t>20 && t<21)) * 1.0e-12' ]],
+        plotList = [
+            ['soma', '1', '.', 'Vm', 'Membrane potential'],
+            ['soma', '1', '.', 'inject', 'current inj'],
+            ['soma', '1', 'K_A', 'Ik', 'K_A current'],
+            ['soma', '1', 'dend/chan', 'conc', 'Unphosph K_A conc'],
+            ['soma', '1', 'dend/Ca', 'conc', 'Chem Ca'],
+        ],
+    )
+    
+    rdes.buildModel()
+    moose.reinit()
+    moose.start( 30 )
+    
+    rdes.display()
+    
+There is only one fundamentally new element in this script:
+
+**adaptor List:** `[source, sourceField, dest, destField, offset, scale]`
+The adaptor list maps between molecular, electrical or even structural 
+quantities in the simulation. At present it is linear mapping, in due course
+it may evolve to an arbitrary function. 
+
+The two adaptorLists in the above script do the following:
+
+      ``[ 'dend/chan', 'conc', 'K_A', 'modulation', 0.0, 70 ]``:
+
+Use the concentration of the 'chan' molecule in the 'dend' compartment, 
+to modulate the conductance of the 'K_A' channel such that the basal
+conductance is zero and 1 millimolar of 'chan' results in a conductance that is
+70 times greater than the baseline conductance of the channel, *Gbar*.
+
+It is advisable to use the field *'modulation'* on channels undergoing scaling,
+rather than to directly assign the conductance *'Gbar'*. This is because 
+*Gbar* is an absolute conductance, and therefore it is scaled to the area of
+the electrical segment. This makes it difficult to keep track of. *Modulation*
+is a simple multiplier term onto *Gbar*, and is therefore easier to work with.
+
+       ``[ 'Ca_conc', 'Ca', 'dend/Ca', 'conc', 0.00008, 2 ]``:
+
+Use the concentration of *Ca* as computed in the electrical model, to assign
+the concentration of molecule *Ca* on the dendrite compartment. There is a
+basal level of 80 nanomolar, and every unit of electrical *Ca* maps to 2 
+millimolar of chemical *Ca*.
+
+The arguments in the adaptorList are:
+
+        * **Source and Dest**: Strings. These can be either a molecular or an 
+          electrical object. To identify a molecular object, it should be 
+          prefixed with the name of the chemical compartment, which is one 
+          of *dend, spine, psd*. Thus *dend/chan* specifies a molecule 
+          named *'chan'* sitting in the *'dend'* compartment.
+
+          To identify an electrical object, just pass in its path, 
+          such as '.' or *'Ca_conc'*.
+
+          Note that the adaptors do **not** need to know anything about the 
+          location.  It is assumed that the adaptors do their job wherever 
+          the specified source and dest coexist. There is a subtlety here 
+          due to the different length and time scales. The rule of thumb 
+          is that the adaptor averages whichever one is subdivided more finely. 
+
+            - Example 1: Molecules are typically spatially partitioned into 
+              short voxels (micron-scale) compared to typical 100-micron 
+              electrical 
+              segments. So an adaptor going from molecules to, say, channel 
+              conductance, would average all the molecular voxels that fit 
+              in the electrical segment.
+            - Example 2: Electrical activity is typically much faster than 
+              chemical.
+              So an adaptor going from an electrical entity (Ca computed from 
+              channel opening) to molecules (Chemical Ca concentration) would
+              average all the time-steps between updates to the molecule.
+
+        * **Fields**: Strings. These are simply the field names on the 
+          objects coupled by the adaptors.
+
+        * **offset and scale**: Doubles. At present the adaptor is just a 
+          straight-line conversion, obeying ``y = mx + c``. The computed 
+          output is *y*, averaged input is *x*, offset is *c* and scale is *m*.
+
+There is a handy new line to specify cellular passive properties:
+
+**passiveDistrib:** `['.', path, field, value, field, value, ... ]`,
+
+        * '.': This is just a placeholder.
+        * path: String. Specifies the object whose parameters are to be changed.
+        * field: String. Name of the field on the object.
+        * value: String, that is the value has to be enclosed in quotes. The
+          value to be assigned to the object.
+
+With these in place, the model behavior is rather neat. It starts out silent,
+then we apply 2 seconds of +ve current injection. 
+
+.. figure:: ../../../../images/ex8.0_multiscale_currInj.png
+   :alt: Current injection stimuli for multiscale model.
+
+   Current injection stimuli for multiscale model.
+
+The cell fires briskly, and keeps firing even when the current injection
+drops to zero. 
+
+.. figure:: ../../../../images/ex8.0_multiscale_cell_spiking.png
+   :alt: Firing responses of cell with multiscale signaling.
+
+   Firing responses of cell with multiscale signaling.
+
+The firing of the neuron leads to Ca influx.
+
+.. figure:: ../../../../images/ex8.0_multiscale_Ca.png
+   :alt: Calcium buildup in cell due to firing.
+
+   Calcium buildup in cell due to firing.
+
+The chemical reactions downstream of Ca lead to phosphorylation of the K_A
+channel. Only the unphosphorylated K_A channel is active, so the net effect
+is to reduce K_A conductance while the Ca influx persists.
+
+.. figure:: ../../../../images/ex8.0_multiscale_KA_conc.png
+   :alt: Removal of KA channel due to phosphorylation.
+
+   Removal of KA channel due to phosphorylation.
+
+
+Since the phosphorylated form has low conductance, the cell becomes more 
+excitable and keeps firing even when the current injection is stopped. It takes
+a later, -ve current injection to turn the firing off again.
+
+Suggestions for things to do with the model:
+
+        - Vary the adaptor settings, which couple electrical to chemical
+          signaling and vice versa.
+        - Play with the channel densities
+        - Open the chem model in moosegui and vary its parameters too.
+
+Multiscale model of CICR in dendrite triggered by synaptic input
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex8.1_synTrigCICR.py*
+
+In this model synaptic input arrives at a dendritic spine, leading to calcium
+influx through the NMDA receptor. An adaptor converts this influx to the 
+concentration of a chemical species, and this then diffuses into the dendrite
+and sets off the CICR.
+
+This example models Calcium events in three compartments: dendrite, ER 
+inside dendrite, and spine. The signaling is a slight change from the 
+toy model used
+in *ex7.2_CICR.py*. Note how the range of CICR wave propagation
+is limited by a domain of the dendrite in which the level of IP3 is elevated.
+
+
+::
+
+    import moose
+    import pylab
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+        turnOffElec = False,
+        chemDt = 0.002,
+        chemPlotDt = 0.02,
+        diffusionLength = 1e-6,
+        numWaveFrames = 50,
+        useGssa = False,
+        addSomaChemCompt = False,
+        addEndoChemCompt = True,
+        # cellProto syntax: ['ballAndStick', 'name', somaDia, somaLength, dendDia, dendLength, numDendSeg]
+        cellProto = [['ballAndStick', 'soma', 10e-6, 10e-6, 2e-6, 40e-6, 4]],
+        spineProto = [['makeActiveSpine()', 'spine']],
+        chemProto = [['./chem/CICRspineDend.g', 'chem']],
+        spineDistrib = [['spine', '#dend#', '10e-6', '0.1e-6']],
+        chemDistrib = [['chem', 'dend#,spine#,head#', 'install', '1' ]],
+        adaptorList = [
+            [ 'Ca_conc', 'Ca', 'spine/Ca', 'conc', 0.00008, 8 ]
+        ],
+        stimList = [
+            ['head0', '0.5', 'glu', 'periodicsyn', '1 + 40*(t>5 && t<6)'],
+            ['head0', '0.5', 'NMDA', 'periodicsyn', '1 + 40*(t>5 && t<6)'],
+            ['dend#',  'g>10e-6 && g<=31e-6', 'dend/IP3', 'conc', '0.0006' ],
+            ],
+        plotList = [
+            ['head#', '1', 'spine/Ca', 'conc', 'Spine Ca conc'],
+            ['dend#', '1', 'dend/Ca', 'conc', 'Dend Ca conc'],
+            ['dend#', '1', 'dend/Ca', 'conc', 'Dend Ca conc', 'wave'],
+            ['dend#', '1', 'dend_endo/CaER', 'conc', 'ER Ca conc', 'wave'],
+            ['soma', '1', '.', 'Vm', 'Memb potl'],
+        ],
+    )
+    moose.seed( 1234 )
+    rdes.buildModel()
+    moose.reinit()
+    moose.start( 16 )
+    rdes.display()
+
+The demo illustrates how to specify the range of elevated IP3 in the *stimList*
+using the second argument, which selects a geometric range of electrical
+compartments.
+
+::
+
+    ['dend#',  'g>10e-6 && g<=31e-6', 'dend/IP3', 'conc', '0.0006' ]
+
+This means to look at all dendrite compartments (first argument), and select 
+those which are between a geometrical distance *g* of 10 to 31 microns 
+from the soma (second argument). The system then
+sets the IP3 concentration (third and fourth arguments) to 0.6 uM 
+(last argument) for all the chemical voxels embedded in these dendrite 
+compartments.
+
+A note on defining the endo compartments: In cases like this, where the
+compartment identity isn't built into the chemical model definition, we need
+a heuristic to decide which compartment is which. The heuristic used in 
+rdesigneur goes like this:
+
+        - Sort chemical compartments in decreasing order by volume
+        - If the addSomaChemCompt flag is **true**, they are assigned to
+          *soma, dendrite, spine-head, spine-psd*, depending on how many
+          compartments are specified. If the flag is **false**, the soma is 
+          omitted.
+        - If the addEndoChemCompt is **true**, then alternate compartments are
+          assigned to the endo_compartment. Here it is
+          *dend, dend_endo, spine-head*.
+          If we had six compartments defined (no soma) it would have been:
+          *dend, dend_endo, spine-head, spine-endo, psd, psd-endo*.
+          The psd-endo doesn't make a lot of biological sense, though.
+
+When we run this model, we trigger a propagating Ca wave from about voxel 
+number 16 of 40. It spreads in both directions, and comes to a halt at voxels
+10 and 30, which mark the limits of the IP3 elevation zone.
+
+.. figure:: ../../../../images/ex8.1_dend_Ca.png
+   :alt: Calcium wave propagation along the dendrite
+
+   Calcium wave propagation along the dendrite
+
+Note two subtle effects on the ER Ca concentration: first, there is a 
+periodic small influx of calcium at voxel 16 due to synaptic input. Second, 
+there is a slow restoration of the ER Ca level toward baseline due to 
+diffusion in the dendrite and the action of pumps to within the ER, and 
+out of the cell. Note also that the gradient within the ER is actually quite
+small, being about a 12% deviation from the resting calcium.
+
+.. figure:: ../../../../images/ex8.1_ER_Ca.png
+   :alt: Calcium depletion and buildup in the ER due to CICR wave.
+
+   Calcium depletion and buildup in the ER due to CICR wave.
+
+
+Multiscale model spanning PSD, spine head and dendrite
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex8.2_multiscale_glurR_phosph_3compt.py*
+
+This is another multiscale model on similar lines to 8.0. It is structurally
+and computationally more complicated, because the action is distributed between
+spines and dendrites, but formally it does the same thing: it turns on and 
+stays on after a strong stimulus, due to phosphorylation of a (receptor) 
+channel leading to greater excitability.
+
+`calcium influx -> chemical activity -> channel modulation -> electrical activity -> calcium influx.`
+
+The model is bistable as long as synaptic input keeps coming along at a basal 
+rate, in this case 1 Hz. 
+
+Here we have two new lines, to do with addition of spines. These are discussed
+in detail in a later example. For now it is enough to know that the
+**spineProto** line defines one of the prototype spines to be used to put into
+the model, and the **spineDistrib** line tells the system where to put them,
+and how widely to space them.
+
+::
+
+    import moose
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+        elecDt = 50e-6,
+        chemDt = 0.002,
+        diffDt = 0.002,
+        chemPlotDt = 0.02,
+        useGssa = False,
+        # cellProto syntax: ['ballAndStick', 'name', somaDia, somaLength, dendDia, d
+    endLength, numDendSegments ]
+        cellProto = [['ballAndStick', 'soma', 12e-6, 12e-6, 4e-6, 100e-6, 2 ]],
+        chemProto = [['./chem/chanPhosph3compt.g', 'chem']],
+        spineProto = [['makeActiveSpine()', 'spine']],
+        chanProto = [
+            ['make_Na()', 'Na'], 
+            ['make_K_DR()', 'K_DR'], 
+            ['make_K_A()', 'K_A' ],
+            ['make_Ca()', 'Ca' ],
+            ['make_Ca_conc()', 'Ca_conc' ]
+        ],
+        passiveDistrib = [['.', 'soma', 'CM', '0.01', 'Em', '-0.06']],
+        spineDistrib = [['spine', '#dend#', '50e-6', '1e-6']],
+        chemDistrib = [['chem', '#', 'install', '1' ]],
+        chanDistrib = [
+            ['Na', 'soma', 'Gbar', '300' ],
+            ['K_DR', 'soma', 'Gbar', '250' ],
+            ['K_A', 'soma', 'Gbar', '200' ],
+            ['Ca_conc', 'soma', 'tau', '0.0333' ],
+            ['Ca', 'soma', 'Gbar', '40' ]
+        ],
+        adaptorList = [
+            [ 'psd/chan_p', 'n', 'glu', 'modulation', 0.1, 1.0 ],
+            [ 'Ca_conc', 'Ca', 'spine/Ca', 'conc', 0.00008, 8 ]
+        ],
+        # Syn input basline 1 Hz, and 40Hz burst for 1 sec at t=20. Syn weight
+        # is 0.5, specified in 2nd argument as a special case stimLists. 
+        stimList = [['head#', '0.5','glu', 'periodicsyn', '1 + 40*(t>10 && t<11)']],
+        plotList = [
+            ['soma', '1', '.', 'Vm', 'Membrane potential'],
+            ['#', '1', 'spine/Ca', 'conc', 'Ca in Spine'],
+            ['#', '1', 'dend/DEND/Ca', 'conc', 'Ca in Dend'],
+            ['#', '1', 'spine/Ca_CaM', 'conc', 'Ca_CaM'],
+            ['head#', '1', 'psd/chan_p', 'conc', 'Phosph gluR'],
+            ['head#', '1', 'psd/Ca_CaM_CaMKII', 'conc', 'Active CaMKII'],
+        ]
+    )
+    moose.seed(123)
+    rdes.buildModel()
+    moose.reinit()
+    moose.start( 25 )
+    rdes.display()
+    
+
+This is how it works:
+
+This is a ball-and-stick model with a couple of spines sitting on the dendrite.
+The spines get synaptic input onto NMDARs and gluRs. There is a baseline
+input rate of 1 Hz thoughout, and there is a burst at 40 Hz for 1 second at 
+t = 10s.
+
+.. figure:: ../../../../images/ex8.2_Vm.png
+   :alt: Membrane potential responses of cell with synaptic input and multiscale signaling
+
+   Membrane potential responses of cell with synaptic input and multiscale signaling
+
+
+At baseline, we just have small EPSPs and little Ca influx. A burst of
+strong synaptic input causes Ca entry into the spine via NMDAR. 
+
+.. figure:: ../../../../images/ex8.2_Ca_spine.png
+   :alt: Calcium influx into spine.
+
+   Calcium influx into spine.
+
+Ca diffuses from the spine into the dendrite and spreads. In the graph below
+we see how Calcium goes into the 50-odd voxels of the dendrite.
+
+.. figure:: ../../../../images/ex8.2_Ca_dend.png
+   :alt: Calcium influx and diffusion in dendrite.
+
+   Calcium influx and diffusion in dendrite.
+
+
+The Ca influx into the spine 
+triggers activation of CaMKII and its translocation to the PSD, where
+it phosphorylates and increases the conductance of gluR. We have two spines
+with slightly different geometry, so the CaMKII activity differs slightly.
+
+.. figure:: ../../../../images/ex8.2_active_CaMKII.png
+   :alt: Activation of CaMKII and translocation to PSD
+
+   Activation of CaMKII and translocation to PSD
+
+
+Now that gluR has a greater weight, the baseline synaptic input keeps 
+Ca trickling in enough to keep the CaMKII active. 
+
+Here are the reactions:
+
+::
+        
+        Ca+CaM <===> Ca_CaM;    Ca_CaM + CaMKII <===> Ca_CaM_CaMKII (all in
+        spine head, except that the Ca_CaM_CaMKII translocates to the PSD)
+
+        chan ------Ca_CaM_CaMKII-----> chan_p; chan_p ------> chan  (all in PSD)
+
+Suggestions:
+
+        - Add GABAR using make_GABA(), put it on soma or dendrite. Stimulate it
+          after 20 s to see if you can turn off the sustained activation
+        - Replace the 'periodicsyn' in stimList with 'randsyn'. This gives
+          Poisson activity at the specified mean frequency. Does the switch
+          remain reliable?
+        - What are the limits of various parameters for this switching? You
+          could try basal synaptic rate, burst rate, the various scaling factors
+          for the adaptors, the densities of various channels, synaptic weight,
+          and so on.
+        - In real life an individual synaptic EPSP is tiny, under a millivolt.
+          How many synapses would you need to achieve this kind of switching?
+          You can play with # of synapses by altering the spacing between
+          spines as the third argument of spineDistrib.
+
+Multiscale model in which spine geometry changes due to signaling
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex8.3_spine_vol_change.py*
+
+This model is very similar to 8.2. The main design difference is that 
+*adaptor*, instead of just modulating the gluR conductance, scales the 
+entire spine cross-section area, with all sorts of electrical and chemical
+ramifications. There are a lot of plots, to illustrate some of these outcomes.
+
+::
+
+    import moose
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+        elecDt = 50e-6,
+        chemDt = 0.002,
+        diffDt = 0.002,
+        chemPlotDt = 0.02,
+        useGssa = False,
+        stealCellFromLibrary = True, # Simply move library model to use for sim
+        cellProto = [['ballAndStick', 'soma', 12e-6, 12e-6, 4e-6, 100e-6, 2 ]],
+        chemProto = [['./chem/chanPhosph3compt.g', 'chem']],
+        spineProto = [['makeActiveSpine()', 'spine']],
+        chanProto = [
+            ['make_Na()', 'Na'], 
+            ['make_K_DR()', 'K_DR'], 
+            ['make_K_A()', 'K_A' ],
+            ['make_Ca()', 'Ca' ],
+            ['make_Ca_conc()', 'Ca_conc' ]
+        ],
+        passiveDistrib = [['.', 'soma', 'CM', '0.01', 'Em', '-0.06']],
+        spineDistrib = [['spine', '#dend#', '50e-6', '1e-6']],
+        chemDistrib = [['chem', '#', 'install', '1' ]],
+        chanDistrib = [
+            ['Na', 'soma', 'Gbar', '300' ],
+            ['K_DR', 'soma', 'Gbar', '250' ],
+            ['K_A', 'soma', 'Gbar', '200' ],
+            ['Ca_conc', 'soma', 'tau', '0.0333' ],
+            ['Ca', 'soma', 'Gbar', '40' ]
+        ],
+        adaptorList = [
+            # This scales the psdArea of the spine by # of chan_p. Note that 
+            # the cross-section area of the spine head is identical to psdArea.
+            [ 'psd/chan_p', 'n', 'spine', 'psdArea', 0.1e-12, 0.01e-12 ],
+            [ 'Ca_conc', 'Ca', 'spine/Ca', 'conc', 0.00008, 8 ]
+        ],
+        # Syn input basline 1 Hz, and 40Hz burst for 1 sec at t=20. Syn wt=10
+        stimList = [['head#', '10','glu', 'periodicsyn', '1 + 40*(t>10 && t<11)']],
+        plotList = [
+            ['soma', '1', '.', 'Vm', 'Membrane potential'],
+            ['#', '1', 'spine/Ca', 'conc', 'Ca in Spine'],
+            ['#', '1', 'dend/DEND/Ca', 'conc', 'Ca in Dend'],
+            ['head#', '1', 'psd/chan_p', 'n', 'Amount of Phospho-chan'],
+            ['head#', '1', 'spine/CaMKII', 'conc', 'Conc of CaMKII in spine'],
+            ['head#', '1', '.', 'Cm', 'Capacitance of spine head'],
+            ['head#', '1', '.', 'Rm', 'Membrane res of spine head'],
+            ['head#', '1', '.', 'Ra', 'Axial res of spine head'],
+            ['head#', '1', 'glu', 'Gbar', 'Conductance of gluR'],
+            ['head#', '1', 'NMDA', 'Gbar', 'Conductance of NMDAR'],
+        ]
+    )
+    moose.seed(123)
+    rdes.buildModel()
+    moose.reinit()
+    moose.start( 25 )
+    rdes.display()
+    
+
+The key *adaptor* line is as follows:
+
+``[ 'psd/chan_p', 'n', 'spine', 'psdArea', 0.1e-12, 0.01e-12 ]``
+
+Here, we use the phosphorylated *chan_p* molecule in the PSD as a proxy for 
+processes that control spine size. We operate on a special object called
+*spine* which manages many aspects of spines in the model (see below). Here
+we control the *psdArea*, which defines the cross-section area of the spine
+head and by extension of the PSD too. We keep a minimum spine area of 0.1 um^2,
+and a scaling factor of 0.01um^2 per phosphorylated molecule.
+
+The reaction system is identical to the one in *ex8.2*: 
+
+::
+        
+        Ca+CaM <===> Ca_CaM;    Ca_CaM + CaMKII <===> Ca_CaM_CaMKII (all in
+        spine head, except that the Ca_CaM_CaMKII translocates to the PSD)
+
+        chan ------Ca_CaM_CaMKII-----> chan_p; chan_p ------> chan  (all in PSD)
+
+Rather than list all the 10 plots, here are a few to show what is going on.
+
+First, just the spiking activity of the cell. Here the burst of activity is
+followed by a few seconds of enhanced synaptic weight, followed by subthreshold
+EPSPs:
+
+.. figure:: ../../../../images/ex8.3_Vm.png
+   :alt: Membrane potential and spiking.
+
+   Membrane potential and spiking.
+
+Then, we fast-forward to the amount of *chan_p* which is the molecule that
+controls spine size scaling: 
+
+.. figure:: ../../../../images/ex8.3_chan_p.png
+   :alt: Molecule that controles spine size
+
+   Molecule that controles spine size
+
+This causes some obvious outcomes. One of them is to increase the synaptic
+conductance of the glutamate receptor. The system assumes that the conductance
+of all channels in the PSD scales linearly with the psdArea.
+
+.. figure:: ../../../../images/ex8.3_gluR.png
+   :alt: Conductance of glutamate receptor
+
+   Conductance of glutamate receptor
+
+Here is one of several non-intuitive outcomes. Because the spine volume has
+increased, the concentration of molecules in the spine is diluted out. So
+the concentration of active CaMKII actually falls when the spine gets bigger.
+In a more detailed model, this would be a race between the increase in spine
+size and the time taken for diffusion and further reactions to replenish 
+CaMKII. In the current model we don't have a diffusive coupling of CaMKII to
+the dendrite, so this replenishment doesn't happen.
+
+.. figure:: ../../../../images/ex8.3_CaMKII_spine.png
+   :alt: Concentration of CaMKII in the spine
+
+   Concentration of CaMKII in the spine
+
+In the simulation we display several other electrical and chemical properties
+that change with spine size. The diffusion properties also change since the 
+cross-section areas are altered. This is harder to visualize but has large 
+effects on coupling to the dendrite,
+especially if the *shaftDiameter* is the parameter scaled by the signaling.
+
+
+Suggestions:
+
+        - The Spine class (instance: spine) manages several possible scaling
+          targets on the spine geometry: shaftLength, shaftDiameter,
+          headLength, headDiameter, psdArea, headVolume, totalLength. Try them
+          out. Think about mechanisms by which molecular concentrations might
+          affect each.
+        - When volume changes, we assume that the molecular numbers stay
+          fixed, so concentration changes. Except for buffered molecules, where
+          we assume concentration remains fixed. Use this to design a bistable
+          simply relying on molecules and spine geometry terms.
+        - Even more interesting, use it to design an oscillator. You could look
+          at Bhalla, BiophysJ 2011 for some ideas.
+
+
+
+Morphology: Load .swc morphology file and view it
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex9.0_load_neuronal_morphology_file.py*
+
+Here we build a passive model using a morphology file in the .swc file
+format (as used by NeuroMorpho.org). The morphology file is predefined
+for Rdesigneur and resides in the directory ``./cells``. We apply a
+somatic current pulse, and view the somatic membrane potential in a
+plot, as before. To make things interesting we display the morphology in
+3-D upon which we represent the membrane potential as colors.
+
+::
+
+    import sys
+    import moose
+    import rdesigneur as rd
+    
+    if len( sys.argv ) > 1:
+        fname = sys.argv[1]
+    else:
+        fname = './cells/h10.CNG.swc'
+    rdes = rd.rdesigneur(
+        cellProto = [[fname, 'elec']],
+        stimList = [['soma', '1', '.', 'inject', 't * 25e-9' ]],
+        plotList = [['#', '1', '.', 'Vm', 'Membrane potential'],
+                ['#', '1', 'Ca_conc', 'Ca', 'Ca conc (uM)']],
+        moogList = [['#', '1', '.', 'Vm', 'Soma potential']]
+    )
+    rdes.buildModel()
+    moose.reinit()
+    rdes.displayMoogli( 0.001, 0.1, rotation = 0.02 )
+
+
+Here the new concept is the cellProto line, which loads in the specified
+cell model:
+
+::
+
+    `[ filename, cellname ]`
+
+The system recognizes the filename extension and builds a model from the
+swc file. It uses the cellname **elec** in this example.
+
+We use a similar line as in the reaction-diffusion example, to build up
+a Moogli display of the cell model:
+
+::
+
+    `moogList = [['#', '1', '.', 'Vm', 'Soma potential']]`
+
+Here we have:
+
+::
+
+    # : the path to use for selecting the compartments to display. 
+    This wildcard means use all compartments.
+    1 : The expression to use for the compartments. Again, `1` means use
+    all of them.
+    . : Which object in the compartment to display. Here we are using the
+    compartment itself, so it is just a dot.
+    Vm : Field to display
+    Soma potential : Title for display.
+
+.. figure:: ../../../../images/ex9.0_passive_cell_morpho.png
+   :alt: 3-D display for passive neuron
+
+   3-D display for passive neuron
+
+Suggestions:
+
+        - The tutorial directory already has a number of pre-loaded files from
+          NeuroMorpho. Pass them in to ex9.0 on the command line:
+
+          `python ex9.0_load_neuronal_morphology_file.py <morpho.swc>`
+        - Grab other morphology files from NeuroMorpho.org,  try them out.
+
+Build an active neuron model by putting channels into a morphology file
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex9.1_chans_in_neuronal_morph.py*
+
+Here we load in a morphology file and distribute voltage-gated ion channels
+over the neuron. The voltage-gated channels are obtained from a
+number of channelML files, located in the ``./channels`` subdirectory.
+Since we have a spatially extended neuron, we need to specify the
+spatial distribution of channel densities too.
+
+::
+
+    import moose
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+        chanProto = [
+            ['./chans/hd.xml'],
+            ['./chans/kap.xml'],
+            ['./chans/kad.xml'],
+            ['./chans/kdr.xml'],
+            ['./chans/na3.xml'],
+            ['./chans/nax.xml'],
+            ['./chans/CaConc.xml'],
+            ['./chans/Ca.xml']
+        ],
+        cellProto = [['./cells/h10.CNG.swc', 'elec']],
+        chanDistrib = [ \
+            ["hd", "#dend#,#apical#", "Gbar", "50e-2*(1+(p*3e4))" ],
+            ["kdr", "#", "Gbar", "p < 50e-6 ? 500 : 100" ],
+            ["na3", "#soma#,#dend#,#apical#", "Gbar", "850" ],
+            ["nax", "#soma#,#axon#", "Gbar", "1250" ],
+            ["kap", "#axon#,#soma#", "Gbar", "300" ],
+            ["kap", "#dend#,#apical#", "Gbar",
+                "300*(H(100-p*1e6)) * (1+(p*1e4))" ],
+            ["Ca_conc", "#", "tau", "0.0133" ],
+            ["kad", "#soma#,#dend#,#apical#", "Gbar", "50" ],
+            ["Ca", "#", "Gbar", "50" ]
+        ],
+        stimList = [['soma', '1', '.', 'inject', '(t>0.02) * 1e-9' ]],
+        plotList = [['#', '1', '.', 'Vm', 'Membrane potential'],
+                ['#', '1', 'Ca_conc', 'Ca', 'Ca conc (uM)']],
+        moogList = [['#', '1', 'Ca_conc', 'Ca', 'Calcium conc (uM)', 0, 120],
+            ['#', '1', '.', 'Vm', 'Soma potential']]
+    )
+
+    rdes.buildModel()
+
+    moose.reinit()
+    rdes.displayMoogli( 0.0002, 0.052 )
+
+Here we make more extensive use of two concepts which we've already seen
+from the single compartment squid model:
+
+1. *chanProto*: This defines numerous channels, each of which is of the
+   form:
+
+   ``[ filename ]``
+
+   or
+
+   ``[ filename, channelname ]``
+
+   or
+
+   ``[ channelFunction(), channelname ]``
+
+If the *channelname* is not specified the system uses the last part of
+the channel name, before the filetype suffix.
+
+2. *chanDistrib*: This defines the spatial distribution of each channel
+   type. Each line is of a form that should be familiar now:
+
+   ``[channelname, region_in_cell, parameter, expression_string]``
+
+-  The *channelname* is the name of the prototype from *chanproto*. This
+   is usually an ion channel, but in the example above you can also see
+   a calcium concentration pool defined.
+-  The *region\_in\_cell* is typically defined using wildcards, so that
+   it generalizes to any cell morphology. For example, the plain
+   wildcard ``#`` means to consider all cell compartments. The wildcard
+   ``#dend#`` means to consider all compartments with the string
+   ``dend`` somewhere in the name. Wildcards can be comma-separated, so
+   ``#soma#,#dend#`` means consider all compartments with either soma or
+   dend in their name. The naming in MOOSE is defined by the model file.
+   Importantly, in **.swc** files MOOSE generates names that respect the
+   classification of compartments into axon, soma, dendrite, and apical
+   dendrite compartments respectively. SWC files generate compartment
+   names such as:
+
+   ::
+
+       soma_<number>
+       dend_<number>
+       apical_<number>
+       axon_<number>
+
+where the number is automatically assigned by the reader. In order to
+select all dendritic compartments, for example, one would use *"#dend#"*
+where the *"#"* acts as a wildcard to accept any string. - The
+*parameter* is usually Gbar, the channel conductance density in *S/m^2*.
+If *Gbar* is zero or less, then the system economizes by not
+incorporating this channel mechanism in this part of the cell.
+Similarly, for calcium pools, if the *tau* is below zero then the
+calcium pool object is simply not inserted into this part of the cell. -
+The *expression\_string* defines the value of the parameter, such as
+Gbar. This is typically a function of position in the cell. The
+expression evaluator knows about several parameters of cell geometry.
+All units are in metres:
+
+-  *x*, *y* and *z* coordinates.
+-  *g*, the geometrical distance from the soma
+-  *p*, the path length from the soma, measured along the dendrites.
+-  *dia*, the diameter of the dendrite.
+-  *L*, The electrotonic length from the soma (no units).
+
+Along with these geometrical arguments, we make liberal use of the
+ternary expressions like *p < 50e-6 ? 500 : 100* or multiplying a channel
+density with a logical function or Heaviside function H(x) to set up the 
+channel distributions. The
+expression evaluator also knows about pretty much all common algebraic,
+trignometric, and logarithmic functions, should you wish to use these.
+
+Also note the two Moogli displays. The first is the calcium
+concentration. The second is the membrane potential in each compartment.
+Easy!
+
+.. figure:: ../../../../images/rdes8_active.png
+   :alt: 3-D display for active neuron
+
+   3-D display for active neuron
+
+Suggestions:
+
+        - Try another morphology file.
+        - Try different channel distributions by editing the chanDistrib lines.
+        - There are numerous predefined channels available within Rdesigneur.
+          These can be defined using the following chanProto options:
+
+          ::
+
+                ['make_HH_Na()', 'HH_Na']
+                ['make_HH_K_DR()', 'HH_K']
+                ['make_Na()', 'Na']
+                ['make_K_DR()', 'K_DR']
+                ['make_K_A()', 'K_A']
+                ['make_K_AHP()', 'K_AHP']
+                ['make_K_C()', 'K_C']
+                ['make_Ca()', 'Ca']
+                ['make_Ca_conc()', 'Ca_conc']
+                ['make_glu()', 'glu']
+                ['make_GABA()', 'GABA']
+
+          Then the chanDistrib can refer to these channels instead.
+        - Deliver stimuli on the dendrites rather than the soma.
+
+
+Build a spiny neuron from a morphology file and put active channels in it.
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*ex9.2_spines_in_neuronal_morpho.py*
+
+This model is one step elaborated from the previous one, in that we now
+also have dendritic spines. MOOSE lets one decorate a bare neuronal
+morphology file with dendritic spines, specifying various geometric
+parameters of their location. As before, we use an swc file for the
+morphology, and the same ion channels and distribution.
+
+::
+
+    import moose
+    import pylab
+    import rdesigneur as rd
+    rdes = rd.rdesigneur(
+        chanProto = [
+            ['./chans/hd.xml'],
+            ['./chans/kap.xml'],
+            ['./chans/kad.xml'],
+            ['./chans/kdr.xml'],
+            ['./chans/na3.xml'],
+            ['./chans/nax.xml'],
+            ['./chans/CaConc.xml'],
+            ['./chans/Ca.xml']
+        ],
+        cellProto = [['./cells/h10.CNG.swc', 'elec']],
+        spineProto = [['makeActiveSpine()', 'spine']],
+        chanDistrib = [
+            ["hd", "#dend#,#apical#", "Gbar", "50e-2*(1+(p*3e4))" ],
+            ["kdr", "#", "Gbar", "p < 50e-6 ? 500 : 100" ],
+            ["na3", "#soma#,#dend#,#apical#", "Gbar", "850" ],
+            ["nax", "#soma#,#axon#", "Gbar", "1250" ],
+            ["kap", "#axon#,#soma#", "Gbar", "300" ],
+            ["kap", "#dend#,#apical#", "Gbar",
+                "300*(H(100-p*1e6)) * (1+(p*1e4))" ],
+            ["Ca_conc", "#", "tau", "0.0133" ],
+            ["kad", "#soma#,#dend#,#apical#", "Gbar", "50" ],
+            ["Ca", "#", "Gbar", "50" ]
+        ],
+        spineDistrib = [['spine', '#dend#,#apical#', '20e-6', '1e-6']],
+        stimList = [['soma', '1', '.', 'inject', '(t>0.02) * 1e-9' ]],
+        plotList = [['#', '1', '.', 'Vm', 'Membrane potential'],
+                ['#', '1', 'Ca_conc', 'Ca', 'Ca conc (uM)']],
+        moogList = [['#', '1', 'Ca_conc', 'Ca', 'Calcium conc (uM)', 0, 120],
+            ['#', '1', '.', 'Vm', 'Soma potential']]
+    )
+
+    rdes.buildModel()
+
+    moose.reinit()
+    rdes.displayMoogli( 0.0002, 0.023 )
+
+Spines are set up in a familiar way: we first define one (or more)
+prototype spines, and then distribute these around the cell. Here is the
+prototype string:
+
+::
+
+        [spine_proto, spinename]
+
+*spineProto*: This is typically a function. One can define one's own,
+but there are several predefined ones in rdesigneur. All these define a
+spine with the following parameters:
+
+-  head diameter 0.5 microns
+-  head length 0.5 microns
+-  shaft length 1 micron
+-  shaft diameter of 0.2 microns
+-  RM = 1.0 ohm-metre square
+-  RA = 1.0 ohm-meter
+-  CM = 0.01 Farads per square metre.
+
+Here are the predefined spine prototypes:
+
+-  *makePassiveSpine()*: This just makes a passive spine with the
+   default parameters
+-  *makeExcSpine()*: This makes a spine with NMDA and glu receptors, and
+   also a calcium pool. The NMDA channel feeds the Ca pool.
+-  *makeActiveSpine()*: This adds a Ca channel to the exc\_spine. and
+   also a calcium pool.
+
+The spine distributions are specified in a familiar way for the first
+few arguments, and then there are multiple (optional) spine-specific
+parameters:
+
+*[spinename, region\_in\_cell, spacing, spacing\_distrib, size,
+size\_distrib, angle, angle\_distrib ]*
+
+Only the first two arguments are mandatory.
+
+-  *spinename*: The prototype name
+-  *region\_in\_cell*: Usual wildcard specification of names of
+   compartments in which to put the spines.
+-  *spacing*: Math expression to define spacing between spines. In the
+   current implementation this evaluates to
+   ``1/probability_of_spine_per_unit_length``. Defaults to 10 microns.
+   Thus, there is a 10% probability of a spine insertion in every
+   micron. This evaluation method has the drawback that it is possible
+   to space spines rather too close to each other. If spacing is zero or
+   less, no spines are inserted.
+-  *spacing\_distrib*: Math expression for distribution of spacing. In
+   the current implementation, this specifies the interval at which the
+   system samples from the spacing probability above. Defaults to 1
+   micron.
+-  *size*: Linear scale factor for size of spine. All dimensions are
+   scaled by this factor. The default spine head here is 0.5 microns in
+   diameter and length. If the scale factor were to be 2, the volume
+   would be 8 times as large. Defaults to 1.0.
+-  *size\_distrib*: Range for size of spine. A random number R is
+   computed in the range 0 to 1, and the final size used is
+   ``size + (R - 0.5) * size_distrib``. Defaults to 0.5
+-  *angle*: This specifies the initial angle at which the spine sticks
+   out of the dendrite. If all angles were zero, they would all point
+   away from the soma. Defaults to 0 radians.
+-  *angle\_distrib*: Specifies a random number to add to the initial
+   angle. Defaults to 2 PI radians, so the spines come out in any
+   direction.
+
+.. figure:: ../../../../images/rdes9_spiny_active.png
+   :alt: 3-D display for spiny active neuron
+
+   3-D display for spiny active neuron
+
+Suggestions:
+
+        - Try different spine settings. Warning: if you put in too many spines
+          it will take much longer to load and run!
+        - Try different spine geometry layouts.
+        - See if you can deliver the current injection to the spine. Hint: the
+          name of the spine compartments is 'head#' where # is the index of the
+          spine.
+
+
+Rdesigneur command reference
+----------------------------
+
+Rdesigneur is a Python class used to build multiscale neuronal models 
+involving Reaction-Diffusion and Electrical SIGnaling in NEURons. 
+The stages in its use are illustrated in the following dummy code snippet:
+
+::
+
+    # 1. Load in the libraries
+    import moose
+    import rdesigneur as rd
+
+    # 2. Define the arguments. This does most of the model setup
+    rdes = rd.rdesigneur( args )
+
+    # 3. Tweak parameters of model building-blocks, for example:
+    a = moose.element( '/library/chem/kinetics/a' )
+    a.diffConst = 0
+    
+    # 4. Build the model
+    rdes.buildModel()
+
+    # 5. Tweak values in the constructed model, for example
+    bv = moose.vec( '/model/chem/dend/b' )
+    bv[0].concInit *= 2
+
+    # 6. Run the model
+    moose.reinit()
+    moose.start( runtime )
+
+    # 7. Display and/or save model output
+    rdes.dispay()
+
+The rdesigneur arguments are provided in the standard Python keyword-argument
+format. For example:
+
+::
+
+    rdes = rd.rdesigneur(
+        turnOffElec = True,
+        chemDt = 0.05,
+        ...
+        chemProto = [ ['makeChemOscillator()', 'osc'] ],
+        ...
+        plotList = [ rd.rplot( relpath = 'dend/a', field = 'conc', title = '[a] (uM)' ) ],
+        ...
+    )
+
+Each argument has a default, hence even 
+`building rdesigneur without arguments`_ will produce a correct, if not very 
+interesting model. 
+
+**Rdesigneur and Prototypes:** Rdesigneur assembles models by taking prototype
+objects and replicating them into the model. These prototypes can be chemical
+reaction systems, ion channels, spines, or entire neurons. All the prototypes
+are placed under the MOOSE object */library*. When building the model, it looks
+up prototypes by name and places them into the resulting model. The rdesigneur
+constructor (step 2 above) builds all these prototypes. Once they are in place,
+the *BuildModel()* method (step 4 above) performs the assembly.
+
+Below we provide the usage of the argument list to rdesigneur, which 
+does most of the model specification.
+
+turnOffElec
+~~~~~~~~~~~
+.. _`turnOffElec`:
+
+Type: bool
+
+Default: False
+
+Use: Turns off electrical calculations. It is a good idea to set this flag 
+**True** if the model doesn't use electrical calculations, it can make the 
+calculations many times faster.
+
+useGssa
+~~~~~~~
+Type: bool
+
+Default: True
+
+Use: Turns on the use of the Gillespie Stochastic Simulation Algorithm (GSSA)
+in dendritic spines. Advisable in models where you worry about stochasticity.
+Also it typically makes the simulations run faster.
+
+combineSegments
+~~~~~~~~~~~~~~~
+
+Type: bool
+
+Default: True
+
+Use: Flag to pass on to the NeuroML loader to tell it to combine segments.
+
+stealCellFromLibrary
+~~~~~~~~~~~~~~~~~~~~
+
+Type: bool
+
+Default: False
+
+Use: Use the prototype loaded-in neuron itself for the main simulation run,
+removing it from the available prototypes.
+It is advisable to set this to *True* if the model is large and complicated. It
+saves memory and in some cases runs more reliably.
+
+verbose
+~~~~~~~
+
+Type: bool
+
+Default: True
+
+Use: Tell rdesigneur to be garrulous when loading and reporting status and 
+errors.
+
+.. _`addSomaChemCompt`:
+
+addSomaChemCompt
+~~~~~~~~~~~~~~~~
+
+Type: bool
+
+Default: False
+
+Use: Specify that the largest chemical compartment (by volume) should be 
+assigned to the cell soma. Most multiscale models don't bother with a soma 
+chemical compartment, and are happy with dendrite and possibly spines, so this
+defaults to False.
+
+.. _`addEndoChemCompt`:
+
+addEndoChemCompt
+~~~~~~~~~~~~~~~~
+
+Type: bool
+
+Default: False
+
+Use: Specify that each of the chemical compartments should contain an internal
+*endo*-compartment. This is typically used for the endoplasmic reticulum in
+`models of calcium-induced calcium release`_ (CICR), however, the 
+EndoCompartments are quite general and can be used for defining chemistry and
+transport involving any membrane-bound organelle. In MOOSE, when you create 
+an EndoCompartment it must be surrounded by a regular compartment, and a 
+voxel of the EndoCompartment appears within every voxel of the surrounding 
+compartment.
+
+diffusionLength
+~~~~~~~~~~~~~~~
+Type: double
+
+Default: 2e-6 (2 microns)
+
+Use: This sets the spatial discretization length of reaction-diffusion models.
+If the diffusion constant is D (in micron^2/sec), then the *diffusionLength*
+should be less than D microns for signaling events that take 1 second. If the
+signaling is faster, *diffusionLength* should be smaller.
+
+temperature
+~~~~~~~~~~~
+
+Type: double
+
+Default: 32 degrees Celsius
+
+Use: ChannelML definitions of ion channels use this value to modulate 
+their kinetics.
+
+chemDt
+~~~~~~
+
+Type: double
+
+Default: 0.1 s
+
+Use: Specify timestep for chemical computations. Note that internally the MOOSE
+solver will probably use finer or adaptive timesteps. The *chemDt* just ensures
+that all the chemical values in different solvers will be synchronized at 
+this interval. You will want to make this somewhat smaller (0.01 to 0.001 s)
+in the case of multiscale simulations with tight coupling between electrical
+and signaling events.
+
+diffDt
+~~~~~~
+
+Type: double
+
+Default: 0.01 s
+
+Use: Specify timestep for diffusion computations, as well as cross-compartment
+reactions and molecular transport across membrane pores. This timestep
+does not apply to voltage-gated and synaptic channels handled by the electrical
+solver, for that use *elecDt*. 
+You will want to make this somewhat smaller (0.01 to 0.001 s)
+in the case of multiscale simulations with tight coupling between electrical
+and signaling events.
+
+elecDt
+~~~~~~
+
+Type: double
+
+Default: 50e-6 s
+
+Use: Specify timestep for electrical calculations, used by the HSolver in
+MOOSE to carry out calculations using Gaussian Elimination and the Crank-
+Nicolson method for ion channels. This works well for slower
+channels, but if you have particularly fast channel kinetics you may wish to
+use *elecDt* of 10 to 20 us.
+
+chemPlotDt
+~~~~~~~~~~
+
+Type: double
+
+Default: 1 s
+
+Use: Timestep for storing and plotting chemical values.
+
+elecPlotDt
+~~~~~~~~~~
+
+Type: double
+
+Default: 100e-6 s
+
+Use: Timestep for storing and plotting electrical values.
+
+funcDt
+~~~~~~
+
+Type: double
+
+Default: 100e-6 s
+
+Use: Timestep for performing Function calculations for inputs and stimuli,
+for electrical models. Only used for electrical models, i.e., 
+when `turnOffElec`_ is False. Otherwise the system uses a *funcDt* equal to
+the *chemDt*.
+
+cellProto
+~~~~~~~~~
+
+Type: List of lists
+
+Default: [] (empty list). This generates the Hodgkin-Huxley configuration where
+length and diameter are 500 microns, RM = 0.333, RA = 3000, and
+CM = 0.01 F/m^2, but no active channels.
+
+Use: This defines which neuronal model specification to use. There are many
+options here:
+
+    1. zero args: make standard soma corresponding to the Hodgkin-Huxley 
+       model. length and diameter are both 500 um.
+    2. [name, library_proto_name]: uses library prototype object.
+    3. [fname.suffix, cellname ]: Loads cell from file. The file type
+       is identified by the suffix, and can be :
+
+        - *.nml*: NeuroML
+        - *.xml*: NeuroML
+        - *.swc*: NeuroMorpho.org format for cellular morphology
+        - *.p*: Genesis format
+
+    4. [moose<Classname>, cellname]: Makes prototype from MOOSE class.
+    5. [funcname, cellname]: Calls named function with specified 
+       name of cell to be made.
+    6. [path, cellname]: Copies path to library as proto
+    7. [libraryName, cellname]: Renames library entry as prototype.
+    8. [somaProto, name, somaDia=5e-4, somaLen=5e-4]
+       Creates a soma with optional specified diameter and length. Defaults
+       as shown.
+    9. [ballAndStick,name, somaDia=10e-6, somaLen=10e-6,
+       dendDia=4e-6, dendLen=200e-6, numDendSeg=1]
+       Creates a ball-and-stick with required type and name arguments. 
+       The remaining arguments are optional. Defaults as shown.
+
+spineProto
+~~~~~~~~~~
+
+.. _`spine prototype`:
+
+Type: List of lists
+
+Default: [] (empty list). This does not define any spines.
+
+Use: Each list entry should be a list containing two strings: *source* and
+*destination*. The *source* defines how to build the prototype. The 
+*destination* specifies its name.
+If the requested *destination* is an object that already exists in the library,
+the system doesn't do anything.
+
+The *source* can be any of:
+
+    - functionName(): Call specified Python function, with the *destination*
+      as the argument. The function is expected to build a prototype of the
+      requested name on '/library'. The following utility functions are 
+      built-in:
+
+        - makePassiveSpine(): Makes a 2-compartment spine with the following 
+          parameters:
+
+            - shaft name: shaft
+            - shaft length = 1 micron
+            - shaft diameter = 0.2 micron
+            - head name: head
+            - head length = 0.5 micron
+            - head diameter = 0.5 micron
+            - RM = 1.0
+            - RA = 1.0
+            - CM = 0.01
+
+        - makeExcSpine(): Same as above but adds in glutamate and NMDA 
+          receptors and a calcium pool. The calcium pool has a pumping tau of 
+          13.333 ms, and is present in the volume of the spine head. 
+          Both receptors have conductances in the form of dual-exponential
+          alpha functions, with a separate opening and closing tau.
+          The glutamate receptor has the following parameters:
+
+            - name: glu
+            - opening tau: 2 ms
+            - closing tau: 9 ms
+            - Gbar, ie, conductance per unit area: 200 Siemens/m^2
+
+          The NMDA receptor has the following parameters:
+
+            - name: NMDA
+            - opening tau: 20 ms
+            - closing tau: 20 ms
+            - Gbar, ie, conductance per unit area: 80 Siemens/m^2
+
+        - makeActiveSpine(): Same as above, but also adds in a voltage-gated
+          calcium channel with *Gbar = 10 Siemens/m^2* into the spine head.
+
+    - Path of existing object in memory, such as */library/source*. In this 
+      case rdesigneur renames the object to */library/destination*.
+    - A filename, with any of the suffices:
+
+        - *.nml*: NeuroML
+        - *.xml*: NeuroML
+        - *.swc*: NeuroMorpho.org format for cellular morphology
+        - *.p*: Genesis format
+
+    - moose::SymCompartment: Make a SymCompartment for the spine. Deprecated.
+    - moose::Compartment: Make a Compartment for the spine. Deprecated.
+
+
+chanProto
+~~~~~~~~~
+
+Type: List of lists
+
+Default: [] (empty list). The empty list does not define any channels.
+
+Use: Each list entry must have a string for the *source*. It can optionally
+have a second string for the *destination*, which is the name to give to the
+*source* channel when it is constructed on */library*.
+
+.. _Open Source Brain: http://www.opensourcebrain.org/
+
+The following options are available for specifying the *source* for 
+making channel prototypes:
+
+        - Filepath. This is relative to the working directory. The following
+          file types are known:
+
+            - xml: ChannelML, which is a subset of NeuroML
+            - nml: ChannelML, which is a subset of NeuroML
+
+          Channels in thse formats are available from `Open Source Brain`_, 
+
+        - Predefined channel prototypes, available as functions within 
+          rdesigneur. This is indicated by the use of braces after the name.
+          The following prototypes are currently available:
+          
+            - make_HH_Na(): Make the classical Hodgkin-Huxley Na channel, with
+              kinetics scaled to SI units.
+            - make_HH_K(): Classical HH delayed rectifier K channel.
+            - make_Na(): Hippocampal pyramidal Na channel from Migliore et al.
+            - make_K_DR(): Hippocampal pyramidal K delayed rectifier channel 
+              from Migliore et al.
+            - make_K_A(): Hippocampal pyramidal A-type K channel from Migliore
+              et al.
+            - make_Ca_conc(): A calcium pool with tau 13.333 ms. This is
+              required for the calcium dynamics of several channels.
+            - make_Ca(): Voltage-gated Calcium channel, based on Traub 1991. It
+              requires the Ca_conc.
+            - make_K_AHP: Voltage and calcium-gated afterhyperpolarization-
+              activated K channel, from Traub. Note that this channel requires
+              the presence of the Ca_conc.
+            - make_K_C: Voltage and calcium-dependent K channel from Traub.
+              This channel requires the presence of the Ca_conc.
+            - make_glu(): Glutamate receptor in the form of dual-exponential
+              alpha functions, with a separate opening (2ms) and closing (9ms)
+              tau. Reversal potential = 0 mV.
+            - make_GABA(): GABA receptor in the form of dual-exponential
+              alpha functions, with a separate opening (4ms) and closing (9ms)
+              tau. Reversal potential = -65 mV.
+
+         - User-defined channel definition functions.
+           These can be from external Python files, using the 
+           full path to the file name minus the suffix. The specific function 
+           within it is then specified. For example,
+
+           ::
+
+               chanProto = [
+                   ['/home/user/models/channelProtos.make_K_AHP()', 'K_AHP']
+               ]
+
+
+chemProto
+~~~~~~~~~
+
+Type: List of lists
+
+Default: [] (empty list). The empty list does not define any chemical systems.
+
+Use: Each list entry must have a string for the *source*. It can optionally
+have a second string for the *destination*, which is the name to give to the
+*source* chemical system when it is constructed on */library*.
+
+.. _DOQCS: https://doqcs.ncbs.res.in/
+.. _BioModels: https://www.ebi.ac.uk/biomodels-main/
+
+The following options are available for specifying the *source* for 
+making channel prototypes:
+
+        - Filepath. This is relative to the working directory. The following
+          file types are known:
+
+            - xml: SBML
+            - sbml: SBML
+            - .g: GENESIS Kinetikit (kkit.g) format.
+
+          Channels in thse formats are available from the `DOQCS`_ database,
+          and from the `BioModels`_ database, 
+        - Predefined functions. At present only one such function is available,
+          **makeChemOscillator()**
+        - User-defined functions. 
+           These can be from external Python files, using the 
+           full path to the file name minus the suffix. The specific function 
+           within it is then specified. For example,
+           ::
+
+               chemProto = [
+                   ['/home/user/models/chemProtos.make_Osc()', 'osc']
+               ]
+
+        - Pool objects. These are created on the fly using the form
+          ::
+
+                chemProto = [['moose:Pool', 'a']]
+
+
+passiveDistrib
+~~~~~~~~~~~~~~
+
+Type: List of lists
+
+Default: [] (empty list). Does nothing.
+
+Use; This is for adjusting the passive properties of the neuron. Each list
+entry is a list of strings, of the form:
+
+::
+        
+        [path, field, expr, [field, expr]...]
+
+Here the *path* is a MOOSE wildcard path, which defines one or more objects. 
+Briefly, the '#' character specifies any string, and the double '##' specifies
+any string at any level in the tree. For example, to specify any compartment
+with the string 'dend' you would use *'#dend#'* and to specify any object 
+anywhere in the tree you would use *'##'*.
+
+The *field* can be any one of the following:
+
+        - RM: Membrane resistivity, in ohms.m^2
+        - RA: Axial resistivity, in ohms.m
+        - CM: Membrane specific capacitance, in Farads/m^2
+        - Rm: Absolute membrane resistance of that segment, in ohms.
+        - Ra: Absolute axial resistance of that segment, in ohms.
+        - Cm: Absolute membrane capacitance of that segment, in Farads.
+        - Em: Membrane resting potential, in Volts.
+        - initVm: Initial value to set the membrane potential, in Volts.
+
+The *expr* is an expression string that is evaluated to give the desired value 
+for the field. This can be as simple as the value itself, but can be a much
+more interesting function of geometrical properties of the cell. The geometry
+arguments available to the *expr* include: 
+        
+        - p: Path length in metres from the soma, measured along the dendrite.
+        - g: Geometrical distance from the soma.
+        - L: Number of electronic length constants from the soma
+        - len: length of the segment of dendrite
+        - dia: diameter of the segment of dendrite
+        - maxP: Maximum path length of any dendrite in the cell.
+        - maxG: Maximum geometrical distance of any dendrite from soma
+        - maxL: Maximum electrotonic distance of any dendrite from the soma
+
+Putting these together, here is an example of using the passiveDistrib:
+
+::
+
+    passiveDistrib = [
+        [ 'soma', 'RM', '1.0', 'CM', '0.02' ],
+        [ '#dend#', 'RM', '1.5 + 0.5*(p>200e-6)', 'CM', '0.01' ],
+    ]
+
+This means set the soma *RM* to 1.0, and *CM* to 0.02, leaving the *RA* as the 
+default. The scaled value for *Rm*, *Ra*, and *Cm* are computed by scaling 
+these terms according to the soma dimensions. 
+For all dendrite compartments, set the *RM* to 1.5 provided it is closer than
+200 microns dendritic path length from the soma, and set the *RM* to 2.0 for
+all dendritic compartments further than this.
+Finally, for all dendrite compartments, set *CM* to 0.01. Note that again 
+the absolute *Rm* and *Cm* will be scaled according to the local compartment
+dimensions.
+
+spineDistrib
+~~~~~~~~~~~~
+
+Type: List of lists
+
+Default: [] (empty list). Does nothing.
+
+Use: This is for inserting dendritic spines onto the neuron.
+Each entry is a list of strings, of the form:
+
+::
+        
+    [proto, path, [spacing, minSpacing, size, sizeDistrib, angle, angleDistrib]]
+
+Of these, the *name* and the *path* are required entries, and the remainder 
+can be provided in pairs. The defaults for these entries are:
+
+::
+
+    ['spine', '#dend#,#apical#', '10e-6', '1e-6', '1', '0.5', '0', '6.2832' ]
+
+
+The interpretation of the arguments is as follows:
+
+    - name: This is the name of the `spine prototype`_. 
+    - path: The wildcard path of compartments on which to insert the spines.
+      In the example above, *'#dend#,#apical#'* means all compartments with
+      the strings *dend* or *apical* in their names.
+    - spacing: The mean spacing between spines. At present the spines are placed
+      with a Poisson distribution. This is a math expression with the same
+      terms as used for the passive distribution, so that the spine spacing
+      can be a function of spine position along the dendritic tree. The form
+      of this expression is shown again below.
+    - minSpacing: The minimum spacing, and the increment along which the 
+      Poisson samples are taken to decide if a spine should be added.
+    - size: Scale factor for size from the prototype spine. All dimension of
+      the spine are scaled by this number: shaft length, shaft diameter,
+      head length and head diameter. This is a math expression, as shown below.
+    - sizeDistrib: The range of distribution of sizes. This is a linear
+      distribution centered around the defined size.
+    - angle: The initial angle of the first spine on each dendrite compartment,
+      in radians. This is a math expression, as shown below.
+    - angleDistrib: The range of of angles around this initial angle.
+      The angle will be chosen from a linear distribution centered around the 
+      centre angle, +/- angleDistrib.
+
+The expression used for spacing, size, and angle is of the form of an 
+an expression string that is evaluated to give the desired value 
+for the field. This can be as simple as the value itself, but can be a much
+more interesting function of geometrical properties of the cell. The geometry
+arguments available to the *expr* include: 
+        
+    - p: Path length in metres from the soma, measured along the dendrite.
+    - g: Geometrical distance from the soma.
+    - L: Number of electronic length constants from the soma
+    - len: length of the segment of dendrite
+    - dia: diameter of the segment of dendrite
+    - maxP: Maximum path length of any dendrite in the cell.
+    - maxG: Maximum geometrical distance of any dendrite from soma
+    - maxL: Maximum electrotonic distance of any dendrite from the soma
+
+For example:
+
+::
+
+        ['spine', '#dend#', '1e-6 + (dia<2e-6)*10', '1e-7', '1', '0.5', '6.28*p/maxP', '0']
+
+**proto**: The prototype spine by the name of *spine* is used.
+
+**path**: All compartments with the string *dend* in their name are used.
+
+**Spacing**: The spines are only placed on branches smaller than 2 microns 
+(otherwise the spine spacing is 10 metres). On these small branches the 
+spacing is, on average, 1 micron.
+
+**Size**: The size is anything from 50% to 150% of the prototype spine size.
+
+**Angle**: The angle is proportional to the distance from the soma, such that
+the spines make a complete spiral (2pi) around the dendrite over its length.
+
+
+chanDistrib
+~~~~~~~~~~~~
+
+Type: List of lists
+
+Default: [] (empty list). Does nothing.
+
+Use: This is for inserting ion channels onto the neuron.
+Each entry is a list of strings, of the form:
+
+::
+        
+    [proto, path, field, expr, [field, expr]...]
+
+The entries here are of the form:
+
+    - proto: Specifies the name of the prototype channel to insert
+    - path: Wildcard path of compartments in which to insert the channel
+    - field: Field to assign to channel, almost always **Gbar**, to set its
+      channel density.
+    - expr: Expression evaluated to obtain value to assign to field. This is a
+      mathematical expression of various geometrical properties of the cell,
+      as listed below.
+
+.. _`usual function`:
+
+The *expr* can be as simple as the value itself, but can be a much
+more interesting function of geometrical properties of the cell. The geometry
+arguments available to the *expr* include: 
+        
+    - p: Path length in metres from the soma, measured along the dendrite.
+    - g: Geometrical distance from the soma.
+    - L: Number of electronic length constants from the soma
+    - len: length of the segment of dendrite
+    - dia: diameter of the segment of dendrite
+    - maxP: Maximum path length of any dendrite in the cell.
+    - maxG: Maximum geometrical distance of any dendrite from soma
+    - maxL: Maximum electrotonic distance of any dendrite from the soma
+
+A typical channel distribution entry is:
+
+::
+
+    ["kdr", "#", "Gbar", "p < 50e-6 ? 500 : 100" ]
+
+Here the *kdr* channel is inserted throughout the cell, and its conductance
+is at 500 Siemens/m^2 for all regions closer than 50 microns, and 100 S/m^2
+for the rest of the cell. Basically there is lots of the channel on and
+near the soma.
+
+chemDistrib
+~~~~~~~~~~~~
+
+Type: List of lists
+
+Default: [] (empty list). Does nothing.
+
+Use: This is for inserting a chemical system into the neuron
+Each entry is a list of strings, of the form:
+
+::
+        
+    [proto, path, 'install', expr]
+
+The entries here are of the form:
+
+    - proto: Specifies the name of the prototype chemical system to insert
+    - path: Wildcard path of compartments in which to insert the channel
+    - 'install': Default string.
+    - expr: Expression evaluated to decide whether to install the chemical
+      system. This is the `usual function`_ of geometrical properties of the
+      cell. It is usually '1', to tell the system to install throughout the
+      *path*.
+
+The chemical distribution is handled specially for assignment to the neuronal
+morphology. This is because a given chemical system will have reactions
+between dendrite, ER, spines and PSD, as well as diffusion between these
+zones. Thus, though it would be convenient,  we cannot simply define separate 
+chemical systems for each cellular compartment. Instead we use one of two
+conventions for doing the assignment.
+
+1. Volume based. If the model format does not permit explicit naming of the
+   chemical compartments in the model, then the assignment is inferred from
+   the volume of each compartment. This limitation applies for the legacy
+   Genesis/kkit **.g** format. It may also apply to SBML models that do not
+   assign suitable names for their chemical compartments. In this case
+   the largest chemical compartment is 
+   assigned to the dendrite, the next (if present) to the spine head, and the 
+   smallest (if present) to the spine PSD.
+
+   This is modified in one of two ways by the flags `addSomaChemCompt`_ and
+   `addEndoChemCompt`_.
+
+   *addSomaChemCompt*  instructs rdesigneur to use the largest compartment for
+   the soma. The remaining compartments follow in the usual order.
+
+   *addEndoChemCompt* instructs rdesigneur to insert an EndoCompartment in
+   each neuronal compartment. The volume order is now dend, dend_endo, 
+   spine-head, spine-head-endo and so on.
+     
+2. Name based. This works for recent SBML models, which can assign a compartment
+   name to each of the chemical compartments. Here the expectation is that the
+   names are one of *soma*, *soma_endo*, *dend*, *dend_endo*, *spine*, 
+   *spine_endo*, *psd*, *psd_endo*.
+   Note that the last one, though permitted, doesn't make much biological
+   sense.
+
+
+adaptorList
+~~~~~~~~~~~
+
+Type: List of lists
+
+Default: [] (empty list). Does nothing.
+
+Use: This is for implementing an adaptor between chemical and electrical, or
+chemical and structural quantities. Adaptors handle the conversion between
+distinct concepts in chemical and electrical models. For example, Calcium
+concentration as computed electrically in the Ca_conc objects, can map to the
+calcium concentration of the ion as a molecule, where it can react, diffuse,
+and undergo other calcium dynamics. Another common use is to map the 
+concentration of the molecular state of an ion channel, to its conductance.
+The adaptor applies the conversion equation **y = mx + c** where **y** is the
+target value, **x** is the source value, **m** is the slope of the conversion,
+and **c** is the offset.
+
+Adaptors automatically average over multiple inputs if the mapping requires.
+Typically electrical segments each contain many chemical voxels, so the
+adaptor averages all the source chemical quantities to apply to the 
+corresponding electrical quantity. Similarly, each chemical timestep is 
+typically much longer than the electrical timestep, so the adaptor averages
+the electrical quantity over the entire duration of the chemical timestep.
+
+Each entry is a list of strings, of the form:
+
+::
+        
+    [source, source_field, dest, dest_field, offset, scaling]
+
+The entries here are:
+
+    - source: Specifies the path of the objects whose quantities need to be
+      converted. In the case of chemical quantities, the path starts with the
+      compartment name, one of *dend*, *spine*, or *psd*. So the molecule
+      Ca in the dendrite would be identified as *dend/Ca*.
+    - source_field: The field on the source object whose value is to be used.
+    - dest: Path of destination object, whose quantities will be assigned.
+      As above, chemical quantities are prefixed by their compartment name.
+    - dest_field: Field to be assigned on the destination object.
+    - offset: Double. In the conversion, what is the value of the dest_field
+      when the source value is zero?. In other words, the quantity **c** in
+      the conversion equation **y = mx + c**
+    - scaling: Double. The slope **m**.
+
+
+stimList
+~~~~~~~~
+
+Type: List of lists
+
+Default: [] (empty list). Does nothing.
+
+Use: Each entry is a list of strings, as follows:
+
+::
+        
+    [path, geometry_expr, dest, dest_field, time_expr]
+
+The entries here are:
+    - path: The usual MOOSE wildcard path to identify electrical compartments
+      over which the stimulus will extend. Note that the stimulus may be to
+      a chemical entity, but the spatial location is specified in terms of
+      the electrical compartments in which the chemical system is embedded.
+    - geometry_expr. This is the `usual function`_ of geometrical properties 
+      of the cell. If it is non-zero, then the stimulus will apply.
+      There is a special case for synaptic inputs in which the *geometry_expr*
+      is repaced with the synaptic weight, recorded as a string.
+    - dest. This is the destination object for the stimulus.
+    - dest_field. This is the field on the destination object to be assigned.
+      There is a special case for synaptic inputs, where the field can be
+      **periodicsyn** or **randsyn**, representing periodic and random
+      synaptic input respectively.
+    - time_expr: This is the time expression of the value of the stimulus.
+      Unlike the *geometry_expr*, the *time_expr* can take the predefined 
+      variable **t** which is the current simulation time. The *time_expr* does
+      not have access to the geometry arguments.
+
+Example 1:
+
+::
+
+    ['head#', '0.5','glu', 'periodicsyn', '1 + 40*(t>10 && t<11)']
+
+This acts on all glutamate receptors on the spine *heads*. It delivers 
+periodic synaptic input with weight 0.5 at a basal rate of 1 Hz, rising
+by 40Hz in the interval between 10 and 11 seconds.
+
+Example 2:
+
+::
+
+    ['soma', '1', '.', 'inject', '(1+cos(t/10))*(t>31.4 && t<94)* 0.5e-9' ]
+
+This acts to deliver a current injection on the soma. It delivers cosine
+input of angular frequency 1/10 radians/s, between times 31.4 and 94 seconds,
+with a peak amplitude of 0.5 nA.
+
+Rdesigneur also supports keyword-based argument lists for the stimList.
+Here each entry is an rstim function as follows:
+
+::
+        
+    rd.rstim( elecpath, geom_expr, relpath, field, expr )
+
+The default values of the arguments are
+
+::
+        
+    rd.rstim(elecpath='soma', geom_expr='1', relpath='.', field='inject', expr='0')
+
+ 
+Example 3: To get the same outcome as example 2, one could use:
+
+::
+
+    rd.rstim( expr=(1+cos(t/10))*(t>31.4 && t<94)* 0.5e-9' )
+
+because most of the arguments are the same as the defaults.
+
+plotList
+~~~~~~~~
+
+Type: List of lists
+
+Default: [] (empty list). Does nothing.
+
+Use: This displays a line plot of cellular activity. 
+Each entry is a list as follows:
+
+::
+        
+    [path, geom_expr, relpath, field, title, 
+        [mode, ymin, ymax,saveFile, saveResolution, showFlag ]
+    ]
+
+The entries here are:
+    - path: string. The usual MOOSE wildcard path to identify electrical 
+      compartments
+      over which the plots will be sampled. Note that the stimulus may be to
+      a chemical entity, but the spatial location is specified in terms of
+      the electrical compartments in which the chemical system is embedded.
+    - geom_expr: string. This is the `usual function`_ of geometrical 
+      properties of the cell. If it is non-zero, then the stimulus will apply.
+      There is a special case for synaptic inputs in which the *geometry_expr*
+      is repaced with the synaptic weight, recorded as a string.
+    - replath: string. Relative path to object whose value is being monitored.
+    - field: string. The field to monitor on the source object.
+    - title: Title string for the generated plot.
+    - mode: Optional. String to decide what kind of plot to make. Options are:
+      
+        - *'time'*: Default. Plot time-series
+        - *'wave'*: Generate wave-plot with compartment/voxel number as x axis,
+          value as y axis, and run through a series of frames for different 
+          time-points durign simulation.
+    - ymin: Double. Optional. Minimum value for y axis. Default = 0.
+    - ymax: Double. Optional. Maximum value for y axis. Default = 0. 
+      If ymin==ymax then the plot autoscales.
+    - saveFile: string. Optional. File in which to save plot contents. 
+      Default = "", to
+      indicate that the file is not saved. Currently it can save in *csv* and
+      *xml* formats. *nsdf* will be implemented soon.
+    - show: Bool. Optional. Flag to decide if the plot should be displayed. 
+      Default=True.
+
+Rdesigneur also supports keyword-based argument lists for the plotList, having
+the same entries as above. Here are two plotList entries with identical 
+outcomes.
+
+::
+
+    ['soma', '1', '.', 'Vm', 'Soma membrane potential'],
+    [rd.rplot( field='Vm', title= 'Soma membrane potential')],
+
+moogList
+~~~~~~~~
+
+Type: List of lists
+
+Default: [] (empty list). Does nothing.
+
+Use: This displays a 3-D plot of cellular activity.
+Each entry is a list as follows:
+
+::
+        
+    [path, geom_expr, relpath, field, title, [ymin, ymax]]
+
+The entries here are:
+    - path: string. The usual MOOSE wildcard path to identify electrical 
+      compartments
+      over which the display will be sampled. Note that the stimulus may be to
+      a chemical entity, but the spatial location is specified in terms of
+      the electrical compartments in which the chemical system is embedded.
+    - geom_expr: string. This is the `usual function`_ of geometrical 
+      properties of the cell. If it is non-zero, then the stimulus will apply.
+      There is a special case for synaptic inputs in which the *geometry_expr*
+      is repaced with the synaptic weight, recorded as a string.
+    - replath: string. Relative path to object whose value is being monitored.
+    - field: string. The field to monitor on the source object.
+    - title: Title string for the generated display.
+    - ymin: Double. Minimum value for y axis. Default = 0.
+    - ymax: Double. Maximum value for y axis. Default = 0. 
+      If ymin==ymax then the plot autoscales.
+    - show: Bool. Flag to decide if it should be displayed. Default=True.
+
+Rdesigneur also supports keyword-based argument lists for the moogList, having
+the same entries as above. Here are two moogList entries with identical 
+outcomes.
+
+::
+
+    ['soma', '1', 'dend/a', 'conc', 'a Conc', 0, 600 ],
+    [rd.rmoog(relpath='dend/a', field='conc', title = 'a Conc', ymax=600)]
+
+
+To run and display moogli, one replaces the *moose.start()* and the 
+*rdes.display()* functions with the line:
+
+::
+
+    rdes.displayMoogli(dt, runtime, rotation, fullscreen, block, azim, elev)
+
+in which the first two arguments are required and the rest are optional and
+can be assigned by keywords.
+
+The arguments are as follows:
+
+    - dt: double. Time interval between frames on the moogli display
+    - runtime: double. Simulation runtime.
+    - rotation: double. How much to rotate the display per frame. 
+      Defaults to pi/500.
+    - fullscreen: bool. Flag to do display on the full screen. 
+      Defaults to False.
+    - azim: double. Azimuth setting. Defaults to 0.0
+    - elev: double. Elevation setting. Defaults to 0.0
+
+The `moogli primer`_ explains how to use the 3-D display.
diff --git a/moose-core/.travis.yml b/moose-core/.travis.yml
index b5f3f688e66c00d97989013b897183b478ca3c70..a89ee791337440c7828cccb68c5424a341c5a962 100644
--- a/moose-core/.travis.yml
+++ b/moose-core/.travis.yml
@@ -15,6 +15,10 @@ notifications:
     on_success: change
     on_failure: always
 
+addons:
+    apt:
+      update: true
+
 before_script:
 - echo "OSX related"
 - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then nvm get head || true; fi
diff --git a/moose-core/.travis/travis_prepare_osx.sh b/moose-core/.travis/travis_prepare_osx.sh
index 65bff743617d0883dddf034c8cc7b7e17fcae747..d8aa29a1719ebd80e12a0e5b2b6920313cf1cceb 100755
--- a/moose-core/.travis/travis_prepare_osx.sh
+++ b/moose-core/.travis/travis_prepare_osx.sh
@@ -39,6 +39,6 @@ echo 'import sys; sys.path.insert(1, "/usr/local/lib/python2.7/site-packages")'
 PATH=/usr/local/bin:/usr/bin:$PATH
 # ensurepip
 python -m ensurepip
-python -m pip install matplotlib --user
+python -m pip install matplotlib --user --upgrade
 python -m pip install pyNeuroML libNeuroML --user
 python -m pip install scipy --user
diff --git a/moose-core/biophysics/MarkovSolver.cpp b/moose-core/biophysics/MarkovSolver.cpp
index 1ab4adc1b6646109457d759b30b10d283aa895df..b5e3ddbba288cd3ecfd8ada9b2f40601d444dd1c 100644
--- a/moose-core/biophysics/MarkovSolver.cpp
+++ b/moose-core/biophysics/MarkovSolver.cpp
@@ -81,12 +81,12 @@ Matrix* MarkovSolver::computePadeApproximant( Matrix* Q1,
 																						unsigned int degreeIndex )
 {
 	Matrix *expQ;
-	Matrix *U, *V, *VplusU, *VminusU, *invVminusU, *Qpower;
+	Matrix *U, *VplusU, *VminusU, *invVminusU, *Qpower;
 	vector< unsigned int >* swaps = new vector< unsigned int >;
 	unsigned int n = Q1->size();
 	unsigned int degree = mCandidates[degreeIndex];
 	double *padeCoeffs;
-
+	Matrix *V = matAlloc(n);
 
 	//Vector of Matrix pointers. Each entry is an even power of Q.
 	vector< Matrix* > QevenPowers;
@@ -131,7 +131,6 @@ Matrix* MarkovSolver::computePadeApproximant( Matrix* Q1,
 		case 7 :
 		case 9 :
 			U = matAlloc( n );
-			V = matAlloc( n );
 
 			QevenPowers.push_back( Q1 );
 
@@ -199,6 +198,7 @@ Matrix* MarkovSolver::computePadeApproximant( Matrix* Q1,
 			matMatAdd( temp, Q6, 1.0, b13[6], FIRST );
 			matMatAdd( temp, Q4, 1.0, b13[4], FIRST );
 			matMatAdd( temp, Q2, 1.0, b13[2], FIRST );
+			delete( V );
 			V = matEyeAdd( temp, b13[0] );
 			delete temp;
 
diff --git a/moose-core/biophysics/MatrixOps.cpp b/moose-core/biophysics/MatrixOps.cpp
index a983ef748304b857df89b969236257e5258d8c89..f0f478c3540243630216e0efe34a3c5f65bd24ef 100644
--- a/moose-core/biophysics/MatrixOps.cpp
+++ b/moose-core/biophysics/MatrixOps.cpp
@@ -128,12 +128,14 @@ void matMatAdd( Matrix* A, Matrix* B, double alpha, double beta,
 	Matrix *C;
 	unsigned int n = A->size();
 
-	if ( resIndex == FIRST )
+	if ( resIndex == FIRST ) {
 		C = A;
-	else if ( resIndex == SECOND )
+	} else if ( resIndex == SECOND ) {
 		C = B;
-	else
+	} else {
 		cerr << "matMatAdd : Invalid index supplied to store result.\n";
+		return;
+	}
 
 	for( unsigned int i = 0; i < n; ++i )
 	{
@@ -481,7 +483,7 @@ Matrix* matAlloc( unsigned int n )
 
 	A->resize( n );
 	for ( unsigned int i = 0; i < n; ++i )
-		(*A)[i].resize( n );
+		(*A)[i].resize( n, 0.0 );
 
 	return A;
 }
@@ -490,7 +492,7 @@ Vector* vecAlloc( unsigned int n )
 {
 	Vector* vec = new Vector;
 
-	vec->resize( n );
+	vec->resize( n, 0.0 );
 
 	return vec;
 }
diff --git a/moose-core/biophysics/RandSpike.cpp b/moose-core/biophysics/RandSpike.cpp
index 0c2e09ffff1825cd06407a8931fd79dd41db58d7..4678970f2f7836f99f3fb6e7bdb2710e48b3a9a4 100644
--- a/moose-core/biophysics/RandSpike.cpp
+++ b/moose-core/biophysics/RandSpike.cpp
@@ -67,6 +67,14 @@ const Cinfo* RandSpike::initCinfo()
 		&RandSpike::setRefractT,
 		&RandSpike::getRefractT
 	);
+	static ValueFinfo< RandSpike, bool > doPeriodic( "doPeriodic",
+		"Flag: when false, do Poisson process with specified mean rate.\n"
+		"When true, fire periodically at specified rate.\n"
+		"Defaults to false. Note that refractory time overrides this: "
+		"Rate cannot exceed 1/refractT.",
+		&RandSpike::setDoPeriodic,
+		&RandSpike::getDoPeriodic
+	);
 	static ReadOnlyValueFinfo< RandSpike, bool > hasFired( "hasFired",
 		"True if RandSpike has just fired",
 		&RandSpike::getFired
@@ -79,6 +87,7 @@ const Cinfo* RandSpike::initCinfo()
 		&rate,		// Value
 		&refractT,	// Value
 		&absRefract,	// Value
+		&doPeriodic,	// Value 
 		&hasFired,	// ReadOnlyValue
 	};
 
@@ -86,7 +95,8 @@ const Cinfo* RandSpike::initCinfo()
 	{
 		"Name", "RandSpike",
 		"Author", "Upi Bhalla",
-		"Description", "RandSpike object, generates random spikes at."
+		"Description", "RandSpike object, generates random or regular "
+		"spikes at "
 		"specified mean rate. Based closely on GENESIS randspike. "
 	};
 	static Dinfo< RandSpike > dinfo;
@@ -111,7 +121,8 @@ RandSpike::RandSpike()
       refractT_(0.0),
       lastEvent_(0.0),
 	  threshold_(0.0),
-	  fired_( 0 )
+	  fired_( false ),
+	  doPeriodic_( false )
 {;}
 
 //////////////////////////////////////////////////////////////////
@@ -121,6 +132,10 @@ RandSpike::RandSpike()
 // Value Field access function definitions.
 void RandSpike::setRate( double rate )
 {
+	if ( rate < 0.0 ) {
+		cout <<"Warning: RandSpike::setRate: Rate must be >= 0. Using 0.\n";
+		rate = 0.0;
+	}
 	rate_ = rate;
 	double prob = 1.0 - rate * refractT_;
 	if ( prob <= 0.0 ) {
@@ -149,6 +164,15 @@ bool RandSpike::getFired() const
 	return fired_;
 }
 
+void RandSpike::setDoPeriodic( bool val )
+{
+	doPeriodic_ = val;
+}
+bool RandSpike::getDoPeriodic() const
+{
+	return doPeriodic_;
+}
+
 
 //////////////////////////////////////////////////////////////////
 // RandSpike::Dest function definitions.
@@ -156,16 +180,23 @@ bool RandSpike::getFired() const
 
 void RandSpike::process( const Eref& e, ProcPtr p )
 {
-	if ( refractT_ > p->currTime - lastEvent_ )
+	if ( refractT_ > p->currTime - lastEvent_  || rate_ <= 0.0 )
 		return;
-	double prob = realRate_ * p->dt;
-	if ( prob >= 1.0 || prob >= mtrand() )
-	{
-		lastEvent_ = p->currTime;
-		spikeOut()->send( e, p->currTime );
-		fired_ = true;
+	fired_ = false;
+	if (doPeriodic_) {
+		if ( (p->currTime - lastEvent_) > 1.0/rate_ ) {
+			lastEvent_ = p->currTime;
+			spikeOut()->send( e, p->currTime );
+			fired_ = true;
+		}
 	} else {
-        fired_ = false;
+		double prob = realRate_ * p->dt;
+		if ( prob >= 1.0 || prob >= mtrand() )
+		{
+			lastEvent_ = p->currTime;
+			spikeOut()->send( e, p->currTime );
+			fired_ = true;
+		}
 	}
 }
 
diff --git a/moose-core/biophysics/RandSpike.h b/moose-core/biophysics/RandSpike.h
index ea0cf595d9d2097351b832092a971149628d2fb6..2a7da3de72c1ead13a743483faf5bbc0496c331a 100644
--- a/moose-core/biophysics/RandSpike.h
+++ b/moose-core/biophysics/RandSpike.h
@@ -24,6 +24,9 @@ class RandSpike
 		void setRefractT( double val );
 		double getRefractT() const;
 
+		void setDoPeriodic( bool val );
+		bool getDoPeriodic() const;
+
         bool getFired() const;
 
 	//////////////////////////////////////////////////////////////////
@@ -42,6 +45,7 @@ class RandSpike
 		double lastEvent_;
 		double threshold_;
 		bool fired_;
+		bool doPeriodic_;
 };
 
 #endif // _RANDSPIKE_H
diff --git a/moose-core/builtins/Function.cpp b/moose-core/builtins/Function.cpp
index 79413c1bb0fea17bee2ebaff277423c278421456..ea0c8ae872cc043db64dd0abe7c9e905559316e8 100644
--- a/moose-core/builtins/Function.cpp
+++ b/moose-core/builtins/Function.cpp
@@ -125,9 +125,19 @@ const Cinfo * Function::initCinfo()
         "When *false*, disables event-driven calculation and turns on "
 		"Process-driven calculations. \n"
         "When *true*, enables event-driven calculation and turns off "
-		"Process-driven calculations. \n",
+		"Process-driven calculations. \n"
+		"Defaults to *false*. \n",
         &Function::setUseTrigger,
         &Function::getUseTrigger);
+    static ValueFinfo< Function, bool > doEvalAtReinit(
+        "doEvalAtReinit",
+        "When *false*, disables function evaluation at reinit, and "
+		"just emits a value of zero to any message targets. \n"
+        "When *true*, does a function evaluation at reinit and sends "
+		"the computed value to any message targets. \n"
+		"Defaults to *false*. \n",
+        &Function::setDoEvalAtReinit,
+        &Function::getDoEvalAtReinit);
     static ElementValueFinfo< Function, string > expr(
         "expr",
         "Mathematical expression defining the function. The underlying parser\n"
@@ -257,6 +267,8 @@ const Cinfo * Function::initCinfo()
                 &rate,
                 &derivative,
                 &mode,
+				&useTrigger,
+				&doEvalAtReinit,
                 &expr,
                 &numVars,
                 &inputs,
@@ -316,7 +328,7 @@ static const Cinfo * functionCinfo = Function::initCinfo();
 
 Function::Function(): _t(0.0), _valid(false), _numVar(0), _lastValue(0.0),
     _value(0.0), _rate(0.0), _mode(1),
-    _useTrigger( false ), _stoich(0)
+    _useTrigger( false ), _doEvalAtReinit( false ), _stoich(0)
 {
     _parser.SetVarFactory(_functionAddVar, this);
     _independent = "x0";
@@ -601,6 +613,16 @@ bool Function::getUseTrigger() const
     return _useTrigger;
 }
 
+void Function::setDoEvalAtReinit(bool doEvalAtReinit )
+{
+    _doEvalAtReinit = doEvalAtReinit;
+}
+
+bool Function::getDoEvalAtReinit() const
+{
+    return _doEvalAtReinit;
+}
+
 double Function::getValue() const
 {
     double value = 0.0;
@@ -770,8 +792,11 @@ void Function::reinit(const Eref &e, ProcPtr p)
         _valid = false;
     }
     _t = p->currTime;
-    _value = 0.0;
-    _lastValue = 0.0;
+	if (_doEvalAtReinit) {
+    	_lastValue = _value = getValue();
+	} else {
+    	_lastValue = _value = 0.0;
+	}
     _rate = 0.0;
     switch (_mode){
         case 1: {
diff --git a/moose-core/builtins/Function.h b/moose-core/builtins/Function.h
index ed6c4517b65f230ebf73f43544f1d6e681d0da97..83f2b90381112ba44fc84603ba8da9af5baf69eb 100644
--- a/moose-core/builtins/Function.h
+++ b/moose-core/builtins/Function.h
@@ -92,6 +92,10 @@ class Function
     void setUseTrigger(bool useTrigger);
     bool getUseTrigger() const;
 
+	// set/get flag to do function evaluation at reinit
+    void setDoEvalAtReinit(bool doEvalAtReinit);
+    bool getDoEvalAtReinit() const;
+
     void setNumVar(unsigned int num);
     unsigned int getNumVar() const;
 
@@ -143,6 +147,7 @@ protected:
     double _rate;
     unsigned int _mode;
     bool _useTrigger;
+    bool _doEvalAtReinit;
      // this stores variables received via incoming messages, identifiers of the form x{i} are included in this
     vector<Variable *> _varbuf;
     // this stores variable values pulled by sending request. identifiers of the form y{i} are included in this
diff --git a/moose-core/builtins/HDF5WriterBase.cpp b/moose-core/builtins/HDF5WriterBase.cpp
index 80c47cbe0dcdb371170ed11a4b9db4b1412c3f46..747a2d8dd76bd134ef37fde2380ab5bed7bcc88e 100644
--- a/moose-core/builtins/HDF5WriterBase.cpp
+++ b/moose-core/builtins/HDF5WriterBase.cpp
@@ -84,7 +84,8 @@ hid_t require_group(hid_t file, string path)
 {
     vector<string> pathTokens;
     moose::tokenize(path, "/", pathTokens);
-    hid_t prev = file, current;
+    hid_t prev = file;
+    hid_t current = -1;
     htri_t exists;
     // Open the container for the event maps
     for (unsigned int ii = 0; ii < pathTokens.size(); ++ii){
diff --git a/moose-core/diffusion/Dsolve.cpp b/moose-core/diffusion/Dsolve.cpp
index 61ffb1bc612c01dde5f917fd15faabd54169e0be..d2f27122fe4eb2a9777200d76468671fa4e99cb8 100644
--- a/moose-core/diffusion/Dsolve.cpp
+++ b/moose-core/diffusion/Dsolve.cpp
@@ -867,9 +867,11 @@ void Dsolve::mapXfersBetweenDsolves(
 			Id pool( srcSolve->pools_[i].getId() );
 			assert( pool != Id() );
 			string poolName = pool.element()->getName();
-			size_t prefixLen = poolName.length() - xlen;
-			if ( poolName.rfind( xferPost ) == prefixLen )
-				srcMap[ poolName.substr( 0, prefixLen) ] = i;
+			if ( poolName.length() > xlen ) {
+				size_t prefixLen = poolName.length() - xlen;
+				if ( poolName.rfind( xferPost ) == prefixLen )
+					srcMap[ poolName.substr( 0, prefixLen) ] = i;
+			}
 	}
 
 	const Dsolve* destSolve = reinterpret_cast< const Dsolve* >(
@@ -889,7 +891,8 @@ void Dsolve::mapChansBetweenDsolves( DiffJunction& jn, Id self, Id other)
 {
 	Dsolve* otherSolve = reinterpret_cast< Dsolve* >(
 					other.eref().data() );
-	vector< ConcChanInfo >& ch = channels_;
+	Dsolve* selfSolve = reinterpret_cast< Dsolve* >( self.eref().data() );
+	vector< ConcChanInfo >& ch = selfSolve->channels_;
 	unsigned int outIndex;
 	for ( unsigned int i = 0; i < ch.size(); ++i ) {
 		outIndex = otherSolve->convertIdToPoolIndex( ch[i].otherPool );
@@ -901,7 +904,7 @@ void Dsolve::mapChansBetweenDsolves( DiffJunction& jn, Id self, Id other)
 	// Now set up the other Dsolve.
 	vector< ConcChanInfo >& ch2 = otherSolve->channels_;
 	for ( unsigned int i = 0; i < ch2.size(); ++i ) {
-		outIndex = convertIdToPoolIndex( ch2[i].otherPool );
+		outIndex = selfSolve->convertIdToPoolIndex( ch2[i].otherPool );
 		if ( outIndex != ~0U ) {
 			jn.otherChannels.push_back(i);
 			ch2[i].otherPool = outIndex;  // replace the Id with the index
@@ -933,6 +936,7 @@ void Dsolve::innerBuildMeshJunctions( Id self, Id other, bool selfIsMembraneBoun
 {
 	DiffJunction jn; // This is based on the Spine Dsolver.
 	jn.otherDsolve = other.value();
+	Dsolve* dself = reinterpret_cast< Dsolve* >( self.eref().data() );
 	if ( selfIsMembraneBound ) {
 		mapChansBetweenDsolves( jn, self, other );
 	} else {
@@ -943,8 +947,9 @@ void Dsolve::innerBuildMeshJunctions( Id self, Id other, bool selfIsMembraneBoun
 
 	mapVoxelsBetweenMeshes( jn, self, other );
 
+
 	// printJunction( self, other, jn );
-	junctions_.push_back( jn );
+	dself->junctions_.push_back( jn );
 }
 
 /////////////////////////////////////////////////////////////
diff --git a/moose-core/diffusion/Dsolve.h b/moose-core/diffusion/Dsolve.h
index d6028e62a4c7fb8bdbbe267fa87f54f8174f2c16..b8197ef4bb300255584c63346db7db02fb1591e6 100644
--- a/moose-core/diffusion/Dsolve.h
+++ b/moose-core/diffusion/Dsolve.h
@@ -96,7 +96,7 @@ class Dsolve: public ZombiePoolInterface
 		 * the junction between any specified pair of Dsolves.
 		 * Note that it builds the junction on the 'self' Dsolve.
 		 */
-		void innerBuildMeshJunctions( Id self, Id other, 
+		static void innerBuildMeshJunctions( Id self, Id other, 
 						bool isMembraneBound );
 
 		/// Sets up map of matching pools for diffusion.
@@ -107,7 +107,8 @@ class Dsolve: public ZombiePoolInterface
 						vector< unsigned int >& srcPools, 
 						vector< unsigned int >& destPools,
 						Id src, Id dest );
-		void mapChansBetweenDsolves( DiffJunction& jn, Id self, Id other);
+		static void mapChansBetweenDsolves( DiffJunction& jn, 
+						Id self, Id other);
 
 		/**
 		 * Computes flux through a junction between diffusion solvers.
diff --git a/moose-core/kinetics/Enz.cpp b/moose-core/kinetics/Enz.cpp
index 2362c0b32eb83ce2247021aa762da822b0163776..f41d109ad984d7cde9275d8fea19338147e2d1ee 100644
--- a/moose-core/kinetics/Enz.cpp
+++ b/moose-core/kinetics/Enz.cpp
@@ -136,7 +136,7 @@ void Enz::vRemesh( const Eref& e )
 void Enz::vSetK1( const Eref& e, double v )
 {
 	r1_ = k1_ = v;
-	double volScale = convertConcToNumRateUsingMesh( e, subOut, 1 );
+	double volScale = convertConcToNumRateUsingMesh( e, enzOut, 1 );
 	Km_ = ( k2_ + k3_ ) / ( k1_ * volScale );
 }
 
@@ -160,7 +160,11 @@ double Enz::vGetK2( const Eref& e ) const
 
 void Enz::vSetKcat( const Eref& e, double v )
 {
-	double ratio = k2_ / k3_;
+	double ratio = 4.0;
+	if ( v < EPSILON )
+			v = EPSILON;
+	if (k3_ > EPSILON)
+		ratio = k2_ / k3_;
 	k3_ = v;
 	k2_ = v * ratio;
 	vSetKm( e, Km_ ); // Update k1_ here as well.
@@ -182,7 +186,7 @@ void Enz::vSetKm( const Eref& e, double v )
 {
 	Km_ = v;
 	double volScale =
-		convertConcToNumRateUsingMesh( e, subOut, 1 );
+		convertConcToNumRateUsingMesh( e, enzOut, 1 );
 	k1_ = ( k2_ + k3_ ) / ( v * volScale );
 }
 
@@ -193,14 +197,14 @@ double Enz::vGetKm( const Eref& e ) const
 
 void Enz::vSetNumKm( const Eref& e, double v )
 {
-	double volScale = convertConcToNumRateUsingMesh( e, subOut, 1 );
+	double volScale = convertConcToNumRateUsingMesh( e, enzOut, 1 );
 	k1_ = ( k2_ + k3_ ) / v;
 	Km_ = v / volScale;
 }
 
 double Enz::vGetNumKm( const Eref& e ) const
 {
-	double volScale = convertConcToNumRateUsingMesh( e, subOut, 1 );
+	double volScale = convertConcToNumRateUsingMesh( e, enzOut, 1 );
 	return Km_ * volScale;
 }
 
@@ -208,7 +212,7 @@ void Enz::vSetRatio( const Eref& e, double v )
 {
 	k2_ = v * k3_;
 	double volScale =
-		convertConcToNumRateUsingMesh( e, subOut, 1 );
+		convertConcToNumRateUsingMesh( e, enzOut, 1 );
 
 	k1_ = ( k2_ + k3_ ) / ( Km_ * volScale );
 }
@@ -224,7 +228,7 @@ void Enz::vSetConcK1( const Eref& e, double v )
 		cout << "Enz::vSetConcK1: Warning: value " << v << " too small\n";
 		return;
 	}
-	double volScale = convertConcToNumRateUsingMesh( e, subOut, 1 );
+	double volScale = convertConcToNumRateUsingMesh( e, enzOut, 1 );
 	r1_ = k1_ = v * volScale;
 	Km_ = ( k2_ + k3_ ) / ( v );
 }
diff --git a/moose-core/kinetics/MMenz.cpp b/moose-core/kinetics/MMenz.cpp
index 8b396ceb107d74c824ffda06067c97ce3d6ec28c..cd03b00fa5655e1c1a32c95ce15820fdfdd433d4 100644
--- a/moose-core/kinetics/MMenz.cpp
+++ b/moose-core/kinetics/MMenz.cpp
@@ -133,6 +133,8 @@ double MMenz::vGetNumKm( const Eref& enz ) const
 
 void MMenz::vSetKcat( const Eref& e, double v )
 {
+	if ( v < EPSILON )
+		v = EPSILON;
 	kcat_ = v;
 }
 
diff --git a/moose-core/kinetics/ReadKkit.cpp b/moose-core/kinetics/ReadKkit.cpp
index d3b5bd4154067e43753f4a4e60d1453da2bb7b4d..8172ae90920e225ab8337be73316c1bd0cdca1a8 100644
--- a/moose-core/kinetics/ReadKkit.cpp
+++ b/moose-core/kinetics/ReadKkit.cpp
@@ -1,3 +1,4 @@
+
 /**********************************************************************
 ** This program is part of 'MOOSE', the
 ** Messaging Object Oriented Simulation Environment.
@@ -162,15 +163,17 @@ static void positionCompt( ObjId compt, double side, bool shiftUp )
 	}
 }
 
-void makeSolverOnCompt( Shell* s, const vector< ObjId >& compts,
+void makeSolverOnCompt( Shell* s,const vector< ObjId >& compts,
 				bool isGsolve )
 {
+
 	if ( compts.size() > 3 ) {
 		cout << "Warning: ReadKkit::makeSolverOnCompt: Cannot handle " <<
 			   compts.size() << " chemical compartments\n";
 		return;
 	}
 	vector< Id > stoichVec;
+	/*
 	if ( compts.size() == 2 ) {
 		double side = Field< double >::get( compts[1], "dy" );
 		positionCompt( compts[0], side, true );
@@ -180,7 +183,8 @@ void makeSolverOnCompt( Shell* s, const vector< ObjId >& compts,
 		positionCompt( compts[0], side, true );
 		positionCompt( compts[2], side, false );
 	}
-
+	*/
+	/*
 	for ( vector< ObjId >::const_iterator
 					i = compts.begin(); i != compts.end(); ++i ) {
 		string simpath = i->path() + "/##";
@@ -189,12 +193,14 @@ void makeSolverOnCompt( Shell* s, const vector< ObjId >& compts,
 			ksolve = s->doCreate( "Gsolve", *i, "gsolve", 1 );
 		else
 			ksolve = s->doCreate( "Ksolve", *i, "ksolve", 1 );
+		dsolve = s->doCreate("Dsolve,")
 		Id stoich = s->doCreate( "Stoich", *i, "stoich", 1 );
 		stoichVec.push_back( stoich );
 		Field< Id >::set( stoich, "compartment", *i );
 		Field< Id >::set( stoich, "ksolve", ksolve );
 		Field< string >::set( stoich, "path", simpath );
 	}
+	*/
 	/* Not needed now that we use xfer pools to cross compartments.
 	if ( stoichVec.size() == 2 ) {
 		SetGet1< Id >::set( stoichVec[1], "buildXreacs", stoichVec[0] );
@@ -221,18 +227,25 @@ void setMethod( Shell* s, Id mgr, double simdt, double plotdt,
 	assert( compt != Id() );
 	string simpath2 = mgr.path() + "/##[ISA=StimulusTable]," +
 			mgr.path() + "/##[ISA=PulseGen]";
-
 	string m = lower( method );
+
+	if ( m == "ksolve" || m =="gsl" ||  m == "gssa" || m == "gsolve" ||
+		m == "gillespie" || m == "stochastic" )
+	{
+		cout << " Warning:  Default solver set is Exponential Euler. To set  \'gsl\' or \'gssa\' solver use function mooseaddChemSolver(modelpath,\'solverType\')"<<"\n";
+	}
+	/*
+	
 	if ( m == "rk4" ) {
 		cout << "Warning, not yet implemented. Using rk5 instead\n";
 		m = "rk5";
 	}
 	if ( m == "ksolve" || m == "gsl" ||
 		m == "rk5" || m == "rkf" || m == "rk" ) {
-			makeSolverOnCompt( s, ret, false );
+			makeSolverOnCompt( s, mgr, ret, false );
 	} else if ( m == "gssa" || m == "gsolve" ||
 		m == "gillespie" || m == "stochastic" ) {
-			makeSolverOnCompt( s, ret, true );
+			makeSolverOnCompt( s, mgr,ret, true );
 	} else if ( m == "ee" || m == "neutral" ) {
 			// s->doUseClock( simpath, "process", 4 );
 			// s->doSetClock( 4, simdt );
@@ -242,7 +255,9 @@ void setMethod( Shell* s, Id mgr, double simdt, double plotdt,
 			// s->doUseClock( simpath, "process", 4 );
 			// s->doSetClock( 4, simdt );
 	}
+	*/
 	s->doUseClock( simpath2, "proc", 11 );
+	s->doSetClock( 10, simdt );
 	s->doSetClock( 11, simdt );
 	s->doSetClock( 12, simdt );
 	s->doSetClock( 13, simdt );
diff --git a/moose-core/kinetics/WriteKkit.cpp b/moose-core/kinetics/WriteKkit.cpp
index 0f8533c05c0df96ed788913205ee10f0c4eac097..c32b1fa024b8b7f0a03fecc6da05ff5f5855607c 100644
--- a/moose-core/kinetics/WriteKkit.cpp
+++ b/moose-core/kinetics/WriteKkit.cpp
@@ -278,10 +278,12 @@ void writePlot( ofstream& fout, Id id,
 {
 	string path = id.path();
 	size_t pos = path.find( "/graphs" );
-	if ( pos == string::npos )
+	if ( pos == string::npos ) {
 		pos = path.find( "/moregraphs" );
-		if ( pos == string::npos )
+		if ( pos == string::npos ) {
 			return;
+		}
+	}
 	path = path.substr( pos );
 	fout << "simundump xplot " << path << " 3 524288 \\\n" <<
 	"\"delete_plot.w <s> <d>; edit_plot.D <w>\" " << textcolour << " 0 0 1\n";
diff --git a/moose-core/ksolve/ZombieEnz.cpp b/moose-core/ksolve/ZombieEnz.cpp
index 361ac111f64eefa17f2bfda8c5eb68c06304f747..e73c27acc30fc776603ee8ea71fb61a19499494f 100644
--- a/moose-core/ksolve/ZombieEnz.cpp
+++ b/moose-core/ksolve/ZombieEnz.cpp
@@ -23,6 +23,8 @@
 #include "CplxEnzBase.h"
 #include "ZombieEnz.h"
 
+#define EPSILON 1e-15
+
 const Cinfo* ZombieEnz::initCinfo()
 {
 		//////////////////////////////////////////////////////////////
@@ -118,8 +120,11 @@ void ZombieEnz::vSetKcat( const Eref& e, double v )
 	double k2 = getK2( e );
 	double k3 = getKcat( e );
 	double ratio = 4.0;
-	if ( k3 > 1e-10 )
+	if ( v < EPSILON )
+		v = EPSILON;
+	if ( k3 > EPSILON ) {
 		ratio = k2/k3;
+	}
 	double Km = (k2 + k3) / concK1_;
 	concK1_ = v * (1.0 + ratio) / Km;
 
diff --git a/moose-core/ksolve/ZombieMMenz.cpp b/moose-core/ksolve/ZombieMMenz.cpp
index 95f163a0f7db6115b543bc6b05c0e06bf2d7fc8d..dc400897603a9fcf9414690b40df04234846d0e4 100644
--- a/moose-core/ksolve/ZombieMMenz.cpp
+++ b/moose-core/ksolve/ZombieMMenz.cpp
@@ -22,6 +22,8 @@
 #include "EnzBase.h"
 #include "ZombieMMenz.h"
 
+#define EPSILON 1e-15
+
 const Cinfo* ZombieMMenz::initCinfo()
 {
 		//////////////////////////////////////////////////////////////
@@ -121,6 +123,8 @@ double ZombieMMenz::vGetNumKm( const Eref& e ) const
 
 void ZombieMMenz::vSetKcat( const Eref& e, double v )
 {
+	if ( v < EPSILON )
+		v = EPSILON;
 	stoich_->setMMenzKcat( e, v );
 }
 
diff --git a/moose-core/python/rdesigneur/fixXreacs.py b/moose-core/python/fixXreacs.py
similarity index 99%
rename from moose-core/python/rdesigneur/fixXreacs.py
rename to moose-core/python/fixXreacs.py
index 19379f5f189b60a02a4dcc3e17899509e5ce3e9c..de7bec638be4fcdc85b03f7598fc8758a5706479 100644
--- a/moose-core/python/rdesigneur/fixXreacs.py
+++ b/moose-core/python/fixXreacs.py
@@ -181,7 +181,7 @@ def restoreXreacs( basepath ):
         #print( "Deleting {}".format( i.parent.path ) )
         #print msgs
         moose.delete( i.parent )
-        for j in msgs:
+        for j in msgs[1:]:
             if len( j ) > 0:
                 args = j.split( ' ' )
                 assert( len( args ) == 4 )
diff --git a/moose-core/python/moose/SBML/readSBML.py b/moose-core/python/moose/SBML/readSBML.py
index 06de82bc3a7317fa1d8525be13e86fb1013d3026..d9b0e90f0b531fb446123c5409c3b46e6bfd8de7 100644
--- a/moose-core/python/moose/SBML/readSBML.py
+++ b/moose-core/python/moose/SBML/readSBML.py
@@ -13,14 +13,15 @@
 **           copyright (C) 2003-2017 Upinder S. Bhalla. and NCBS
 Created : Thu May 13 10:19:00 2016(+0530)
 Version
-Last-Updated: Sat Jan 6 1:21:00 2018(+0530)
+Last-Updated: Fri May 21 11:21:00 2018(+0530)
           By:HarshaRani
 **********************************************************************/
 2018
-Jan6 :  - only if valid model exists, then printing the no of compartment,pool,reaction etc
+May 18: - cleanedup and connected cplx pool to correct parent enzyme 
+Jan 6:  - only if valid model exists, then printing the no of compartment,pool,reaction etc
         - at reaction level a check made to see if path exist while creating a new reaction
 2017
-Oct 4 : - loadpath is cleaned up
+Oct 4:  - loadpath is cleaned up
 Sep 13: - After EnzymaticReaction's k2 is set, explicity ratio is set to 4 to make sure it balance.
         - If units are defined in the rate law for the reaction then check is made and if not in milli mole the base unit 
           then converted to milli unit
@@ -31,11 +32,11 @@ Sep 12: - Now mooseReadSBML return model and errorFlag
         - errorFlag is set for Rules (for now piecewise is set which is not read user are warned)
         - rateLaw are also calculated depending on units and number of substrates/product
 
-Sep 8 : -functionDefinitions is read, 
+Sep 8 : - functionDefinitions is read, 
         - if Kf and Kb unit are not defined then checked if substance units is defined and depending on this unit Kf and Kb is calculated
             -kf and kb units is not defined and if substance units is also not defined validator fails 
-Aug 9 : a check made to for textColor while adding to Annotator
-Aug 8 : removed "findCompartment" function to chemConnectUtil and imported the function from the same file
+Aug 9 : - a check made to for textColor while adding to Annotator
+Aug 8 : - removed "findCompartment" function to chemConnectUtil and imported the function from the same file
 
    TODO in
     -Compartment
@@ -251,7 +252,7 @@ def checkGroup(basePath,model):
                             groupInfo[p.getId()] =[mem.getIdRef()]
     return groupInfo
 def setupEnzymaticReaction(enz, groupName, enzName,
-                           specInfoMap, modelAnnotaInfo):
+                           specInfoMap, modelAnnotaInfo,deletcplxMol):
     enzPool = (modelAnnotaInfo[groupName]["enzyme"])
     enzPool = str(idBeginWith(enzPool))
     enzParent = specInfoMap[enzPool]["Mpath"]
@@ -259,13 +260,14 @@ def setupEnzymaticReaction(enz, groupName, enzName,
     cplx = str(idBeginWith(cplx))
     complx = moose.element(specInfoMap[cplx]["Mpath"].path)
     enzyme_ = moose.Enz(enzParent.path + '/' + enzName)
-    moose.move(complx, enzyme_)
-    moose.connect(enzyme_, "cplx", complx, "reac")
+    complx1 = moose.Pool(enzyme_.path+'/'+moose.element(complx).name)
+    specInfoMap[cplx]["Mpath"] = complx1
+    moose.connect(enzyme_, "cplx", complx1, "reac")
     moose.connect(enzyme_, "enz", enzParent, "reac")
-
     sublist = (modelAnnotaInfo[groupName]["substrate"])
     prdlist = (modelAnnotaInfo[groupName]["product"])
-
+    deletcplxMol.append(complx.path)
+    complx = complx1
     for si in range(0, len(sublist)):
         sl = sublist[si]
         sl = str(idBeginWith(sl))
@@ -280,7 +282,6 @@ def setupEnzymaticReaction(enz, groupName, enzName,
 
     if (enz.isSetNotes):
         pullnotes(enz, enzyme_)
-
     return enzyme_, True
 
 
@@ -547,7 +548,7 @@ def createReaction(model, specInfoMap, modelAnnotaInfo, globparameterIdValue,fun
     # ToDo
     # -- I need to check here if any substance/product is if ( constant == true && bcondition == false)
     # cout <<"The species "<< name << " should not appear in reactant or product as per sbml Rules"<< endl;
-
+    deletecplxMol = []
     errorFlag = True
     reactSBMLIdMooseId = {}
     msg = ""
@@ -589,7 +590,7 @@ def createReaction(model, specInfoMap, modelAnnotaInfo, globparameterIdValue,fun
         if (groupName != "" and list(
                 modelAnnotaInfo[groupName]["stage"])[0] == 3):
             reaction_, reactionCreated = setupEnzymaticReaction(
-                reac, groupName, rName, specInfoMap, modelAnnotaInfo)
+                reac, groupName, rName, specInfoMap, modelAnnotaInfo,deletecplxMol)
             reaction_.k3 = modelAnnotaInfo[groupName]['k3']
             reaction_.concK1 = modelAnnotaInfo[groupName]['k1']
             reaction_.k2 = modelAnnotaInfo[groupName]['k2']
@@ -710,6 +711,9 @@ def createReaction(model, specInfoMap, modelAnnotaInfo, globparameterIdValue,fun
                         elif reaction_.className == "MMenz":
                             reaction_.kcat = kfvalue
                             reaction_.Km = kbvalue
+    for l in deletecplxMol:
+        if moose.exists(l):
+            moose.delete(moose.element(l))
     return (errorFlag, msg)
 
 
@@ -1151,6 +1155,7 @@ def createSpecies(basePath, model, comptSbmlidMooseIdMap,
                     poolInfo.color = v
                 elif k == 'Color':
                     poolInfo.textColor = v
+                    
             specInfoMap[sId] = {
                 "Mpath": poolId,
                 "const": constant,
diff --git a/moose-core/python/moose/SBML/writeSBML.py b/moose-core/python/moose/SBML/writeSBML.py
index 8491b46a8aba3bfb9b2359fddce84931da0c3e28..8124611b4802e3f1b27ff2af7115e45371ae174d 100644
--- a/moose-core/python/moose/SBML/writeSBML.py
+++ b/moose-core/python/moose/SBML/writeSBML.py
@@ -13,11 +13,12 @@
 **           copyright (C) 2003-2017 Upinder S. Bhalla. and NCBS
 Created : Friday May 27 12:19:00 2016(+0530)
 Version
-Last-Updated: Sat 6 Jan 01:10:00 2018(+0530)
+Last-Updated: Mon 30 Apr 15:10:00 2018(+0530)
           By: HarshaRani
 **********************************************************************/
 /****************************
 2018
+Apr 30: indentation corrected while writting annotation for enzymecomplex
 Jan 6: for Product_formation_, k3 units depends on noofSub, prd was passed which is fixed
 2017
 Dec 15: If model path exists is checked
@@ -143,7 +144,7 @@ def mooseWriteSBML(modelpath, filename, sceneitems={}):
                 if moose.exists(key.path+'/info'):
                     ginfo = moose.element(key.path+'/info')
                 else:
-                    moose.Annotator(key.path+'/info')
+                    ginfo = moose.Annotator(key.path+'/info')
                 groupCompartment = findCompartment(key)
                 if ginfo.color != '':
                     grpAnno = "<moose:GroupAnnotation>"
@@ -231,7 +232,6 @@ def writeEnz(modelpath, cremodel_, sceneitems,groupInfo):
                 compt = comptVec.name + "_" + \
                     str(comptVec.getId().value) + "_" + \
                     str(comptVec.getDataIndex()) + "_"
-            
             #Writting out S+E -> SE*
             enzsetId = str(idBeginWith(cleanEnzname +
                                          "_" + str(enz.getId().value) +
@@ -254,7 +254,6 @@ def writeEnz(modelpath, cremodel_, sceneitems,groupInfo):
                         enzAnno = enzAnno + "<moose:enzyme>" + \
                             (str(idBeginWith(convertSpecialChar(
                                 nameList_[i])))) + "</moose:enzyme>\n"
-
                     #Finding Substrate, (S)
                     enzSub = enz.neighbors["sub"]
                     if not enzSub:
@@ -277,7 +276,6 @@ def writeEnz(modelpath, cremodel_, sceneitems,groupInfo):
                                 enzAnno = enzAnno + "<moose:product>" + \
                                     nameList_[i] + "</moose:product>\n"
                             foundEnzymeComplex = True
-
             if foundEnzymeComplex:
                 # Only if S+E->SE* found, reaction is created
                 enzyme = cremodel_.createReaction()
@@ -318,15 +316,16 @@ def writeEnz(modelpath, cremodel_, sceneitems,groupInfo):
                 printParameters(kl, "k1", k1, unit)
                 punit = parmUnit(noofPrd - 1, cremodel_)
                 printParameters(kl, "k2", k2, punit)
-
                 if groupName != moose.element('/'):
                     if groupName not in groupInfo:
-                        groupInfo[groupName]=[enzsetId]
+                        #groupInfo[groupName]=[enzsetId]
+                        groupInfo[groupName]=[nameList_[0]]
                     else:
-                        groupInfo[groupName].append(enzsetId)       
+                        #groupInfo[groupName].append(enzsetId)
+                        groupInfo[groupName].append(nameList_[0])
             else:
                 if secplxerror:
-                    print ("\'"+enz.name+"\' this enzyme is not written to file because,"+ secplxerror)
+                    print ("\'"+enz.parent.name+ "/"+enz.name+"\' this enzyme is not written to file because,"+ secplxerror)
             
             #Here SE* -> E+ P
             foundEnzymeEP = False
@@ -335,6 +334,7 @@ def writeEnz(modelpath, cremodel_, sceneitems,groupInfo):
                                         "_" + str(enz.getDataIndex()) +
                                         "_" + "Product_formation_"))
             cplxeperror = ""
+            enzAnno2 = ""
             #enzSubt = ""
             enzOut = enz.neighbors["enzOut"]
             if not enzOut:
@@ -375,16 +375,15 @@ def writeEnz(modelpath, cremodel_, sceneitems,groupInfo):
                             for i in range(0, len(nameList_)):
                                 enzAnno2 = enzAnno2 + "<moose:product>" + \
                                             nameList_[i] + "</moose:product>\n"
-                                enzAnno2 += "<moose:groupName>" + cleanEnzname + "_" + \
-                                str(enz.getId().value) + "_" + \
-                                str(enz.getDataIndex()) + "_" + "</moose:groupName>\n"
-                                enzAnno2 += "<moose:stage>2</moose:stage> \n"
-                                if enzannoexist:
-                                    enzAnno2 = enzAnno2 + enzGpnCorCol
-                                enzAnno2 += "</moose:EnzymaticReaction>"
-
-                            foundEnzymeEP = True
-            
+                        enzAnno2 += "<moose:groupName>" + cleanEnzname + "_" + \
+                            str(enz.getId().value) + "_" + \
+                            str(enz.getDataIndex()) + "_" + "</moose:groupName>\n"
+                        enzAnno2 += "<moose:stage>2</moose:stage> \n"
+                        if enzannoexist:
+                            enzAnno2 = enzAnno2 + enzGpnCorCol
+                        enzAnno2 += "</moose:EnzymaticReaction>"
+
+                        foundEnzymeEP = True
             if foundEnzymeEP:
                 enzyme = cremodel_.createReaction()
                 enzyme.setId(enzsetIdP)
@@ -407,9 +406,11 @@ def writeEnz(modelpath, cremodel_, sceneitems,groupInfo):
                 printParameters(kl, "k3", k3, unit)
                 if groupName != moose.element('/'):
                     if groupName not in groupInfo:
-                        groupInfo[groupName]=[enzsetIdP]
+                        #groupInfo[groupName]=[nameList_[0]]
+                        pass
                     else:
-                        groupInfo[groupName].append(enzsetIdP)
+                        #groupInfo[groupName].append(nameList_[0])
+                        pass
             else:
                 print (cplxeperror)
         elif(enz.className == "MMenz" or enz.className == "ZombieMMenz"):
@@ -776,6 +777,7 @@ def writeFunc(modelpath, cremodel_):
     foundFunc = False
     for func in funcs:
         if func:
+            #not neccessary parent is compartment can be group also
             if func.parent.className == "CubeMesh" or func.parent.className == "CyclMesh":
                 if len(moose.element(func).neighbors["valueOut"]) > 0:
                     funcEle = moose.element(
@@ -785,8 +787,16 @@ def writeFunc(modelpath, cremodel_):
                     funcEle.name + "_" + str(funcEle.getId().value) + "_" + str(funcEle.getDataIndex()) + "_"))
                     expr = " "
                     expr = str(moose.element(func).expr)
-                    if not expr:
+                    if expr:
                         foundFunc = True
+                        item = func.path + '/x[0]'
+                        sumtot = moose.element(item).neighbors["input"]
+                        for i in range(0, len(sumtot)):
+                            v = "x" + str(i)
+                            if v in expr:
+                                z = str(idBeginWith(str(convertSpecialChar(sumtot[i].name + "_" + str(moose.element(
+                                    sumtot[i]).getId().value) + "_" + str(moose.element(sumtot[i]).getDataIndex())) + "_")))
+                                expr = expr.replace(v, z)
             else:
                 foundFunc = True
                 fName = idBeginWith(convertSpecialChar(func.parent.name +
diff --git a/moose-core/python/moose/chemMerge/merge.py b/moose-core/python/moose/chemMerge/merge.py
index 49d7d7162b9ee6ee4c98d86b5769d6bc68967343..d3d800582fd3428c253ce0fed2716b64889b18d7 100644
--- a/moose-core/python/moose/chemMerge/merge.py
+++ b/moose-core/python/moose/chemMerge/merge.py
@@ -12,7 +12,7 @@
 #**           copyright (C) 2003-2017 Upinder S. Bhalla. and NCBS
 #Created : Friday Dec 16 23:19:00 2016(+0530)
 #Version
-#Last-Updated: Wed Oct 25 16:25:33 2017(+0530)
+#Last-Updated: Wed May 21 11:52:33 2018(+0530)
 #         By: Harsha
 #**********************************************************************/
 
@@ -36,17 +36,21 @@
 #       --- if same Enz Name and same sub and prd then nothing is copied
 #       --- if same Enz Name but sub or prd is different then duplicated and copied
 #   -- Function are copied only if destination pool to which its suppose to connect doesn't exist with function of its own
+#       which is a limitation in moose that no function can be connected to same pool
 #
 '''
 Change log
-Oct 25: line to load SBML file was commented, which is uncommented now and also while copying MMenz had a problem which also cleaned up
-Oct 14: absolute import with mtypes just for python3
+May 21 : Instead of A and B changed to S and D (source and destination), 
+        - at Pool level Neutral and its objected where copied, but again at Enz and Reac level copying was done which caused duplicates which is taken care
+        - If Neutral object name is changed for destination, then change made to source file which would be easy to copy else path issue will come
+Oct 25 : line to load SBML file was commented, which is uncommented now and also while copying MMenz had a problem which also cleaned up
+Oct 14 : absolute import with mtypes just for python3
 
-Oct 12: clean way of cheking the type of path provided, filepath,moose obj, moose path are taken,
+Oct 12 : clean way of cheking the type of path provided, filepath,moose obj, moose path are taken,
         if source is empty then nothing to copy, 
         if destination was empty list is update with new object
 
-Oct 11: missing group are copied instead of creating one in new path which also copies Annotator info
+Oct 11 : missing group are copied instead of creating one in new path which also copies Annotator info
         earlier if user asked to save the model, it was saving default to kkit format, now user need to run the command to save (if this is run in command)
         To check: When Gui is allowed to merge 2 models, need to see what happens
 
@@ -113,34 +117,33 @@ def mergeChemModel(src,des):
         grpNotcopiedyet = []
         dictComptA = dict( [ (i.name,i) for i in moose.wildcardFind(modelA+'/##[ISA=ChemCompt]') ] )
         dictComptB = dict( [ (i.name,i) for i in moose.wildcardFind(modelB+'/##[ISA=ChemCompt]') ] )
+                
         poolNotcopiedyet = []
         if len(dictComptA):
             for key in list(dictComptA.keys()):
                 if key not in dictComptB:
-                    # if compartmentname from modelB does not exist in modelA, then copy
+                    # if compartment name from modelB does not exist in modelA, then copy
                     copy = moose.copy(dictComptA[key],moose.element(modelB))
+
                     dictComptB[key]=moose.element(copy)
                 else:
-                    #if compartmentname from modelB exist in modelA,
+                    #if compartment name from modelB exist in modelA,
                     #volume is not same, then change volume of ModelB same as ModelA
                     if abs(dictComptB[key].volume - dictComptA[key].volume):
                         #hack for now
                         while (abs(dictComptB[key].volume - dictComptA[key].volume) != 0.0):
                             dictComptA[key].volume = float(dictComptB[key].volume)
                     dictComptB = dict( [ (i.name,i) for i in moose.wildcardFind(modelB+'/##[ISA=ChemCompt]') ] )
-
+                    
                     #Mergering pool
-                    poolMerge(dictComptB[key],dictComptA[key],poolNotcopiedyet)
-
-            if grpNotcopiedyet:
-                # objA = moose.element(comptA).parent.name
-                # if not moose.exists(objA+'/'+comptB.name+'/'+bpath.name):
-                #   print bpath
-                #   moose.copy(bpath,moose.element(objA+'/'+comptB.name))
-                pass
+                    poolMerge(dictComptA[key],dictComptB[key],poolNotcopiedyet)
+
+            
             comptBdict =  comptList(modelB)
+
             poolListinb = {}
             poolListinb = updatePoolList(comptBdict)
+            
             R_Duplicated, R_Notcopiedyet,R_Daggling = [], [], []
             E_Duplicated, E_Notcopiedyet,E_Daggling = [], [], []
             for key in list(dictComptA.keys()):
@@ -148,27 +151,27 @@ def mergeChemModel(src,des):
                 funcExist,funcNotallowed = functionMerge(dictComptB,dictComptA,key)
 
                 poolListinb = updatePoolList(dictComptB)
-                R_Duplicated,R_Notcopiedyet,R_Daggling = reacMerge(dictComptB,dictComptA,key,poolListinb)
+                R_Duplicated,R_Notcopiedyet,R_Daggling = reacMerge(dictComptA,dictComptB,key,poolListinb)
 
                 poolListinb = updatePoolList(dictComptB)
                 E_Duplicated,E_Notcopiedyet,E_Daggling = enzymeMerge(dictComptB,dictComptA,key,poolListinb)
-            '''
-            if isinstance(src, str):
-                if os.path.isfile(src) == True:
-                    spath, sfile = os.path.split(src)
-                else:
-                    sfile = src
-            else:
-                sfile = src
-            if isinstance(des, str):
-                print " A str",des
-                if os.path.isfile(des) == True:
-                    dpath, dfile = os.path.split(des)
-                else:
-                    dfile = des
-            else:
-                dfile = des
-            '''
+            
+            # if isinstance(src, str):
+            #     if os.path.isfile(src) == True:
+            #         spath, sfile = os.path.split(src)
+            #     else:
+            #         sfile = src
+            # else:
+            #     sfile = src
+            # if isinstance(des, str):
+            #     print " A str",des
+            #     if os.path.isfile(des) == True:
+            #         dpath, dfile = os.path.split(des)
+            #     else:
+            #         dfile = des
+            # else:
+            #     dfile = des
+            
             print("\nThe content of %s (src) model is merged to %s (des)." %(sfile, dfile))
             # Here any error or warning during Merge is written it down
             if funcExist:
@@ -216,6 +219,7 @@ def mergeChemModel(src,des):
                     print ("Enzyme:")
                     for ed in list(E_Daggling):
                         print ("%s " %str(ed.name))
+            
             ## Model is saved
             print ("\n ")
             print ('\nMerged model is available under moose.element(\'%s\')' %(modelB))
@@ -249,6 +253,7 @@ def mergeChemModel(src,des):
             #     print ('  If you are in python terminal you could save \n   >moose.mooseWriteKkit(\'%s\',\'filename.g\')' %(modelB))
             #     print ('  If you are in python terminal you could save \n   >moose.mooseWriteSBML(\'%s\',\'filename.g\')' %(modelB))
             #return modelB
+        
     else:
         print ('\nSource file has no objects to copy(\'%s\')' %(modelA))
         return moose.element('/')
@@ -375,62 +380,72 @@ def deleteSolver(modelRoot):
             if moose.exists((st_ksolve).path):
                 moose.delete(st_ksolve)
 
-def poolMerge(comptA,comptB,poolNotcopiedyet):
-
-    aCmptGrp = moose.wildcardFind(comptA.path+'/#[TYPE=Neutral]')
-    aCmptGrp = aCmptGrp +(moose.element(comptA.path),)
-
-    bCmptGrp = moose.wildcardFind(comptB.path+'/#[TYPE=Neutral]')
-    bCmptGrp = bCmptGrp +(moose.element(comptB.path),)
-
-    objA = moose.element(comptA.path).parent.name
-    objB = moose.element(comptB.path).parent.name
-    for bpath in bCmptGrp:
-        grp_cmpt = ((bpath.path).replace(objB,objA)).replace('[0]','')
-        if moose.exists(grp_cmpt) :
-            if moose.element(grp_cmpt).className != bpath.className:
+def poolMerge(comptS,comptD,poolNotcopiedyet):
+    #Here from source file all the groups are check if exist, if doesn't exist then create those groups
+    #Then for that group pools are copied
+    SCmptGrp = moose.wildcardFind(comptS.path+'/#[TYPE=Neutral]')
+    SCmptGrp = SCmptGrp +(moose.element(comptS.path),)
+    
+    DCmptGrp = moose.wildcardFind(comptD.path+'/#[TYPE=Neutral]')
+    DCmptGrp = DCmptGrp +(moose.element(comptD.path),)
+    
+    objS = moose.element(comptS.path).parent.name
+    objD = moose.element(comptD.path).parent.name
+    
+    for spath in SCmptGrp:
+        grp_cmpt = ((spath.path).replace(objS,objD)).replace('[0]','')
+        if moose.exists(grp_cmpt):
+            #If path exist, but its not the Neutral obj then creating a neutral obj with _grp
+            #It has happened that pool, reac, enz name might exist with the same name, which when tried to create a group
+            # it silently ignored the path and object copied under that pool instead of Group
+            if moose.element(grp_cmpt).className != spath.className:
                 grp_cmpt = grp_cmpt+'_grp'
-                bpath.name = bpath.name+"_grp"
-                l = moose.Neutral(grp_cmpt)
+                moose.Neutral(grp_cmpt)
+                # If group name is changed while creating in destination, then in source file the same is changed,
+                # so that later path issue doens't come 
+                spath.name = spath.name+'_grp'
         else:
-            #moose.Neutral(grp_cmpt)
-            src = bpath
-            srcpath = (bpath.parent).path
-            des = srcpath.replace(objB,objA)
-            moose.copy(bpath,moose.element(des))
-
-        apath = moose.element(bpath.path.replace(objB,objA))
-
-        bpoollist = moose.wildcardFind(bpath.path+'/#[ISA=PoolBase]')
-        apoollist = moose.wildcardFind(apath.path+'/#[ISA=PoolBase]')
-        for bpool in bpoollist:
-            if bpool.name not in [apool.name for apool in apoollist]:
-                copied = copy_deleteUnlyingPoolObj(bpool,apath)
+            #Neutral obj from src if doesn't exist in destination,then create src's Neutral obj in des
+            src = spath
+            srcpath = (spath.parent).path
+            des = srcpath.replace(objS,objD)
+            moose.Neutral(moose.element(des).path+'/'+spath.name)
+        
+        dpath = moose.element(spath.path.replace(objS,objD))
+        spoollist = moose.wildcardFind(spath.path+'/#[ISA=PoolBase]')
+        dpoollist = moose.wildcardFind(dpath.path+'/#[ISA=PoolBase]')
+        #check made, for a given Neutral or group if pool doesn't exist then copied
+        # but some pool if enzyme cplx then there are holded untill that enzyme is copied in
+        # `enzymeMerge` function        
+        for spool in spoollist:
+            if spool.name not in [dpool.name for dpool in dpoollist]:
+                copied = copy_deleteUnlyingPoolObj(spool,dpath)
                 if copied == False:
                     #hold it for later, this pool may be under enzyme, as cplx
-                    poolNotcopiedyet.append(bpool)
-
+                    poolNotcopiedyet.append(spool)
+    
 def copy_deleteUnlyingPoolObj(pool,path):
     # check if this pool is under compartement or under enzyme?(which is enzyme_cplx)
     # if enzyme_cplx then don't copy untill this perticular enzyme is copied
-    # case: This enzyme_cplx might exist in modelA if enzyme exist
-    # which will automatically copie's the pool
+    # case: This enzyme_cplx might exist in modelA if enzyme exist then this
+    # will automatically copie's the pool
     copied = False
 
     if pool.parent.className not in ["Enz","ZombieEnz","MMenz","ZombieMMenz"]:
-        poolcopied = moose.copy(pool,path)
-        copied = True
-        # deleting function and enzyme which gets copied if exist under pool
-        # This is done to ensure daggling function / enzyme not copied.
-        funclist = []
-        for types in ['setConc','setN','increment']:
-            funclist.extend(moose.element(poolcopied).neighbors[types])
-
-        for fl in funclist:
-            moose.delete(fl)
-        enzlist = moose.element(poolcopied).neighbors['reac']
-        for el in list(set(enzlist)):
-            moose.delete(el.path)
+         if path.className in ["Neutral","CubeMesh","CyclMesh"]:
+            poolcopied = moose.copy(pool,path)
+            copied = True
+            # deleting function and enzyme which gets copied if exist under pool
+            # This is done to ensure daggling function / enzyme not copied.
+            funclist = []
+            for types in ['setConc','setN','increment']:
+                funclist.extend(moose.element(poolcopied).neighbors[types])
+
+            for fl in funclist:
+                moose.delete(fl)
+            enzlist = moose.element(poolcopied).neighbors['reac']
+            for el in list(set(enzlist)):
+                moose.delete(el.path)
     return copied
 
 def updatePoolList(comptAdict):
@@ -439,88 +454,90 @@ def updatePoolList(comptAdict):
         poolListina[key] = plist
     return poolListina
 
-def enzymeMerge(comptA,comptB,key,poolListina):
+def enzymeMerge(comptD,comptS,key,poolListind):
     war_msg = ""
     RE_Duplicated, RE_Notcopiedyet, RE_Daggling = [], [], []
-    comptApath = moose.element(comptA[key]).path
-    comptBpath = moose.element(comptB[key]).path
-    objA = moose.element(comptApath).parent.name
-    objB = moose.element(comptBpath).parent.name
-    enzyListina = moose.wildcardFind(comptApath+'/##[ISA=EnzBase]')
-    enzyListinb = moose.wildcardFind(comptBpath+'/##[ISA=EnzBase]')
-    for eb in enzyListinb:
-        eBsubname, eBprdname = [],[]
-        eBsubname = subprdList(eb,"sub")
-        eBprdname = subprdList(eb,"prd")
+    comptDpath = moose.element(comptD[key]).path
+    comptSpath = moose.element(comptS[key]).path
+    objD = moose.element(comptDpath).parent.name
+    objS = moose.element(comptSpath).parent.name
+    #nzyListina => enzyListind
+
+    enzyListind = moose.wildcardFind(comptDpath+'/##[ISA=EnzBase]')
+    enzyListins = moose.wildcardFind(comptSpath+'/##[ISA=EnzBase]')
+    for es in enzyListins:
+        eSsubname, eSprdname = [],[]
+        eSsubname = subprdList(es,"sub")
+        eSprdname = subprdList(es,"prd")
         allexists, allexistp = False, False
         allclean = False
 
-        poolinAlist = poolListina[findCompartment(eb).name]
-        for pA in poolinAlist:
-            if eb.parent.name == pA.name:
-                eapath = eb.parent.path.replace(objB,objA)
+        poolinDlist = poolListind[findCompartment(es).name]
+        for pD in poolinDlist:
+            if es.parent.name == pD.name:
+                edpath = es.parent.path.replace(objS,objD)
 
-                if not moose.exists(eapath+'/'+eb.name):
+                if not moose.exists(edpath+'/'+es.name):
                     #This will take care
                     #  -- If same enzparent name but different enzyme name
                     #  -- or different parent/enzyme name
-                    if eBsubname and eBprdname:
-                        allexists = checkexist(eBsubname,objB,objA)
-                        allexistp = checkexist(eBprdname,objB,objA)
+                    if eSsubname and eSprdname:
+                        allexists = checkexist(eSsubname,objS,objD)
+                        allexistp = checkexist(eSprdname,objS,objD)
                         if allexists and allexistp:
-                            enzPool = moose.element(pA.path)
-                            eapath = eb.parent.path.replace(objB,objA)
-                            enz = moose.element(moose.copy(eb,moose.element(eapath)))
+                            enzPool = moose.element(pD.path)
+                            edpath = es.parent.path.replace(objS,objD)
+                            enz = moose.element(moose.copy(es,moose.element(edpath)))
                             enzPool = enz.parent
-                            if eb.className in ["ZombieEnz","Enz"]:
+                            if es.className in ["ZombieEnz","Enz"]:
                                 moose.connect(moose.element(enz),"enz",enzPool,"reac")
-                            if eb.className in ["ZombieMMenz","MMenz"]:
+                            if es.className in ["ZombieMMenz","MMenz"]:
                                 moose.connect(enzPool,"nOut",enz,"enzDest")
-                            connectObj(enz,eBsubname,"sub",comptA,war_msg)
-                            connectObj(enz,eBprdname,"prd",comptA,war_msg)
+                            connectObj(enz,eSsubname,"sub",comptD,war_msg)
+                            connectObj(enz,eSprdname,"prd",comptD,war_msg)
                             allclean = True
                         else:
                             # didn't find sub or prd for this Enzyme
-                            RE_Notcopiedyet.append(eb)
+                            RE_Notcopiedyet.append(es)
                     else:
                         #   -- it is dagging reaction
-                        RE_Daggling.append(eb)
+                        RE_Daggling.append(es)
                 else:
                     #Same Enzyme name
                     #   -- Same substrate and product including same volume then don't copy
                     #   -- different substrate/product or if sub/prd's volume is different then DUPLICATE the Enzyme
                     allclean = False
-                    ea = moose.element(eb.path.replace(objB,objA))
-                    eAsubname = subprdList(ea,"sub")
-                    eBsubname = subprdList(eb,"sub")
-                    hasSamenoofsublen,hasSameS,hasSamevols = same_len_name_vol(eAsubname,eBsubname)
-
-                    eAprdname = subprdList(ea,"prd")
-                    eBprdname = subprdList(eb,"prd")
-                    hasSamenoofprdlen,hasSameP,hasSamevolp = same_len_name_vol(eAprdname,eBprdname)
+                    ed = moose.element(es.path.replace(objS,objD))
+                    eDsubname = subprdList(ed,"sub")
+                    eSsubname = subprdList(es,"sub")
+                    hasSamenoofsublen,hasSameS,hasSamevols = same_len_name_vol(eDsubname,eSsubname)
+
+                    eDprdname = subprdList(ed,"prd")
+                    eSprdname = subprdList(es,"prd")
+                    hasSamenoofprdlen,hasSameP,hasSamevolp = same_len_name_vol(eDprdname,eSprdname)
                     if not all((hasSamenoofsublen,hasSameS,hasSamevols,hasSamenoofprdlen,hasSameP,hasSamevolp)):
                         # May be different substrate or product or volume of Sub/prd may be different,
                         # Duplicating the enzyme
-                        if eBsubname and eBprdname:
+                        if eSsubname and eSprdname:
                             allexists,allexistp = False,False
-                            allexists = checkexist(eBsubname,objB,objA)
-                            allexistp = checkexist(eBprdname,objB,objA)
+                            allexists = checkexist(eSsubname,objS,objD)
+                            allexistp = checkexist(eSprdname,objS,objD)
                             if allexists and allexistp:
-                                eb.name = eb.name+"_duplicated"
-                                if eb.className in ["ZombieEnz","Enz"]:
-                                    eapath = eb.parent.path.replace(objB,objA)
-                                    enz = moose.copy(eb,moose.element(eapath))
-                                    moose.connect(enz, 'enz', eapath, 'reac' )
-
-                                if eb.className in ["ZombieMMenz","MMenz"]:
-                                    eapath = eb.parent.path.replace(objB,objA)
-                                    enz = moose.copy(eb,moose.element(eapath))
+                                es.name = es.name+"_duplicated"
+                                if es.className in ["ZombieEnz","Enz"]:
+                                    edpath = es.parent.path.replace(objS,objD)
+                                    enz = moose.copy(es,moose.element(edpath))
+                                    moose.connect(enz, 'enz', edpath, 'reac' )
+
+                                if es.className in ["ZombieMMenz","MMenz"]:
+                                    edpath = es.parent.path.replace(objS,objD)
+                                    enz = moose.copy(es,moose.element(edpath))
                                     enzinfo = moose.Annotator(enz.path+'/info')
                                     moose.connect(moose.element(enz).parent,"nOut",moose.element(enz),"enzDest")
                                     #moose.connect(moose.element(enz),"enz",moose.element(enz).parent,"reac")
 
-                                connectObj(enz,eBsubname,"sub",comptA,war_msg)
-                                connectObj(enz,eBprdname,"prd",comptA,war_msg)
+                                connectObj(enz,eSsubname,"sub",comptD,war_msg)
+                                connectObj(enz,eSprdname,"prd",comptD,war_msg)
                                 RE_Duplicated.append(enz)
                                 allclean = True
                             else:
@@ -531,51 +548,53 @@ def enzymeMerge(comptA,comptB,key,poolListina):
                     if not allclean:
                         # didn't find sub or prd for this enzyme
                         #   --  it may be connected Enzyme cplx
-                        if eBsubname and eBprdname:
-                            RE_Notcopiedyet.append(eb)
+                        if eSsubname and eSprdname:
+                            RE_Notcopiedyet.append(es)
                         else:
-                            RE_Daggling.append(eb)
+                            RE_Daggling.append(es)
 
     return RE_Duplicated,RE_Notcopiedyet,RE_Daggling
 
-def reacMerge(comptA,comptB,key,poolListina):
+def reacMerge(comptS,comptD,key,poolListina):
     RE_Duplicated, RE_Notcopiedyet, RE_Daggling = [], [], []
     war_msg = ""
-    comptApath = moose.element(comptA[key]).path
-    comptBpath = moose.element(comptB[key]).path
-    objA = moose.element(comptApath).parent.name
-    objB = moose.element(comptBpath).parent.name
-    reacListina = moose.wildcardFind(comptApath+'/##[ISA=ReacBase]')
-    reacListinb = moose.wildcardFind(comptBpath+'/##[ISA=ReacBase]')
-    for rb in reacListinb:
-        rBsubname, rBprdname = [],[]
-        rBsubname = subprdList(rb,"sub")
-        rBprdname = subprdList(rb,"prd")
+    comptSpath = moose.element(comptS[key]).path
+    comptDpath = moose.element(comptD[key]).path
+    objS = moose.element(comptSpath).parent.name
+    objD = moose.element(comptDpath).parent.name
+    
+    reacListins = moose.wildcardFind(comptSpath+'/##[ISA=ReacBase]')
+    reacListind = moose.wildcardFind(comptDpath+'/##[ISA=ReacBase]')
+    
+    for rs in reacListins:
+        rSsubname, rSprdname = [],[]
+        rSsubname = subprdList(rs,"sub")
+        rSprdname = subprdList(rs,"prd")
         allexists, allexistp = False, False
         allclean = False
 
-        if rb.name not in [ra.name for ra in reacListina]:
+        if rs.name not in [rd.name for rd in reacListind]:
             # reaction name not found then copy
             # And assuming that pools are copied earlier EXPECT POOL CPLX
-            #To be assured the it takes correct compartment name incase reaction sub's
-            #belongs to different compt
-            key = findCompartment(rb).name
-            if rBsubname and rBprdname:
-                allexists =  checkexist(rBsubname,objB,objA)
-                allexistp = checkexist(rBprdname,objB,objA)
+            # To be assured the it takes correct compartment name incase reaction sub's
+            # belongs to different compt
+            key = findCompartment(rs).name
+            if rSsubname and rSprdname:
+                allexists =  checkexist(rSsubname,objS,objD)
+                allexistp =  checkexist(rSprdname,objS,objD)
                 if allexists and allexistp:
-                    rapath = rb.parent.path.replace(objB,objA)
-                    reac = moose.copy(rb,moose.element(rapath))
-                    connectObj(reac,rBsubname,"sub",comptA,war_msg)
-                    connectObj(reac,rBprdname,"prd",comptA,war_msg)
+                    rdpath = rs.parent.path.replace(objS,objD)
+                    reac = moose.copy(rs,moose.element(rdpath))
+                    connectObj(reac,rSsubname,"sub",comptD,war_msg)
+                    connectObj(reac,rSprdname,"prd",comptD,war_msg)
                     allclean = True
                 else:
                     # didn't find sub or prd for this reaction
                     #   --  it may be connected Enzyme cplx
-                    RE_Notcopiedyet.append(rb)
+                    RE_Notcopiedyet.append(rs)
             else:
                 #   -- it is dagging reaction
-                RE_Daggling.append(rb)
+                RE_Daggling.append(rs)
                 #print ("This reaction \""+rb.path+"\" has no substrate/product daggling reaction are not copied")
                 #war_msg = war_msg+"\nThis reaction \""+rb.path+"\" has no substrate/product daggling reaction are not copied"
 
@@ -583,30 +602,31 @@ def reacMerge(comptA,comptB,key,poolListina):
             #Same reaction name
             #   -- Same substrate and product including same volume then don't copy
             #   -- different substrate/product or if sub/prd's volume is different then DUPLICATE the reaction
+            
             allclean = False
-            for ra in reacListina:
-                if rb.name == ra.name:
-                    rAsubname = subprdList(ra,"sub")
-                    rBsubname = subprdList(rb,"sub")
-                    hasSamenoofsublen,hasSameS,hasSamevols = same_len_name_vol(rAsubname,rBsubname)
-
-                    rAprdname = subprdList(ra,"prd")
-                    rBprdname = subprdList(rb,"prd")
-                    hasSamenoofprdlen,hasSameP,hasSamevolp = same_len_name_vol(rAprdname,rBprdname)
+            for rd in reacListind:
+                if rs.name == rd.name:
+                    rSsubname = subprdList(rs,"sub")
+                    rDsubname = subprdList(rd,"sub")
+                    hasSamenoofsublen,hasSameS,hasSamevols = same_len_name_vol(rSsubname,rDsubname)
+
+                    rSprdname = subprdList(rs,"prd")
+                    rDprdname = subprdList(rd,"prd")
+                    hasSamenoofprdlen,hasSameP,hasSamevolp = same_len_name_vol(rSprdname,rDprdname)
                     if not all((hasSamenoofsublen,hasSameS,hasSamevols,hasSamenoofprdlen,hasSameP,hasSamevolp)):
                         # May be different substrate or product or volume of Sub/prd may be different,
                         # Duplicating the reaction
-                        if rBsubname and rBprdname:
+                        if rSsubname and rSprdname:
                             allexists,allexistp = False,False
-                            allexists = checkexist(rBsubname,objB,objA)
-                            allexistp = checkexist(rBprdname,objB,objA)
+                            allexists = checkexist(rSsubname,objS,objD)
+                            allexistp = checkexist(rSprdname,objS,objD)
                             if allexists and allexistp:
-                                rb.name = rb.name+"_duplicated"
+                                rs.name = rs.name+"_duplicated"
                                 #reac = moose.Reac(comptA[key].path+'/'+rb.name+"_duplicated")
-                                rapath = rb.parent.path.replace(objB,objA)
-                                reac = moose.copy(rb,moose.element(rapath))
-                                connectObj(reac,rBsubname,"sub",comptA,war_msg)
-                                connectObj(reac,rBprdname,"prd",comptA,war_msg)
+                                rdpath = rs.parent.path.replace(objS,objD)
+                                reac = moose.copy(rs,moose.element(rdpath))
+                                connectObj(reac,rSsubname,"sub",comptD,war_msg)
+                                connectObj(reac,rSprdname,"prd",comptD,war_msg)
                                 RE_Duplicated.append(reac)
                                 allclean = True
                             else:
@@ -617,11 +637,11 @@ def reacMerge(comptA,comptB,key,poolListina):
                     if not allclean:
                         # didn't find sub or prd for this reaction
                         #   --  it may be connected Enzyme cplx
-                        if rBsubname and rBprdname:
-                            RE_Notcopiedyet.append(rb)
+                        if rSsubname and rSprdname:
+                            RE_Notcopiedyet.append(rs)
                         else:
-                            RE_Daggling.append(rb)
-
+                            RE_Daggling.append(rs)
+    
     return RE_Duplicated,RE_Notcopiedyet,RE_Daggling
 
 def subprdList(reac,subprd):
@@ -704,6 +724,7 @@ def mooseIsInstance(element, classNames):
 
 
 if __name__ == "__main__":
+
     try:
         sys.argv[1]
     except IndexError:
@@ -712,7 +733,7 @@ if __name__ == "__main__":
     else:
         src = sys.argv[1]
         if not os.path.exists(src):
-            print("Filename or path does not exist",src)
+            print("Filename or path does not exist %s." %(src))
         else:
             try:
                 sys.argv[2]
@@ -722,10 +743,12 @@ if __name__ == "__main__":
             else:
                 des = sys.argv[2]
                 if not os.path.exists(src):
-                    print("Filename or path does not exist",des)
+                    print("Filename or path does not exist %s." %(des))
                     exit(0)
                 else:
+                    print ("src and des %s, %s." %(src, des))
                     mergered = mergeChemModel(src,des)
+
                 '''
                 try:
                     sys.argv[3]
diff --git a/moose-core/python/moose/chemUtil/add_Delete_ChemicalSolver.py b/moose-core/python/moose/chemUtil/add_Delete_ChemicalSolver.py
index 05bd4a0a233f792f177bcc833beed7292efe3dc6..cc350ec6087ac1b731b0a274b75eeeebb8a3de77 100644
--- a/moose-core/python/moose/chemUtil/add_Delete_ChemicalSolver.py
+++ b/moose-core/python/moose/chemUtil/add_Delete_ChemicalSolver.py
@@ -1,11 +1,35 @@
 # -*- coding: utf-8 -*-
 import moose
+from fixXreacs import fixXreacs
+
+def positionCompt( compt ):
+    i = 0
+    while (i != len(compt)-1):
+        #print "PositionCompt ", compt[i+1],compt[i+1].volume, compt[i], compt[i].volume
+        compt[i+1].x1 += compt[i].x1
+        compt[i+1].x0 += compt[i].x1
+        i += 1
 
 def moosedeleteChemSolver(modelRoot):
     """Delete solvers from Chemical Compartment
 
     """
     compts = moose.wildcardFind(modelRoot + '/##[ISA=ChemCompt]')
+    for compt in compts:
+        if moose.exists(compt.path + '/stoich'):
+            st = moose.element(compt.path + '/stoich')
+            st_ksolve = st.ksolve
+            st_dsolve = st.dsolve
+            
+            moose.delete(st)
+            if moose.exists((st_ksolve).path):
+                moose.delete(st_ksolve)
+                print("KSolver is deleted for modelpath %s " % modelRoot)
+            if moose.exists((st_dsolve).path):
+                moose.delete(st_dsolve)
+                print("DSolver is deleted for modelpath %s " % modelRoot)
+    '''
+    compts = moose.wildcardFind(modelRoot + '/##[ISA=ChemCompt]')
     for compt in compts:
         if moose.exists(compt.path + '/stoich'):
             st = moose.element(compt.path + '/stoich')
@@ -15,6 +39,7 @@ def moosedeleteChemSolver(modelRoot):
                 moose.delete(st_ksolve)
                 print("Solver is deleted for modelpath %s " % modelRoot)
 
+    '''
 
 def mooseaddChemSolver(modelRoot, solver):
     """
@@ -58,6 +83,56 @@ def mooseaddChemSolver(modelRoot, solver):
 
 
 def setCompartmentSolver(modelRoot, solver):
+    comptlist = dict((c, c.volume) for c in moose.wildcardFind(modelRoot + '/##[ISA=ChemCompt]'))
+    comptVol = {}
+    compts = []
+    vol  = [v for k,v in comptlist.items()]
+    volumeSort = sorted(vol)
+    for k,v in comptlist.items():
+        comptVol[k]= v
+    for volSor in volumeSort:
+        for a,b in comptVol.items():
+            if b == volSor:
+                compts.append(a)
+    
+    #compts = [key for key, value in sorted(comptlist.items(), key=lambda (k,v): (v,k))] 
+    if ( len(compts) == '0'):
+        print ("Atleast one compartment is required ")
+        return
+    else:
+        if ( len(compts) > 3 ):
+            print ("Warning: setSolverOnCompt Cannot handle " ,  len(compts) , " chemical compartments\n")
+            return;
+
+        elif (len(compts) >1 ):
+            positionCompt(compts)
+
+        fixXreacs( modelRoot )
+
+        for compt in compts:
+            if solver != 'ee':
+                if (solver == 'gsl') or (solver == 'Runge Kutta'):
+                    ksolve = moose.Ksolve(compt.path + '/ksolve')
+                if (solver == 'gssa') or (solver == 'Gillespie'):
+                    ksolve = moose.Gsolve(compt.path + '/gsolve')
+                
+                dsolve = moose.Dsolve(compt.path+'/dsolve')
+                stoich = moose.Stoich(compt.path + '/stoich')
+                stoich.compartment = compt
+                stoich.ksolve = ksolve
+                stoich.dsolve = dsolve
+                stoich.path = compt.path + "/##"
+        ksolveList = moose.wildcardFind(modelRoot+'/##[ISA=Ksolve]')
+        dsolveList = moose.wildcardFind(modelRoot+'/##[ISA=Dsolve]')
+        stoichList = moose.wildcardFind(modelRoot+'/##[ISA=Stoich]')
+        
+        i = 0
+        while(i < len(dsolveList)-1):
+            dsolveList[i+1].buildMeshJunctions(dsolveList[i])
+            i += 1
+        
+        print( " Solver is added to model path %s" % modelRoot )
+    '''
     compts = moose.wildcardFind(modelRoot + '/##[ISA=ChemCompt]')
     for compt in compts:
         if (solver == 'gsl') or (solver == 'Runge Kutta'):
@@ -80,3 +155,4 @@ def setCompartmentSolver(modelRoot, solver):
     for i in stoichList:
         i.filterXreacs()
     print( " Solver is added to model path %s" % modelRoot )
+    '''
diff --git a/moose-core/python/moose/utils.py b/moose-core/python/moose/utils.py
index 37bf0deb9f82cc233d4f8f96de103b2c0c83cc15..9abf7ae5d2636cbccfc80cb0c19535233c4f6def 100644
--- a/moose-core/python/moose/utils.py
+++ b/moose-core/python/moose/utils.py
@@ -23,7 +23,6 @@ import re
 
 from moose.moose_constants import *
 from moose.print_utils import *
-
 # Print and Plot utilities.
 try:
     from moose.plot_utils import *
@@ -341,7 +340,10 @@ def autoposition(root):
         stack.extend([childcomp for childcomp in map(moose.element, comp.neighbors['raxial']) if childcomp.z == 0])
     return ret
 
-
+def loadModel(filename, target,method='ee'):
+    moose.loadModel(filename,target)
+    moose.mooseaddChemSolver(target,method)
+	
 def readcell_scrambled(filename, target, method='ee'):
     """A special version for handling cases where a .p file has a line
     with specified parent yet to be defined.
diff --git a/moose-core/python/rdesigneur/moogul.py b/moose-core/python/rdesigneur/moogul.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f2ecba50b89d1808e711e471474307ca8e70197
--- /dev/null
+++ b/moose-core/python/rdesigneur/moogul.py
@@ -0,0 +1,314 @@
+# Moogul.py: MOOSE Graphics Using Lines
+# This is a fallback graphics interface for displaying neurons using
+# regular matplotlib routines.
+# Put in because the GL versions like moogli need all sorts of difficult 
+# libraries and dependencies.
+# Copyright (C) Upinder S. Bhalla NCBS 2018
+# This program is licensed under the GNU Public License version 3.
+#
+
+import moose
+import numpy as np
+import matplotlib.pyplot as plt
+from mpl_toolkits.mplot3d.art3d import Line3DCollection
+
+class MoogulError( Exception ):
+    def __init__( self, value ):
+        self.value = value
+    def __str__( self ):
+        return repr( self.value )
+
+class MooView:
+    ''' The MooView class is a window in which to display one or more 
+    moose cells, using the MooCell class.'''
+    def __init__( self, swx = 10, swy = 12, hideAxis = True
+    ):
+        plt.ion()
+        self.fig_ = plt.figure( figsize = (swx, swy) )
+        self.ax = self.fig_.add_subplot(111, projection='3d' )
+        self.drawables_ = []
+        self.fig_.canvas.mpl_connect("key_press_event", self.moveView )
+        plt.rcParams['keymap.xscale'] = ''
+        plt.rcParams['keymap.yscale'] = ''
+        plt.rcParams['keymap.zoom'] = ''
+        plt.rcParams['keymap.back'] = ''
+        plt.rcParams['keymap.home'] = ''
+        plt.rcParams['keymap.forward'] = ''
+        plt.rcParams['keymap.all_axes'] = ''
+        self.hideAxis = hideAxis
+        if self.hideAxis:
+            self.ax.set_axis_off()
+        #self.ax.margins( tight = True )
+        self.ax.margins()
+        self.sensitivity = 7.0 # degrees rotation
+        self.zoom = 1.05
+
+    def addDrawable( self, n ):
+        self.drawables_.append( n )
+
+    def firstDraw( self, rotation = 0.0, elev = 0.0, azim = 0.0 ):
+        self.coordMax = 0.0 
+        self.coordMin = 0.0
+        if rotation == 0.0:
+            self.doRotation = False
+            self.rotation = 7 # default rotation per frame, in degrees.
+        else:
+            self.doRotation = True
+            self.rotation = rotation * 180/np.pi # arg units: radians/frame
+        
+        self.azim = azim * 180/np.pi
+        self.elev = elev * 180/np.pi
+        for i in self.drawables_:
+            cmax, cmin = i.drawForTheFirstTime( self.ax )
+            self.coordMax = max( cmax, self.coordMax )
+            self.coordMin = min( cmin, self.coordMin )
+        if self.coordMin == self.coordMax:
+            self.coordMax = 1+self.coordMin
+
+            
+        self.ax.set_xlim3d( self.coordMin, self.coordMax )
+        self.ax.set_ylim3d( self.coordMin, self.coordMax )
+        self.ax.set_zlim3d( self.coordMin, self.coordMax )
+        self.ax.view_init( elev = self.elev, azim = self.azim )
+        #self.ax.view_init( elev = -80.0, azim = 90.0 )
+        #self.colorbar = plt.colorbar( self.drawables_[0].segments )
+        self.colorbar = self.fig_.colorbar( self.drawables_[0].segments )
+        self.colorbar.set_label( self.drawables_[0].fieldInfo[3])
+        self.timeStr = self.ax.text2D( 0.05, 0.05, 
+                "Time= 0.0", transform=self.ax.transAxes)
+        self.fig_.canvas.draw()
+        plt.show()
+
+    def updateValues( self ):
+        time = moose.element( '/clock' ).currentTime
+        self.timeStr.set_text( "Time= " + str(time) )
+        for i in self.drawables_:
+            i.updateValues()
+        if self.doRotation and abs( self.rotation ) < 120:
+            self.ax.azim += self.rotation
+        #self.fig_.canvas.draw()
+        plt.pause(0.001)
+
+    def moveView(self, event):
+        x0 = self.ax.get_xbound()[0]
+        x1 = self.ax.get_xbound()[1]
+        xk = (x0 - x1) / self.sensitivity
+        y0 = self.ax.get_ybound()[0]
+        y1 = self.ax.get_ybound()[1]
+        yk = (y0 - y1) / self.sensitivity
+        z0 = self.ax.get_zbound()[0]
+        z1 = self.ax.get_zbound()[1]
+        zk = (z0 - z1) / self.sensitivity
+
+        if event.key == "up" or event.key == "k":
+            self.ax.set_ybound( y0 + yk, y1 + yk )
+        if event.key == "down" or event.key == "j":
+            self.ax.set_ybound( y0 - yk, y1 - yk )
+        if event.key == "left" or event.key == "h":
+            self.ax.set_xbound( x0 + xk, x1 + xk )
+        if event.key == "right" or event.key == "l":
+            self.ax.set_xbound( x0 - xk, x1 - xk )
+        if event.key == "ctrl+up":
+            self.ax.set_zbound( z0 + zk, z1 + zk )
+        if event.key == "ctrl+down":
+            self.ax.set_zbound( z0 - zk, z1 - zk )
+        if event.key == "." or event.key == ">": # zoom in, bigger
+            self.ax.set_xbound( x0/self.zoom, x1/self.zoom )
+            self.ax.set_ybound( y0/self.zoom, y1/self.zoom )
+            self.ax.set_zbound( z0/self.zoom, z1/self.zoom )
+        if event.key == "," or event.key == "<": # zoom out, smaller
+            self.ax.set_xbound( x0*self.zoom, x1*self.zoom )
+            self.ax.set_ybound( y0*self.zoom, y1*self.zoom )
+            self.ax.set_zbound( z0*self.zoom, z1*self.zoom )
+        if event.key == "a": # autoscale to fill view.
+            self.ax.set_xlim3d( self.coordMin, self.coordMax )
+            self.ax.set_ylim3d( self.coordMin, self.coordMax )
+            self.ax.set_zlim3d( self.coordMin, self.coordMax )
+        if event.key == "p": # pitch
+            self.ax.elev += self.sensitivity
+        if event.key == "P":
+            self.ax.elev -= self.sensitivity
+        if event.key == "y": # yaw
+            self.ax.azim += self.sensitivity
+        if event.key == "Y":
+            self.ax.azim -= self.sensitivity
+        # Don't have anything for roll
+        if event.key == "g":
+            self.hideAxis = not self.hideAxis
+            if self.hideAxis:
+                self.ax.set_axis_off()
+            else:
+                self.ax.set_axis_on()
+        if event.key == "t": # Turn on/off twisting/autorotate
+            self.doRotation = not self.doRotation
+        if event.key == "?": # Print out help for these commands
+            self.printMoogulHelp()
+
+        self.fig_.canvas.draw()
+
+    def printMoogulHelp( self ):
+        print( '''
+            Key bindings for Moogul:
+            Up or k:    pan object up
+            Down or j:  pan object down
+            left or h:  pan object left. Bug: direction depends on azimuth.
+            right or l:  pan object right Bug: direction depends on azimuth
+            . or >:     Zoom in: make object appear bigger
+            , or <:     Zoom out: make object appear smaller
+            a:          Autoscale to fill view
+            p:          Pitch down
+            P:          Pitch up
+            y:          Yaw counterclockwise
+            Y:          Yaw counterclockwise
+            g:          Toggle visibility of grid
+            t:          Toggle turn (rotation along long axis of cell)
+            ?:          Print this help page.
+        ''')
+
+#####################################################################
+
+class MooDrawable:
+    ''' Base class for drawing things'''
+    def __init__( self,
+        fieldInfo, field, relativeObj, maxLineWidth,
+        colormap,
+        lenScale, diaScale, autoscale,
+        valMin, valMax
+    ):
+        self.field = field
+        self.relativeObj = relativeObj
+        self.maxLineWidth = maxLineWidth
+        self.lenScale = lenScale
+        self.diaScale = diaScale
+        self.colormap = colormap
+        self.autoscale = autoscale
+        self.valMin = valMin
+        self.valMax = valMax
+        self.fieldInfo = fieldInfo
+        self.fieldScale = fieldInfo[2]
+        #FieldInfo = [baseclass, fieldGetFunc, scale, axisText, min, max]
+
+    def updateValues( self ):
+        ''' Obtains values from the associated cell'''
+        self.val = np.array([moose.getField( i, self.field, 'double' ) for i in self.activeObjs]) * self.fieldScale
+        cmap = plt.get_cmap( self.colormap )
+        if self.autoscale:
+            valMin = min( self.val )
+            valMax = max( self.val )
+        else:
+            valMin = self.valMin
+            valMax = self.valMax
+        scaleVal = (self.val - valMin) / (valMax - valMin)
+        self.rgba = [ cmap(i) for i in scaleVal ]
+        self.segments.set_color( self.rgba )
+        return
+
+    def drawForTheFirstTime( self, ax ):
+        self.segments = Line3DCollection( self.activeCoords, 
+                linewidths = self.linewidth, cmap = plt.get_cmap(self.colormap) )
+        self.cax = ax.add_collection3d( self.segments )
+        self.segments.set_array( self.valMin + np.array( range( len(self.activeCoords) ) ) * (self.valMax-self.valMin)/len(self.activeCoords) )
+        return self.coordMax, self.coordMin
+
+
+
+
+#####################################################################
+
+class MooNeuron( MooDrawable ):
+    ''' Draws collection of line segments of defined dia and color'''
+    def __init__( self,
+        neuronId,
+        fieldInfo,
+        field = 'Vm', 
+        relativeObj = '.', 
+        maxLineWidth = 20, 
+        colormap = 'jet', 
+        lenScale = 1e6, diaScale = 1e6, autoscale = False, 
+        valMin = -0.1, valMax = 0.05,
+    ):
+        #self.isFieldOnCompt = 
+            #field in ( 'Vm', 'Im', 'Rm', 'Cm', 'Ra', 'inject', 'diameter' )
+        
+        MooDrawable.__init__( self, fieldInfo, field = field, 
+                relativeObj = relativeObj, maxLineWidth = maxLineWidth, 
+                colormap = colormap, lenScale = lenScale, 
+                diaScale = diaScale, autoscale = autoscale, 
+                valMin = valMin, valMax = valMax )
+        self.neuronId = neuronId
+        self.updateCoords()
+
+    def updateCoords( self ):
+        ''' Obtains coords from the associated cell'''
+        self.compts_ = moose.wildcardFind( self.neuronId.path + "/#[ISA=CompartmentBase]" )
+        # Matplotlib3d isn't able to do full rotations about an y axis,
+        # which is what the NeuroMorpho models use, so
+        # here we shuffle the axes around. Should be an option.
+        #coords = np.array([[[i.x0,i.y0,i.z0],[i.x,i.y,i.z]] 
+            #for i in self.compts_])
+        coords = np.array([[[i.z0,i.x0,i.y0],[i.z,i.x,i.y]] 
+            for i in self.compts_])
+        dia = np.array([i.diameter for i in self.compts_])
+        if self.relativeObj == '.':
+            self.activeCoords = coords
+            self.activeDia = dia
+            self.activeObjs = self.compts_
+        else:
+            self.activeObjs = []
+            self.activeCoords = []
+            self.activeDia = []
+            for i,j,k in zip( self.compts_, coords, dia ):
+                if moose.exists( i.path + '/' + self.relativeObj ):
+                    elm = moose.element( i.path + '/' + self.relativeObj )
+                    self.activeObjs.append( elm )
+                    self.activeCoords.append( j )
+                    self.activeDia.append( k )
+
+        self.activeCoords = np.array( self.activeCoords ) * self.lenScale
+        self.coordMax = np.amax( self.activeCoords )
+        self.coordMin = np.amin( self.activeCoords )
+        self.linewidth = np.array( [ min(self.maxLineWidth, 1 + int(i * self.diaScale )) for i in self.activeDia ] )
+
+        return
+
+#####################################################################
+class MooReacSystem( MooDrawable ):
+    ''' Draws collection of line segments of defined dia and color'''
+    def __init__( self,
+        mooObj, fieldInfo,
+        field = 'conc', 
+        relativeObj = '.', 
+        maxLineWidth = 100, 
+        colormap = 'jet', 
+        lenScale = 1e6, diaScale = 20e6, autoscale = False, 
+        valMin = 0.0, valMax = 1.0
+    ):
+        
+        MooDrawable.__init__( self, fieldInfo, field = field, 
+                relativeObj = relativeObj, maxLineWidth = maxLineWidth, 
+                colormap = colormap, lenScale = lenScale, 
+                diaScale = diaScale, autoscale = autoscale, 
+                valMin = valMin, valMax = valMax )
+        self.mooObj = mooObj
+        self.updateCoords()
+
+    def updateCoords( self ):
+        ''' For now a dummy cylinder '''
+        dx = 1e-6
+        dummyDia = 20e-6
+        numObj = len( self.mooObj )
+        x = np.arange( 0, (numObj+1) * dx, dx )
+        y = np.zeros( numObj + 1)
+        z = np.zeros( numObj + 1)
+
+        coords = np.array([[[i*dx,0,0],[(i+1)*dx,0,0]] for i in range( numObj )] )
+        dia = np.ones( numObj ) * dummyDia
+        self.activeCoords = coords
+        self.activeDia = dia
+        self.activeObjs = self.mooObj
+        self.activeCoords = np.array( self.activeCoords ) * self.lenScale
+        self.coordMax = np.amax( self.activeCoords )
+        self.coordMin = np.amin( self.activeCoords )
+        self.linewidth = np.array( [ min(self.maxLineWidth, 1 + int(i * self.diaScale )) for i in self.activeDia ] )
+
+        return
diff --git a/moose-core/python/rdesigneur/rdesigneur.py b/moose-core/python/rdesigneur/rdesigneur.py
index 0ef8d5c45c81c01f2a230e9f6cdcce9ffc50cd9d..66a2ea68996ee4dae577254b438c40a2b9c72dc4 100644
--- a/moose-core/python/rdesigneur/rdesigneur.py
+++ b/moose-core/python/rdesigneur/rdesigneur.py
@@ -28,8 +28,12 @@ import sys
 import time
 
 import rdesigneur.rmoogli as rmoogli
-import rdesigneur.fixXreacs as fixXreacs
 from rdesigneur.rdesigneurProtos import *
+import fixXreacs
+#from . import fixXreacs
+#from rdesigneur.rmoogli import *
+#import rmoogli
+#from rdesigneurProtos import *
 
 from moose.neuroml.NeuroML import NeuroML
 from moose.neuroml.ChannelML import ChannelML
@@ -194,9 +198,9 @@ class rdesigneur:
             self.buildChemDistrib()
             self._configureSolvers()
             self.buildAdaptors()
+            self._buildStims()
             self._buildPlots()
             self._buildMoogli()
-            self._buildStims()
             self._configureHSolve()
             self._configureClocks()
             if self.verbose:
@@ -332,6 +336,19 @@ class rdesigneur:
     # Here are the functions to build the type-specific prototypes.
     ################################################################
     def buildCellProto( self ):
+        # cellProtoList args:
+        # Option 1: zero args: make standard soma, len and dia 500 um.
+        # Option 2: [name, library_proto_name]: uses library proto
+        # Option 3: [fname.suffix, cellname ]: Loads cell from file
+        # Option 4: [moose<Classname>, cellname]: Makes proto of class
+        # Option 5: [funcname, cellname]: Calls named function with specified name of cell to be made.
+        # Option 6: [path, cellname]: Copies path to library as proto
+        # Option 7: [libraryName, cellname]: Renames library entry as proto
+        # Below two options only need the first two args, rest are optional
+        # Defailt values are given.
+        # Option 8: [somaProto,name, somaDia=5e-4, somaLen=5e-4]
+        # Option 9: [ballAndStick,name, somaDia=10e-6, somaLen=10e-6, 
+        #       dendDia=4e-6, dendLen=200e-6, numDendSeg=1]
         if len( self.cellProtoList ) == 0:
             ''' Make HH squid model sized compartment:
             len and dia 500 microns. CM = 0.01 F/m^2, RA =
@@ -339,6 +356,7 @@ class rdesigneur:
             self.elecid = makePassiveHHsoma( name = 'cell' )
             assert( moose.exists( '/library/cell/soma' ) )
             self.soma = moose.element( '/library/cell/soma' )
+            return
 
             '''
             self.elecid = moose.Neuron( '/library/cell' )
@@ -350,7 +368,11 @@ class rdesigneur:
             '''
 
         for i in self.cellProtoList:
-            if self.checkAndBuildProto( "cell", i, \
+            if i[0] == 'somaProto':
+                self._buildElecSoma( i )
+            elif i[0] == 'ballAndStick':
+                self._buildElecBallAndStick( i )
+            elif self.checkAndBuildProto( "cell", i, \
                 ["Compartment", "SymCompartment"], ["swc", "p", "nml", "xml"] ):
                 self.elecid = moose.element( '/library/' + i[1] )
             else:
@@ -394,11 +416,73 @@ class rdesigneur:
                 ["Pool"], ["g", "sbml", "xml" ] ):
                 self._loadChem( i[0], i[1] )
             self.chemid = moose.element( '/library/' + i[1] )
+    ################################################################
+    def _buildElecSoma( self, args ):
+        parms = [ 'somaProto', 'soma', 5e-4, 5e-4 ] # somaDia, somaLen
+        for i in range( len(args) ):
+            parms[i] = args[i]
+        cell = moose.Neuron( '/library/' + parms[1] )
+        buildCompt( cell, 'soma', dia = parms[2], dx = parms[3] )
+        self.elecid = cell
+        return cell
+        
+    ################################################################
+    def _buildElecBallAndStick( self, args ):
+        parms = [ 'ballAndStick', 'cell', 10e-6, 10e-6, 4e-6, 200e-6, 1 ] # somaDia, somaLen, dendDia, dendLen, dendNumSeg
+        for i in range( len(args) ):
+            parms[i] = args[i]
+        if parms[6] <= 0:
+            return _self.buildElecSoma( parms[:4] )
+        cell = moose.Neuron( '/library/' + parms[1] )
+        prev = buildCompt( cell, 'soma', dia = args[2], dx = args[3] )
+        dx = parms[5]/parms[6]
+        x = prev.x
+        for i in range( parms[6] ):
+            compt = buildCompt( cell, 'dend' + str(i), x = x, dx = dx, dia = args[4] )
+            moose.connect( prev, 'axial', compt, 'raxial' )
+            prev = compt
+            x += dx
+        self.elecid = cell
+        return cell
 
+    ################################################################
+    def _buildVclampOnCompt( self, dendCompts, spineCompts, stimInfo ):
+        # stimInfo = [path, geomExpr, relPath, field, expr_string]
+        stimObj = []
+        for i in dendCompts + spineCompts:
+            vclamp = make_vclamp( name = 'vclamp', parent = i.path )
+            moose.connect( i, 'VmOut', vclamp, 'sensedIn' )
+            moose.connect( vclamp, 'currentOut', i, 'injectMsg' )
+            stimObj.append( vclamp )
+
+        return stimObj
+
+    def _buildSynInputOnCompt( self, dendCompts, spineCompts, stimInfo, doPeriodic = False ):
+        # stimInfo = [path, geomExpr, relPath, field, expr_string]
+        # Here we hack geomExpr to use it for the syn weight. We assume it
+        # is just a number. In due course
+        # it should be possible to actually evaluate it according to geom.
+        synWeight = float( stimInfo[1] )
+        stimObj = []
+        for i in dendCompts + spineCompts:
+            path = i.path + '/' + stimInfo[2] + '/sh/synapse[0]'
+            if moose.exists( path ):
+                synInput = make_synInput( name='synInput', parent=path )
+                synInput.doPeriodic = doPeriodic
+                moose.element(path).weight = synWeight
+                moose.connect( synInput, 'spikeOut', path, 'addSpike' )
+                stimObj.append( synInput )
+        return stimObj
+        
     ################################################################
     # Here we set up the distributions
     ################################################################
     def buildPassiveDistrib( self ):
+	# [. path field expr [field expr]...]
+        # RM, RA, CM set specific values, per unit area etc.
+        # Ra, Ra, Cm set absolute values.
+        # Also does Em, Ek, initVm
+	# Expression can use p, g, L, len, dia, maxP, maxG, maxL.
         temp = []
         for i in self.passiveDistrib:
             temp.extend( i )
@@ -444,6 +528,14 @@ class rdesigneur:
         self.elecid.spineDistribution = temp
 
     def buildChemDistrib( self ):
+        # Orig format [chem, elecPath, install, expr]
+        #   where chem and install were not being used.
+        # Modified format [chemLibPath, elecPath, newChemName, expr]
+        # chemLibPath is name of chemCompt or even group on library
+        # If chemLibPath has multiple compts on it, then the smaller ones
+        # become endoMeshes, scaled as per original.
+        # As a backward compatibility hack, if the newChemName == 'install'
+        # we use the default naming.
         for i in self.chemDistrib:
             pair = i[1] + " " + i[3]
             # Assign any other params. Possibly the first param should
@@ -515,11 +607,11 @@ class rdesigneur:
         # Put in stuff to go through fields if the target is a chem object
         field = plotSpec[3]
         if not field in knownFields:
-            print("Warning: Rdesigneur::_parseComptField: Unknown field '", field, "'")
+            print("Warning: Rdesigneur::_parseComptField: Unknown field '{}'".format( field ) )
             return (), ""
 
         kf = knownFields[field] # Find the field to decide type.
-        if ( kf[0] == 'CaConcBase' or kf[0] == 'ChanBase' or kf[0] == 'NMDAChan' ):
+        if ( kf[0] == 'CaConcBase' or kf[0] == 'ChanBase' or kf[0] == 'NMDAChan' or kf[0] == 'VClamp' ):
             objList = self._collapseElistToPathAndClass( comptList, plotSpec[2], kf[0] )
             return objList, kf[1]
         elif (field == 'n' or field == 'conc' or field == 'volume'  ):
@@ -561,6 +653,9 @@ class rdesigneur:
             'Vm':('CompartmentBase', 'getVm', 1000, 'Memb. Potential (mV)' ),
             'spikeTime':('CompartmentBase', 'getVm', 1, 'Spike Times (s)'),
             'Im':('CompartmentBase', 'getIm', 1e9, 'Memb. current (nA)' ),
+            'Cm':('CompartmentBase', 'getCm', 1e12, 'Memb. capacitance (pF)' ),
+            'Rm':('CompartmentBase', 'getRm', 1e-9, 'Memb. Res (GOhm)' ),
+            'Ra':('CompartmentBase', 'getRa', 1e-6, 'Axial Res (MOhm)' ),
             'inject':('CompartmentBase', 'getInject', 1e9, 'inject current (nA)' ),
             'Gbar':('ChanBase', 'getGbar', 1e9, 'chan max conductance (nS)' ),
             'modulation':('ChanBase', 'getModulation', 1, 'chan modulation (unitless)' ),
@@ -570,7 +665,8 @@ class rdesigneur:
             'Ca':('CaConcBase', 'getCa', 1e3, 'Ca conc (uM)' ),
             'n':('PoolBase', 'getN', 1, '# of molecules'),
             'conc':('PoolBase', 'getConc', 1000, 'Concentration (uM)' ),
-            'volume':('PoolBase', 'getVolume', 1e18, 'Volume (um^3)' )
+            'volume':('PoolBase', 'getVolume', 1e18, 'Volume (um^3)' ),
+            'current':('VClamp', 'getCurrent', 1e9, 'Holding Current (nA)')
         }
         graphs = moose.Neutral( self.modelPath + '/graphs' )
         dummy = moose.element( '/' )
@@ -645,13 +741,25 @@ class rdesigneur:
     ################################################################
     # Here we display the plots and moogli
     ################################################################
-    def displayMoogli( self, moogliDt, runtime, rotation = math.pi/500.0, fullscreen = False):
-        rmoogli.displayMoogli( self, moogliDt, runtime, rotation, fullscreen )
 
-    def display( self ):
+    def displayMoogli( self, moogliDt, runtime, rotation = math.pi/500.0, fullscreen = False, block = True, azim = 0.0, elev = 0.0 ):
+        rmoogli.displayMoogli( self, moogliDt, runtime, rotation = rotation, fullscreen = fullscreen, azim = azim, elev = elev )
+        pr = moose.PyRun( '/model/updateMoogli' )
+
+        pr.runString = '''
+import rdesigneur.rmoogli
+rdesigneur.rmoogli.updateMoogliViewer()
+'''
+        moose.setClock( pr.tick, moogliDt )
+        moose.reinit()
+        moose.start( runtime )
+        if block:
+            self.display( len( self.moogNames ) + 1 )
+
+    def display( self, startIndex = 0 ):
         import matplotlib.pyplot as plt
         for i in self.plotNames:
-            plt.figure( i[2] )
+            plt.figure( i[2] + startIndex )
             plt.title( i[1] )
             plt.xlabel( "Time (s)" )
             plt.ylabel( i[4] )
@@ -670,7 +778,7 @@ class rdesigneur:
                     plt.plot( t, j.vector * i[3] )
         if len( self.moogList ) > 0:
             plt.ion()
-        plt.show(block=True)
+        plt.show( block=True )
         
         #This calls the _save function which saves only if the filenames have been specified
         self._save()                                            
@@ -689,6 +797,9 @@ class rdesigneur:
 
         knownFields = {
             'Vm':('CompartmentBase', 'getVm', 1000, 'Memb. Potential (mV)' ),
+            'Cm':('CompartmentBase', 'getCm', 1e12, 'Memb. capacitance (pF)' ),
+            'Rm':('CompartmentBase', 'getRm', 1e-9, 'Memb. Res (GOhm)' ),
+            'Ra':('CompartmentBase', 'getRa', 1e-6, 'Axial Res (MOhm)' ),
             'spikeTime':('CompartmentBase', 'getVm', 1, 'Spike Times (s)'),
             'Im':('CompartmentBase', 'getIm', 1e9, 'Memb. current (nA)' ),
             'inject':('CompartmentBase', 'getInject', 1e9, 'inject current (nA)' ),
@@ -700,7 +811,8 @@ class rdesigneur:
             'Ca':('CaConcBase', 'getCa', 1e3, 'Ca conc (uM)' ),
             'n':('PoolBase', 'getN', 1, '# of molecules'),
             'conc':('PoolBase', 'getConc', 1000, 'Concentration (uM)' ),
-            'volume':('PoolBase', 'getVolume', 1e18, 'Volume (um^3)' )
+            'volume':('PoolBase', 'getVolume', 1e18, 'Volume (um^3)' ),
+            'current':('VClamp', 'getCurrent', 1e9, 'Holding Current (nA)')
         }
 
         save_graphs = moose.Neutral( self.modelPath + '/save_graphs' )
@@ -898,24 +1010,41 @@ class rdesigneur:
                 'inject':('CompartmentBase', 'setInject'),
                 'Ca':('CaConcBase', 'getCa'),
                 'n':('PoolBase', 'setN'),
-                'conc':('PoolBase', 'setConc')
+                'conc':('PoolBase', 'setConc'),
+                'vclamp':('CompartmentBase', 'setInject'),
+                'randsyn':('SynChan', 'addSpike'),
+                'periodicsyn':('SynChan', 'addSpike')
         }
         stims = moose.Neutral( self.modelPath + '/stims' )
         k = 0
+        # Stimlist = [path, geomExpr, relPath, field, expr_string]
         for i in self.stimList:
             pair = i[0] + " " + i[1]
             dendCompts = self.elecid.compartmentsFromExpression[ pair ]
             spineCompts = self.elecid.spinesFromExpression[ pair ]
-            stimObj, stimField = self._parseComptField( dendCompts, i, knownFields )
-            stimObj2, stimField2 = self._parseComptField( spineCompts, i, knownFields )
-            assert( stimField == stimField2 )
-            stimObj3 = stimObj + stimObj2
+            #print( "pair = {}, numcompts = {},{} ".format( pair, len( dendCompts), len( spineCompts ) ) )
+            if i[3] == 'vclamp':
+                stimObj3 = self._buildVclampOnCompt( dendCompts, spineCompts, i )
+                stimField = 'commandIn'
+            elif i[3] == 'randsyn':
+                stimObj3 = self._buildSynInputOnCompt( dendCompts, spineCompts, i )
+                stimField = 'setRate'
+            elif i[3] == 'periodicsyn':
+                stimObj3 = self._buildSynInputOnCompt( dendCompts, spineCompts, i, doPeriodic = True )
+                stimField = 'setRate'
+            else:
+                stimObj, stimField = self._parseComptField( dendCompts, i, knownFields )
+                stimObj2, stimField2 = self._parseComptField( spineCompts, i, knownFields )
+                assert( stimField == stimField2 )
+                stimObj3 = stimObj + stimObj2
             numStim = len( stimObj3 )
             if numStim > 0:
                 funcname = stims.path + '/stim' + str(k)
                 k += 1
                 func = moose.Function( funcname )
                 func.expr = i[4]
+                if i[3] == 'vclamp': # Hack to clean up initial condition
+                    func.doEvalAtReinit = 1
                 for q in stimObj3:
                     moose.connect( func, 'valueOut', q, stimField )
 
@@ -1189,7 +1318,7 @@ class rdesigneur:
             return
         if not hasattr( self, 'dendCompt' ):
             raise BuildError( "configureSolvers: no chem meshes defined." )
-        fixXreacs.fixXreacs( self.modelPath )
+        fixXreacs.fixXreacs( self.chemid.path )
         dmksolve = moose.Ksolve( self.dendCompt.path + '/ksolve' )
         dmdsolve = moose.Dsolve( self.dendCompt.path + '/dsolve' )
         dmstoich = moose.Stoich( self.dendCompt.path + '/stoich' )
@@ -1241,13 +1370,12 @@ class rdesigneur:
             return
         # Sort comptlist in decreasing order of volume
         sortedComptlist = sorted( comptlist, key=lambda x: -x.volume )
-        if ( len( sortedComptlist ) != 3 ):
-            print("loadChem: Require 3 chem compartments, have: ",\
-                len( sortedComptlist ))
-            return False
-        sortedComptlist[0].name = 'dend'
-        sortedComptlist[1].name = 'spine'
-        sortedComptlist[2].name = 'psd'
+        if ( len( sortedComptlist ) >= 1 ):
+            sortedComptlist[0].name = 'dend'
+        if ( len( sortedComptlist ) >= 2 ):
+            sortedComptlist[1].name = 'spine'
+        if ( len( sortedComptlist ) >= 3 ):
+            sortedComptlist[2].name = 'psd'
 
     ################################################################
 
diff --git a/moose-core/python/rdesigneur/rdesigneurProtos.py b/moose-core/python/rdesigneur/rdesigneurProtos.py
index 1c22ea0cbc68a695f7c653cf0f4a0bba3e023231..ec5d705936d16a3fe624afa12dead0f83dc99e7d 100644
--- a/moose-core/python/rdesigneur/rdesigneurProtos.py
+++ b/moose-core/python/rdesigneur/rdesigneurProtos.py
@@ -49,7 +49,10 @@ import moose
 import math
 from moose import utils
 
-EREST_ACT = -70e-3
+EREST_ACT = -0.060
+ECA = 0.080
+EK =    -0.075
+SOMA_A = 3.32e-9
 per_ms = 1e3
 PI = 3.14159265359
 FaradayConst = 96485.3365 # Coulomb/mol
@@ -106,6 +109,329 @@ def make_HH_K(name = 'HH_K', parent='/library', vmin=-120e-3, vmax=40e-3, vdivs=
     k.tick = -1
     return k
 
+#/========================================================================
+#/                Tabchannel Na Hippocampal cell channel
+#/========================================================================
+def make_Na( name ):
+    if moose.exists( '/library/' + name ):
+        return
+    Na = moose.HHChannel( '/library/' + name )
+    Na.Ek = 0.055             #    V
+    Na.Gbar = 300 * SOMA_A    #    S
+    Na.Gk = 0                 #    S
+    Na.Xpower = 2
+    Na.Ypower = 1
+    Na.Zpower = 0
+
+    xgate = moose.element( Na.path + '/gateX' )
+    xA = np.array( [ 320e3 * (0.0131 + EREST_ACT),
+        -320e3, -1.0, -1.0 * (0.0131 + EREST_ACT), -0.004, 
+        -280e3 * (0.0401 + EREST_ACT), 280e3, -1.0, 
+        -1.0 * (0.0401 + EREST_ACT), 5.0e-3, 
+        3000, -0.1, 0.05 ] )
+    xgate.alphaParms = xA
+
+    ygate = moose.element( Na.path + '/gateY' )
+    yA = np.array( [ 128.0, 0.0, 0.0, -1.0 * (0.017 + EREST_ACT), 0.018,
+        4.0e3, 0.0, 1.0, -1.0 * (0.040 + EREST_ACT), -5.0e-3, 
+        3000, -0.1, 0.05 ] )
+    ygate.alphaParms = yA
+    return Na
+
+#========================================================================
+#                Tabchannel K(DR) Hippocampal cell channel
+#========================================================================
+def make_K_DR( name ):
+    if moose.exists( '/library/' + name ):
+        return
+    K_DR = moose.HHChannel( '/library/' + name )
+    K_DR.Ek = EK                #    V
+    K_DR.Gbar = 150 * SOMA_A    #    S
+    K_DR.Gk = 0                 #    S
+    K_DR.Xpower = 1
+    K_DR.Ypower = 0
+    K_DR.Zpower = 0
+
+    xgate = moose.element( K_DR.path + '/gateX' )
+    xA = np.array( [ 16e3 * (0.0351 + EREST_ACT), 
+        -16e3, -1.0, -1.0 * (0.0351 + EREST_ACT), -0.005,
+        250, 0.0, 0.0, -1.0 * (0.02 + EREST_ACT), 0.04,
+        3000, -0.1, 0.05 ] )
+    xgate.alphaParms = xA
+    return K_DR
+
+#========================================================================
+#                Tabchannel K(A) Hippocampal cell channel
+#========================================================================
+def make_K_A( name ):
+    if moose.exists( '/library/' + name ):
+        return
+    K_A = moose.HHChannel( '/library/' + name )
+    K_A.Ek = EK                #    V
+    K_A.Gbar = 50 * SOMA_A    #    S
+    K_A.Gk = 0                #    S
+    K_A.Xpower = 1
+    K_A.Ypower = 1
+    K_A.Zpower = 0
+
+    xgate = moose.element( K_A.path + '/gateX' )
+    xA = np.array( [ 20e3 * (0.0131 + EREST_ACT), 
+        -20e3, -1.0, -1.0 * (0.0131 + EREST_ACT), -0.01,
+        -17.5e3 * (0.0401 + EREST_ACT), 
+        17.5e3, -1.0, -1.0 * (0.0401 + EREST_ACT), 0.01,
+        3000, -0.1, 0.05 ] )
+    xgate.alphaParms = xA
+
+    ygate = moose.element( K_A.path + '/gateY' )
+    yA = np.array( [ 1.6, 0.0, 0.0, 0.013 - EREST_ACT, 0.018,
+        50.0, 0.0, 1.0, -1.0 * (0.0101 + EREST_ACT), -0.005,
+        3000, -0.1, 0.05 ] )
+    ygate.alphaParms = yA
+
+#//========================================================================
+#//                      Tabulated Ca Channel
+#//========================================================================
+
+def make_Ca( name ):
+    if moose.exists( '/library/' + name):
+        return
+    Ca = moose.HHChannel( '/library/' + name )
+    Ca.Ek = ECA
+    Ca.Gbar = 40 * SOMA_A
+    Ca.Gk = 0
+    Ca.Xpower = 2
+    Ca.Ypower = 1
+    Ca.Zpower = 0
+
+    xgate = moose.element( Ca.path + '/gateX' )
+    xA = np.array( [ 1.6e3, 0, 1.0, -1.0 * (0.065 + EREST_ACT), -0.01389, -20e3 * (0.0511 + EREST_ACT), 20e3, -1.0, -1.0 * (0.0511 + EREST_ACT), 5.0e-3, 3000, -0.1, 0.05 ] )
+#    xgate.min = -0.1
+#    xgate.max = 0.05
+#    xgate.divs = 3000
+#// Converting Traub's expressions for the gCa/s alpha and beta functions
+#// to SI units and entering the A, B, C, D and F parameters, we get:
+#    xgate.alpha( 1.6e3, 0, 1.0, -1.0 * (0.065 + EREST_ACT), -0.01389 )
+#    xgate.beta( -20e3 * (0.0511 + EREST_ACT), 20e3, -1.0, -1.0 * (0.0511 + EREST_ACT), 5.0e-3 )
+    #xgate.setupAlpha( xA )
+    xgate.alphaParms = xA
+
+
+#  The Y gate (gCa/r) is not quite of this form.  For V > EREST_ACT, alpha =
+#  5*{exp({-50*(V - EREST_ACT)})}.  Otherwise, alpha = 5.  Over the entire
+#  range, alpha + beta = 5.  To create the Y_A and Y_B tables, we use some
+#  of the pieces of the setupalpha function.
+    ygate = moose.element( Ca.path + '/gateY' )
+    ygate.min = -0.1
+    ygate.max = 0.05
+    ygate.divs = 3000
+    yA = np.zeros( (ygate.divs + 1), dtype=float)
+    yB = np.zeros( (ygate.divs + 1), dtype=float)
+
+
+#Fill the Y_A table with alpha values and the Y_B table with (alpha+beta)
+    dx = (ygate.max - ygate.min)/ygate.divs
+    x = ygate.min
+    for i in range( ygate.divs + 1 ):
+        if ( x > EREST_ACT):
+            yA[i] = 5.0 * math.exp( -50 * (x - EREST_ACT) )
+        else:
+            yA[i] = 0.0
+        #yB[i] = 6.0 - yA[i]
+        yB[i] = 5.0
+        x += dx
+    ygate.tableA = yA
+    ygate.tableB = yB
+# Tell the cell reader that the current from this channel must be fed into
+# the Ca_conc pool of calcium.
+    addmsg1 = moose.Mstring( Ca.path + '/addmsg1' )
+    addmsg1.value = '.    IkOut    ../Ca_conc    current'
+# in some compartments, whe have an NMDA_Ca_conc object to put the current
+# into.
+    addmsg2 = moose.Mstring( Ca.path + '/addmsg2' )
+    addmsg2.value = '.    IkOut    ../NMDA_Ca_conc    current'
+# As we typically use the cell reader to create copies of these prototype
+#elements in one or more compartments, we need some way to be sure that the
+#needed messages are established.  Although the cell reader has enough
+#information to create the messages which link compartments to their channels
+#and to other adjacent compartments, it most be provided with the information
+#needed to establish additional messages.  This is done by placing the
+#message string in a user-defined field of one of the elements which is
+#involved in the message.  The cell reader recognizes the added object names
+#"addmsg1", "addmsg2", etc. as indicating that they are to be
+#evaluated and used to set up messages.  The paths are relative to the
+#element which contains the message string in its added field.  Thus,
+#"../Ca_conc" refers to the sibling element Ca_conc and "."
+#refers to the Ca element itself.
+
+
+#/*************************************************************************
+#Next, we need an element to take the Calcium current calculated by the Ca
+#channel and convert it to the Ca concentration.  The "Ca_concen" object
+#solves the equation dC/dt = B*I_Ca - C/tau, and sets Ca = Ca_base + C.  As
+#it is easy to make mistakes in units when using this Calcium diffusion
+#equation, the units used here merit some discussion.
+
+#With Ca_base = 0, this corresponds to Traub's diffusion equation for
+#concentration, except that the sign of the current term here is positive, as
+#GENESIS uses the convention that I_Ca is the current flowing INTO the
+#compartment through the channel.  In SI units, the concentration is usually
+#expressed in moles/m^3 (which equals millimoles/liter), and the units of B
+#are chosen so that B = 1/(ion_charge * Faraday * volume). Current is
+#expressed in amperes and one Faraday = 96487 coulombs.  However, in this
+#case, Traub expresses the concentration in arbitrary units, current in
+#microamps and uses tau = 13.33 msec.  If we use the same concentration units,
+#but express current in amperes and tau in seconds, our B constant is then
+#10^12 times the constant (called "phi") used in the paper.  The actual value
+#used will be typically be determined by the cell reader from the cell
+#parameter file.  However, for the prototype channel we wlll use Traub's
+#corrected value for the soma.  (An error in the paper gives it as 17,402
+#rather than 17.402.)  In our units, this will be 17.402e12.
+
+#*************************************************************************/
+
+
+#//========================================================================
+#//                      Ca conc
+#//========================================================================
+
+def make_Ca_conc( name ):
+    if moose.exists( '/library/' + name ):
+        return
+    conc = moose.CaConc( '/library/tempName' )
+    conc.name = name
+    conc.tau = 0.013333  # sec
+    conc.B  = 17.402e12 # Curr to conc conversion for soma
+    conc.Ca_base = 0.00000
+
+#This Ca_concen element should receive a message from any calcium channels
+# with the current going through the channel. Here we have this specified
+# in the Ca channel, with the idea that more than one channel might
+# contribute Ca ions to this calcium pool. In the original GENESIS file
+# this was specified here in make_Ca_conc.
+
+#========================================================================
+#             Tabulated Ca-dependent K AHP Channel
+#========================================================================
+
+# This is a tabchannel which gets the calcium concentration from Ca_conc
+#  in order to calculate the activation of its Z gate.  It is set up much
+#  like the Ca channel, except that the A and B tables have values which are
+#  functions of concentration, instead of voltage.
+
+def make_K_AHP( name ):
+    if moose.exists( '/library/' + name ):
+        return
+    K_AHP = moose.HHChannel( '/library/' + name )
+    K_AHP.Ek = EK    #            V
+    K_AHP.Gbar = 8 * SOMA_A #    S
+    K_AHP.Gk = 0    #    S
+    K_AHP.Xpower = 0
+    K_AHP.Ypower = 0
+    K_AHP.Zpower = 1
+
+    zgate = moose.element( K_AHP.path + '/gateZ' )
+    xmax = 500.0
+    zgate.min = 0
+    zgate.max = xmax
+    zgate.divs = 3000
+    zA = np.zeros( (zgate.divs + 1), dtype=float)
+    zB = np.zeros( (zgate.divs + 1), dtype=float)
+    dx = (zgate.max - zgate.min)/zgate.divs
+    x = zgate.min
+    for i in range( zgate.divs + 1 ):
+            zA[i] = min( 0.02 * CA_SCALE * x, 10 )
+            zB[i] = 1.0
+            x = x + dx
+
+    zgate.tableA = zA
+    zgate.tableB = zB
+    addmsg1 = moose.Mstring( K_AHP.path + '/addmsg1' )
+    addmsg1.value = '../Ca_conc    concOut    . concen'
+# Use an added field to tell the cell reader to set up a message from the
+# Ca_Conc with concentration info, to the current K_AHP object.
+
+
+#//========================================================================
+#//  Ca-dependent K Channel - K(C) - (vdep_channel with table and tabgate)
+#//========================================================================
+
+#The expression for the conductance of the potassium C-current channel has a
+#typical voltage and time dependent activation gate, where the time dependence
+#arises from the solution of a differential equation containing the rate
+#parameters alpha and beta.  It is multiplied by a function of calcium
+#concentration that is given explicitly rather than being obtained from a
+#differential equation.  Therefore, we need a way to multiply the activation
+#by a concentration dependent value which is determined from a lookup table.
+#This is accomplished by using the Z gate with the new tabchannel "instant"
+#field, introduced in GENESIS 2.2, to implement an "instantaneous" gate for
+#the multiplicative Ca-dependent factor in the conductance.
+
+def make_K_C( name ):
+    if moose.exists( '/library/' + name ):
+        return
+    K_C = moose.HHChannel( '/library/' + name )
+    K_C.Ek = EK                    #    V
+    K_C.Gbar = 100.0 * SOMA_A     #    S
+    K_C.Gk = 0                    #    S
+    K_C.Xpower = 1
+    K_C.Zpower = 1
+    K_C.instant = 4                # Flag: 0x100 means Z gate is instant.
+    K_C.useConcentration = 1
+
+    # Now make a X-table for the voltage-dependent activation parameter.
+    xgate = moose.element( K_C.path + '/gateX' )
+    xgate.min = -0.1
+    xgate.max = 0.05
+    xgate.divs = 3000
+    xA = np.zeros( (xgate.divs + 1), dtype=float)
+    xB = np.zeros( (xgate.divs + 1), dtype=float)
+    dx = (xgate.max - xgate.min)/xgate.divs
+    x = xgate.min
+    for i in range( xgate.divs + 1 ):
+        alpha = 0.0
+        beta = 0.0
+        if (x < EREST_ACT + 0.05):
+            alpha = math.exp( 53.872 * (x - EREST_ACT) - 0.66835 ) / 0.018975
+            beta = 2000* (math.exp ( (EREST_ACT + 0.0065 - x)/0.027)) - alpha
+        else:
+            alpha = 2000 * math.exp( ( EREST_ACT + 0.0065 - x)/0.027 )
+            beta = 0.0
+        xA[i] = alpha
+        xB[i] = alpha + beta
+        x = x + dx
+    xgate.tableA = xA
+    xgate.tableB = xB
+
+# Create a table for the function of concentration, allowing a
+# concentration range of 0 to 200, with 3000 divisions.  This is done
+# using the Z gate, which can receive a CONCEN message.  By using
+# the "instant" flag, the A and B tables are evaluated as lookup tables,
+#  rather than being used in a differential equation.
+    zgate = moose.element( K_C.path + '/gateZ' )
+    zgate.min = 0.0
+    xmax = 150.0
+    zgate.max = xmax
+    zgate.divs = 3000
+    zA = np.zeros( (zgate.divs + 1), dtype=float)
+    zB = np.zeros( (zgate.divs + 1), dtype=float)
+    dx = ( zgate.max -  zgate.min)/ zgate.divs
+    x = zgate.min
+    #CaScale = 100000.0 / 250.0e-3
+    for i in range( zgate.divs + 1 ):
+        zA[i] = min( 1000.0, x * CA_SCALE / (250 * xmax ) )
+        zB[i] = 1000.0
+        x += dx
+    zgate.tableA = zA
+    zgate.tableB = zB
+
+# Now we need to provide for messages that link to external elements.
+# The message that sends the Ca concentration to the Z gate tables is stored
+# in an added field of the channel, so that it may be found by the cell
+# reader.
+    addmsg1 = moose.Mstring( K_C.path + '/addmsg1' )
+    addmsg1.value = '../Ca_conc    concOut    . concen'
+
+
 #========================================================================
 #                SynChan: Glu receptor
 #========================================================================
@@ -131,14 +457,15 @@ def make_GABA( name ):
     if moose.exists( '/library/' + name ):
         return
     GABA = moose.SynChan( '/library/' + name )
-    GABA.Ek = EK + 10.0e-3
-    GABA.tau1 = 4.0e-3
-    GABA.tau2 = 9.0e-3
+    GABA.Ek = -0.065            # V
+    GABA.tau1 = 4.0e-3          # s
+    GABA.tau2 = 9.0e-3          # s
     sh = moose.SimpleSynHandler( GABA.path + '/sh' )
     moose.connect( sh, 'activationOut', GABA, 'activation' )
     sh.numSynapses = 1
     sh.synapse[0].weight = 1
 
+#========================================================================
 
 def makeChemOscillator( name = 'osc', parent = '/library' ):
     model = moose.Neutral( parent + '/' + name )
@@ -248,7 +575,7 @@ def transformNMDAR( path ):
     # compartment, it builds it on 'pa'. It places the compartment
     # on the end of 'prev', and at 0,0,0 otherwise.
 
-def buildCompt( pa, name, RM = 1.0, RA = 1.0, CM = 0.01, dia = 1.0e-6, x = 0.0, y = 0.0, z = 0.0, dx = 10e-6, dy = 0.0, dz = 0.0 ):
+def buildCompt( pa, name, RM = 1.0, RA = 1.0, CM = 0.01, dia = 1.0e-6, x = 0.0, y = 0.0, z = 0.0, dx = 10e-6, dy = 0.0, dz = 0.0, Em = -0.065, initVm = -0.065 ):
     length = np.sqrt( dx * dx + dy * dy + dz * dz )
     compt = moose.Compartment( pa.path + '/' + name )
     compt.x0 = x
@@ -264,6 +591,8 @@ def buildCompt( pa, name, RM = 1.0, RA = 1.0, CM = 0.01, dia = 1.0e-6, x = 0.0,
     compt.Ra = length * RA / xa
     compt.Rm = RM / sa
     compt.Cm = CM * sa
+    compt.Em = Em
+    compt.initVm = initVm
     return compt
 
 def buildComptWrapper( pa, name, length, dia, xoffset, RM, RA, CM ):
@@ -289,8 +618,6 @@ def buildSyn( name, compt, Ek, tau1, tau2, Gbar, CM ):
 # Utility function, borrowed from proto18.py, for making an LCa channel.
 # Based on Traub's 91 model, I believe.
 def make_LCa( name = 'LCa', parent = '/library' ):
-        EREST_ACT = -0.060 #/* hippocampal cell resting potl */
-        ECA = 0.140 + EREST_ACT #// 0.080
         if moose.exists( parent + '/' + name ):
                 return
         Ca = moose.HHChannel( parent + '/' + name )
@@ -327,80 +654,39 @@ def make_LCa( name = 'LCa', parent = '/library' ):
         return Ca
 ######################################################################
 
-# Derived from : squid/electronics.py
-# Description: 
-# Author: Subhasis Ray
-# Maintainer: 
-# Created: Wed Feb 22 00:53:38 2012 (+0530)
-# Version: 
-# Last-Updated: Fri May 04 16:35:40 2018 (+0530)
-#           By: Upi
-#     Update #: 221
+def make_vclamp( name = 'Vclamp', parent = '/library' ):
+    if moose.exists( '/library/' + name ):
+        return
+    vclamp = moose.VClamp( parent + '/' + name )
+    vclamp.mode = 0     # Default. could try 1, 2 as well
+    vclamp.tau = 0.2e-3 # lowpass filter for command voltage input
+    vclamp.ti = 20e-6   # Integral time
+    vclamp.td = 5e-6    # Differential time. Should it be >= dt?
+    vclamp.gain = 0.00005   # Gain of vclamp ckt.
 
-# Change log:
-# 
-# 2012-02-22 23:22:30 (+0530) Subha - the circuitry put in a class.
-# 2018-05-04 23:22:30 (+0530) Upi - Adapted for Rdesigneur
-# 
+    # Connect voltage clamp circuitry
+    addmsg1 = moose.Mstring( vclamp.path + '/addmsg1' )
+    addmsg1.value = '.  currentOut  ..  injectMsg'
+    addmsg2 = moose.Mstring( vclamp.path + '/addmsg2' )
+    addmsg2.value = '.. VmOut . sensedIn'
 
-# Code:
+    return vclamp
 
-class ClampCircuit(moose.Neutral):
-    """Container for a Voltage-Clamp/Current clamp circuit."""
-    defaults = {
-        'level1': 25.0e-3,
-        'width1': 50.0e-3,
-        'delay1': 2.0e-3,
-        'delay2': 1e3,
-        'trigMode': 0,
-        'delay3': 1e6
-        }
-    def __init__(self, path ):
-        moose.Neutral.__init__(self, path)        
-        '''
-        self.pulsegen = moose.PulseGen(path+"/pulse") # holding voltage/current generator
-        self.pulsegen.count = 2
-        self.pulsegen.baseLevel = -65.0e-3
-        self.pulsegen.firstLevel = -40.0e-3
-        self.pulsegen.firstWidth = 50.0e-3
-        self.pulsegen.firstDelay = 2.0e-3
-        self.pulsegen.secondDelay = 0.0
-        self.pulsegen.trigMode = 2
-        self.gate = moose.PulseGen(path+"/gate") # holding voltage/current generator
-        self.gate.level[0] = 1.0
-        self.gate.delay[0] = 0.0
-        self.gate.width[0] = 1e3
-        moose.connect(self.gate, 'output', self.pulsegen, 'input')
-        '''
-        self.lowpass = moose.RC(path+"/lowpass") # lowpass filter
-        self.lowpass.R = 1.0
-        self.lowpass.C = 0.03
-        self.vclamp = moose.DiffAmp(path+"/vclamp")
-        self.vclamp.gain = 1.0
-        self.vclamp.saturation = 1e10
-        self.iclamp = moose.DiffAmp(path+"/iclamp")
-        self.iclamp.gain = 0.0
-        self.iclamp.saturation = 1e10
-        self.pid = moose.PIDController(path+"/pid")
-        self.pid.gain = 0.5
-        self.pid.tauI = 0.02e-3
-        self.pid.tauD = 0.005e-3
-        self.pid.saturation = 1e7
-        # Connect voltage clamp circuitry
-        #moose.connect(self.pulsegen, "output", self.lowpass, "injectIn")
-        moose.connect(self.lowpass, "output", self.vclamp, "plusIn")
-        moose.connect(self.vclamp, "output", self.pid, "commandIn")
-        #moose.connect(compartment, "VmOut", self.pid, "sensedIn")
-        #moose.connect(self.pid, "output", compartment, "injectMsg")
-        addmsg1 = moose.Mstring( path + '/addmsg1' )
-        addmsg1.value = './pid  output  ..  injectMsg'
-        addmsg2 = moose.Mstring( path + '/addmsg2' )
-        addmsg2.value = '.. VmOut ./pid  sensedIn'
+######################################################################
 
-def make_vclamp( name = 'Vclamp', parent = '/library' ):
+def make_synInput( name = 'RandSpike', parent = '/library' ):
     if moose.exists( '/library/' + name ):
         return
-    vclamp = ClampCircuit( parent + '/' + name )
+    rs = moose.RandSpike( parent + '/' + name + '_rs' )
+    rs.rate = 0     # mean firing rate
+    rs.refractT = 5e-3 # 5 ms.
+    
+
+    # Connect rand spike to channel that it is sitting on.
+    addmsg1 = moose.Mstring( rs.path + '/addmsg1' )
+    addmsg1.value = '.  spikeOut  ../sh/synapse[0]  addSpike'
+
+    return rs
 
 ######################################################################
 
diff --git a/moose-core/python/rdesigneur/rmoogli.py b/moose-core/python/rdesigneur/rmoogli.py
index fcb1a1209f03b4f542f63b0fee38f169588dabb0..f98549c0b2f9b4109774da64d57a68ebbb9396a5 100644
--- a/moose-core/python/rdesigneur/rmoogli.py
+++ b/moose-core/python/rdesigneur/rmoogli.py
@@ -1,178 +1,53 @@
-# -*- coding: utf-8 -*-
-#########################################################################
-## rdesigneur0_4.py ---
-## This program is part of 'MOOSE', the
-## Messaging Object Oriented Simulation Environment.
-##           Copyright (C) 2014 Upinder S. Bhalla. and NCBS
-## It is made available under the terms of the
-## GNU General Public License version 2 or later.
-## See the file COPYING.LIB for the full notice.
-#########################################################################
-
-import math
-import sys
-import moose
-import os
-
-# Check if DISPLAY environment variable is properly set. If not, warn the user
-# and continue.
-hasDisplay = True
-display = os.environ.get('DISPLAY',  '' )
-if not display:
-    hasDisplay = False
-    print( "Warning: Environment variable DISPLAY is not set."
-            " Did you forget to pass -X or -Y switch to ssh command?\n"
-            "Anyway, MOOSE will continue without graphics.\n"
-            )
-
-hasMoogli = True
-
-if hasDisplay:
-    try:
-        import matplotlib
-        from PyQt4 import QtGui
-        import moogli
-        import moogli.extensions.moose
-        app = QtGui.QApplication(sys.argv)
-    except Exception as e:
-        print( 'Warning: Moogli not found. All moogli calls will use dummy functions' )
-        hasMoogli = False
-
-
-runtime = 0.0
-moogliDt = 1.0
-rotation = math.pi / 500.0
-
-def getComptParent( obj ):
-    k = moose.element(obj)
-    while not k.isA[ "CompartmentBase" ]:
-        if k == moose.element( '/' ):
-            return k.path
-        k = moose.element( k.parent )
-    return k.path
-
-#######################################################################
-## Here we set up the callback functions for the viewer
-def prelude( view ):
-    view.home()
-    view.pitch( math.pi / 2.0 )
-    view.zoom( 0.05 )
-    #network.groups["soma"].set( "color", moogli.colors.RED )
-
-# This func is used for the first viewer, it has to handle advancing time.
-def interlude( view ):
-    moose.start( moogliDt )
-    val = [ moose.getField( i, view.mooField, "double" ) * view.mooScale for i in view.mooObj ]
-    view.mooGroup.set("color", val, view.mapper)
-    view.yaw( rotation )
-    #print moogliDt, len( val ), runtime
-    if moose.element("/clock").currentTime >= runtime:
-        view.stop()
-
-# This func is used for later viewers, that don't handle advancing time.
-def interlude2( view ):
-    val = [ moose.getField( i, view.mooField, "double" ) * view.mooScale for i in view.mooObj ]
-
-    view.mooGroup.set("color", val, view.mapper)
-    view.yaw( rotation )
-    if moose.element("/clock").currentTime >= runtime:
-        view.stop()
-
-def postlude( view ):
-    view.rd.display()
-
-def makeMoogli( rd, mooObj, moogliEntry, fieldInfo ):
-    if not hasMoogli:
-        return None
-    mooField = moogliEntry[3]
+from __future__ import absolute_import, print_function
+# rmoogli.py: rdesigneur Moogli interface
+# This is a fallback version designed to work with moogul but using almost
+# the same interface as far as rdesigneur is concerned.
+# Put in because the GL versions like moogli need all sorts of difficult 
+# libraries and dependencies.
+# Copyright (C) Upinder S. Bhalla NCBS 2018
+# This program is licensed under the GNU Public License version 3.
+
+import rdesigneur.moogul as moogul
+mooViews = []
+
+def makeMoogli( rd, mooObj, args, fieldInfo ):
+    #mooObj is currently poorly handled. Ideally it should simply be a 
+    # vector of objects to plot, each with coords. This could be readily
+    # used to build up the display in a neutral manner.
+    # Another version is to have a vector of objects to plot, only as a 
+    # way to get at their fields. We would separately need mapping to
+    # neuron compartments and index along length.
+    # Cleaner still would be to have the C code give a vector of values
+    # For now it means something different for chem and elec displays.
+    #moogliEntry = [elecPath,bool,whichObjToDisplay,FieldToDisplay,titleForDisplay,rangeMin,rangeMax]
+    mooField = args[3]
+    relObjPath = args[2]
     numMoogli = len( mooObj )
-    network = moogli.extensions.moose.read( path = rd.elecid.path, vertices=15)
-    #print len( network.groups["spine"].shapes )
-    #print len( network.groups["dendrite"].shapes )
-    #print len( network.groups["soma"].shapes )
-    #soma = network.groups["soma"].shapes[ '/model/elec/soma']
-    #print network.groups["soma"].shapes
-
-    soma = network.groups["soma"].shapes[ rd.elecid.path + '/soma[0]']
-    if ( mooField == 'n' or mooField == 'conc' ):
-        updateGroup = soma.subdivide( numMoogli )
-        displayObj = mooObj
-    else:
-        shell = moose.element( '/' )
-        displayObj = [i for i in mooObj if i != shell ]
-        cpa = [getComptParent( i ) for i in displayObj ]
-        updateGroup = moogli.Group( "update" )
-        updateShapes = [network.shapes[i] for i in cpa]
-        #print "########### Len( cpa, mooObj ) = ", len( cpa ), len( mooObj ), len( updateShapes )
-        updateGroup.attach_shapes( updateShapes )
-
-    normalizer = moogli.utilities.normalizer(
-                    moogliEntry[5], moogliEntry[6],
-                    clipleft =True,
-                    clipright = True )
-    colormap = moogli.colors.MatplotlibColorMap(matplotlib.cm.rainbow)
-    mapper = moogli.utilities.mapper(colormap, normalizer)
 
-
-    viewer = moogli.Viewer("Viewer")
-    viewer.setWindowTitle( moogliEntry[4] )
-    if ( mooField == 'n' or mooField == 'conc' ):
-        viewer.attach_shapes( updateGroup.shapes.values())
-        viewer.detach_shape(soma)
-    else:
-        viewer.attach_shapes(network.shapes.values())
-
-    if len( rd.moogNames ) == 0:
-        view = moogli.View("main-view",
-                       prelude=prelude,
-                       interlude=interlude,
-                       postlude = postlude)
+    viewer = moogul.MooView()
+    if mooField == 'n' or mooField == 'conc':
+        #moogul.updateDiffCoords( mooObj )
+        reacSystem = moogul.MooReacSystem( mooObj, fieldInfo, 
+                field = mooField, relativeObj = relObjPath, 
+                valMin = args[5], valMax = args[6] )
+        viewer.addDrawable( reacSystem )
     else:
-        view = moogli.View("main-view",
-                       prelude=prelude,
-                       interlude=interlude2)
+        neuron = moogul.MooNeuron( rd.elecid, fieldInfo,
+                field = mooField, relativeObj = relObjPath,
+                valMin = args[5], valMax = args[6] )
+        viewer.addDrawable( neuron )
 
-    cb = moogli.widgets.ColorBar(id="cb",
-                                 title=fieldInfo[3],
-                                 text_color=moogli.colors.BLACK,
-                                 position=moogli.geometry.Vec3f(0.975, 0.5, 0.0),
-                                 size=moogli.geometry.Vec3f(0.30, 0.05, 0.0),
-                                 text_font="/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-R.ttf",
-                                 orientation=math.pi / 2.0,
-                                 text_character_size=16,
-                                 label_formatting_precision=0,
-                                 colormap=moogli.colors.MatplotlibColorMap(matplotlib.cm.rainbow),
-                                 color_resolution=100,
-                                 scalar_range=moogli.geometry.Vec2f(
-                                     moogliEntry[5],
-                                     moogliEntry[6]))
-    cb.set_num_labels(3)
-    view.attach_color_bar(cb)
-    view.rd = rd
-    view.mooObj = displayObj
-    view.mooGroup = updateGroup
-    view.mooField = mooField
-    view.mooScale = fieldInfo[2]
-    view.mapper = mapper
-    viewer.attach_view(view)
     return viewer
 
-def displayMoogli( rd, _dt, _runtime, _rotation, fullscreen = False ):
-    if not hasMoogli:
-        return None
-    global runtime
-    global moogliDt
-    global rotation
-    runtime = _runtime
-    moogliDt = _dt
-    rotation = _rotation
+def updateMoogliViewer():
+    for i in mooViews:
+        i.updateValues()
+    
+
+def displayMoogli( rd, _dt, _runtime, rotation = 0.0, fullscreen = False, azim = 0.0, elev = 0.0 ):
+    global mooViews
+    mooViews = rd.moogNames
     for i in rd.moogNames:
-        if fullscreen:
-            i.showMaximized()
-        else:
-            i.show()
-        i.start()
-    #viewer.showMaximized()
-    #viewer.show()
-    #viewer.start()
-    return app.exec_()
+        i.firstDraw( rotation = rotation, azim = azim, elev = elev ) 
+        # rotation in radians/frame, azim, elev in radians.
+
diff --git a/moose-core/tests/python/test_kkit.py b/moose-core/tests/python/test_kkit.py
index 8ba4fd2b3f57eb643e4bf537695c5f4012b4ea5a..ba194d63c44f58abb5f0c1d8a3235bed5f42f92e 100644
--- a/moose-core/tests/python/test_kkit.py
+++ b/moose-core/tests/python/test_kkit.py
@@ -23,7 +23,9 @@ def main():
                 runtime = float( sys.argv[2] )
         if ( len( sys.argv ) == 4 ):
                 solver = sys.argv[3]
-        modelId = moose.loadModel( mfile, 'model', solver )
+        modelId = moose.loadModel( mfile, 'model')
+        moose.mooseaddChemSolver('model',solver)
+
         # Increase volume so that the stochastic solver gssa
         # gives an interesting output
         #compt = moose.element( '/model/kinetics' )
diff --git a/moose-core/tests/python/test_negative_value_flag.py b/moose-core/tests/python/test_negative_value_flag.py
index 35c37ad7c83c01dc35faeaa28e6abb568cda2fc6..7b073975de42881f5abab9f8cb4f40c6f029e12f 100644
--- a/moose-core/tests/python/test_negative_value_flag.py
+++ b/moose-core/tests/python/test_negative_value_flag.py
@@ -35,7 +35,8 @@ def main():
     if ( len( sys.argv ) == 4 ):
             solver = sys.argv[3]
 
-    modelId = moose.loadModel( mfile, 'model', solver )
+    modelId = moose.loadModel( mfile, 'model')
+    moose.mooseaddChemSolver('model',solver)
     moose.element( '/model/kinetics/neuroNOS/nNOS.arg' ).concInit = 0.1
     moose.reinit()
     moose.start( runtime )