/* ---------------------   PROCEEDURES USED IN CELL SETUP  -------------------------*/

/*  To make the distal membrane less conductive, vis-a-vis Stuart G.
and Spruston N., J. Neuroscience 18(10) 3501-3510, 1998, we deceay 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",   "")
     $o1.defvar("channel:pas","steep",   "50",   "")

     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",  "35", "")             
     $o1.defvar("channel:pas","dhalf",   "210",   "")
     $o1.defvar("channel:pas","steep",   "50",   "")

     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 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",   "")
     $o1.defvar("channel:h","steep",   "50",   "")

     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 < xdist < 350. For xdist < 100,
g_A_distal(x) = 0 and for xdist > 350 g_A_distal(x) = constant =
g_A_distal(350) 
*/

proc A_insert() {
     $o1.defvar("channel:kap","kap_distal_maxfactor", "1", "maximum cond. factor in dendrites")
     $o1.defvar("channel:kap","kap_distal_distance", "100", "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", "distance in dendrites for maximum cond.")

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

       } else if (xdist < kad_distal_distance ) {
          gkabar_kap(x) = 0
          gkabar_kad(x) = kad_distal_maxfactor*kad_init*fr
          gbar_kdBG(x) = kdBG_init
          
       } else {
          gkabar_kap(x) = 0
          gkabar_kad(x) = kad_distal_maxfactor*kad_init
          gbar_kdBG(x) = kdBG_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", "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 calsium pumps along the
apical trunk with maximum conductances in 50 < xdist < 200 
*/

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", "distance in dendrites for maximum cond.")
  
     for (x) {  
       xdist = find_vector_distance_precise(secname(),x)
       fr = xdist/kca_distal_distance 
       insert cad    // calsium buffering mechanism
       insert cadL    // HVAl L-type calsium buffering mechanism
       insert cadN    // HVAm N-type calsium buffering mechanism
       insert kca    // slow AHP K++ current
       insert mykca  // medium AHP K++ current

	if (xdist < kca_distal_distance) {       
            gbar_kca(x) = 5*soma_kca
            gkbar_mykca = 5*mykca_init*(kca_distal_distance - xdist)/kca_distal_distance
        } else {
            gbar_kca(x) = 0.25*soma_kca
            gkbar_mykca = 0.25*mykca_init
       }

     }
}

/* Inserting LVA Ca++ T-type channels along the apical trunk in
a linearly increasing manner, for xdist > 100 um 
*/

proc apical_caT_insert() {
     $o1.defvar("channel:cat","caT_distal_distance", "300", "distance in dendrites for maximum cond.")
     $o1.defvar("channel:cat","caT_proximal_distance", "100", "distance in dendrites for maximum cond.")

     for (x) {  
        xdist = find_vector_distance_precise(secname(),x)
        fr = xdist/caT_distal_distance
        insert cat  
         if (xdist < caT_proximal_distance) {
            gcatbar_cat(x) =  soma_caT/10 
	 }	else if (xdist < caT_distal_distance) {
           gcatbar_cat(x) = soma_caT*(1+2.4*fr)
          // gcatbar_cat(x) = soma_caT*(1+6*fr)
        } else {
           //gcatbar_cat(x) = 7*soma_caT 
          gcatbar_cat(x) = 3.4*soma_caT 
        } 
    }
}


/* Inserting HVAm Ca++ R-type and N-type, and HVA L-type channesls along
the apical trunk. The R-type current is distributed as T-type current, in 
a linearly increasing manner, for xdist < 300 um. 
The L-type current is distributed in a 
linearly decreasing conductance for distances xdist  < 100 um
while the N-type current is distributed in a
fixed conductance, as does L-type for distances xdist  > 100 um
*/

proc apical_caR_insert() {
     $o1.defvar("channel:car","caR_distal_distance", "300", "distance in dendrites for maximum cond.")

     for (x) {  
         xdist = find_vector_distance_precise(secname(),x)
         fr = xdist/caR_distal_distance
         insert car
         if (xdist < 50) {
            gcabar_car(x) =  soma_caR/2 
	 }	else if (xdist < caR_distal_distance) {
            gcabar_car(x) =  soma_caR*(1+5*fr)
         } else {
            gcabar_car(x) = 6*soma_caR         0 

         } 

     }
}


proc apical_caL_caN_insert() {
     $o1.defvar("channel:cal","caL_distal_distance", "100", "distance in dendrites for maximum cond.")

     for (x) {  
         xdist = find_vector_distance_precise(secname(),x)
         fr = xdist/caL_distal_distance
         insert cal
         insert can
         if (xdist < caL_distal_distance) {
            gcalbar_cal(x) = soma_caL*(1-2.*fr/3.)
         gcalbar_can(x) = soma_caN*(1-2.*fr/3.)
         } else {
            gcalbar_cal(x) = soma_caL/6.
         gcalbar_can(x) = soma_caN/4.
         }
     }
}
/* Seting 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 um from 
the parent trunk are set equal to the parent trunk conductances. For dendrites located beyond  300 (or/and 350) 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", "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=gcabar_car(1) hold_cal=gcalbar_cal(1) hold_can=gcalbar_can(1) 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_kdBG=gbar_kdBG(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_kdBG = gbar_kdBG(1)
        trunk_h  = gbar_h(1)
        trunk_pas = g_pas(1)
        trunk_Ra = Ra 
        trunk_car  = gcabar_car(1)
        trunk_can  = gcalbar_can(1)
        trunk_cal  = gcalbar_cal(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] {
//           printf("\t-- %s --\n", secname()) access all oblique paths from parent trunk to root oblique
                           
	   if (!sec_count) {              // skip all trunk sections
               sec_count=sec_count+1
               continue
            }         
                insert kap 
                insert kad
                insert kdBG
                insert h     
                insert pas         
                insert car
                insert can
                insert cal
                insert cat
                insert kca
                insert mykca
                insert km
                insert nap
                insert cad
                insert cadL
                insert cadN

                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_kdBG(x) = trunk_kdBG   
                        gbar_h(x) = trunk_h  
                        g_pas(x) = trunk_pas
                        gcabar_car(x) = trunk_car
                        gcalbar_can(x) = trunk_can
                        gcalbar_cal(x) = trunk_cal
                        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_kdBG(x) = hold_kdBG   
                        gbar_h(x) = hold_h  
                        g_pas(x) = hold_g_pas

                        Ra = Ra_default
                        gcabar_car(x) = 2*hold_car
                        gcalbar_can(x) = hold_can 
                        gcalbar_cal(x) = hold_cal 
                        ar2_hha_old(x) = 0.8*hold_ar2_hha_old  // set to 80% of dend. 46 value  
                        gbar_kca(x) = hold_kca
                        gkbar_mykca = mykca_init 
                        gnabar_nap(x) = hold_nap  
                        gbar_km(x) = hold_km             // set to 2 times the dend 46 value

             
                        if (xdist > 300 ) {                // for xdist > 300 um increase:
                           gkabar_kad(x) = 1.3*1.9*hold_kad      // A-current,
                           gcabar_car(x) = 10*hold_car       // Ca++-R current,
                           gkbar_hha_old(x) = 1.07*hold_kdr // delayed rectifier
                         }

                        if (xdist > 350) {               // for xdist > 350 um increase even more:
                           gcabar_car(x) = 12*hold_car       // Ca++-R current,
                           ar2_hha_old(x) = 0.7*hold_ar2_hha_old  // set to 80% of dend. 46 value  
                           gnabar_nap(x)=2*hold_nap      // Na+ persistent                   

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


/* Seting 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 1.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_kdBG=gbar_kdBG(1) hold_h=gbar_h(1)}", khsection)
execute1($o1.tmp_str)

forsec basal_tree_list {

      insert kap 
      insert kad
      insert kdBG
      insert h                
      insert pas
     
      for (x) {
         gkabar_kap(x) = 1.6*hold_kap
         gkabar_kad(x) = 1.6*hold_kad
         gbar_kdBG(x) = hold_kdBG
         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 PROCEEDURES ROUTINELY USED IN CELL SETUP______*/

//__________________________________________________________________________________________________________


/* ____________      CELL SET-UP PROCEEDURE      _____________ */

maximum_segment_length=75
strdef sectype
objref CAN_temp, CAL_temp, CAT_temp, KAD_temp, KAP_temp, NA_temp

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", "-66","Initial voltage of sections.")
   //$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.0", "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", "60.0/23.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 rectifie 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_caR = 0.00015
    soma_caN = 0.0002
    soma_caL = 0.0003
    soma_caT = 0.00015 
    soma_kca = 0.005
    soma_km = 0.00022
    mykca_init = 0.0003
    soma_hbar = 2.4*0.0000078
    soma_kap = 0.006
    soma_kdBG = 0.0006 
    kad_init = 1.04*0.0072
    kdBG_init = 0.001

// 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 kdBG  //  D current
                   gbar_kdBG = soma_kdBG
                   ek         = -80
		   
            insert km  // m-type potassium current
                   gbar_km    = soma_km
                   ek         = -80 
           
            insert cal // HVAl Ca++-L type current
                   gcalbar_cal = soma_caL
           
            insert can // HVAm Ca++-N type current
                   gcalbar_can = soma_caN
           
            insert car // HVAm Ca++-R type current
                   gcabar_car = soma_caR/10
            
            insert cat // LVA Ca++-T type current
                   gcatbar_cat = soma_caT/10

            insert kca   // K(Ca) sAHP potassium type current
                 
                   gbar_kca = 5*soma_kca
         
            insert mykca // K(Ca) mAHP potassium type current
	           gkbar_mykca = 4*mykca_init
        
            insert cad  // [Ca++] pool model

            insert cadL  // L-type [Ca++] pool model

            insert cadN  // N-type [Ca++] pool model

            $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_caT_insert($o1)      // Inserting LVA Ca++ T-type current
          apical_caR_insert($o1) // Inserting HVAm Ca++ R-type and N-type currents
          apical_caL_caN_insert($o1) // Inserting HVAl Ca++  L-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.8", "Somatic value of ar2")
         $o1.defvar("channel:na", "min_ar2", "0.25", "Minimum value of ar2")
         $o1.defvar("channel:na", "decay_end", "300.0", "Distance beyond which all values are min_ar2")
         $o1.defvar("channel:na", "decay_start", "50.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_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

            insert kdBG // Insert D current
                  gbar_kdBG       = soma_kdBG

         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         = -77 
     }
     forall if (ismembrane("hha2")) { // zero out gl (leak conductance) since g_pass is taking its place
       gl_hha2 = 0  
       ek      = -77 
     }

    forall if(ismembrane("ca_ion")) {
      eca = 140
      cai =  2.4e-4 // for pump  
      cao = 2
      ion_style("ca_ion",0,1,0,0,0)
      vshift_ca = 0
    }

    forall if(ismembrane("cal_ion")) {
      eca = 140
      cali =  0.8e-4 // for sIAHP, although what counts is the ratio car = cai/cac, cac=0.025 => car=1e-3, minf =car/(1+car)
      ion_style("cal_ion",0,1,0,0,0)
      vshift_cal = 0
    }

    forall if(ismembrane("can_ion")) {
      eca = 140
      cani = 0.8e-4 // for cagk
      ion_style("can_ion",0,1,0,0,0)
      vshift_can = 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)
   
   $o1.xopen_library("Terrence","current-balance") // balance current to -70 mV
   current_balance(v_init)

}

proc init() {
finitialize(v_init)
fcurrent()
cvode.re_init()
}