// UI
objref vBoxMainPanel, vBoxLeftPanel, vBoxCentralPanel, vBoxRightPanel, plotShapeMainV, graphMainSomaV
// 0 - Uniform distribution selected, 1 - Distribution from file selected
// Diameter distribution of leaves
distrStatusLeaves = 0
// Diameter distribution of stalks
distrStatusStalks = 0

// change the volume of astocyte 
// 
DiameterParameter = 0
LengthChange=1
proc changeVolume(){

ParDiam = 1
forall {
        for j = 0, n3d()-1 {
            if ( x3d(j) > 0.01 &&  y3d(j) > 0.01) {
                pt3dchange(j, x3d(j)*$2, y3d(j)*$2, z3d(j)*$2,  diam+diam*$1/100) //randomStretch.uniform(-1, 1)+z3d(j)
            } else {
                pt3dchange(j, x3d(j)*$2, y3d(j)*$2, z3d(j)*$2, diam+diam*$1/100) // randomStretch.uniform(-1, 1)+z3d(j)
            }
        }
    }
	DiameterParameter = 0
	LengthChange = 1
	$1 =0
	$2 = 1
} 
// end

// Change distribution of Leaves
// $1 - Boolean. 0 - uniform distribution. 1 - distribution from file.
proc distrSelectedLeaves() {
    if (numarg() >= 1) {
        distrStatusLeaves = $1
    }
    setLeaves(MaxDimLeaves, MinDimLeaves, MaxLenLeaves, MinLenLeaves, distrStatusLeaves, DensityGluTransporters, GPassive)
}

// Change distribution of Stalks
// $1 - Boolean. 0 - uniform distribution. 1 - distribution from file.
proc distrSelectedStalks() {
    if (numarg() >= 1) {
        distrStatusStalks = $1
    }
    setStalks(MaxDimStalk, MinDimStalk, MaxLenStalk, MinLenStalk, distrStatusStalks, DensityGluTransporters)
}

// Runs selected simulation from UI.
// $1 - Number of selected simulation
proc SimulationSelected() {
    if ($1 >= 1 && $1 <= 7 && currentMechanismSetup == 1) {
        InsertGlutamateMechanisms(0)
        InsertElectricMechanisms(1)
        currentMechanismSetup = 0
    } else if ($1 == 8 && currentMechanismSetup == 0) {
        InsertElectricMechanisms(0)
        InsertGlutamateMechanisms(1)
        currentMechanismSetup = 1
    } else if ($1 == 9) { // && currentMechanismSetup == 0) {
        InsertElectricMechanisms(0)
       InsertPotassiumMechanisms(1)
        currentMechanismSetup = 0 
    }
    
	
	
    // Update advance() proc and run
    if ($1 == 1) {
        load_file(1, "Simulations/AdvanceProcs/AdvDefault.hoc")
        FrapCircle()
    } else if ($1 == 2) {
        load_file(1, "Simulations/AdvanceProcs/AdvFrapLine.hoc")
        FrapLine()
    } else if ($1 == 3) {
        load_file(1, "Simulations/AdvanceProcs/AdvDefault.hoc")
        SpatialVoltage()
    } else if ($1 == 4) {
        load_file(1, "Simulations/AdvanceProcs/AdvDefault.hoc")
        ConstantStimulations()
    } else if ($1 == 5) {        
        load_file(1, "Simulations/AdvanceProcs/AdvDefault.hoc")
        FrequencyStimulations()
    } else if ($1 == 6) {
        load_file(1, "Simulations/AdvanceProcs/AdvCalciumDynamics.hoc")
        RunCaSimulation()
    } else if ($1 == 7) {
        load_file(1, "Simulations/AdvanceProcs/AdvCalciumWave.hoc")
        CalciumWave()
    } else if ($1 == 8) {
        load_file(1, "Simulations/AdvanceProcs/AdvGlutamate.hoc")
        RunAstroGlu(OnlySingleGluSimulations)
    } else if ($1 == 9) {
        load_file(1, "Simulations/AdvanceProcs/AdvPotassium.hoc")
        RunAstroPotasasium(OnlySingleGluSimulations) 
    }
}

// Shows main program UI.
proc showMainUi() {
    vBoxMainPanel = new HBox()
    vBoxMainPanel.intercept(1)
    {
// Left panel of main menu
        vBoxLeftPanel = new VBox()
        vBoxLeftPanel.intercept(1)
        {
            xpanel("Leaf geometry")
            xlabel("======================= Leaf Geometry =======================")
            xlabel("Main parameters of nanoscopic processes (Leaves)")
            //xlabel("")
            xlabel("-------------------------------------------------------------------------------------------------------------------------")
            if (nanoDistrLoaded == 1) {
                xradiobutton("Diameter distribution from file", "distrSelectedLeaves(1)", 1)
                xradiobutton("Stochastic uniform distribution of diameters between  Min and Max", "distrSelectedLeaves(0)")
            } else {
                xlabel("Stochastic uniform distribution of diameters between  Min and Max")
            }
            xvalue("Max diameter of Leaves (um)","MaxDimLeaves", 1, "distrSelectedLeaves()", 0, 1)
            xvalue("Min diameter of Leaves (um)","MinDimLeaves", 1, "distrSelectedLeaves()", 0, 1)			
            xlabel("-------------------------------------------------------------------------------------------------------------------------")
            xlabel("Stochastic uniform distribution of lengths between Min and Max")
            xvalue("Max length of Leaves (um)","MaxLenLeaves", 1, "distrSelectedLeaves()", 0, 1)
            xvalue("Min length of Leaves (um)","MinLenLeaves", 1, "distrSelectedLeaves()", 0, 1)
			xlabel("========== Volume modification. Changes of diameters and lengths of segments =======")
			xlabel("========== Change diameters in % to diameters =======")
			xvalue("Diameter change","DiameterParameter", 1, "changeVolume(DiameterParameter, LengthChange)", 0, 1)
			xlabel("========== Changing length by multiplying by parameter =======")
			xvalue("Length change","LengthChange", 1, "changeVolume(DiameterParameter, LengthChange)", 0, 1)
            xlabel("==========Specific membrane  conductance =======")
			xlabel("This membrane conductivity is scaled to base of leaf cylinders")
			xvalue("Specific membrane conductance, Gm (S/cm2)","GPassive", 1, "distrSelectedLeaves()", 0, 1)
			//xlabel("=============================================================")
            xpanel(0)

            xpanel("Stalks Geometry")
            xlabel("======================= Stalks Geometry =======================")
            xlabel("Stalks are thin higher-order branches that")
            xlabel("connect nanoscopic processes (Leaves)")
            xlabel("-------------------------------------------------------------------------------------------------------------------------")
            if (nanoDistrLoaded == 1) {
                xradiobutton("Diameter distribution from file", "distrSelectedStalks(1)", 1)
                xradiobutton("Stochastic uniform  distribution of diameters between Min and Max", "distrSelectedStalks(0)")
            } else {
                xlabel("Stochastic uniform  distribution of diameters between Min and Max")
            }
            xvalue("Max diameter of Stalks (um)",  "MaxDimStalk", 1, "distrSelectedStalks()", 0, 1)
            xvalue("Min diameter of Stalks (um)",  "MinDimStalk", 1, "distrSelectedStalks()", 0, 1)
            xlabel("-------------------------------------------------------------------------------------------------------------------------")
            xlabel("Stochastic uniform  distribution of lengths between Min and Max")
            xvalue("Max length of Stalks (um)","MaxLenStalk", 1, "distrSelectedStalks()", 0, 1)
            xvalue("Min length of Stalks (um)","MinLenStalk", 1, "distrSelectedStalks()", 0, 1)
            //xlabel("=============================================================")
            xpanel(0)
		


            xpanel("")
            xlabel("========= Dendritic geometry ================================")
			// xlabel("========= For library stem tree files only =========")
            //xlabel("Seed of random number to modify Z coordinate")
            //xlabel("of each segment from - 1 to 1 um")
            //xvalue("Z coordinate Random number","Z_coordinate", 1, "stretch(Z_coordinate, ScalingDiam)", 0, 1)
            
			   xvalue("Scaling of diameter","ScalingDiam", 1, "stretch(Z_coordinate, ScalingDiam)", 0, 1)
			
			//xvalue("Length x and Y","LengthXY", 1, "stretchXY(LengthXY, LengthZ)", 0, 1)
            //xvalue("Length z","LengthZ", 1, "stretchXY(LengthXY, LengthZ)", 0, 1)
            xlabel("----Gap Junctions----------------------------------------------------------------------")
			xvalue("Number of Gap junctions, evenly distributed on dendritic tree", "NumberDendrites")
            xvalue("Gap junction resistance (Megohm)","GapResistance", 1,"res_gap(GapResistance, potential)", 0, 1  )
            xvalue("Gap junction reverse potential (mV)","potential", 1,"res_gap(GapResistance, potential)", 0, 1  )
            xlabel("=============================================================")
            xpanel(0)

            xpanel("Diffusion-escape Gap Junction",0)
            xlabel("Diffusion-escape Gap Junction ")
			xstatebutton("Switch Gap junctions, external - switch off and internal - switch on",&SwitchOffGapJunction, "CaGapFlux(jd/(1e+6),SwitchOffGapJunction)")
			xlabel(" To switch off both Gap junction, it is necessary to equate the Diffusion leak rate to zero")
            xvalue("Diffusion leak rate, jg (nA/mM)","jd", 1,"CaGapFlux(jd/(1e+6), SwitchOffGapJunction)", 0, 1  )
			//xvalue("Maximum distance between Gap Junctions, Distance (um)","Distance", 1,"CaGapFlux(jd/(1e+6), Distance)", 0, 1  )
            xpanel(0)
        }
        vBoxLeftPanel.intercept(0)	//ends intercept mode
        vBoxLeftPanel.map("Geometry") // ends of Geometry of Astrocyte 

        // Plots
        vBoxCentralPanel = new VBox()
        vBoxCentralPanel.intercept(1)
        {
            // Space plot of Voltage
            plotShapeMainV = new PlotShape(0)
            fast_flush_list.append(plotShapeMainV)
            plotShapeMainV.size(-50,50,-50,50)
            plotShapeMainV.view(-50, -50, 100, 100, 165, 169, 400.64, 400.32)
            plotShapeMainV.exec_menu("Shape Plot")
            plotShapeMainV.variable("v")
            plotShapeMainV.show(0)
            plotShapeMainV.scale(-85,-80)  // mV, scale of voltage on 3D plots
			plotShapeMainV.label(0.0340357, 0.94, "Voltage (mV)", 2, 1, 0, 0, 1)

            graphMainSomaV = new Graph()
            addplot(graphMainSomaV,0)
            graphMainSomaV.size(0, tstop, -85, -80)
            graphMainSomaV.addvar("soma.v(0.5)")
			graphMainSomaV.label(0.0340357, 0.94, "Voltage (mV)", 2, 1, 0, 0, 1)
            graphMainSomaV.label(0.45, 0.01, "Time (ms)", 2, 1, 0, 0, 1)
        }
        vBoxCentralPanel.intercept(0)
        vBoxCentralPanel.map("Plots")

        // Right panel of main menu
        xpanel("Various scenarios for calculating astrocyte dynamics")
        xlabel("To display the radial distribution of: S/V ratio,")
        xlabel("tissue volume fraction, volume, surface area, and branch diameter")
        xlabel("Results are  saved to file VolumeFraction.txt")
        xbutton("Geometrical Parameters", "GeometricalParameters()")
        xlabel("====================== Simulations ======================")
       //xlabel("Simulation of FRAP experiment with  round-spot bleaching")
       //xbutton("FRAP with round-spot bleaching", "SimulationSelected(1)")
        xlabel("---------------------------------------------------------------------------------------------------------")
        xlabel("Simulation of line-scan FRAP")
        xbutton("Line-scan FRAP","SimulationSelected(2)")
        xlabel("---------------------------------------------------------------------------------------------------------")
        xlabel("Simulation of  spatial distribution of voltage along dendrites") 
        xbutton("Membrane voltage distribution", "SimulationSelected(3)")
        xlabel("---------------------------------------------------------------------------------------------------------")
        xlabel("Parameters of somatic stimuli")
        xbutton("Constant electric stimuli", "SimulationSelected(4)")
        //xlabel("---------------------------------------------------------------------------------------------------------")
        //xlabel("Parameters of sinusoidal stimulations into soma")
        //xbutton("Variable electric stimuli","SimulationSelected(5)")
        xlabel("---------------------------------------------------------------------------------------------------------")
        xlabel("Parameters for microscopic calcium dynamics")
        xbutton("Microscopic calcium dynamics", "SimulationSelected(6)")
        xlabel("---------------------------------------------------------------------------------------------------------")
        xlabel("Calcium Wave simulations")
        xbutton("Calcium Wave", "SimulationSelected(7)")
        xlabel("---------------------------------------------------------------------------------------------------------")
        xlabel("Astrocyte model with Glutamate transporters")
        xbutton("Membrane biophysics with glutamate transport", "SimulationSelected(8)")
		xlabel("Astrocyte model with potassium dynamics")
        xbutton("Dynamics of intra and extracellular K+", "SimulationSelected(9)")
        xlabel("=======================================================")
        xlabel("By default active Ca2+ mechanisms are only inserted into soma and dendrites")
        xlabel("and are uninserted during 'Glutamate dynamics' to speed up computation.")
        xlabel("Active Ca2+ mechanisms can be inserted using the following parameters.")
        xlabel("Simulation should be restarted after changing any of them.")
        xstatebutton("Insert Ca active mechanism in leaves (excluding 'Glutamate dynamics')", &cadifusInElectricalLeaves, "InsertCadifusInElectricalLeaves(cadifusInElectricalLeaves)")
        xstatebutton("Insert Ca active mechanism everywhere in 'Glutamate dynamics'", &cadifusInAllGlu, "InsertCadifusInAllGlu(cadifusInAllGlu)")
        xpanel()
    }
    vBoxMainPanel.intercept(0)
    vBoxMainPanel.map("Repertoire of computation")
}

proc showRunPanel() {
    xpanel("RunControl", 0)
    xvalue("Init","v_init", 1,"stdinit()", 1, 1 )
    xbutton("Init & Run","run()")
    xbutton("Stop","stoprun=1")
    xvalue("Continue til","runStopAt", 1,"{continuerun(runStopAt) stoprun=1}", 1, 1 )
    xvalue("Continue for","runStopIn", 1,"{continuerun(t + runStopIn) stoprun=1}", 1, 1 )
    xbutton("Single Step","steprun()")
    xvalue("t","t", 2 )
    xvalue("Tstop","tstop", 1,"tstop_changed()", 0, 1 )
    xvalue("dt","dt", 1,"setdt()", 0, 1 )
    xvalue("Points plotted/ms","steps_per_ms", 1,"setdt()", 0, 1 )
    xvalue("Scrn update invl","screen_update_invl", 1,"", 0, 1 )
    xvalue("Real Time","realtime", 0,"", 0, 1 )
    xpanel(0,166)
}