objref nil

strdef astro_name
astro_name = "CA1"
celsius = 34
// init model
objref cvode,py_obj
{
    //activate CVODE
    cvode = new CVode()
    cvode.use_daspk(1)
    cvode.active(1)
    //cvode.minstep(0.0001)
    cvode.cache_efficient(1)
    //cvode.atol(1e-6)
    //cvode.rtol(1e-5)
}
// model default parms
double lenUnits[1]
lenUnits = 1

objref  secref,sGap,gaplist
gaplist = new List()

gapcount = 30000 //NAGY (2007) CellComm Adhesion 
//gapcount = 0
ki_sim_flag = 0

proc set_ki_sim() {localobj sr
//trigger ki sim
    if (ki_sim_flag == 0) {
        ki_sim_flag = 1
    }
    forsec $o1{
        insert kdifl
        sr = new SectionRef()
        ki0_kdifl = 120 
        if (sr.nchild == 0 || sr.has_parent() ==  0) {
            gap_kdifl = 1
        }
    }
}

func calc_fhspace(){local min_ecs,max_ecs,max_d,min_d
// set fhspace 
    min_ecs = 400
    max_ecs = 1000
    min_d = 0.1
    max_d = 6.5 

    return min_ecs + (max_ecs-min_ecs)*log($1/min_d)/log(max_d/min_d) 
}

// clear morphologyto
// create astrocyte
total_surf = 0
{
    forall {
        delete_section()
    }

    // load morphology file
    //xopen("./Geometry/threeCompartmentGeom.hoc")
    // xopen("./Geometry/NodeMod.hoc")
    {xopen("./Geometry/GeometryAstrocyteCA1.hoc")}

    // inserting membrane mechanisms
    forall {
        Ra = 100
        cm = 0.8
        insert pas
        e_pas = -85
        g_pas = 1/1450        
        insert kir2
        insert nakpump
        // insert ncx
        // imax_ncx = 10
        //insert twik
        //for (x) total_surf = total_surf + area(x)
        insert kleak
        insert naleak
        insert clleak
        //clleak is for purely creating cl ion

        insert k_acc
        fhspace_k_acc = calc_fhspace(diam)
        if (ki_sim_flag == 1 ) {
            insert kdifl
        }
        //insert na_acc
        //insert nai_acc
        //insert ca_acc
        insert GEVI

        if (L > lenUnits) {
            nseg = int(L/lenUnits)
        }
        secref = new SectionRef()
        if (secref.nchild == 0 && gapcount > 0){
            if (ki_sim_flag == 1&& ismembrane("kdifl")) {
                gap_kdifl = 0
                no_clamp_kdifl = 0
            }
            sGap = new Gap(0.7)
            gaplist.append(sGap)
            gapcount = gapcount - 1
        }

    }
}
//psection()
//print total_surf
//forall total_area_twik = total_surf
objref r
r = nil

proc koclamp() { 
  //clamp ko
    // print $1
    forall {
        flag_k_acc = 2
        ko0_k_acc = $1
        // psection()
    }
}

proc setSeed() {local seed
//set seed
    seed = $1 
    r = new Random(seed)
}

// Function to get end section
obfunc getPath() {localobj current_section,sl
// get path of current to soma section
    $o1 current_section = new SectionRef()
    sl = new SectionList()
    while (current_section.has_parent()) {
        current_section.sec sl.append()
        current_section.parent current_section = new SectionRef()
    }
    //sl.printnames()
    return sl
}

obfunc get_randomfinalSection() {local rint,countDist,nchildless,blacklist_count localobj child_sections, current_section, blacklist,secref
//get random end point further than $1 argument from soma
    child_sections = new SectionList()
    blacklist = new SectionList()
    // Start from the currently accessed section
    $o1 current_section = new SectionRef()
    current_section.root() current_section = new SectionRef()
    current_section.sec { distance(0,0.5) } // set origin at root
    // find total candidate
    nchildless = 0
    forall {
        secref = new SectionRef()
        if (secref.nchild == 0){
            nchildless = nchildless + 1
        }
    }
    // Iterate through parent sections
    blacklist_count = 0
    while (current_section.nchild > 0 && blacklist_count < nchildless) {
        current_section.sec {
            // psection()
            child_sections.append()
        }
        if (current_section.nchild > 1){
            rint = r.discunif(0,current_section.nchild - 1)
        } else if (current_section.nchild == 1) {
            rint = 0
        }
        current_section.child[rint] current_section = new SectionRef()
        // check distance and reselect if closer than 50
        current_section.sec countDist = distance(0.5)
        if (current_section.nchild == 0 && countDist < 30) {
            current_section.sec {
                blacklist.append()
            }
            blacklist_count = blacklist_count + 1
            // current_section.sec {
            //     psection()
            // }
            // printf("Found but changing\n")
            // go back and reselect if not suitable
            current_section.root() current_section = new SectionRef()
        }
    }
    return current_section
}

obfunc shiftPAP() {local shift_dist,totalShift localobj current_section
// shfit location by $2 from endpoint
    shift_dist = $2 //micron
    $o1 current_section = new SectionRef()
    totalShift = 0
    while (totalShift < shift_dist) {
        totalShift = totalShift + L
        current_section.parent current_section = new SectionRef()
    }
    //print "shifted PAP from end by ", totalShift
    return current_section
}

obfunc get_midAstrocytePAP() {localobj candidate
//get last section fitting criteria
    soma { distance(0,0.5) } // set origin at root
    forall {if (diam < $1 && distance(0.5) < $2) {
            candidate = new SectionRef()
    }} return candidate
}


obfunc get_randomSection() {local lenThr,rloc,rint localobj current_section, child_sections
//get random any section 
    lenThr = $2
    child_sections = new SectionList()
    // Start from the currently accessed section
    $o1 current_section = new SectionRef()
    current_section.root() current_section = new SectionRef()
    current_section.sec { distance(0,0.5) } // set origin at root
    // Iterate through parent sections
    while (current_section.nchild > 0) {
        current_section.sec {
            // psection()
            child_sections.append()
        }
        // random selection Goto child or self
        if (current_section.nchild > 1){
            rint = r.discunif(0,current_section.nchild)
        } else if (current_section.nchild == 1) {
            rint = 0
        }
        // if random self check if appropriate
        if (rint  == current_section.nchild) {
            if (current_section.sec.L / current_section.sec.nseg < lenThr) {
                rloc = r.discunif(0,current_section.sec.nseg) / current_section.sec.nseg
                // Simplified PAP
                // ToDo make smarter extract other PAPs
                // or specifically select as PAP
                create artificialPAP
                artificialPAP {
                    L = 0.3
                    diam = 0.1
                    nseg = 1
                }
                artificialPAP connect current_section.sec(rloc), 1

                return artificialPAP
            } else {
                rint = r.discunif(0,current_section.nchild - 1)                
            }
        }
        current_section.child[rint] current_section = new SectionRef()            
    }
    return current_section    
}

obfunc get_NodeSection() {local ID,skipCount localobj current_section,strobj
// find arbitrary defined Node named section
    ID = $2
    skipCount = 0
    strobj = new StringFunctions()
    forall {
        if (strobj.substr(secname(),"Node") >= 0) {
            if (ID == skipCount) {
                current_section = new SectionRef()
                return current_section
            } else {
                skipCount += 1
            }
        }
    }
    return
}

obfunc get_parent_sections() {local totalLen, lenThr localobj parent_sections, current_section 
// Function to get parent sections
    parent_sections = new SectionList()

    // Start from the currently accessed section
    // $o1 {psection()}
    $o1 current_section = new SectionRef()
    totalLen = 0
    lenThr = $2 // micron
    // Iterate through parent sections
    if (lenThr > 0) {
        current_section.sec {
            // psection()
            parent_sections.append()
        }
    }
    while (current_section.has_parent && totalLen < lenThr) {
        totalLen = totalLen + current_section.sec.L
        // current_section.sec {
        //     psection()
        // }

        current_section.parent {
            parent_sections.append()
            current_section = new SectionRef()
        }
    }
    // parent_sections.printnames()
    parent_sections.unique()
    return parent_sections
}


// objref sref,slPAP
objref slPAP,PAP

// soma sref = new SectionRef()
// get_randomfinalSection(sref).sec sref = new SectionRef()
// sref.sec slPAP = get_parent_sections(sref)
// forsec slPAP{psection()}
// slPAP.printnames()

obfunc getLeaf() {localobj sec,leaf
// get leaflet 
    forsec $o1 {
        sec = new SectionRef()
        // psection()
        if (sec.nchild == 0) {
            leaf = new SectionRef()
        }
    }
    return leaf
}
proc convertSoma2slPAP() {localobj sl
// convert soma section as defined PAP
    sl = new SectionList()
    soma sl.append()
    slPAP = sl
}

proc setK_range() {localobj sref
//set k in range
    forsec $o1{
        for (x) if (x >0 && x < $5) {
            sref = new SectionRef()
            if ($4 > 0){
                //instantaneous switch of bath if flag 1
                flag_k_acc(x) = $4
                //relative change of bath
                ko0_k_acc(x) = $2 + getPAPK(sref)
                //relative change of ko
                ko(x) = $2 + getPAPK(sref)
            } else {
                //relative change of ko
                //ko = $2 + getPAPK(sref)
                flag_k_acc(x) = 0
                //change of ko
                ko0_k_acc(x) = $3
            }
        }
    }
}


proc pb() {localobj sr,child
// get primary branch
    soma sr = new SectionRef()
    for i=0,sr.nchild-1 {
        sr.child[i] {
            diam = $1
        }
    }

}

obfunc random_pb() {local rloc localobj sr
// get random primary branch
    soma sr = new SectionRef()
    rloc = r.discunif(0,sr.nchild-1) 
    sr.child[rloc] sr = new SectionRef() 
    return sr
}

obfunc all_pb() {local rloc localobj sr,sl
// get all primary branch
    soma sr = new SectionRef()
    sl = new SectionList()
    soma sl.append()
    for i=0,sr.nchild-1 {
        sr.child[i] sl.append()
    }
    return sl
}

obfunc all_child() {local depth localobj sr,sl
//get all child of section
    $o1 sr = new SectionRef()

    sl = new SectionList()
    sr.sec sl.append()
    depth = $2 
    while (depth > 0) {
        forsec sl {
            sr = new SectionRef()
            for i=0,sr.nchild - 1{
                sr.child[i] sl.append()
            }
        }
        depth = depth - 1
    }
    return sl
}




proc convertPB2slPAP() {localobj sl
// convert primary branch to PAP format
    sl = new SectionList()
    sl.append()
    slPAP = sl
}



// inserting NMDARs
objref sNMDA, NMDAs, nc, ncNMDAList,stim

NMDAs = new List()
ncNMDAList = new List()

// Below calls were buggy so direct call from python h() interface
// proc initStim() {
//     stim = new NetStim(.5)
//     stim.start = $1
//     stim.number = 1
//     stim.interval = 1
//     stim.noise = 0
// }

// proc setStimParms() {
//     stim.number = $1
//     if ($2 > 0) {
//         stim.interval = $2
//     } else {
//         stim.interval = tstop
//     }
// }
// slPAP.printnames()
// print(lenPAP)

proc setNMDAs(){local lenPAP
//initialize NMDAR
    lenPAP = 0
    // $o1.printnames()
    forsec $o1 {
        //sNMDA = new Exp5NMDA(0.5)
        //NMDAs.append(sNMDA)
        //nc = new NetCon(stim,NMDAs.o(lenPAP))
        segLen = L / nseg
        if (segLen >= lenUnits){
            for i = 0,nseg-1 {
                pos = segLen * (i+0.5)
                normPos = pos/L
                sNMDA = new Exp5NMDA_N2C(normPos)
                NMDAs.append(sNMDA)
                nc = new NetCon(stim,NMDAs.o(lenPAP))
                ncNMDAList.append(nc)
                lenPAP = lenPAP + 1
            }
        } else {
            sNMDA = new Exp5NMDA_N2C(0.5)
            NMDAs.append(sNMDA)
            nc = new NetCon(stim,NMDAs.o(lenPAP))
            ncNMDAList.append(nc)
            lenPAP = lenPAP + 1
        }
    }
}


// setup NMDAR call for finit
proc fINITNMDA(){
    for i = 0, ncNMDAList.count - 1 {
        ncNMDAList.o(i).weight = 1
        ncNMDAList.o(i).delay = 0
        // print(nc.weight)
    }
}
objref FinNMDA
FinNMDA = new FInitializeHandler(3,"fINITNMDA()")

// inserting GABAaRs
objref sGABAa, GABAas, nc, ncGABAaList

GABAas = new List()
ncGABAaList = new List()

// slPAP.printnames()
// print(lenPAP)
proc setGABAas(){local lenPAP
// initialize GABAR
    lenPAP = 0
    // $o1.printnames()
    forsec $o1 {
        segLen = L / nseg
        if (segLen >= lenUnits){
            for i = 0,nseg-1 {
                pos = segLen * (i+0.5)
                normPos = pos/L
                sGABAa = new inhSyn(normPos)
                GABAas.append(sGABAa)
                nc = new NetCon(stim,GABAas.o(lenPAP))
                ncGABAaList.append(nc)
                lenPAP = lenPAP + 1
            }
        } else {
            sGABAa = new inhSyn(0.5)
            GABAas.append(sGABAa)
            nc = new NetCon(stim,GABAas.o(lenPAP))
            ncGABAaList.append(nc)
            lenPAP = lenPAP + 1
        }
    }
}

// set GABAR for finit
proc fINITGABAa(){
    for i = 0, ncGABAaList.count - 1 {
        ncGABAaList.o(i).weight = 1.5
        ncGABAaList.o(i).delay = 0
        // print(nc.weight)
    }
}
objref FinGABAa
FinGABAa = new FInitializeHandler(3,"fINITGABAa()")

objref sGluT, GluTs,ncGluList

GluTs = new List()
ncGluList = new List()

proc setGluTs(){local lenPAP localobj sref
//initialize GluTs
    // $o1.printnames()
    lenGluTs = 0
    forall {
        segLen = L / nseg
        for i = 0,nseg-1 {
            pos = segLen * (i+0.5)
            normPos = pos/L
            sGluT = new GluTrans(normPos)
            GluTs.append(sGluT)
            ifsec $o1 {
                // psection()

                // print(lenPAP)
                nc = new NetCon(stim,sGluT)
                ncGluList.append(nc)
            }
            lenGluTs = lenGluTs + 1
        }
    }

}

//set GluTs for finit
proc fINITGLUT(){
    for i = 0, ncGluList.count - 1 {
        ncGluList.o(i).weight = 1
        ncGluList.o(i).delay = 0
        // print(nc.weight)
    }
}
objref FinGluT
FinGluT = new FInitializeHandler(3,"fINITGLUT()")

ko0 = 3.5

//initialize ion parms 
proc initIon(){local iki,inai
    iki = 120 //ek set to -92
    inai = 15 // Verhratsky A 2019 review

    // set global Ki
    ki0_k_ion = iki
    nai0_na_ion = inai
    nao0_na_ion = 140


    // set initial Ko Ki
    forall {
        nao = 140
        nai = inai
        //nai0_nai_acc = inai
        ko = ko0 
        ki = iki
        if (ki_sim_flag == 1&& ismembrane("kdifl")) {
            ki0_kdifl = iki 
        }
        ko0_k_acc = ko0
        //kob_twik = iki 
        clo = 130
        cli = 30
        //cao = 2
        //cai = 50e-6 // 50 nM
        km_na_nakpump = inai
        km_k_nakpump = ko0 
    }
}


objref FinIon
{FinIon = new FInitializeHandler(1,"initIon()")}
// if no na_acc
{ion_style("na_ion",1,1,1,0,0)}

// Experimental manipulations
proc setK(){local tmp localobj sref
// define k in section
    // $o1.printnames()
    forsec $o1 {
        sref = new SectionRef()
        if ($4 > 0){
            //instantaneous switch of bath if flag 1
            flag_k_acc = $4
            //relative change of bath
            ko0_k_acc = $2 + getPAPK(sref)
            //relative change of ko
            ko = $2 + getPAPK(sref)
        } else {
            //relative change of ko
            //ko = $2 + getPAPK(sref)
            flag_k_acc = 0
            //change of ko
            ko0_k_acc = $3
        }
        // psection()
        // printf("%g\n",getPAPK(sref))
    }
    soma sref = new SectionRef()
    // printf("%g\n",getPAPK(sref))
}

proc setK_point(){local tmp localobj sref
// define k at mid segment of section
    // $o1.printnames()
    forsec $o1 {
        sref = new SectionRef()
        if ($4 > 0){
            //instantaneous switch of bath if flag 1
            flag_k_acc(0.5) = $4
            //relative change of bath
            ko0_k_acc(0.5) = $2 + getPAPK(sref)
            //relative change of ko
            ko(0.5) = $2 + getPAPK(sref)
        } else {
            //relative change of ko
            //ko = $2 + getPAPK(sref)
            flag_k_acc(0.5) = 0
            //change of ko
            ko0_k_acc(0.5) = $3
        }
        // psection()
        // printf("%g\n",getPAPK(sref))
    }
    soma sref = new SectionRef()
    // printf("%g\n",getPAPK(sref))
}

obfunc getWholetree(){localobj sl
// get whole astrocyte
    sl = new SectionList()
    soma { sl.wholetree() }
    return sl
}

proc setkin(){
  // set internal k
    forall {
        ki = $1
    }
}
proc turnoff_ki_diff(){
  // trigger ki off
    if (ki_sim_flag == 1) {
        forall {
            if (ismembrane("kdifl")){
                Dk_kdifl = 0
            }
        }
}}

proc ki_clamp(){
  //clamp ki
    if (ki_sim_flag == 1) {
        forall {
            if (ismembrane("kdifl")){
                no_clamp_kdifl = 1 - $1 
            }
        }

}}

proc set_gap_k(){
  // set gap junction k baseline
    if (ki_sim_flag == 1) {
        forall {
            if (ismembrane("kdifl")){
                gap_kdifl = $1 
            }
        }
}}

proc setGEVI(){
  // change tau of  GEVI
    forall {
        tON_GEVI = $1
        tOFF_GEVI = $2
    }
}

proc setSlowing(){
  // set ko diffusion value by scaling
    forsec $o1 {
        slowing_k_acc = $2
    }
}

proc changeBaseline(){
  // set ko value
    forsec $o1 {
        ko0_k_acc = $2
    }
}


func getkin(){
  // get ki at soma
    forsec "soma" {
        return ki
    }
}

func getPAPK(){local papko
// get pap k
    $o1 {
        papko = ko
        // printf("%g\n",ko)
    } //warning message if return in between sectionList
    return papko
}

objref ic,vc,electrodeList
{electrodeList = new List()}

proc delaysec() {
  // shift voltage clamp event to resolve CVODE conflict
    vc.rs = 1e9
    //depends on cvode
    cvode.event($1, "vc.rs = 0.001")
}
objref fih


proc clampSwitch() {
  // electrode with various mode
    if ($1 > 4){
        // voltage clamp at far edge
        soma {vc = new SEClamp(0.01)}
        vc.dur1 = tstop
        vc.amp1 = $2  // mV depolarization (dV = 20)
        electrodeList.append(vc)
        //---------------------------------------------------
    } else if ($1 > 3) {
      // voltage clamp at leaf
        getLeaf(slPAP) {vc = new SEClamp(0.5)}
        vc.dur[0] = tstop
        vc.amp[0] = $2   // mV depolarization (dV = 20)
        electrodeList.append(vc)
    } else if ($1 > 1) {
        //------------current Clamp---------------------------
        if ($1 > 2){
            soma {ic = new IClamp(0.5)}
        } else {
            getLeaf(slPAP) {ic = new IClamp(0.5)}
        }
        ic.dur = tstop - 20
        ic.del = 0  // ms starts with glutamate
        ic.amp = $2   // nA current injection (1 pA)
        electrodeList.append(ic)
        //---------------------------------------------------
    } else if ($1 > 0) {
        // voltage clamp
        soma {vc = new SEClamp(0.5)}
        vc.dur1 = tstop
        vc.amp1 = $2  // mV depolarization (dV = 20)
        electrodeList.append(vc)
        //---------------------------------------------------

    } else {
        // Pulse Current
        getLeaf(slPAP) {ic = new IClamp(0.5)}
        ic.dur = 0.002
        ic.delay = 10  // ms starts with glutamate
        ic.amp = $2 * 0.001  // nA current injection
        electrodeList.append(ic)
        //---------------------------------------------------
    }
}


// Function to plot neuron topology with highlighted sections
// Uses NEURON functions (refer to python plot_shape for more modern)
proc plot_topology() {localobj rando, sref,slPAP,ps
    sref = new SectionList()
    soma { sref.wholetree() }
    // Plot the astrocyte's topology
    ps = new PlotShape(sref)

    // $o1.printnames()

    // Settings
    // ps.exec_menu("Shape Plot")
    ps.exec_menu("Show Diam")
    // Save the plot as a PostScript file
    ps.color_all(1)
    // if possible set custom color
    soma ps.color(3)
    ps.color_list($o2,4)

    ps.beginline()
    ps.line(30,-30)
    ps.line(50,-30)
    ps.flush()

    ps.printfile($s1)
}

proc plot_varMorph() {localobj rando, sref,slPAP,ps
    // plot variable in morphology
    sref = new SectionList()
    soma { sref.wholetree() }
    // Plot the astrocyte's topology
    ps = new PlotShape(sref)
    ps.variable($s1) // plot variable 2
    if (strcmp($s1,"v")==0){
        ps.scale(-90,-10)
    } else if (strcmp($s1,"ko")==0) {
        ps.scale(3,10)
    } else if (strcmp($s1,"Ri_inputRes")==0) {
        ps.scale(0,1500)
    } else if (strcmp($s1,"diam")==0) {
        ps.scale(0,5)
    } else if (strcmp($s1,"nseg")==0) {
        ps.scale(0,10)
    }
    ps.exec_menu("Shape Plot")
    ps.exec_menu("Show Diam")
    ps.flush()
    ps.printfile($s2)//print as arg 2 file name
}

proc plotPAP_topology() {local x,y,count,size localobj rando, sref,slPAP,ps
  // plot pap zoomed morph
    size = 10
    sref = new SectionList()
    soma { sref.wholetree() }// Think of a way to zoom
    // Plot the astrocyte's topology
    ps = new PlotShape(sref)
    ps.color_all(1)

    soma sref = new SectionRef()
    // $o2.printnames()

    // Highlight specified sections
    ps.color_list($o2,2)
    x = 0
    y = 0
    count = 0
    forsec $o2 {
        x = x + x3d(0.5)
        y = y + y3d(0.5)
        count = count + 1
        ps.len_scale(10)
    }
    x = x / count
    y = y / count
    // Settings
    ps.exec_menu("Shape Plot")
    ps.exec_menu("Show Diam")
    ps.size(x-size,x+size,y+size,y-size)
    // ps.view(x-size,y-size,2*size,2*size,0,0,size*20,size*20)
    ps.flush()
    ps.printfile($s1)
}

proc plotPAP_varMorph() {local size localobj rando, sref,slPAP,ps
// plot pap variable and zoomed morph
    size = 10
    sref = new SectionList()
    soma { sref.wholetree() }
    // Plot the astrocyte's topology
    ps = new PlotShape(sref)
    ps.variable($s1) // plot variable 2
    if (strcmp($s1,"v")==0){
        ps.scale(-80,-60)
    } else if (strcmp($s1,"ko")==0) {
        ps.scale(3.5,5)
    }
    soma sref = new SectionRef()
    // $o3.printnames()

    // Highlight specified sections
    ps.color_list($o3,2)
    x = 0
    y = 0
    count = 0
    forsec $o3 {
        x = x + x3d(0.5)
        y = y + y3d(0.5)
        count = count + 1
        ps.len_scale(10)
    }
    x = x / count
    y = y / count
    // Settings
    ps.exec_menu("Shape Plot")
    ps.exec_menu("Show Diam")
    ps.size(x-size,x+size,y+size,y-size)
    // ps.view(x-size,y-size,2*size,2*size,0,0,size*20,size*20)
    ps.flush()
    ps.printfile($s2)//print as arg 2 file name
}


proc measure_input_resistance() {localobj zz
// measure input resistance using Impedence set to no alternating current
    zz = new Impedance()
    zz.loc(0.5)  // sets origin for impedance calculations to middle of section
    zz.compute(0,1)  // DC input R
    Ri_inputRes = zz.input(0.01)
}

objref stim_ri
proc measure_input_resistance_direct() {
  // actually do current clamp
    stim_ri = new IClamp(0.5)
    stim_ri.del = $1 
    stim_ri.dur=$2
    stim_ri.amp=-0.01
}


proc getAllRi() {localobj all_sections
// find and set all Ri for section
    all_sections = new SectionList()
    all_sections.wholetree()

    forsec all_sections {  // Loop over all sections
        print secname()
        insert inputRes
        measure_input_resistance()
    }
}

// flag to trigger ko sim
proc ko_sim_off() {
  // no diffusion
    forall {
        flag_k_acc = 2
    }
}
proc ko_sim_on() {
  // simulate ko diffusion
    forall {
        flag_k_acc = 0
    }
}


proc kbath_off() {
  // slow clearance
    forall {
        tauk_0_k_acc = exp(700) // esenntially infinite kclearence (Never clears) 3/0
    }
}
proc kbath_on() {
  // reimplement clearance
    forall {
        tauk_k_acc = 1 //((1e-4)*fhspace_k_acc - diam/2) * ((1e-4)*fhspace_k_acc - diam/2)/2/Dk_k_acc
    }
}
proc kbath_rule() {
  //set clearence tau to arbitray value
    forall {
        tauk_0_k_acc = $1 // esenntially decide tauk
    }
}

proc set_kobase(){
  // set ko baseline
    forall {
        ko0_k_acc = $1
    }
}

proc setNak_pump(){
  // set nak pump total current
    forall {
        if ($1 == 0) {
            totalpump_nakpump = 0
        }
    }
}

proc setECS(){local soma_area,total_area,scaled_fhspace
// set ecs depth if flag $2 is true turn off 
    if ($2 == 0) {
        forall fhspace_k_acc = $1
    } else {
        soma_diam = 0
        soma {soma_diam = soma_diam + diam}
        forall {
            total_diam = 0
            total_diam = total_diam + diam
            scaled_fhspace = $1 * total_diam/soma_diam 
        }
    }
}

proc set_gleakNa() {local tmp_gk, rmp,count_kir,tmp_gna
// set gleakNa
    forall {
        rmp = $1 
        count_kir = count_kir2 + multiple_kir2*count_std_kir2

        tmp_gk = (count_kir *gkbar_kir2*A_kir2*sqrt(3)*(1e-4)*linf_kir2+ gleak_kleak*area(0.5))
        tmp_gna = -((rmp-ek)* tmp_gk)/(rmp-ena)
        tmp_gna = tmp_gna/area(0.5)
        gleak_naleak = tmp_gna
    }
}

func u_glut() {
  // u function for glutamate transporter voltage  dependency
    return exp($2*$1/(2*(26.7)))
}

proc print_progress(){local max_time
// print current progress
    if ($1 < 0) {
        max_time = tstop
    } else {
        max_time = $1
    }

    soma {
        insert prnt_prog
        completion_prnt_prog = max_time
    }

}

func get_distance() {local dx, dy, dz,xo,yo,zo
// get distance from soma 
    soma xo = x3d(0)
    soma yo = y3d(0)
    soma zo = z3d(0)
    dx = $1 - xo
    dy = $2 - yo
    dz = $3 - zo

    return sqrt(dx*dx+dy*dy+dz*dz)
}

func get_max_dist () { local maxDist,tmp
// get fartheset distance from soma
    maxDist = 0.0
    forall {
        for i=0, n3d() - 1 {
            tmp =  get_distance(x3d(i),y3d(i),z3d(i))
            if (tmp > maxDist) {
                maxDist = tmp
            }
        } 
    }
    return maxDist
}



objref shell_compartments
shell_compartments = new List()

obfunc define_shell() {local max_p,tmp,j,maxDist,total_shells,shell_width,synapse localobj synapse_track,sl,removed
// define shells within morphology
    total_shells = $1
    synapse = $2
    maxDist = get_max_dist()
    shell_width = (maxDist + 1)/ total_shells
    r.discunif(0,max_p)

    max_p = 0
    forall {max_p = max_p + 1}
    max_p = int(max_p / total_shells/synapse)
    if (max_p > 0) {
        max_p = max_p - 1
    } else {
        max_p = 0
    }

    synapse_track = new Vector(total_shells)
    for i=0,total_shells-1 {
        synapse_track.x[i] = 0
        shell_compartments.append(new SectionList())
    }


    forall {
        for i=0, n3d() - 1 {
            tmp = get_distance(x3d(i),y3d(i),z3d(i))
            j = -1
            while (tmp >= 0) {
                tmp = tmp - shell_width
                j = j + 1
            }
            insert shell
            num_shell = j
            if (synapse_track.x[j] < synapse*lenUnits) {
                shell_compartments.o(j).append()
                if (L > lenUnits){
                    syn_add = int(L / lenUnits)
                    if (syn_add < L/lenUnits){
                        syn_add = syn_add + 1
                    }

                } else {
                    syn_add = 1
                }
                synapse_track.x[j] = synapse_track.x[j] +syn_add 
            }
    }}
    removed = new Vector()
    for i=0,total_shells-1 {
        removed.append(shell_compartments.o(i).unique())
    }
    return removed

}

proc set_all_pp(){
  // set all point processes on or off
    for i=0, ncNMDAList.count - 1{
        ncNMDAList.o(i).active($1)
    }
    for i=0,ncGABAaList.count - 1{
        ncGABAaList.o(i).active($1)
    }

    for i=0,ncGluList.count - 1{
        ncGluList.o(i).active($1)
    }

}

proc select_shell() {local mode localobj tmpsl
// select a shell within the defined comparment shells
    mode = $2

    tmpsl = new SectionList()
    if ($1 == shell_compartments.count){
        print "adding all shells"
        for i=0,shell_compartments.count-1 {
            if (mode > 0) {
                if (i < 5) {
                    continue
                }

            } else if (mode > 1) {
                if (i < 6) {
                    continue
                }
            }

            forsec shell_compartments.o(i) {
                tmpsl.append()
            }
        }
    } else {
        tmpsl = shell_compartments.o($1-1)
    }
    slPAP = tmpsl
}

proc set_vgap(){
  // set voltage gap
    for i=0,gaplist.count - 1{
        gaplist.o(i).VoltageGap = $1

    }
}



proc kir_rect_off(){
  // turn kir rectification off
    forall{
        rect_off_kir2 = $1
    }
}

func adjacent_total_diam(){local total_diam localobj sref
//get diameter of nearest neighbor
    total_diam = 0
    sref = new SectionRef()
    for i=0, sref.nchild - 1 {
        sref.child[i] {total_diam = total_diam + diam}
        if (sref.has_parent()) {
            sref.parent {total_diam = total_diam+diam}
        }
    }
    return total_diam

}