load_file("nrngui.hoc")
xopen("Purk_active.hoc")

access somaA
celsius = 34
tstop =1000
dt = 0.02
steps_per_ms = 1/dt
dtsim = 0.02



finitialize(v_init)

strdef tmpstr
strdef outDir
strdef cmd 
objref outfile0

outfile0 = new File()

objref ps
ps = new ParallelContext()
st = ps.time

objref ward_num
ward_num = new Vector(400,0)

objref stim_st
stim_st = new Vector(400,20000)


proc setdrive() {
  stim1.amp = $1
}

func distscale() {local key localobj returnvec
	key = $1
	returnvec = new Vector()
	returnvec = calc_prc_single(key)
	ps.pack(returnvec)
	ps.post(key)
	return key
}
	  
	  objref apc
obfunc calc_prc_single() {local base_num localobj APs
    base_num = $1

    shift = base_num-(int(base_num/10000))*10000
    base_num = int(base_num/10000)
    stim2.del = stim_st.x[base_num-1]+ 0.5* shift
    curr = -0.2+0.1*(base_num-1)
	setdrive (curr)
  APs = new Vector()
  somaA apc = new APCount(0.5)
  apc.thresh = -20
  apc.record(APs)

    run()
    return APs
}

ps.runworker()

objref threshvec
threshvec=new Vector()
objref basalvec

proc calc_basal() {
 sprint(outDir,"simdata")
    sprint(cmd, "system(\"mkdir -p %s\")",outDir)
	execute(cmd)
	
	sprint(tmpstr,"%s/basal_condition.dat",outDir) 
	outfile0.wopen(tmpstr)
	for i = 1, $1 {
	    cutag=10000*i
	    ps.submit("distscale",cutag)
	}
		while (ps.working()) {
		key = ps.retval()
		ps.look_take(key)
		
		threshvec = ps.upkvec()
		
		print "received key ",key
	    cuno=int(key/10000)
	    outfile0.printf ("%e %e %e\n", cuno, threshvec.x[threshvec.size()-1]-threshvec.x[threshvec.size()-2],threshvec.x[threshvec.size()-3])
      	outfile0.flush()
      	ward_num.x[cuno-1] = int((threshvec.x[threshvec.size()-1]-threshvec.x[threshvec.size()-2])*2)
      	stim_st.x[cuno-1] = threshvec.x[threshvec.size()-3]

        }
        outfile0.close()
}


calc_basal(11)

stim_opt = 1

print "the time used to set basal firing rates is",ps.time-st