/* Sets nseg in each section to an odd value
   so that its segments are no longer than 
     d_lambda x the AC length constant
   at frequency freq in that section.

   Be sure to specify your own maxRa and maxcm before calling geom_nseg()

   To understand why this works, 
   and the advantages of using an odd value for nseg,
   see  Hines, M.L. and Carnevale, N.T.
        NEURON: a tool for neuroscientists.
        The Neuroscientist 7:123-135, 2001.
*/

// these are reasonable values for most models
freq = 300 //original:100     // Hz, frequency at which AC length constant will be computed
d_lambda = 0.1 //original:0.1
//objref nsegvec
//nsegvec = new Vector(2)
	
func lambda_f() { local i, x1, x2, d1, d2, lam
        if (n3d() < 2) {
                return 1e5*sqrt(diam/(4*PI*$1*Ra*cm))
        }
// above was too inaccurate with large variation in 3d diameter
// so now we use all 3-d points to get a better approximate lambda
        x1 = arc3d(0)
        d1 = diam3d(0)
        lam = 0
        for i=1, n3d()-1 {
                x2 = arc3d(i)
                d2 = diam3d(i)
                lam += (x2 - x1)/sqrt(d1 + d2)
                x1 = x2   d1 = d2
				
        }
		//print "lam, L = ", lam, L
        //  length of the section in units of lambda
        lam *= sqrt(2) * 1e-5*sqrt(4*PI*$1*Ra*cm)
	//print CELLINDEX, "$1, Ra, cm", $1, Ra, cm
	//print CELLINDEX, "$1*Ra*cm", $1*Ra*cm
	//print secname(), "lam, L = ", lam, L
	if(!lam){
		return 1
        }else {return L/lam}
}

proc geom_nseg_shared() {
	area(0.5) // make sure diam reflects 3d points

		forsec cellList.o[CELLINDEX].allreg { 
		/*
			if (maxRa.x(CELLINDEX) == 0 || maxcm.x(CELLINDEX) == 0) {
				thisRa = Ra
				thiscm = cm
			} else {
				thisRa = maxRa.x(CELLINDEX)
				thiscm = maxcm.x(CELLINDEX)
			}
			*/
			//nsegvec.x(0) = n3d()
			//nsegvec.x(1) = 
			//print "L = ", L
			//if (1) printf("lambda=%g\n",lambda_f(freq))
			nseg = int((int(L+0.5)/(d_lambda*lambda_f(freq))+0.9)/2)*2 + 1 //nsegvec.min()
			//print CELLINDEX, nseg, L, d_lambda, freq, lambda_f(freq)
			//print "nseg = ", nseg,"    ", secname()," L=   ",L,"  Ra = ",Ra,"  cm =  ",cm
		}
}

proc geom_nseg() {
	geom_nseg_shared()
	// increase nseg even further (tribute to Josef):
	if (accuracy == 2) {
		forsec cellList.o[CELLINDEX].allreg nseg*=3
	}
	if (accuracy == 1) {
		forsec cellList.o[CELLINDEX].regsoma nseg*=3
		forsec cellList.o[CELLINDEX].allaxonreg nseg*=3
	}
}