/* Original model from Poirazi et al. 2003, "CA1 pyramidal neuron: as a 2-layer NN and subthreshold synaptic summation", model DB accession # 20212 at senselab.med.yale.edu. Modified by Fiona Muellner, MPI Neurobiology, March 2015 (email: fiona.muellner@gmail.com). 

Modifications:

All length variables have been scaled by the factor of 2 to match the scaled cell_mul2.

Removed all R-type Ca2+-channels (car) which behave very unphysiologically by opening at voltage-step OFFset,  not ONset, due to a much faster inactivation than activation time constant (typo?). Compare dynamics e.g. to Randall & Tsien 1997, "Contrasting Biophysical and Pharmacological Properties of T-type and R-type Calcium Channels".

Modified the cad-mechanism to correct the surface-volume-ratio which should vary with dendrite diameter (see Anwar et. al. 2014, "Dendritic diameters affect the spatial variability of intracellular calcium dynamics in computer models"); has an effect on Ca2+-amplitudes, but not Ca2+-inhibition.

Modified the cat-mechanism (T-type channels) to replace the dummy-ion Ca by the ion ca, which updates cai.

Set ek = -80mV for all mechanisms (has been -77mV for some); minimally reduces Vrest.

Changed density of the LH-channels (calH) to linearly increase along the first 50um apical dendritic tree (conductance increased step-wise before).

Increased medium Ca2+-dependent K+-current density (mykca_init) 3x, to prevent Ca2+-spikes in terminal branches.

Modified the linear function increasing the Na+ spike attenuation variable ar2_hha_old with distance to remove abrupt steps in current density.

Switched off current-balance.hoc. It forces e_pas to arbitrarily negative potentials. E.g. when Ih density is increased, this results in a paradoxical hyperpolarizing net-effect of Ih. 

Chose finer segmentation (maximum segment length 25um, minimum 3 segments.


*/


/* ----- PROCEDURES USED IN CELL SETUP -------*/

/*  To make the distal membrane less conductive (comment FM: more conductive), vis-a-vis Stuart G. and Spruston N., J. Neuroscience 18(10) 3501-3510, 1998, we decay Rm from proximal to distal sigmoidally */

proc Rm_sigmoid() { local rm
     $o1.defvar("channel:pas","Rm_soma", "Rm_default", "")
     $o1.defvar("channel:pas","Rm_end",  "12e3", "")
     $o1.defvar("channel:pas","dhalf",   "200*2.0",   "")
     $o1.defvar("channel:pas","steep",   "50*2.0",   "")

     for (x) {  
       xdist = find_vector_distance_precise(secname(),x)    // calc. perpedicular distance      
       rm = Rm_soma + (Rm_end - Rm_soma)/(1.0 + exp((dhalf-xdist)/steep))
       g_pas(x) = 1.0/rm
     }

}

/* Changing Ra sigmoidally along the apical trunk (obsolete in this case)*/

proc Ra_sigmoid() {  
     $o1.defvar("channel:pas","Ra_soma", "Ra_default", "")  
     $o1.defvar("channel:pas","Ra_end",  "Ra_default*0.7", "")             
     $o1.defvar("channel:pas","dhalf",   "210*2.0",   "")
     $o1.defvar("channel:pas","steep",   "50*2.0",   "")

     for (x) {  
       xdist = find_vector_distance_precise(secname(),x)  //calc. perpedicular distance
       Ra = Ra_soma + (Ra_end - Ra_soma)/(1.0 + exp((dhalf-xdist)/steep))
     }
}

/* To make the distal trunk h-current conductance, g_h, about 7
times higher (at 300*2.0 um) than the somatic value vis-a-vis Magee J., J. of Neuroscience 18(19) 7613-7624, 1998, we vary I_h
conductance sigmoidally along the apical trunk.
*/

proc apical_h_insert_sig() {
     $o1.defvar("channel:h","gh_soma", "soma_hbar", "")
     $o1.defvar("channel:h","gh_end",  "soma_hbar*9", "")
     $o1.defvar("channel:h","dhalf",   "280*2.0",   "")
     $o1.defvar("channel:h","steep",   "50*2.0",   "")

     for (x) {  
       xdist = find_vector_distance_precise(secname(),x)  //calc. perpedicular distance
       insert h
       gbar_h(x) = gh_soma + (gh_end - gh_soma)/(1.0 + exp((dhalf-xdist)/steep))

       }  
}

/* Inserting proximal (kap) and distal(kad) A-type channels
along the apical trunk. Proximal I_A is distributed in a fixed
conductance over the first 100 um from the cell
body. Distal-type I_A is distributed in a linearly increasing
manner for distances 100*2.0 < xdist < 350*2.0. For xdist < 100*2.0, g_A_distal(x) = 0 and for xdist > 350*2.0 g_A_distal(x) = constant = g_A_distal(350*2.0) 
*/

proc A_insert() {
     $o1.defvar("channel:kap","kap_distal_maxfactor", "1", "maximum cond. factor in dendrites")
     $o1.defvar("channel:kap","kap_distal_distance", "100*2.0", "distance in dendrites for maximum cond.")
     $o1.defvar("channel:kad","kad_distal_maxfactor", "6.5", "maximum cond. factor in dendrites")
     $o1.defvar("channel:kad","kad_distal_distance", "350*2.0", "distance in dendrites for maximum cond.")

     for (x) {  
       xdist=find_vector_distance_precise(secname(),x)
	  fr = xdist/kad_distal_distance
       
       insert kap
       insert kad 
       ek = -80
	  if (xdist < kap_distal_distance ) {
          gkabar_kad(x) = 0
          gkabar_kap(x) = soma_kap

       } else if (xdist < kad_distal_distance ) {
          gkabar_kap(x) = 0
          gkabar_kad(x) = kad_distal_maxfactor*kad_init*fr
	     
       } else {
          gkabar_kap(x) = 0
          gkabar_kad(x) = kad_distal_maxfactor*kad_init
       }
     }
}


/* Inserting m-type potassium current with a fixed conductance along the apical trunk 
*/

proc apical_km_insert() {
     $o1.defvar("channel:km","km_distal_maxfactor", "1", "maximum cond. factor in dendrites")
     $o1.defvar("channel:km","km_distal_distance", "350*2.0", "distance in dendrites for maximum cond.")
     
     for (x) {  
       //xdist = find_vector_distance_precise(secname(),x)
       //fr = xdist/km_distal_distance
       insert km
       gbar_km(x)=soma_km
     }
}


/* Inserting K(Ca++)-type channels and calcium pumps along the
apical trunk with maximum conductances in 50*2.0 < xdist < 200*2.0 
*/

proc apical_kca_insert() {
     $o1.defvar("channel:kca","kca_distal_maxfactor", "1", "maximum cond. factor in dendrites")
     $o1.defvar("channel:kca","kca_distal_distance", "200*2.0", "distance in dendrites for maximum cond.")
  
     for (x) {  
       xdist = find_vector_distance_precise(secname(),x)
       fr = xdist/kca_distal_distance 
       insert cad    // calcium pump/buffering mechanism
       insert kca    // slow AHP K++ current
       insert mykca  // medium AHP K++ current

	if (xdist < kca_distal_distance && xdist > 50*2.0) {       
            gbar_kca(x) = 5*soma_kca
            gkbar_mykca = 2*mykca_init
        } else {
            gbar_kca(x) = 0.5*soma_kca
            gkbar_mykca = 0.25*mykca_init
       }

     }
}

/* Inserting LVA (comment FM: HVA) Ca++ T-type channels along the apical trunk in a linearly increasing manner, for xdist > 100*2.0 um 
*/

proc apical_caT_insert() {
     $o1.defvar("channel:cat","caT_distal_maxfactor", "4", "maximum cond. factor in dendrites")
     $o1.defvar("channel:cat","caT_distal_distance", "350*2.0", "distance in dendrites for maximum cond.")

     for (x) {  
        xdist = find_vector_distance_precise(secname(),x)
	   fr = xdist/caT_distal_distance
        insert cat  
        if (xdist < 100*2.0) {
           gcatbar_cat(x) = 0
        } else {
           gcatbar_cat(x) = caT_distal_maxfactor*soma_caT*fr
        } 
    }
}


/* Inserting HVA Ca++ R-type and HVA L-type channesls along the apical trunk. The R-type current is distributed in a fixed conductance while the L-type current is distributed in a maximum fixed conductance for distances xdist > 50*2.0 um and in a very small (modification FM: linearly increasing) conductance for xdist < 50*2.0 um

*/

proc apical_caR_caLH_insert() {
     for (x) {  
         xdist = find_vector_distance_precise(secname(),x)
         //insert car
         //gcabar_car(x) = 0.1*soma_car

         insert calH
         if (xdist > 50*2.0) {            
            gcalbar_calH(x) = 4.6*soma_caLH
         } else {
            //gcalbar_calH(x) = 0.1*soma_caLH
		 gcalbar_calH(x) = (0.1 + 4.5*xdist/(50*2.0))*soma_caLH
         }
     }
}


/* Setting conductances in all apical oblique dendrites so that the values of all dedrites after an initial section
are the same (or a multiple) as the values in apical_dendrite[46]. The values in the initial section of 50*2.0 um from 
the parent trunk are set equal to the parent trunk conductances. For dendrites located beyond  300*2.0 (or/and 350*2.0) um, 
we increase the Na+-persistent current, the A current, the Ca++ and K(Ca++) conductances and reduce the spike 
attenuation coefficent. */

strdef khsection
proc khoblique_peri_decay() { local i,x,d
$o1.defvar("channel:obliques", "khsection", "\"apical_dendrite[46]\"", "Trunk section used for oblique conductance values")
$o1.defvar("morphology:apical-non-trunk", "peri_trunkl", "50.0*2.0", "Length of the peri-trunk region")

// Holding the conductance values from apical_dendrite[46] 

//sprint($o1.tmp_str,"%s { hold_cat=gcatbar_cat(1) hold_car=soma_car hold_calH=soma_caLH hold_nap=0.0004*gnabar_hha_old }", khsection)
sprint($o1.tmp_str,"%s { hold_cat=gcatbar_cat(1) hold_calH=soma_caLH hold_nap=0.0004*gnabar_hha_old }", khsection)
execute1($o1.tmp_str)
sprint($o1.tmp_str,"%s { hold_h=gbar_h(1) hold_ar2_hha_old=ar2_hha_old(1) hold_kdr=gkbar_hha_old(1) }", khsection)
execute1($o1.tmp_str)
sprint($o1.tmp_str,"%s { hold_g_pas=g_pas(1) hold_Ra=Ra hold_kap=gkabar_kap(1) hold_kad=gkabar_kad(1) }", khsection) 
execute1($o1.tmp_str)
sprint($o1.tmp_str,"%s { hold_mykca=gkbar_mykca(1) hold_kca=gbar_kca(1) hold_km=gbar_km(1) }", khsection)
execute1($o1.tmp_str)

     for i=0,plcount {
    
        // set the origin to the currently accessed section 
        access opl[i].trunk_section.sec
        xdist = find_vector_distance_precise(secname(),0)
        distance(0,1)
        
        trunk_kap = gkabar_kap(1)  // holding the parent trunk values
        trunk_kad = gkabar_kad(1)
        trunk_h  = gbar_h(1)
        trunk_pas = g_pas(1)
        trunk_Ra = Ra 
        //trunk_car  = gcabar_car(1)
        trunk_calH  = gcalbar_calH(1)
        trunk_cat  = gcatbar_cat(1)
        trunk_kca  = gbar_kca(1)
        trunk_mykca  = gkbar_mykca(1)
        trunk_km  = gbar_km(1)
        trunk_nap  = 0.2*hold_nap // No persistent I_Na at the trunk => hold a small persent of hold_nap value
        trunk_ar2_hha_old  = ar2_hha_old(1) // spike attenuation variable

        sec_count=0
  
       forsec pl[i] {
                           
	   if (!sec_count) {              // skip all trunk sections
               sec_count=sec_count+1
               continue
            }         
                insert kap 
                insert kad
                insert h     
                insert pas         
                //insert car
                insert calH
                insert cat
                insert kca
                insert mykca
                insert km
                insert nap
                insert cad

                e_pas = v_init
                ek = -80
			


                for (x) {
                  if (x > 0 && x < 1) {
                     d = distance(1,x)
                     if (d < peri_trunkl) {   // for distances close to the parent trunk section keep trunk values
                        Ra = Ra_default  
                        gkabar_kap(x) = trunk_kap  
                        gkabar_kad(x) = trunk_kad   
                        gbar_h(x) = trunk_h  
                        g_pas(x) = trunk_pas
                        //gcabar_car(x) = trunk_car
                        gcalbar_calH(x) = trunk_calH
                        gcatbar_cat(x) = trunk_cat  
                        gbar_kca(x) = trunk_kca  
                        gkbar_mykca = mykca_init 
                        gbar_km(x) = trunk_km
                        gnabar_nap(x) = trunk_nap
                        ar2_hha_old(x) = trunk_ar2_hha_old         
                    
                     } else {          // for further distances set conductances to apical_dendrite[46] values (or a multiple)            
                        gkabar_kap(x) = hold_kap  
                        gkabar_kad(x) = 1.25*hold_kad   
                        gbar_h(x) = hold_h  
                        g_pas(x) = hold_g_pas

                        Ra = Ra_default
                        //gcabar_car(x) = hold_car
                        gcalbar_calH(x) = hold_calH 
                        gcatbar_cat(x) = hold_cat  
                        ar2_hha_old(x) = 0.8*hold_ar2_hha_old  // set to 80% of dend. 46 value  
                        gbar_kca(x) = hold_kca
                        gkbar_mykca = 1.1*mykca_init 
                        gnabar_nap(x) = hold_nap  
                        gbar_km(x) = 2*hold_km             // set to 2 times the dend 46 value
             
                        if (xdist > 300*2.0) {                // for xdist > 300*2.0 um increase:
                           gkabar_kad(x) = 1.3*1.9*hold_kad      // A-current,
                           //gcabar_car(x) = 13*hold_car       // Ca++-R current,
                           gcalbar_calH(x) = 14*hold_calH     // Ca++-L current,
                           gbar_kca(x) = 5*soma_kca         // slow AHP current  
                           gkbar_hha_old(x) = 1.07*hold_kdr // delayed rectifier
                         }

                        if (xdist > 350*2.0) {               // for xdist > 350*2.0 um increase even more:
                           gcalbar_calH(x)=15*hold_calH  // Ca++-L current,
                           //gcabar_car(x) = 13*hold_car       // Ca++-R current,
			   ar2_hha_old(x) = 0.95         // less spike attenuation 
                           gnabar_nap(x)=2*hold_nap      // Na+ persistent                   

                        }
                           
                     } 
   		}
	    }
         
          sec_count=sec_count+1
        }
    }
}


/* Setting conductance values in all basal dendrites to be the
same as the values in apical_dendrite[14], except for the A
current conductance which is 0.6 times higher.  
*/

proc khbasal_fixed() { local i,x,d
$o1.defvar("channel:basal", "khsection", "\"apical_dendrite[14]\"", "Trunk section used for basal conductance values")
sprint($o1.tmp_str,"%s { hold_g_pas=g_pas(1) hold_kap=gkabar_kap(1)  hold_kad=gkabar_kad(1) hold_h=gbar_h(1)}", khsection)
execute1($o1.tmp_str)

forsec basal_tree_list {

      insert kap 
      insert kad
      insert h                
      insert pas
     
      for (x) {
         gkabar_kap(x) = 1.6*hold_kap
         gkabar_kad(x) = 1.6*hold_kad
         gbar_h(x) = soma_hbar
         g_pas(x) =  hold_g_pas
         Ra = Ra_default
         e_pas = v_init
         ek = -80 
	    
     }
  }
}

/* The Na channels developed Mel and modified by Brannon,
Poirazi (hha2 and hha_old) both reduce activation as function
of voltage. In other words, they show actvity-dependent
attenuation of conductance.  Within both of these mechanisms,
ar2 ([0..1]) is used to inversely describe the intensity of
voltage-dependent attenuation. 0 is maximum attenuation, 1 is
no attenuation.

Within the cell model, we vary the amount of attenuation along
the apical trunk as a function of distance from the cell body
such that proximal sections show little attenuation and distal
sections show comparably more (with the exception of distal
obliques).

We typically decay ar2 linearly from proximal to distal with
the maximum and minimum values of decay as
parameters. Initialize these parameters: 
*/

max_ar2=0
min_ar2=0
decay_start=0 /* The distance at which decay starts. 
              The distance at which decay ends.
              */
decay_end=0

strdef ar24_tmp_str
objref  strobj, ar24_f
strobj=new StringFunctions()
ar2_firsttime=1

proc ar2_log() {

  if (!ar2_firsttime) { return }

  ar24_f=new File() 
  sprint($o3.tmp_str3, "%s/ar2_log", $o3.generic_dir)
  ar24_f.wopen($o3.tmp_str3)
  ar24_f.printf("%s:",$s1)

  while (strobj.substr($s2, "*") > -1) {
    //printf("substr:%d\n", strobj.substr($s2, "*"))

      index=strobj.head($s2, "\\*", ar24_tmp_str)
    //printf("index:%d\n", index)

      strobj.right($s2, 1+index)
     //printf("%s ... %s \n", ar24_tmp_str, $s2)

      $o3.create_variable("ar24_val", ar24_tmp_str)
      ar24_f.printf("%s:%g:", ar24_tmp_str, ar24_val)
     //printf("%s:%g", ar24_tmp_str, ar24_val)
  }

  $o3.create_variable("ar24_val", $s2)
  ar24_f.printf("%s:%g\n", $s2, ar24_val)
  //printf("%s:%g\n", $s2, ar24_val)

  ar24_f.close()
  ar2_firsttime=0
}


/*______ END OF PROCEDURES ROUTINELY USED IN CELL SETUP______*/



/* ____________   CELL SET-UP PROCEDURE    _____________ */

maximum_segment_length=0.5*25
strdef sectype

proc cell_setup() {

  // Set passive membrane properties
  
    $o1.defvar("passive", "Rm_default", "200000","Specific membrane resistance. ")
    $o1.defvar("passive", "Rm_trunk", "Rm_default","Non-oblique dendritic specific membrane resistance.")
    $o1.defvar("passive", "Rm_non_trunk", "Rm_default","Apical oblique specific membrane resistance.")
    $o1.defvar("passive", "Rm_basal", "Rm_default","Basal specific membrane resistance.")
    $o1.defvar("passive", "Rm_tip", "Rm_default","Tip specific membrane resistance.")
    $o1.defvar("passive", "Rm_soma", "Rm_default", "Somatic specific membrane resistance.")
    $o1.defvar("passive", "Rm_axon", "Rm_default", "Axonal specific membrane resistance. ")
    $o1.defvar("passive", "Ra_default", "50","Specific axial resistance. ")
    $o1.defvar("passive", "Ra_basal", "Ra_default","Basal specific axial resistance.")
    $o1.defvar("passive", "Ra_trunk", "Ra_default","Somatic specific axial resistance.")
    $o1.defvar("passive", "Ra_non_trunk","Ra_default","Somatic specific axial resistance.")
    $o1.defvar("passive", "Ra_soma", "Ra_default","Somatic specific axial resistance.")
    $o1.defvar("passive", "Ra_tip", "Ra_default","Apical tip specific axial resistance.")
    $o1.defvar("passive", "Ra_axon", "Ra_default","Axonal specific axial resistance. ")
    $o1.defvar("passive", "Cm_default", "1","Default specific capacitance.")
    $o1.defvar("passive", "Cm_axon", "Cm_default","Axonal specific capacitance. ")
    $o1.defvar("passive", "Cm_soma", "Cm_default","Somatic specific capacitance. ")
    $o1.defvar("passive", "Cm_trunk", "Cm_default","Trunk specific capacitance.")
    $o1.defvar("passive","Cm_non_trunk", "Cm_default","Oblique specific capacitance.")
    $o1.defvar("passive", "Cm_basal", "Cm_default","Basal specific capacitance.")
    $o1.defvar("passive", "Cm_tip", "Cm_default","Apical tip specific capacitance.")

    $o1.defvar("general", "v_init", "-70","Initial voltage of sections.")


  // SEVERELY affects experiment results
  $o1.defvar("general", "celsius", "34","Temperature of slice.")
        
  // Set HH Sodium - Potassium properties

    $o1.defvar("channel:na", "gna_default", "0.007", "Default Na conductance.")
    $o1.defvar("channel:na", "gna_trunk", "gna_default", "Trunk Na conductance. ")
    $o1.defvar("channel:na", "trunk_non_trunk_ratio", "1", "Non-trunk Na conductance ratio")
    $o1.defvar("channel:na", "gna_non_trunk", "trunk_non_trunk_ratio*gna_default", "Non-trunk Na conductance")
    $o1.defvar("channel:na", "gna_tip", "gna_non_trunk", "Oblique Tip Na conductance.")
    $o1.defvar("channel:na", "gna_basal", "gna_default", "Basal Na conductance.")
    $o1.defvar("channel:na", "gna_axon", "0.1", "Axonal Na conductance. ")
    $o1.defvar("channel:na", "gna_soma", "gna_default", "Somatic Na conductance. ")

// Set delayed rectifier properties as a percent of Na conductances
   
    $o1.defvar("channel:na-kdr", "kdr_div", "10.0/1.24", "Default ratio of Na to kdr conductances")
    $o1.defvar("channel:na-k", "kdr_div_soma", "10.0/2.0", " Soma Na-kdr divider")
    $o1.defvar("channel:na-k", "kdr_div_axon", "kdr_div_soma", " Axon Na-kdr divider")
    $o1.defvar("channel:na-k", "kdr_div_trunk", "kdr_div"," Trunk Na-kdr divider")
    $o1.defvar("channel:na-k", "kdr_div_non_trunk", "kdr_div", "Non-trunk Na-kdr divider")
    $o1.defvar("channel:na-k", "kdr_div_tip", "kdr_div", "Oblique Tips Na-kdr divider")
    $o1.defvar("channel:na-k", "kdr_div_basal", "kdr_div", "Basal Na-kdr divider")

// Set delayed rectifier conductances

    $o1.defvar("channel:kdr", "gkdrbar_default", "gna_default/kdr_div", "Default KDR conductance. ")
    $o1.defvar("channel:kdr", "gkdrbar_axon", "gna_axon/kdr_div_axon",  "Axonal  KDR conductance. ")
    $o1.defvar("channel:kdr", "gkdrbar_basal", "gna_basal/kdr_div_basal","Basal  KDR conductance. ")
    $o1.defvar("channel:kdr", "gkdrbar_soma", "gna_soma/kdr_div_soma", "Somatic  KDR conductance. ")
    $o1.defvar("channel:kdr", "gkdrbar_trunk", "gna_trunk/kdr_div_trunk", "Trunk KDR conductance. ")
    $o1.defvar("channel:kdr", "gkdrbar_non_trunk", "gna_non_trunk/kdr_div_non_trunk", "Non-Trunk KDR conductance. ")
    $o1.defvar("channel:kdr", "gkdrbar_tip", "gna_tip/kdr_div_tip", "Oblique Tip KDR conductance. ")
    $o1.defvar("channel:kdr", "gkdrbar_basal", "gna_basal/kdr_div_basal", "Basal KDR conductance. ")

    $o1.xopen_library("Terrence","cut-sections")
    cut_sections(maximum_segment_length)

// make 3-d mapping of cell sections

    $o1.xopen_library("Terrence","map-segments-to-3d")
    map_segments_to_3d()

// prepare to make a graph with cell configuration
    $o1.tmpo2=new Shape()
        
// Set initial conductance values 

    soma_caL = 0.014     
    //soma_car = 0.0003
    //gsomacar = 0.003 
    soma_caLH =0.95*0.000333
    soma_caT = 0.0001
    soma_kca = 0.0001
    soma_km = 0.06
    mykca_init = 1.1*0.015*3
    soma_hbar = 1.872e-5
    soma_kap = 0.0075
    kad_init = 1.04*0.0072

// Start inserting mechanisms in cell

      sectype ="soma"
      forsec "soma" {

            insert hha2    // HH mechanism with low threshold for Na spikes (-57 mV)
                    gnabar_hha2 = gna_soma
                    gkbar_hha2  = gkdrbar_soma
                    gl_hha2     = 0
                    el_hha2     = v_init
                    ena         = 50

            insert pas    // leak conductance
                    g_pas =  1/Rm_soma
                    e_pas = v_init
                    Ra    = Ra_soma

            insert h     // h current 
                   gbar_h  = soma_hbar
                   K_h     = 8.8
                   vhalf_h = -82

            insert kap  // proximal A current
                   gkabar_kap = soma_kap
                   ek         = -80
			   
            insert km  // m-type potassium current
                   gbar_km    = soma_km
                   ek         = -80 
			              
            insert cal // HVA Ca++-L type current
                   gcalbar_cal = soma_caL/2
           
            insert cat // LVA Ca++-T type current
                   gcatbar_cat = soma_caT/2

            //insert somacar // HVAm Ca++-R type current
            //       gcabar_somacar = gsomacar
            
            insert kca   // K(Ca) sAHP potassium type current
                   gbar_kca = 5*soma_kca
         
            insert mykca // K(Ca) mAHP potassium type current
	           gkbar_mykca = 5.5*mykca_init
        
            insert cad  // calcium pump/buffering mechanism

            $o1.tmpo2.color(2)            
      }

//  Configure Axon

      sectype="axon"
      forsec axon_sec_list {

              insert hha2  // HH mechanism with low threshold for Na spikes (-57 mV)
                    gnabar_hha2 = gna_axon
                    gkbar_hha2  = gkdrbar_axon
                    gl_hha2     = 0
                    el_hha2     = v_init
                    ena         = 50
     
              insert pas  // leak conductance
                    g_pas       = 1/Rm_axon
                    e_pas       = v_init
                    Ra          = Ra_axon
                    cm          = Cm_axon

               insert km  // m-type potassium current
                    gbar_km     = 0.5*soma_km
                    ek          = -80
                    
   
               $o1.tmpo2.color(1)
      }
    
//  Configure apical trunk
 
      forsec apical_trunk_list {

          apical_h_insert_sig($o1)    // Inserting h-current
          apical_caR_caLH_insert($o1) // Inserting Ca++ R-type and Ca++ L-type currents
          apical_caT_insert($o1)      // Inserting Ca++ T-type current
          apical_kca_insert($o1)      // Inserting K(Ca) sAHP and mAHP potassium currents
          apical_km_insert($o1)       // Inserting m-type potassium current
          A_insert($o1)               // Inserting A-current
   
          insert hha_old // HH mechanism with high threshold for Na spikes (-50 mV)
                    gnabar_hha_old = gna_trunk
                    gkbar_hha_old  = gkdrbar_trunk
                    ena            = 50
                    
          insert pas // leak conductance
                    e_pas          = v_init
                    el_hha_old     = v_init
                    Ra             = Ra_trunk
                    cm             = Cm_trunk

          Rm_sigmoid($o1)   // configure Rm along apical trunk
          Ra_sigmoid($o1)   // configure Ra along apical trunk
          $o1.tmpo2.color(4)
           
// Set the Na+ spike attenuation variable (linearly decreasing from soma to 300 um)

         $o1.defvar("channel:na", "max_ar2", "0.95", "Somatic value of ar2")
         $o1.defvar("channel:na", "min_ar2", "0.30", "Minimum value of ar2")
         $o1.defvar("channel:na", "decay_end", "300.0*2.0", "Distance beyond which all values are min_ar2")
         $o1.defvar("channel:na", "decay_start", "50.0*2.0", "Distance at which ar2 starts to decrease")
         m_ar2 = (max_ar2 - min_ar2)/(decay_start - decay_end)
            for (x) {
                xdist = find_vector_distance_precise(secname(),x)
                if (xdist < decay_start) { 
                  ar2_hha_old(x) = max_ar2 
                } else if (xdist > decay_end) {               
                  ar2_hha_old(x) = min_ar2 
                } else {               
               // ar2_hha_old(x) = max_ar2 + m_ar2*xdist
			ar2_hha_old(x) = max_ar2 + m_ar2*(xdist - decay_start)

                }
            }
            ar2_log("linear", "min_ar2*max_ar2*m_ar2*decay_start*decay_end",$o1)
      }


// Configure the apical-non-trunk section: insert basic mechanisms  
 
    sectype = "apical non-trunk"

    forsec apical_non_trunk_list {
            
              insert hha_old // HH mechanism with high threshold for Na spikes (-50 mV)
                     gnabar_hha_old = gna_non_trunk
                     gkbar_hha_old  = gkdrbar_non_trunk
                     el_hha_old     = v_init  
                     ena            = 50
              
               insert pas // passive properties
                     g_pas     = 1/Rm_non_trunk
                     e_pas     = v_init                     
                     Ra        = Ra_non_trunk
                     cm        = Cm_non_trunk
             
                $o1.tmpo2.color(3)
    }
    khoblique_peri_decay($o1)  // Configure the apical oblique dendrites

// Configure the basal dendrites

   sectype = "basal tree"
   forsec basal_tree_list {
            insert hha_old // HH mechanism with high threshold for Na spikes (-50 mV)
                    gnabar_hha_old = gna_basal
                    gkbar_hha_old  = gkdrbar_basal
                    el_hha_old     = v_init
                    gl_hha_old     = 0
  
            insert pas // passive properties
                    g_pas          = 1/Rm_basal
                    e_pas          = v_init
                    Ra             = Ra_basal
                    cm             = Cm_basal

            insert kap // Insert proximal A current
                  gkabar_kap       = 2.5*soma_kap

         Ra_sigmoid($o1) // configure Ra
        $o1.tmpo2.color(5)
      }
   khbasal_fixed($o1) // Configure basal dendrites         
   
    forsec "soma" { g_pas=1/Rm_soma } // force Rm at all soma sections

    forall if (ismembrane("hha_old")) {  // zero out gl (leak conductance) since g_pass is taking its place
       gl_hha_old = 0  
       ek         = -80 
	  
     }
     forall if (ismembrane("hha2")) { // zero out gl (leak conductance) since g_pass is taking its place
       gl_hha2 = 0  
       ek      = -80
	  
     }

    forall if(ismembrane("ca_ion")) {
      eca = 140
      ion_style("ca_ion",0,1,0,0,0)
      vshift_ca = 0
    }

  // Account for spines (obsolete in this case) 

   forall {
        for (x) {
          if (x > 0 && x < 1) {
                diam(x)=diam(x)*1.0
                }
        }
   }

   // Print a postcript file in the generic directory with the cell configuration

//   sprint($o1.tmp_str2, "%s/configure_sections.eps", $o1.generic_dir)
//   $o1.tmpo2.printfile($o1.tmp_str2)
  
// Comment FM: current-balance forces e_pas to arbitrarily low values, which produces paradoxical results e.g. if ih conductances are increased. Switched off for this simulation, resulting in a resting membrane potential of ~-68mV.
//   $o1.xopen_library("Terrence","current-balance") // balance current to -70 mV
//   current_balance(v_init)

}

proc init() {
finitialize(v_init)
fcurrent()
}