
//
//CAESAR. Copyright (C) 2005 T.J.Coulthard
//This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation;  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License (http://www.gnu.org/copyleft/gpl.html) for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//

// 5.9c
// Feb 09. Changed slide to slide_5

// Version 6.0
// refer to www.coulthard.org.uk - and the discussion board for details on changes prior to this.
// archived versions of the code are also kept on that website.


using System.IO;
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text;
using System.Net;
using System.Xml;  //JMW
//using System.Threading;


namespace caesar1
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
        private System.Drawing.Bitmap m_objDrawingSurface;
		//JMW
		[System.Runtime.InteropServices.DllImport("gdi32.dll")]
		public static extern long BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, 
			int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwROP);

		private System.ComponentModel.IContainer components;

		//Jorge variables
        public static double sedOut = 0;//amount of sediment at outlet, plotted
        public static double waterOut = 0;//amount of water at outlet, plotted
        public static int plotType = 0;
        public static double magnifyValue = 0;
        public static int updateClick = 0;
        private double[] zoomFactor = { .25, .33, .50, .66, .80, 1, 1.25, 1.5, 2.0, 2.5, 3.0 };
        private double[] contrastFactor = { 1, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, 2.6, 2.8, 3 };
        private double contrastMultiplier = 0;
        public int imageCount = 1;
        public int imageCount2 = 1;
        int coordinateDone = 0;
        double urfinalLati, urfinalLongi, llfinalLati, llfinalLongi, yurcorner, xurcorner = 0;
        public string kml = "";
        public string KML_FILE_NAME = "animation\\animation.kml";
        int save_time2, save_interval2 = 0;
        public string startDate, kmlTime;
        public DateTime googleTime;
        public string[] DateArray;
        public string[] DateArray2;
       
        
        // toms global variables
        const Single g = 9.81F;
		const Single kappa = 0.4F;
		int SW=2;
		double water_depth_erosion_threshold=0.01;
		int input_time_step=60;
		int number_of_points=0;
		double globalsediq=0;
		double time_1=1;
		double save_time=0;
		double creep_time=1;
        double soil_erosion_time = 1;
		double init_discharge=80;
		int tot_number_of_tracer_points=0;
		int input_type_flag=0; // 0 is water input from points, 1 is input from hydrograph or rainfall file.
		int smoothradius=1;
		double failureangle=45;
		double saveinterval=1000;
		double fexp=1;
		int counter=0;
		Timer gameClock;
		Graphics graphics;
		int xmax, ymax;
        double xll, yll;
		int init_route_number_of_scans=2;
		int maxiterations;
		int maxcycle;
		const int ACTIVE_FACTOR=1;
		const int TRUE=1;
		const int FALSE=0;
		double ERODEFACTOR=0.05;
		double DX=5;
		double root=7.07;
		double fiveroot=10.04;
		int LIMIT=1;
		double MIN_Q=0.01;
		double CREEP_RATE=0.0025;
        double SOIL_RATE = 0.0025;
		double active=0.2;
		int G_MAX=10;
		int TRACERS=1;
		double lateral_constant=0.0000002;
		int grain_array_tot=1;
		int y_min=2;
		double time_factor;
		double j=0.000000001; //start of hydrological model paramneters
		double jo=0.000000001;
		double j_mean;
		double old_j_mean=0;
		double new_j_mean=0;
		double M=0.005;
		double K=0.01;
		double baseflow=0.00000005; //end of hyd model variables usually 0.0000005 changed 2/11/05
		public static double cycle=0;
		double rain_factor=1;
		double sediQ=0;
		double grow_grass_time=0;
		double init_cycle=0;
		double output_file_save_interval=60;
		double min_time_step=0;
		double vegTauCrit=100;
		double cross_stream_grad_factor=0;
        int graphics_scale = 5; // value that controls the number of bmp pixels per model pixel for the output images.
        int max_time_step = 0;
        int dune_mult = 5;

        // KAtharine
        int variable_m_value_flag = 0;

		// grain size variables - the sizes
		double d0=10.27; // grass usually 0.27  changed TJ
		double d1=0.0005;
		double d2=0.001;
		double d3=0.002;
		double d4=0.004;
		double d5=0.008;
		double d6=0.016;
		double d7=0.032;
		double d8=0.064;
		double d9=0.128;
		double d10=500000; //bedrock (not sure used now..)
		// grain size proportions for each fraction... as a proportion of 1.
		
		double d1prop=0.144;
		double d2prop=0.022;
		double d3prop=0.019;
		double d4prop=0.029;
		double d5prop=0.068;
		double d6prop=0.146;
		double d7prop=0.22;
		double d8prop=0.231;
		double d9prop=0.121;

		// Gez
		double previous;
		int hours = 0;
		double new_cycle = 0;
		double old_cycle = 0;
		double tx = 60;
		double Tx = 0;
		double tlastcalc = 0;
		double Qs_step = 0;
		double Qs_hour = 0;
		double Qs_over = 0;
		double Qs_last = 0;
		double Qw_newvol = 0;
		double Qw_oldvol = 0;
		double Qw_lastvol = 0;
		double Qw_stepvol = 0;
		double Qw_hourvol = 0;
		double Qw_hour = 0;
		double Qw_overvol = 0;
		double temptotal = 0;
		double old_sediq = 0;
        double[] sum_grain, sum_grain2, old_sum_grain,old_sum_grain2, Qg_step, Qg_step2, Qg_hour, Qg_hour2, Qg_over, Qg_over2, Qg_last,Qg_last2;
		string CATCH_FILE = "catchment.dat";
        string CATCH_FILE2 = "tracer_output.txt";
		// end gez

		// toms global arrays
		double[,] elev,bedrock,init_elevs, discharge,temp_depth,
			water_depth,area,dist,tempcreep,water_depth2,lat_vol,Tau, Tau2, old_water_depth, pool_depth, 
            left_in, left_out, right_in, right_out, up_in, up_out, down_in, down_out, flowout, flowin,
            area_depth, sand, elev2, sand2;
		int[,] index,cross_scan,down_scan,minesites, width, qcounter;
		int[,,] flow_dir;
		double[,,] max_flow,grain,temp;
		double[,,,] strata;
        double[] extra_elev, hourly_rain_data, hourly_m_value, bedrock_depth, temp_grain;
		double[,] tracerhydrograph, hydrograph, dischargeinput, tracerinput;
		double[,,] inputfile;
        double[,] mineinput;
		int[,] inpoints;
        int[,] mine_inpoints;
		double[,,] veg;
		double[,] edge, edge2; //TJC 27/1/05 array for edges

		// MJ global vars
		double[] fallVelocity;
		bool[] isSuspended;
		double[,,,] tempsusp,Vsusp;
		double[,] tempsusptot,Vsusptot,Csusptot;
		int[] deltaX = new int[9] {0,0,1,1,1,0,-1,-1,-1};
		int[] deltaY = new int[9] {0,-1,-1,0,1,1,1,0,-1};
		int nActualGridCells;
		double Jw_newvol = 0.0;
		double Jw_oldvol = 0.0;
		double Jw_lastvol = 0.0;
		double Jw_stepvol = 0.0;
		double Jw_hourvol = 0.0;
		double Jw_hour = 0.0;
		double Jw_overvol = 0.0;
		double k_evap = 0.0;

		// JOE global vars
		string[] inputheader;			//Read from ASCII DEM <JOE 20050605>
		double[,] soil_saturation;		// <JOE 20050605>
		double[,] slopeAnalysis;  // Initially calculated in percent slope, coverted to radians
		double[,] aspect;		  // Radians
		double[,] hillshade;	  // 0 to 255
		double hue = 360.0;		// Ranges between 0 and 360 degrees
		double sat = 0.90;		// Ranges between 0 and 1.0 (where 1 is 100%)
		double val = 1.0;		// Ranges between 0 and 1.0 (where 1 is 100%)
		double red = 0.0;
		double green = 0.0;
		double blue = 0.0;

        // siberia submodel parameters
        double m1 = 1.70;
        double n1 = 0.69;
        double Beta3 = 0.000186;
        double m3 = 0.79;
        double Beta1 = 1067;

        // sedi tpt flags   
        int einstein = 0;
        int wilcock = 0;

        int div_inputs = 1;


		//JMW Vars
		string basetext = "CAESAR - Cellular Automaton Evolutionary Slope And River model 6.0 (3/6/2009)";
		string cfgname = null ;  //Config file name
		string workdir = "c:\\program files\\Caesar\\work\\";
		AviWriter aw; // <JMW 20041018>
		private Bitmap bmp;  // <JMW 20041018>
		private Graphics mygraphics;
		//private Boolean DoingGraphics;  // <JMW 20041108>
		//Form2 form2; // <JMW 20041018>
		// JMW end

		private System.Windows.Forms.Button button2;
		private System.Windows.Forms.MainMenu mainMenu1;
		private System.Windows.Forms.MenuItem menuItem1;
		private System.Windows.Forms.MenuItem menuItem3;
		private System.Windows.Forms.MenuItem menuItem4;
		private System.Windows.Forms.MenuItem menuItem5;
		private System.Windows.Forms.MenuItem menuItem6;
		private System.Windows.Forms.MenuItem menuItem11;
		private System.Windows.Forms.MenuItem menuItem12;
		private System.Windows.Forms.MenuItem menuItem13;
		private System.Windows.Forms.MenuItem menuItem14;
		private System.Windows.Forms.MenuItem menuItem15;
		private System.Windows.Forms.MenuItem menuItem16;
		private System.Windows.Forms.MenuItem menuItem17;
		private System.Windows.Forms.MenuItem menuItem18;
		private System.Windows.Forms.MenuItem menuItem19;
		private System.Windows.Forms.MenuItem menuItem20;
		private System.Windows.Forms.MenuItem menuItem21;
		private System.Windows.Forms.MenuItem menuItem22;
		private System.Windows.Forms.MenuItem menuItem23;
		private System.Windows.Forms.MenuItem menuItem24;
		private System.Windows.Forms.MenuItem menuItem25;
		private System.Windows.Forms.MenuItem menuItemConfigFile;
		private System.Windows.Forms.MenuItem menuItemConfigFileOpen;
		private System.Windows.Forms.MenuItem menuItemConfigFileSave;
		private System.Windows.Forms.MenuItem menuItemConfigFileSaveAs;
		private System.Windows.Forms.MenuItem menuItem2;
		private System.Windows.Forms.MenuItem menuItem10;
		private System.Windows.Forms.MenuItem menuItem9;
		private System.Windows.Forms.MenuItem menuItem8;
		private System.Windows.Forms.MenuItem menuItem7;
        private System.Windows.Forms.TabControl tabControl1;
		private System.Windows.Forms.TabPage GridTab;
		private System.Windows.Forms.TabPage NumericalTab;
		private System.Windows.Forms.TabPage GrainTab;
		private System.Windows.Forms.TabPage HydrologyTab;
		private System.Windows.Forms.TextBox gp3box;
		private System.Windows.Forms.TextBox gp4box;
		private System.Windows.Forms.TextBox gp5box;
		private System.Windows.Forms.TextBox gp6box;
		private System.Windows.Forms.TextBox gp7box;
		private System.Windows.Forms.TextBox gp8box;
		private System.Windows.Forms.TextBox gp9box;
		private System.Windows.Forms.TextBox gp2box;
		private System.Windows.Forms.TextBox gp1box;
		private System.Windows.Forms.TextBox g3box;
		private System.Windows.Forms.TextBox g4box;
		private System.Windows.Forms.TextBox g5box;
		private System.Windows.Forms.TextBox g6box;
		private System.Windows.Forms.TextBox g7box;
		private System.Windows.Forms.TextBox g8box;
		private System.Windows.Forms.TextBox g9box;
		private System.Windows.Forms.TextBox g2box;
		private System.Windows.Forms.TextBox g1box;
		private System.Windows.Forms.Label label22;
		private System.Windows.Forms.Label label21;
		private System.Windows.Forms.Label label20;
		private System.Windows.Forms.Label label19;
		private System.Windows.Forms.Label label18;
		private System.Windows.Forms.Label label17;
		private System.Windows.Forms.Label label16;
		private System.Windows.Forms.Label label15;
		private System.Windows.Forms.Label label14;
		private System.Windows.Forms.Label label13;
        private System.Windows.Forms.Label label6;
		private System.Windows.Forms.TextBox input_time_step_box;
		private System.Windows.Forms.TextBox infile4;
		private System.Windows.Forms.TextBox infile3;
		private System.Windows.Forms.TextBox infile2;
		private System.Windows.Forms.TextBox infile1;
		private System.Windows.Forms.TextBox ybox1;
		private System.Windows.Forms.TextBox ybox2;
		private System.Windows.Forms.TextBox ybox3;
		private System.Windows.Forms.TextBox ybox4;
		private System.Windows.Forms.TextBox xbox2;
		private System.Windows.Forms.TextBox xbox3;
		private System.Windows.Forms.TextBox xbox4;
		private System.Windows.Forms.TextBox xbox1;
		private System.Windows.Forms.Label label29;
		private System.Windows.Forms.Label label44;
		private System.Windows.Forms.Label label43;
		private System.Windows.Forms.Label label41;
		private System.Windows.Forms.CheckBox inbox2;
		private System.Windows.Forms.CheckBox inbox3;
		private System.Windows.Forms.CheckBox inbox4;
		private System.Windows.Forms.CheckBox inbox1;
        private System.Windows.Forms.Label label42;
		private System.Windows.Forms.TabPage DescriptionTab;
		private System.Windows.Forms.TextBox DescBox;
		private System.Windows.Forms.TextBox ytextbox;
		private System.Windows.Forms.TextBox xtextbox;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.TextBox dxbox;
		private System.Windows.Forms.Label label11;
		private System.Windows.Forms.Label label50;
		private System.Windows.Forms.TextBox activebox;
		private System.Windows.Forms.Label label49;
		private System.Windows.Forms.TextBox mintimestepbox;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.TextBox smoothbox;
		private System.Windows.Forms.TextBox cyclemaxbox;
		private System.Windows.Forms.TextBox itermaxbox;
		private System.Windows.Forms.TextBox minqbox;
		private System.Windows.Forms.TextBox limitbox;
		private System.Windows.Forms.TextBox erodefactorbox;
		private System.Windows.Forms.TextBox initscansbox;
        private System.Windows.Forms.Label label31;
        private System.Windows.Forms.Label label35;
		private System.Windows.Forms.Label label27;
		private System.Windows.Forms.Label label26;
		private System.Windows.Forms.Label label12;
		private System.Windows.Forms.Label label10;
        private System.Windows.Forms.Label label9;
        private System.Windows.Forms.Label label5;
		private System.Windows.Forms.TextBox textBox3;
		private System.Windows.Forms.TextBox textBox2;
		private System.Windows.Forms.Label label48;
		private System.Windows.Forms.Label label46;
		private System.Windows.Forms.Label label47;
        private System.Windows.Forms.Label label51;
		private System.Windows.Forms.StatusBar statusBar1;
		private System.Windows.Forms.StatusBarPanel IterationStatusPanel;
		private System.Windows.Forms.StatusBarPanel TimeStatusPanel;
		private System.Windows.Forms.StatusBarPanel QwStatusPanel;
		private System.Windows.Forms.StatusBarPanel QsStatusPanel;
		private System.Windows.Forms.StatusBarPanel InfoStatusPanel;
		private System.Windows.Forms.StatusBarPanel tempStatusPanel;
		private System.Windows.Forms.Button start_button;
        private System.Windows.Forms.Button button1;
		private System.Windows.Forms.MenuItem menuItem26;
		private System.Windows.Forms.MenuItem menuItem27;
		private System.Windows.Forms.TextBox k_evapBox;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.MenuItem menuItem28;
		private System.Windows.Forms.MenuItem menuItem29;
		private System.Windows.Forms.CheckBox suspGS1box;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.Label label28;
		private System.Windows.Forms.TextBox fallGS2box;
		private System.Windows.Forms.TextBox fallGS1box;
		private System.Windows.Forms.CheckBox suspGS2box;
		private System.Windows.Forms.CheckBox suspGS3box;
		private System.Windows.Forms.CheckBox suspGS4box;
		private System.Windows.Forms.CheckBox suspGS5box;
		private System.Windows.Forms.CheckBox suspGS6box;
		private System.Windows.Forms.CheckBox suspGS7box;
		private System.Windows.Forms.CheckBox suspGS8box;
		private System.Windows.Forms.CheckBox suspGS9box;
		private System.Windows.Forms.Label gpSumLabel;
		private System.Windows.Forms.Label gpSumLabel2;
		private System.Windows.Forms.TextBox fallGS3box;
		private System.Windows.Forms.TextBox fallGS4box;
		private System.Windows.Forms.TextBox fallGS5box;
		private System.Windows.Forms.TextBox fallGS6box;
		private System.Windows.Forms.TextBox fallGS7box;
		private System.Windows.Forms.TextBox fallGS8box;
		private System.Windows.Forms.TextBox fallGS9box;
		private System.Windows.Forms.MenuItem menuItem30;
		private System.Windows.Forms.MenuItem menuItem31;
		private System.Windows.Forms.MenuItem menuItem32;
		private System.Windows.Forms.MenuItem menuItem33;
		private System.Windows.Forms.MenuItem menuItem34;
		private System.Windows.Forms.CheckBox overrideheaderBox;
		private System.Windows.Forms.TabPage tabPage1;
		private System.Windows.Forms.TextBox lateralratebox;
        private System.Windows.Forms.Label label7;
        private System.Windows.Forms.CheckBox newlateral;
		private System.Windows.Forms.Button button4;
        private System.Windows.Forms.Button button3;
		private System.Windows.Forms.CheckBox recirculatebox;
		private System.Windows.Forms.CheckBox checkBox3;
		private System.Windows.Forms.Panel Panel1;
		private System.Windows.Forms.Label label52;
        private System.Windows.Forms.CheckBox bedslope_box;
		private System.Windows.Forms.ToolTip toolTip1;
        private System.Windows.Forms.GroupBox groupBox1;
		private System.Windows.Forms.Label label54;
		private System.Windows.Forms.CheckBox latbox1;
        private System.Windows.Forms.CheckBox latbox2;
		private System.Windows.Forms.TextBox tempdata1;
        private System.Windows.Forms.TextBox tempdata2;
		private System.Windows.Forms.CheckBox veltaubox;
		private System.Windows.Forms.TabPage tabPage2;
		private System.Windows.Forms.TextBox vegTauCritBox;
		private System.Windows.Forms.Label label36;
		private System.Windows.Forms.TextBox infile5;
		private System.Windows.Forms.TextBox ybox5;
		private System.Windows.Forms.TextBox xbox5;
		private System.Windows.Forms.CheckBox inbox5;
		private System.Windows.Forms.TextBox infile6;
		private System.Windows.Forms.TextBox ybox6;
		private System.Windows.Forms.TextBox xbox6;
		private System.Windows.Forms.CheckBox inbox6;
		private System.Windows.Forms.TextBox infile7;
		private System.Windows.Forms.TextBox ybox7;
		private System.Windows.Forms.TextBox xbox7;
		private System.Windows.Forms.CheckBox inbox7;
		private System.Windows.Forms.TextBox infile8;
		private System.Windows.Forms.TextBox ybox8;
		private System.Windows.Forms.TextBox xbox8;
		private System.Windows.Forms.CheckBox inbox8;
		private System.Windows.Forms.Button button5;
		private System.Windows.Forms.TextBox propremaining;
		private System.Windows.Forms.Label label57;
        private System.Windows.Forms.TextBox Q2box;
        private CheckBox nolateral;
        private TabPage FilesTab;
        private Label label59;
        private TextBox mvalueloadbox;
        private CheckBox reach_mode_box;
        private CheckBox catchment_mode_box;
        private CheckBox checkBoxGenerateTimeSeries;
        private CheckBox checkBoxGenerateIterations;
        private TextBox IterationOutbox;
        private TextBox TimeseriesOutBox;
        private TextBox outputfilesaveintervalbox;
        private TextBox saveintervalbox;
        private Label label45;
        private Label label33;
        private CheckBox uniquefilecheck;
        private CheckBox checkBoxGenerateAVIFile;
        private TextBox textBoxAVIFile;
        private TextBox tracergrainbox;
        private Label label38;
        private Label label32;
        private TextBox tracerhydrofile;
        private TextBox tracerfile;
        private TextBox raindataloadbox;
        private TextBox bedrockbox;
        private TextBox graindataloadbox;
        private TextBox openfiletextbox;
        private CheckBox tracerbox;
        private Label label30;
        private Label label25;
        private Label label39;
        private Label label24;
        private Label label23;
        private CheckBox grassbox;
        private CheckBox jmeaninputfilebox;
        private Smallwisdom.Windows.Forms.ZoomPanImageBox zoomPanImageBox1;
        private MenuItem menuItem35;
        private MenuItem menuItem36;
        private MenuItem menuItem37;
        private TrackBar trackBar1;
        private Label label61;
        private GroupBox groupBox2;
        private ComboBox comboBox1;
        private Label label62;
        private GroupBox groupBox3;
        private Label label63;
        private TrackBar trackBar2;
        private TabPage tabPage3;
        private TextBox mine_input_textBox;
        private TextBox mineY_textBox;
        private TextBox mineX_textBox;
        private Label label64;
        private Label label65;
        private Label label66;
        private CheckBox mine_checkBox;
        private TextBox tracerOutputtextBox;
        private CheckBox tracerOutcheckBox;
        private Label label60;
        private TextBox avge_smoothbox;
        private TextBox mvaluebox;
        private Label label37;
        private TextBox grasstextbox;
        private Label label40;
        private TabPage tabPage4;
        private Label label67;
        private TextBox soil_ratebox;
        private TextBox slopebox;
        private TextBox creepratebox;
        private Label label34;
        private Label label8;
        private Label label69;
        private Label label68;
        private Label label70;
        private Label label73;
        private Label label72;
        private Label label71;
        private TextBox m3Box;
        private TextBox n1Box;
        private TextBox m1Box;
        private TextBox Beta3Box;
        private TextBox Beta1Box;
        private CheckBox SiberiaBox;
        private Label label75;
        private Label label74;
        private TextBox max_time_step_Box;
        private Label label76;
        private TextBox googleBeginDate;
        private Label label78;
        private TextBox googAnimationSaveInterval;
        private Label label79;
        private TextBox googleAnimationTextBox;
        private CheckBox googleAnimationCheckbox;
        private Label label82;
        private Label label81;
        private Label label80;
        private Button graphicToGoogleEarthButton;
        private TextBox textBox4;
        private CheckBox einsteinbox;
        private CheckBox wilcockbox;
        private Label label83;
        private TextBox div_inputs_box;
        private CheckBox checkBox1;
        private TabPage tabPage5;
        private CheckBox DuneBox;
        private Button pause;
        private Button button7;
        private Label label89;
        private Label label88;
        private Label label87;
        private Label label86;
        private Label label85;
        private Label label84;
        private TextBox slab_depth_box;
        private TextBox shadow_angle_box;
        private TextBox upstream_check_box;
        private TextBox depo_prob_box;
        private TextBox offset_box;
        private TextBox init_depth_box;
        private Label label55;
        private Label label53;
        private CheckBox checkBox2;
		double[,] climate_data;

		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
            this.button2 = new System.Windows.Forms.Button();
            this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);
            this.menuItemConfigFile = new System.Windows.Forms.MenuItem();
            this.menuItemConfigFileOpen = new System.Windows.Forms.MenuItem();
            this.menuItemConfigFileSaveAs = new System.Windows.Forms.MenuItem();
            this.menuItemConfigFileSave = new System.Windows.Forms.MenuItem();
            this.menuItem1 = new System.Windows.Forms.MenuItem();
            this.menuItem30 = new System.Windows.Forms.MenuItem();
            this.menuItem3 = new System.Windows.Forms.MenuItem();
            this.menuItem4 = new System.Windows.Forms.MenuItem();
            this.menuItem5 = new System.Windows.Forms.MenuItem();
            this.menuItem6 = new System.Windows.Forms.MenuItem();
            this.menuItem2 = new System.Windows.Forms.MenuItem();
            this.menuItem7 = new System.Windows.Forms.MenuItem();
            this.menuItem8 = new System.Windows.Forms.MenuItem();
            this.menuItem9 = new System.Windows.Forms.MenuItem();
            this.menuItem10 = new System.Windows.Forms.MenuItem();
            this.menuItem26 = new System.Windows.Forms.MenuItem();
            this.menuItem27 = new System.Windows.Forms.MenuItem();
            this.menuItem28 = new System.Windows.Forms.MenuItem();
            this.menuItem31 = new System.Windows.Forms.MenuItem();
            this.menuItem32 = new System.Windows.Forms.MenuItem();
            this.menuItem35 = new System.Windows.Forms.MenuItem();
            this.menuItem36 = new System.Windows.Forms.MenuItem();
            this.menuItem37 = new System.Windows.Forms.MenuItem();
            this.menuItem11 = new System.Windows.Forms.MenuItem();
            this.menuItem12 = new System.Windows.Forms.MenuItem();
            this.menuItem13 = new System.Windows.Forms.MenuItem();
            this.menuItem14 = new System.Windows.Forms.MenuItem();
            this.menuItem15 = new System.Windows.Forms.MenuItem();
            this.menuItem16 = new System.Windows.Forms.MenuItem();
            this.menuItem17 = new System.Windows.Forms.MenuItem();
            this.menuItem18 = new System.Windows.Forms.MenuItem();
            this.menuItem19 = new System.Windows.Forms.MenuItem();
            this.menuItem20 = new System.Windows.Forms.MenuItem();
            this.menuItem21 = new System.Windows.Forms.MenuItem();
            this.menuItem22 = new System.Windows.Forms.MenuItem();
            this.menuItem23 = new System.Windows.Forms.MenuItem();
            this.menuItem24 = new System.Windows.Forms.MenuItem();
            this.menuItem25 = new System.Windows.Forms.MenuItem();
            this.menuItem29 = new System.Windows.Forms.MenuItem();
            this.menuItem33 = new System.Windows.Forms.MenuItem();
            this.menuItem34 = new System.Windows.Forms.MenuItem();
            this.tabControl1 = new System.Windows.Forms.TabControl();
            this.FilesTab = new System.Windows.Forms.TabPage();
            this.checkBox2 = new System.Windows.Forms.CheckBox();
            this.textBox4 = new System.Windows.Forms.TextBox();
            this.outputfilesaveintervalbox = new System.Windows.Forms.TextBox();
            this.TimeseriesOutBox = new System.Windows.Forms.TextBox();
            this.googleBeginDate = new System.Windows.Forms.TextBox();
            this.label78 = new System.Windows.Forms.Label();
            this.googAnimationSaveInterval = new System.Windows.Forms.TextBox();
            this.label79 = new System.Windows.Forms.Label();
            this.googleAnimationTextBox = new System.Windows.Forms.TextBox();
            this.googleAnimationCheckbox = new System.Windows.Forms.CheckBox();
            this.tracerOutputtextBox = new System.Windows.Forms.TextBox();
            this.tracerOutcheckBox = new System.Windows.Forms.CheckBox();
            this.jmeaninputfilebox = new System.Windows.Forms.CheckBox();
            this.label59 = new System.Windows.Forms.Label();
            this.mvalueloadbox = new System.Windows.Forms.TextBox();
            this.reach_mode_box = new System.Windows.Forms.CheckBox();
            this.catchment_mode_box = new System.Windows.Forms.CheckBox();
            this.checkBoxGenerateTimeSeries = new System.Windows.Forms.CheckBox();
            this.checkBoxGenerateIterations = new System.Windows.Forms.CheckBox();
            this.IterationOutbox = new System.Windows.Forms.TextBox();
            this.saveintervalbox = new System.Windows.Forms.TextBox();
            this.label45 = new System.Windows.Forms.Label();
            this.label33 = new System.Windows.Forms.Label();
            this.uniquefilecheck = new System.Windows.Forms.CheckBox();
            this.checkBoxGenerateAVIFile = new System.Windows.Forms.CheckBox();
            this.textBoxAVIFile = new System.Windows.Forms.TextBox();
            this.tracergrainbox = new System.Windows.Forms.TextBox();
            this.label38 = new System.Windows.Forms.Label();
            this.label32 = new System.Windows.Forms.Label();
            this.tracerhydrofile = new System.Windows.Forms.TextBox();
            this.tracerfile = new System.Windows.Forms.TextBox();
            this.raindataloadbox = new System.Windows.Forms.TextBox();
            this.bedrockbox = new System.Windows.Forms.TextBox();
            this.graindataloadbox = new System.Windows.Forms.TextBox();
            this.openfiletextbox = new System.Windows.Forms.TextBox();
            this.tracerbox = new System.Windows.Forms.CheckBox();
            this.label30 = new System.Windows.Forms.Label();
            this.label25 = new System.Windows.Forms.Label();
            this.label39 = new System.Windows.Forms.Label();
            this.label24 = new System.Windows.Forms.Label();
            this.label23 = new System.Windows.Forms.Label();
            this.tabPage1 = new System.Windows.Forms.TabPage();
            this.nolateral = new System.Windows.Forms.CheckBox();
            this.label54 = new System.Windows.Forms.Label();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.label60 = new System.Windows.Forms.Label();
            this.avge_smoothbox = new System.Windows.Forms.TextBox();
            this.label57 = new System.Windows.Forms.Label();
            this.propremaining = new System.Windows.Forms.TextBox();
            this.label55 = new System.Windows.Forms.Label();
            this.latbox2 = new System.Windows.Forms.CheckBox();
            this.latbox1 = new System.Windows.Forms.CheckBox();
            this.newlateral = new System.Windows.Forms.CheckBox();
            this.lateralratebox = new System.Windows.Forms.TextBox();
            this.label7 = new System.Windows.Forms.Label();
            this.NumericalTab = new System.Windows.Forms.TabPage();
            this.label53 = new System.Windows.Forms.Label();
            this.max_time_step_Box = new System.Windows.Forms.TextBox();
            this.label76 = new System.Windows.Forms.Label();
            this.Q2box = new System.Windows.Forms.TextBox();
            this.veltaubox = new System.Windows.Forms.CheckBox();
            this.label52 = new System.Windows.Forms.Label();
            this.bedslope_box = new System.Windows.Forms.CheckBox();
            this.label3 = new System.Windows.Forms.Label();
            this.k_evapBox = new System.Windows.Forms.TextBox();
            this.label51 = new System.Windows.Forms.Label();
            this.label47 = new System.Windows.Forms.Label();
            this.textBox3 = new System.Windows.Forms.TextBox();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.label48 = new System.Windows.Forms.Label();
            this.label46 = new System.Windows.Forms.Label();
            this.label50 = new System.Windows.Forms.Label();
            this.activebox = new System.Windows.Forms.TextBox();
            this.mintimestepbox = new System.Windows.Forms.TextBox();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.smoothbox = new System.Windows.Forms.TextBox();
            this.cyclemaxbox = new System.Windows.Forms.TextBox();
            this.itermaxbox = new System.Windows.Forms.TextBox();
            this.minqbox = new System.Windows.Forms.TextBox();
            this.limitbox = new System.Windows.Forms.TextBox();
            this.erodefactorbox = new System.Windows.Forms.TextBox();
            this.initscansbox = new System.Windows.Forms.TextBox();
            this.label31 = new System.Windows.Forms.Label();
            this.label35 = new System.Windows.Forms.Label();
            this.label27 = new System.Windows.Forms.Label();
            this.label26 = new System.Windows.Forms.Label();
            this.label12 = new System.Windows.Forms.Label();
            this.label10 = new System.Windows.Forms.Label();
            this.label9 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.label49 = new System.Windows.Forms.Label();
            this.GrainTab = new System.Windows.Forms.TabPage();
            this.einsteinbox = new System.Windows.Forms.CheckBox();
            this.wilcockbox = new System.Windows.Forms.CheckBox();
            this.fallGS9box = new System.Windows.Forms.TextBox();
            this.fallGS8box = new System.Windows.Forms.TextBox();
            this.fallGS7box = new System.Windows.Forms.TextBox();
            this.fallGS6box = new System.Windows.Forms.TextBox();
            this.fallGS5box = new System.Windows.Forms.TextBox();
            this.fallGS4box = new System.Windows.Forms.TextBox();
            this.fallGS3box = new System.Windows.Forms.TextBox();
            this.gpSumLabel = new System.Windows.Forms.Label();
            this.gpSumLabel2 = new System.Windows.Forms.Label();
            this.suspGS9box = new System.Windows.Forms.CheckBox();
            this.suspGS8box = new System.Windows.Forms.CheckBox();
            this.suspGS7box = new System.Windows.Forms.CheckBox();
            this.suspGS6box = new System.Windows.Forms.CheckBox();
            this.suspGS5box = new System.Windows.Forms.CheckBox();
            this.suspGS4box = new System.Windows.Forms.CheckBox();
            this.suspGS3box = new System.Windows.Forms.CheckBox();
            this.suspGS2box = new System.Windows.Forms.CheckBox();
            this.fallGS2box = new System.Windows.Forms.TextBox();
            this.fallGS1box = new System.Windows.Forms.TextBox();
            this.label28 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.suspGS1box = new System.Windows.Forms.CheckBox();
            this.gp3box = new System.Windows.Forms.TextBox();
            this.gp4box = new System.Windows.Forms.TextBox();
            this.gp5box = new System.Windows.Forms.TextBox();
            this.gp6box = new System.Windows.Forms.TextBox();
            this.gp7box = new System.Windows.Forms.TextBox();
            this.gp8box = new System.Windows.Forms.TextBox();
            this.gp9box = new System.Windows.Forms.TextBox();
            this.gp2box = new System.Windows.Forms.TextBox();
            this.gp1box = new System.Windows.Forms.TextBox();
            this.g3box = new System.Windows.Forms.TextBox();
            this.g4box = new System.Windows.Forms.TextBox();
            this.g5box = new System.Windows.Forms.TextBox();
            this.g6box = new System.Windows.Forms.TextBox();
            this.g7box = new System.Windows.Forms.TextBox();
            this.g8box = new System.Windows.Forms.TextBox();
            this.g9box = new System.Windows.Forms.TextBox();
            this.g2box = new System.Windows.Forms.TextBox();
            this.g1box = new System.Windows.Forms.TextBox();
            this.label22 = new System.Windows.Forms.Label();
            this.label21 = new System.Windows.Forms.Label();
            this.label20 = new System.Windows.Forms.Label();
            this.label19 = new System.Windows.Forms.Label();
            this.label18 = new System.Windows.Forms.Label();
            this.label17 = new System.Windows.Forms.Label();
            this.label16 = new System.Windows.Forms.Label();
            this.label15 = new System.Windows.Forms.Label();
            this.label14 = new System.Windows.Forms.Label();
            this.label13 = new System.Windows.Forms.Label();
            this.label6 = new System.Windows.Forms.Label();
            this.DescriptionTab = new System.Windows.Forms.TabPage();
            this.DescBox = new System.Windows.Forms.TextBox();
            this.GridTab = new System.Windows.Forms.TabPage();
            this.overrideheaderBox = new System.Windows.Forms.CheckBox();
            this.dxbox = new System.Windows.Forms.TextBox();
            this.label11 = new System.Windows.Forms.Label();
            this.ytextbox = new System.Windows.Forms.TextBox();
            this.xtextbox = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.HydrologyTab = new System.Windows.Forms.TabPage();
            this.label83 = new System.Windows.Forms.Label();
            this.div_inputs_box = new System.Windows.Forms.TextBox();
            this.mvaluebox = new System.Windows.Forms.TextBox();
            this.label37 = new System.Windows.Forms.Label();
            this.infile8 = new System.Windows.Forms.TextBox();
            this.ybox8 = new System.Windows.Forms.TextBox();
            this.xbox8 = new System.Windows.Forms.TextBox();
            this.inbox8 = new System.Windows.Forms.CheckBox();
            this.infile7 = new System.Windows.Forms.TextBox();
            this.ybox7 = new System.Windows.Forms.TextBox();
            this.xbox7 = new System.Windows.Forms.TextBox();
            this.inbox7 = new System.Windows.Forms.CheckBox();
            this.infile6 = new System.Windows.Forms.TextBox();
            this.ybox6 = new System.Windows.Forms.TextBox();
            this.xbox6 = new System.Windows.Forms.TextBox();
            this.inbox6 = new System.Windows.Forms.CheckBox();
            this.infile5 = new System.Windows.Forms.TextBox();
            this.ybox5 = new System.Windows.Forms.TextBox();
            this.xbox5 = new System.Windows.Forms.TextBox();
            this.inbox5 = new System.Windows.Forms.CheckBox();
            this.input_time_step_box = new System.Windows.Forms.TextBox();
            this.infile4 = new System.Windows.Forms.TextBox();
            this.infile3 = new System.Windows.Forms.TextBox();
            this.infile2 = new System.Windows.Forms.TextBox();
            this.infile1 = new System.Windows.Forms.TextBox();
            this.ybox1 = new System.Windows.Forms.TextBox();
            this.ybox2 = new System.Windows.Forms.TextBox();
            this.ybox3 = new System.Windows.Forms.TextBox();
            this.ybox4 = new System.Windows.Forms.TextBox();
            this.xbox2 = new System.Windows.Forms.TextBox();
            this.xbox3 = new System.Windows.Forms.TextBox();
            this.xbox4 = new System.Windows.Forms.TextBox();
            this.xbox1 = new System.Windows.Forms.TextBox();
            this.label29 = new System.Windows.Forms.Label();
            this.label44 = new System.Windows.Forms.Label();
            this.label43 = new System.Windows.Forms.Label();
            this.label41 = new System.Windows.Forms.Label();
            this.inbox2 = new System.Windows.Forms.CheckBox();
            this.inbox3 = new System.Windows.Forms.CheckBox();
            this.inbox4 = new System.Windows.Forms.CheckBox();
            this.inbox1 = new System.Windows.Forms.CheckBox();
            this.label42 = new System.Windows.Forms.Label();
            this.tabPage2 = new System.Windows.Forms.TabPage();
            this.grasstextbox = new System.Windows.Forms.TextBox();
            this.label40 = new System.Windows.Forms.Label();
            this.label36 = new System.Windows.Forms.Label();
            this.vegTauCritBox = new System.Windows.Forms.TextBox();
            this.tabPage3 = new System.Windows.Forms.TabPage();
            this.mine_input_textBox = new System.Windows.Forms.TextBox();
            this.mineY_textBox = new System.Windows.Forms.TextBox();
            this.mineX_textBox = new System.Windows.Forms.TextBox();
            this.label64 = new System.Windows.Forms.Label();
            this.label65 = new System.Windows.Forms.Label();
            this.label66 = new System.Windows.Forms.Label();
            this.mine_checkBox = new System.Windows.Forms.CheckBox();
            this.tabPage4 = new System.Windows.Forms.TabPage();
            this.label75 = new System.Windows.Forms.Label();
            this.label74 = new System.Windows.Forms.Label();
            this.label73 = new System.Windows.Forms.Label();
            this.label72 = new System.Windows.Forms.Label();
            this.label71 = new System.Windows.Forms.Label();
            this.m3Box = new System.Windows.Forms.TextBox();
            this.n1Box = new System.Windows.Forms.TextBox();
            this.m1Box = new System.Windows.Forms.TextBox();
            this.Beta3Box = new System.Windows.Forms.TextBox();
            this.Beta1Box = new System.Windows.Forms.TextBox();
            this.SiberiaBox = new System.Windows.Forms.CheckBox();
            this.label70 = new System.Windows.Forms.Label();
            this.label69 = new System.Windows.Forms.Label();
            this.label68 = new System.Windows.Forms.Label();
            this.label67 = new System.Windows.Forms.Label();
            this.soil_ratebox = new System.Windows.Forms.TextBox();
            this.slopebox = new System.Windows.Forms.TextBox();
            this.creepratebox = new System.Windows.Forms.TextBox();
            this.label34 = new System.Windows.Forms.Label();
            this.label8 = new System.Windows.Forms.Label();
            this.tabPage5 = new System.Windows.Forms.TabPage();
            this.label89 = new System.Windows.Forms.Label();
            this.label88 = new System.Windows.Forms.Label();
            this.label87 = new System.Windows.Forms.Label();
            this.label86 = new System.Windows.Forms.Label();
            this.label85 = new System.Windows.Forms.Label();
            this.label84 = new System.Windows.Forms.Label();
            this.slab_depth_box = new System.Windows.Forms.TextBox();
            this.shadow_angle_box = new System.Windows.Forms.TextBox();
            this.upstream_check_box = new System.Windows.Forms.TextBox();
            this.depo_prob_box = new System.Windows.Forms.TextBox();
            this.offset_box = new System.Windows.Forms.TextBox();
            this.init_depth_box = new System.Windows.Forms.TextBox();
            this.DuneBox = new System.Windows.Forms.CheckBox();
            this.statusBar1 = new System.Windows.Forms.StatusBar();
            this.InfoStatusPanel = new System.Windows.Forms.StatusBarPanel();
            this.IterationStatusPanel = new System.Windows.Forms.StatusBarPanel();
            this.TimeStatusPanel = new System.Windows.Forms.StatusBarPanel();
            this.QwStatusPanel = new System.Windows.Forms.StatusBarPanel();
            this.QsStatusPanel = new System.Windows.Forms.StatusBarPanel();
            this.tempStatusPanel = new System.Windows.Forms.StatusBarPanel();
            this.start_button = new System.Windows.Forms.Button();
            this.button1 = new System.Windows.Forms.Button();
            this.button4 = new System.Windows.Forms.Button();
            this.button3 = new System.Windows.Forms.Button();
            this.tempdata1 = new System.Windows.Forms.TextBox();
            this.recirculatebox = new System.Windows.Forms.CheckBox();
            this.checkBox3 = new System.Windows.Forms.CheckBox();
            this.Panel1 = new System.Windows.Forms.Panel();
            this.tempdata2 = new System.Windows.Forms.TextBox();
            this.graphicToGoogleEarthButton = new System.Windows.Forms.Button();
            this.label82 = new System.Windows.Forms.Label();
            this.label81 = new System.Windows.Forms.Label();
            this.label80 = new System.Windows.Forms.Label();
            this.button5 = new System.Windows.Forms.Button();
            this.grassbox = new System.Windows.Forms.CheckBox();
            this.checkBox1 = new System.Windows.Forms.CheckBox();
            this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
            this.trackBar1 = new System.Windows.Forms.TrackBar();
            this.label61 = new System.Windows.Forms.Label();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.label62 = new System.Windows.Forms.Label();
            this.comboBox1 = new System.Windows.Forms.ComboBox();
            this.groupBox3 = new System.Windows.Forms.GroupBox();
            this.label63 = new System.Windows.Forms.Label();
            this.trackBar2 = new System.Windows.Forms.TrackBar();
            this.pause = new System.Windows.Forms.Button();
            this.button7 = new System.Windows.Forms.Button();
            this.zoomPanImageBox1 = new Smallwisdom.Windows.Forms.ZoomPanImageBox();
            this.tabControl1.SuspendLayout();
            this.FilesTab.SuspendLayout();
            this.tabPage1.SuspendLayout();
            this.groupBox1.SuspendLayout();
            this.NumericalTab.SuspendLayout();
            this.GrainTab.SuspendLayout();
            this.DescriptionTab.SuspendLayout();
            this.GridTab.SuspendLayout();
            this.HydrologyTab.SuspendLayout();
            this.tabPage2.SuspendLayout();
            this.tabPage3.SuspendLayout();
            this.tabPage4.SuspendLayout();
            this.tabPage5.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.InfoStatusPanel)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.IterationStatusPanel)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.TimeStatusPanel)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.QwStatusPanel)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.QsStatusPanel)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.tempStatusPanel)).BeginInit();
            this.Panel1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
            this.groupBox2.SuspendLayout();
            this.groupBox3.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.trackBar2)).BeginInit();
            this.SuspendLayout();
            // 
            // button2
            // 
            this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.button2.Location = new System.Drawing.Point(4, 258);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(100, 24);
            this.button2.TabIndex = 7;
            this.button2.Text = "load data";
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // mainMenu1
            // 
            this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemConfigFile,
            this.menuItem1,
            this.menuItem2,
            this.menuItem35,
            this.menuItem11});
            // 
            // menuItemConfigFile
            // 
            this.menuItemConfigFile.Index = 0;
            this.menuItemConfigFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemConfigFileOpen,
            this.menuItemConfigFileSaveAs,
            this.menuItemConfigFileSave});
            this.menuItemConfigFile.Text = "Config &File";
            // 
            // menuItemConfigFileOpen
            // 
            this.menuItemConfigFileOpen.Index = 0;
            this.menuItemConfigFileOpen.Text = "&Open";
            this.menuItemConfigFileOpen.Click += new System.EventHandler(this.menuItemConfigFileOpen_Click);
            // 
            // menuItemConfigFileSaveAs
            // 
            this.menuItemConfigFileSaveAs.Index = 1;
            this.menuItemConfigFileSaveAs.Text = "Save &As";
            this.menuItemConfigFileSaveAs.Click += new System.EventHandler(this.menuItemConfigFileSave_Click);
            // 
            // menuItemConfigFileSave
            // 
            this.menuItemConfigFileSave.Index = 2;
            this.menuItemConfigFileSave.Text = "&Save";
            this.menuItemConfigFileSave.Click += new System.EventHandler(this.menuItemConfigFileSave_Click);
            // 
            // menuItem1
            // 
            this.menuItem1.Index = 1;
            this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItem30,
            this.menuItem3,
            this.menuItem4,
            this.menuItem5,
            this.menuItem6});
            this.menuItem1.Text = "&Top Graphics";
            // 
            // menuItem30
            // 
            this.menuItem30.Index = 0;
            this.menuItem30.Text = "DEM";
            this.menuItem30.Click += new System.EventHandler(this.menuItem30_Click);
            // 
            // menuItem3
            // 
            this.menuItem3.Checked = true;
            this.menuItem3.Index = 1;
            this.menuItem3.Text = "water depth (low scale)";
            this.menuItem3.Click += new System.EventHandler(this.menuItem3_Click);
            // 
            // menuItem4
            // 
            this.menuItem4.Index = 2;
            this.menuItem4.Text = "erosion/dep";
            this.menuItem4.Click += new System.EventHandler(this.menuItem4_Click);
            // 
            // menuItem5
            // 
            this.menuItem5.Index = 3;
            this.menuItem5.Text = "Grass/veg cover";
            this.menuItem5.Click += new System.EventHandler(this.menuItem5_Click);
            // 
            // menuItem6
            // 
            this.menuItem6.Index = 4;
            this.menuItem6.Text = "Mannings value";
            this.menuItem6.Click += new System.EventHandler(this.menuItem6_Click);
            // 
            // menuItem2
            // 
            this.menuItem2.Index = 2;
            this.menuItem2.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItem7,
            this.menuItem8,
            this.menuItem9,
            this.menuItem10,
            this.menuItem26,
            this.menuItem27,
            this.menuItem28,
            this.menuItem31,
            this.menuItem32});
            this.menuItem2.Text = "&Top graphics II";
            // 
            // menuItem7
            // 
            this.menuItem7.Index = 0;
            this.menuItem7.Text = "lateral gradient";
            this.menuItem7.Click += new System.EventHandler(this.menuItem7_Click);
            // 
            // menuItem8
            // 
            this.menuItem8.Index = 1;
            this.menuItem8.Text = "Bed sheer stress";
            this.menuItem8.Click += new System.EventHandler(this.menuItem8_Click);
            // 
            // menuItem9
            // 
            this.menuItem9.Index = 2;
            this.menuItem9.Text = "grainsize (new scale)";
            this.menuItem9.Click += new System.EventHandler(this.menuItem9_Click);
            // 
            // menuItem10
            // 
            this.menuItem10.Index = 3;
            this.menuItem10.Text = "tracer";
            this.menuItem10.Click += new System.EventHandler(this.menuItem10_Click);
            // 
            // menuItem26
            // 
            this.menuItem26.Index = 4;
            this.menuItem26.Text = "Drainage area";
            this.menuItem26.Click += new System.EventHandler(this.menuItem26_Click);
            // 
            // menuItem27
            // 
            this.menuItem27.Index = 5;
            this.menuItem27.Text = "susp conc";
            this.menuItem27.Click += new System.EventHandler(this.menuItem27_Click);
            // 
            // menuItem28
            // 
            this.menuItem28.Index = 6;
            this.menuItem28.Text = "susp vol";
            this.menuItem28.Click += new System.EventHandler(this.menuItem28_Click);
            // 
            // menuItem31
            // 
            this.menuItem31.Index = 7;
            this.menuItem31.Text = "flow velocity";
            this.menuItem31.Click += new System.EventHandler(this.menuItem31_Click);
            // 
            // menuItem32
            // 
            this.menuItem32.Index = 8;
            this.menuItem32.Text = "soil saturation";
            this.menuItem32.Click += new System.EventHandler(this.menuItem32_Click);
            // 
            // menuItem35
            // 
            this.menuItem35.Enabled = false;
            this.menuItem35.Index = 3;
            this.menuItem35.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItem36,
            this.menuItem37});
            this.menuItem35.Text = "Chart";
            // 
            // menuItem36
            // 
            this.menuItem36.Index = 0;
            this.menuItem36.Text = "Hourly sediment";
            this.menuItem36.Click += new System.EventHandler(this.menuItem36_Click);
            // 
            // menuItem37
            // 
            this.menuItem37.Index = 1;
            this.menuItem37.Text = "Hourly discharge";
            this.menuItem37.Click += new System.EventHandler(this.menuItem37_Click);
            // 
            // menuItem11
            // 
            this.menuItem11.Index = 4;
            this.menuItem11.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItem12,
            this.menuItem13,
            this.menuItem14,
            this.menuItem15,
            this.menuItem16,
            this.menuItem17,
            this.menuItem18,
            this.menuItem19,
            this.menuItem20,
            this.menuItem21,
            this.menuItem22,
            this.menuItem23,
            this.menuItem24,
            this.menuItem25,
            this.menuItem29,
            this.menuItem33,
            this.menuItem34});
            this.menuItem11.Text = "Save Options";
            // 
            // menuItem12
            // 
            this.menuItem12.Checked = true;
            this.menuItem12.Index = 0;
            this.menuItem12.Text = "elevations";
            this.menuItem12.Click += new System.EventHandler(this.menuItem12_Click);
            // 
            // menuItem13
            // 
            this.menuItem13.Checked = true;
            this.menuItem13.Index = 1;
            this.menuItem13.Text = "elev diff";
            this.menuItem13.Click += new System.EventHandler(this.menuItem13_Click);
            // 
            // menuItem14
            // 
            this.menuItem14.Checked = true;
            this.menuItem14.Index = 2;
            this.menuItem14.Text = "grainsize";
            this.menuItem14.Click += new System.EventHandler(this.menuItem14_Click);
            // 
            // menuItem15
            // 
            this.menuItem15.Checked = true;
            this.menuItem15.Index = 3;
            this.menuItem15.Text = "total tracer g/s";
            this.menuItem15.Click += new System.EventHandler(this.menuItem15_Click);
            // 
            // menuItem16
            // 
            this.menuItem16.Index = 4;
            this.menuItem16.Text = "tracer layer1";
            this.menuItem16.Click += new System.EventHandler(this.menuItem16_Click);
            // 
            // menuItem17
            // 
            this.menuItem17.Index = 5;
            this.menuItem17.Text = "tracer layer2";
            this.menuItem17.Click += new System.EventHandler(this.menuItem17_Click);
            // 
            // menuItem18
            // 
            this.menuItem18.Index = 6;
            this.menuItem18.Text = "tracer layer3";
            this.menuItem18.Click += new System.EventHandler(this.menuItem18_Click);
            // 
            // menuItem19
            // 
            this.menuItem19.Index = 7;
            this.menuItem19.Text = "tracer layer4";
            this.menuItem19.Click += new System.EventHandler(this.menuItem19_Click);
            // 
            // menuItem20
            // 
            this.menuItem20.Index = 8;
            this.menuItem20.Text = "tracer layer5";
            this.menuItem20.Click += new System.EventHandler(this.menuItem20_Click);
            // 
            // menuItem21
            // 
            this.menuItem21.Index = 9;
            this.menuItem21.Text = "tracer layer6";
            this.menuItem21.Click += new System.EventHandler(this.menuItem21_Click);
            // 
            // menuItem22
            // 
            this.menuItem22.Index = 10;
            this.menuItem22.Text = "tracer layer7";
            this.menuItem22.Click += new System.EventHandler(this.menuItem22_Click);
            // 
            // menuItem23
            // 
            this.menuItem23.Index = 11;
            this.menuItem23.Text = "tracer layer8";
            this.menuItem23.Click += new System.EventHandler(this.menuItem23_Click);
            // 
            // menuItem24
            // 
            this.menuItem24.Index = 12;
            this.menuItem24.Text = "tracer layer9";
            this.menuItem24.Click += new System.EventHandler(this.menuItem24_Click);
            // 
            // menuItem25
            // 
            this.menuItem25.Index = 13;
            this.menuItem25.Text = "water depth";
            this.menuItem25.Click += new System.EventHandler(this.menuItem25_Click);
            // 
            // menuItem29
            // 
            this.menuItem29.Checked = true;
            this.menuItem29.Index = 14;
            this.menuItem29.Text = "d50 top layer";
            this.menuItem29.Click += new System.EventHandler(this.menuItem29_Click);
            // 
            // menuItem33
            // 
            this.menuItem33.Index = 15;
            this.menuItem33.Text = "flow velocity";
            this.menuItem33.Click += new System.EventHandler(this.menuItem33_Click);
            // 
            // menuItem34
            // 
            this.menuItem34.Index = 16;
            this.menuItem34.Text = "Veloc vectors";
            this.menuItem34.Click += new System.EventHandler(this.menuItem34_Click);
            // 
            // tabControl1
            // 
            this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.tabControl1.Controls.Add(this.FilesTab);
            this.tabControl1.Controls.Add(this.tabPage1);
            this.tabControl1.Controls.Add(this.NumericalTab);
            this.tabControl1.Controls.Add(this.GrainTab);
            this.tabControl1.Controls.Add(this.DescriptionTab);
            this.tabControl1.Controls.Add(this.GridTab);
            this.tabControl1.Controls.Add(this.HydrologyTab);
            this.tabControl1.Controls.Add(this.tabPage2);
            this.tabControl1.Controls.Add(this.tabPage3);
            this.tabControl1.Controls.Add(this.tabPage4);
            this.tabControl1.Controls.Add(this.tabPage5);
            this.tabControl1.Location = new System.Drawing.Point(4, 3);
            this.tabControl1.Name = "tabControl1";
            this.tabControl1.SelectedIndex = 0;
            this.tabControl1.Size = new System.Drawing.Size(915, 248);
            this.tabControl1.TabIndex = 143;
            // 
            // FilesTab
            // 
            this.FilesTab.Controls.Add(this.checkBox2);
            this.FilesTab.Controls.Add(this.textBox4);
            this.FilesTab.Controls.Add(this.outputfilesaveintervalbox);
            this.FilesTab.Controls.Add(this.TimeseriesOutBox);
            this.FilesTab.Controls.Add(this.googleBeginDate);
            this.FilesTab.Controls.Add(this.label78);
            this.FilesTab.Controls.Add(this.googAnimationSaveInterval);
            this.FilesTab.Controls.Add(this.label79);
            this.FilesTab.Controls.Add(this.googleAnimationTextBox);
            this.FilesTab.Controls.Add(this.googleAnimationCheckbox);
            this.FilesTab.Controls.Add(this.tracerOutputtextBox);
            this.FilesTab.Controls.Add(this.tracerOutcheckBox);
            this.FilesTab.Controls.Add(this.jmeaninputfilebox);
            this.FilesTab.Controls.Add(this.label59);
            this.FilesTab.Controls.Add(this.mvalueloadbox);
            this.FilesTab.Controls.Add(this.reach_mode_box);
            this.FilesTab.Controls.Add(this.catchment_mode_box);
            this.FilesTab.Controls.Add(this.checkBoxGenerateTimeSeries);
            this.FilesTab.Controls.Add(this.checkBoxGenerateIterations);
            this.FilesTab.Controls.Add(this.IterationOutbox);
            this.FilesTab.Controls.Add(this.saveintervalbox);
            this.FilesTab.Controls.Add(this.label45);
            this.FilesTab.Controls.Add(this.label33);
            this.FilesTab.Controls.Add(this.uniquefilecheck);
            this.FilesTab.Controls.Add(this.checkBoxGenerateAVIFile);
            this.FilesTab.Controls.Add(this.textBoxAVIFile);
            this.FilesTab.Controls.Add(this.tracergrainbox);
            this.FilesTab.Controls.Add(this.label38);
            this.FilesTab.Controls.Add(this.label32);
            this.FilesTab.Controls.Add(this.tracerhydrofile);
            this.FilesTab.Controls.Add(this.tracerfile);
            this.FilesTab.Controls.Add(this.raindataloadbox);
            this.FilesTab.Controls.Add(this.bedrockbox);
            this.FilesTab.Controls.Add(this.graindataloadbox);
            this.FilesTab.Controls.Add(this.openfiletextbox);
            this.FilesTab.Controls.Add(this.tracerbox);
            this.FilesTab.Controls.Add(this.label30);
            this.FilesTab.Controls.Add(this.label25);
            this.FilesTab.Controls.Add(this.label39);
            this.FilesTab.Controls.Add(this.label24);
            this.FilesTab.Controls.Add(this.label23);
            this.FilesTab.Location = new System.Drawing.Point(4, 22);
            this.FilesTab.Name = "FilesTab";
            this.FilesTab.Size = new System.Drawing.Size(907, 222);
            this.FilesTab.TabIndex = 0;
            this.FilesTab.Text = "Files";
            this.FilesTab.UseVisualStyleBackColor = true;
            // 
            // checkBox2
            // 
            this.checkBox2.AutoSize = true;
            this.checkBox2.Location = new System.Drawing.Point(317, 17);
            this.checkBox2.Name = "checkBox2";
            this.checkBox2.Size = new System.Drawing.Size(109, 17);
            this.checkBox2.TabIndex = 193;
            this.checkBox2.Text = "advanced mode?";
            this.checkBox2.UseVisualStyleBackColor = true;
            // 
            // textBox4
            // 
            this.textBox4.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.textBox4.Location = new System.Drawing.Point(707, 223);
            this.textBox4.Multiline = true;
            this.textBox4.Name = "textBox4";
            this.textBox4.ReadOnly = true;
            this.textBox4.Size = new System.Drawing.Size(103, 47);
            this.textBox4.TabIndex = 192;
            this.textBox4.Text = "only for DTMs using British National Grid";
            // 
            // outputfilesaveintervalbox
            // 
            this.outputfilesaveintervalbox.Location = new System.Drawing.Point(208, 327);
            this.outputfilesaveintervalbox.Name = "outputfilesaveintervalbox";
            this.outputfilesaveintervalbox.Size = new System.Drawing.Size(56, 20);
            this.outputfilesaveintervalbox.TabIndex = 166;
            this.outputfilesaveintervalbox.Text = "60";
            // 
            // TimeseriesOutBox
            // 
            this.TimeseriesOutBox.Location = new System.Drawing.Point(208, 303);
            this.TimeseriesOutBox.Name = "TimeseriesOutBox";
            this.TimeseriesOutBox.Size = new System.Drawing.Size(112, 20);
            this.TimeseriesOutBox.TabIndex = 168;
            this.TimeseriesOutBox.Text = "catchment.dat";
            // 
            // googleBeginDate
            // 
            this.googleBeginDate.AcceptsTab = true;
            this.googleBeginDate.Location = new System.Drawing.Point(589, 276);
            this.googleBeginDate.Name = "googleBeginDate";
            this.googleBeginDate.Size = new System.Drawing.Size(100, 20);
            this.googleBeginDate.TabIndex = 191;
            // 
            // label78
            // 
            this.label78.AutoSize = true;
            this.label78.Location = new System.Drawing.Point(463, 279);
            this.label78.Name = "label78";
            this.label78.Size = new System.Drawing.Size(120, 13);
            this.label78.TabIndex = 190;
            this.label78.Text = "begin date (yyyy-mm-dd)";
            // 
            // googAnimationSaveInterval
            // 
            this.googAnimationSaveInterval.Location = new System.Drawing.Point(589, 250);
            this.googAnimationSaveInterval.Name = "googAnimationSaveInterval";
            this.googAnimationSaveInterval.Size = new System.Drawing.Size(56, 20);
            this.googAnimationSaveInterval.TabIndex = 188;
            this.googAnimationSaveInterval.Text = "1000";
            // 
            // label79
            // 
            this.label79.Location = new System.Drawing.Point(431, 250);
            this.label79.Name = "label79";
            this.label79.Size = new System.Drawing.Size(152, 25);
            this.label79.TabIndex = 189;
            this.label79.Text = "Save file every * mins";
            this.label79.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.toolTip1.SetToolTip(this.label79, "How often the avi file AND the other data files are saved");
            // 
            // googleAnimationTextBox
            // 
            this.googleAnimationTextBox.Location = new System.Drawing.Point(589, 224);
            this.googleAnimationTextBox.Name = "googleAnimationTextBox";
            this.googleAnimationTextBox.Size = new System.Drawing.Size(112, 20);
            this.googleAnimationTextBox.TabIndex = 185;
            this.googleAnimationTextBox.Text = "animation.kmz";
            this.toolTip1.SetToolTip(this.googleAnimationTextBox, "File name for avi file");
            // 
            // googleAnimationCheckbox
            // 
            this.googleAnimationCheckbox.Location = new System.Drawing.Point(400, 224);
            this.googleAnimationCheckbox.Name = "googleAnimationCheckbox";
            this.googleAnimationCheckbox.Size = new System.Drawing.Size(195, 24);
            this.googleAnimationCheckbox.TabIndex = 184;
            this.googleAnimationCheckbox.Text = "Generate Google Earth Animation";
            this.toolTip1.SetToolTip(this.googleAnimationCheckbox, "Check to generate a movie file of the screen display");
            // 
            // tracerOutputtextBox
            // 
            this.tracerOutputtextBox.Location = new System.Drawing.Point(721, 147);
            this.tracerOutputtextBox.Name = "tracerOutputtextBox";
            this.tracerOutputtextBox.Size = new System.Drawing.Size(112, 20);
            this.tracerOutputtextBox.TabIndex = 181;
            this.tracerOutputtextBox.Text = "tracer_output.txt";
            // 
            // tracerOutcheckBox
            // 
            this.tracerOutcheckBox.Location = new System.Drawing.Point(589, 145);
            this.tracerOutcheckBox.Name = "tracerOutcheckBox";
            this.tracerOutcheckBox.Size = new System.Drawing.Size(160, 24);
            this.tracerOutcheckBox.TabIndex = 180;
            this.tracerOutcheckBox.Text = "Generate tracer output";
            // 
            // jmeaninputfilebox
            // 
            this.jmeaninputfilebox.AutoSize = true;
            this.jmeaninputfilebox.Location = new System.Drawing.Point(274, 123);
            this.jmeaninputfilebox.Name = "jmeaninputfilebox";
            this.jmeaninputfilebox.Size = new System.Drawing.Size(245, 17);
            this.jmeaninputfilebox.TabIndex = 179;
            this.jmeaninputfilebox.Text = "if checked, jmean is read direct from rainfall file";
            this.jmeaninputfilebox.UseVisualStyleBackColor = true;
            // 
            // label59
            // 
            this.label59.AutoSize = true;
            this.label59.Location = new System.Drawing.Point(19, 147);
            this.label59.Name = "label59";
            this.label59.Size = new System.Drawing.Size(102, 13);
            this.label59.TabIndex = 177;
            this.label59.Text = "Variable M value file";
            // 
            // mvalueloadbox
            // 
            this.mvalueloadbox.Location = new System.Drawing.Point(132, 147);
            this.mvalueloadbox.Name = "mvalueloadbox";
            this.mvalueloadbox.Size = new System.Drawing.Size(118, 20);
            this.mvalueloadbox.TabIndex = 176;
            this.mvalueloadbox.Text = "null";
            // 
            // reach_mode_box
            // 
            this.reach_mode_box.Checked = true;
            this.reach_mode_box.CheckState = System.Windows.Forms.CheckState.Checked;
            this.reach_mode_box.Location = new System.Drawing.Point(196, 5);
            this.reach_mode_box.Name = "reach_mode_box";
            this.reach_mode_box.Size = new System.Drawing.Size(147, 42);
            this.reach_mode_box.TabIndex = 175;
            this.reach_mode_box.Text = "Reach Mode";
            this.toolTip1.SetToolTip(this.reach_mode_box, "CAESAR can run in both catchment and reach mode combined. But if you have reach m" +
                    "ode selected, you should enter an input file in the hydrology tab");
            // 
            // catchment_mode_box
            // 
            this.catchment_mode_box.Location = new System.Drawing.Point(54, 9);
            this.catchment_mode_box.Name = "catchment_mode_box";
            this.catchment_mode_box.Size = new System.Drawing.Size(147, 34);
            this.catchment_mode_box.TabIndex = 174;
            this.catchment_mode_box.Text = "Catchment mode";
            this.toolTip1.SetToolTip(this.catchment_mode_box, "CAESAR can run in both catchment and reach mode, but if you have catchment mode c" +
                    "hecked, you should input a rainfall data file");
            this.catchment_mode_box.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged);
            // 
            // checkBoxGenerateTimeSeries
            // 
            this.checkBoxGenerateTimeSeries.Location = new System.Drawing.Point(44, 304);
            this.checkBoxGenerateTimeSeries.Name = "checkBoxGenerateTimeSeries";
            this.checkBoxGenerateTimeSeries.Size = new System.Drawing.Size(170, 24);
            this.checkBoxGenerateTimeSeries.TabIndex = 173;
            this.checkBoxGenerateTimeSeries.Text = "Generate time series output";
            // 
            // checkBoxGenerateIterations
            // 
            this.checkBoxGenerateIterations.Location = new System.Drawing.Point(401, 308);
            this.checkBoxGenerateIterations.Name = "checkBoxGenerateIterations";
            this.checkBoxGenerateIterations.Size = new System.Drawing.Size(152, 24);
            this.checkBoxGenerateIterations.TabIndex = 172;
            this.checkBoxGenerateIterations.Text = "Generate iteration output";
            // 
            // IterationOutbox
            // 
            this.IterationOutbox.Location = new System.Drawing.Point(561, 308);
            this.IterationOutbox.Name = "IterationOutbox";
            this.IterationOutbox.Size = new System.Drawing.Size(112, 20);
            this.IterationOutbox.TabIndex = 170;
            this.IterationOutbox.Text = "iterout.dat";
            // 
            // saveintervalbox
            // 
            this.saveintervalbox.Location = new System.Drawing.Point(208, 251);
            this.saveintervalbox.Name = "saveintervalbox";
            this.saveintervalbox.Size = new System.Drawing.Size(56, 20);
            this.saveintervalbox.TabIndex = 163;
            this.saveintervalbox.Text = "1000";
            // 
            // label45
            // 
            this.label45.Location = new System.Drawing.Point(48, 327);
            this.label45.Name = "label45";
            this.label45.Size = new System.Drawing.Size(152, 24);
            this.label45.TabIndex = 167;
            this.label45.Text = "Save file every * mins";
            this.label45.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label33
            // 
            this.label33.Location = new System.Drawing.Point(48, 251);
            this.label33.Name = "label33";
            this.label33.Size = new System.Drawing.Size(152, 25);
            this.label33.TabIndex = 165;
            this.label33.Text = "Save file every * mins";
            this.label33.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.toolTip1.SetToolTip(this.label33, "How often the avi file AND the other data files are saved");
            // 
            // uniquefilecheck
            // 
            this.uniquefilecheck.Location = new System.Drawing.Point(272, 251);
            this.uniquefilecheck.Name = "uniquefilecheck";
            this.uniquefilecheck.Size = new System.Drawing.Size(120, 25);
            this.uniquefilecheck.TabIndex = 164;
            this.uniquefilecheck.Text = "unique file name?";
            this.toolTip1.SetToolTip(this.uniquefilecheck, "Whether the data files are given a unqiu file name - ");
            // 
            // checkBoxGenerateAVIFile
            // 
            this.checkBoxGenerateAVIFile.Location = new System.Drawing.Point(44, 224);
            this.checkBoxGenerateAVIFile.Name = "checkBoxGenerateAVIFile";
            this.checkBoxGenerateAVIFile.Size = new System.Drawing.Size(128, 24);
            this.checkBoxGenerateAVIFile.TabIndex = 162;
            this.checkBoxGenerateAVIFile.Text = "Generate Avi File";
            this.toolTip1.SetToolTip(this.checkBoxGenerateAVIFile, "Check to generate a movie file of the screen display");
            // 
            // textBoxAVIFile
            // 
            this.textBoxAVIFile.Location = new System.Drawing.Point(208, 224);
            this.textBoxAVIFile.Name = "textBoxAVIFile";
            this.textBoxAVIFile.Size = new System.Drawing.Size(112, 20);
            this.textBoxAVIFile.TabIndex = 161;
            this.textBoxAVIFile.Text = "out.avi";
            this.toolTip1.SetToolTip(this.textBoxAVIFile, "File name for avi file");
            // 
            // tracergrainbox
            // 
            this.tracergrainbox.Location = new System.Drawing.Point(721, 106);
            this.tracergrainbox.Name = "tracergrainbox";
            this.tracergrainbox.Size = new System.Drawing.Size(120, 20);
            this.tracergrainbox.TabIndex = 108;
            this.tracergrainbox.Text = "null";
            // 
            // label38
            // 
            this.label38.Location = new System.Drawing.Point(585, 106);
            this.label38.Name = "label38";
            this.label38.Size = new System.Drawing.Size(128, 24);
            this.label38.TabIndex = 107;
            this.label38.Text = "tracer grainsize data file";
            this.label38.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label32
            // 
            this.label32.Location = new System.Drawing.Point(585, 82);
            this.label32.Name = "label32";
            this.label32.Size = new System.Drawing.Size(128, 24);
            this.label32.TabIndex = 106;
            this.label32.Text = "tracer sediment vol file";
            this.label32.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // tracerhydrofile
            // 
            this.tracerhydrofile.Location = new System.Drawing.Point(721, 82);
            this.tracerhydrofile.Name = "tracerhydrofile";
            this.tracerhydrofile.Size = new System.Drawing.Size(120, 20);
            this.tracerhydrofile.TabIndex = 105;
            this.tracerhydrofile.Text = "null";
            // 
            // tracerfile
            // 
            this.tracerfile.Location = new System.Drawing.Point(721, 58);
            this.tracerfile.Name = "tracerfile";
            this.tracerfile.Size = new System.Drawing.Size(120, 20);
            this.tracerfile.TabIndex = 104;
            this.tracerfile.Text = "null";
            // 
            // raindataloadbox
            // 
            this.raindataloadbox.Location = new System.Drawing.Point(131, 121);
            this.raindataloadbox.Name = "raindataloadbox";
            this.raindataloadbox.Size = new System.Drawing.Size(120, 20);
            this.raindataloadbox.TabIndex = 103;
            this.raindataloadbox.Text = "null";
            // 
            // bedrockbox
            // 
            this.bedrockbox.Location = new System.Drawing.Point(131, 97);
            this.bedrockbox.Name = "bedrockbox";
            this.bedrockbox.Size = new System.Drawing.Size(120, 20);
            this.bedrockbox.TabIndex = 102;
            this.bedrockbox.Text = "null";
            // 
            // graindataloadbox
            // 
            this.graindataloadbox.Location = new System.Drawing.Point(131, 73);
            this.graindataloadbox.Name = "graindataloadbox";
            this.graindataloadbox.Size = new System.Drawing.Size(120, 20);
            this.graindataloadbox.TabIndex = 101;
            this.graindataloadbox.Text = "null";
            // 
            // openfiletextbox
            // 
            this.openfiletextbox.Location = new System.Drawing.Point(131, 49);
            this.openfiletextbox.Name = "openfiletextbox";
            this.openfiletextbox.Size = new System.Drawing.Size(120, 20);
            this.openfiletextbox.TabIndex = 100;
            this.openfiletextbox.Text = "whole9.dat";
            // 
            // tracerbox
            // 
            this.tracerbox.Location = new System.Drawing.Point(596, 38);
            this.tracerbox.Name = "tracerbox";
            this.tracerbox.Size = new System.Drawing.Size(88, 23);
            this.tracerbox.TabIndex = 99;
            this.tracerbox.Text = "tracer run?";
            this.toolTip1.SetToolTip(this.tracerbox, "Check to run in \'tracer mode\'");
            // 
            // label30
            // 
            this.label30.Location = new System.Drawing.Point(585, 58);
            this.label30.Name = "label30";
            this.label30.Size = new System.Drawing.Size(128, 24);
            this.label30.TabIndex = 98;
            this.label30.Text = "tracer input file";
            this.label30.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label25
            // 
            this.label25.Location = new System.Drawing.Point(19, 121);
            this.label25.Name = "label25";
            this.label25.Size = new System.Drawing.Size(104, 24);
            this.label25.TabIndex = 97;
            this.label25.Text = "Rainfall data file";
            this.label25.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.toolTip1.SetToolTip(this.label25, "Hourly rainfall data - in an ascii format");
            // 
            // label39
            // 
            this.label39.Location = new System.Drawing.Point(19, 97);
            this.label39.Name = "label39";
            this.label39.Size = new System.Drawing.Size(104, 24);
            this.label39.TabIndex = 96;
            this.label39.Text = "Bedrock data file";
            this.label39.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.toolTip1.SetToolTip(this.label39, "A DEM of the bedrock - below which the model cannot erode");
            // 
            // label24
            // 
            this.label24.Location = new System.Drawing.Point(19, 73);
            this.label24.Name = "label24";
            this.label24.Size = new System.Drawing.Size(104, 24);
            this.label24.TabIndex = 58;
            this.label24.Text = "Grain data file";
            this.label24.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label23
            // 
            this.label23.Location = new System.Drawing.Point(19, 49);
            this.label23.Name = "label23";
            this.label23.Size = new System.Drawing.Size(104, 24);
            this.label23.TabIndex = 56;
            this.label23.Text = "DEM data file";
            this.label23.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // tabPage1
            // 
            this.tabPage1.Controls.Add(this.nolateral);
            this.tabPage1.Controls.Add(this.label54);
            this.tabPage1.Controls.Add(this.groupBox1);
            this.tabPage1.Controls.Add(this.newlateral);
            this.tabPage1.Controls.Add(this.lateralratebox);
            this.tabPage1.Controls.Add(this.label7);
            this.tabPage1.Location = new System.Drawing.Point(4, 22);
            this.tabPage1.Name = "tabPage1";
            this.tabPage1.Size = new System.Drawing.Size(907, 243);
            this.tabPage1.TabIndex = 6;
            this.tabPage1.Text = "lateral erosion";
            this.tabPage1.UseVisualStyleBackColor = true;
            // 
            // nolateral
            // 
            this.nolateral.Checked = true;
            this.nolateral.CheckState = System.Windows.Forms.CheckState.Checked;
            this.nolateral.Location = new System.Drawing.Point(22, 11);
            this.nolateral.Name = "nolateral";
            this.nolateral.Size = new System.Drawing.Size(121, 28);
            this.nolateral.TabIndex = 158;
            this.nolateral.Text = "No Lateral erosion";
            this.nolateral.CheckedChanged += new System.EventHandler(this.nolateral_CheckedChanged);
            // 
            // label54
            // 
            this.label54.Location = new System.Drawing.Point(335, 38);
            this.label54.Name = "label54";
            this.label54.Size = new System.Drawing.Size(400, 388);
            this.label54.TabIndex = 155;
            this.label54.Click += new System.EventHandler(this.label54_Click);
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.label60);
            this.groupBox1.Controls.Add(this.avge_smoothbox);
            this.groupBox1.Controls.Add(this.label57);
            this.groupBox1.Controls.Add(this.propremaining);
            this.groupBox1.Controls.Add(this.label55);
            this.groupBox1.Controls.Add(this.latbox2);
            this.groupBox1.Controls.Add(this.latbox1);
            this.groupBox1.Location = new System.Drawing.Point(22, 100);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(286, 291);
            this.groupBox1.TabIndex = 154;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Parameters for lateral method 2";
            // 
            // label60
            // 
            this.label60.Location = new System.Drawing.Point(88, 168);
            this.label60.Name = "label60";
            this.label60.Size = new System.Drawing.Size(186, 27);
            this.label60.TabIndex = 9;
            this.label60.Text = "length of edge smoothing";
            // 
            // avge_smoothbox
            // 
            this.avge_smoothbox.Location = new System.Drawing.Point(8, 165);
            this.avge_smoothbox.Name = "avge_smoothbox";
            this.avge_smoothbox.Size = new System.Drawing.Size(73, 20);
            this.avge_smoothbox.TabIndex = 8;
            this.avge_smoothbox.Text = "100";
            // 
            // label57
            // 
            this.label57.Location = new System.Drawing.Point(88, 205);
            this.label57.Name = "label57";
            this.label57.Size = new System.Drawing.Size(186, 27);
            this.label57.TabIndex = 7;
            this.label57.Text = "Proportion remaining after lat erosion";
            // 
            // propremaining
            // 
            this.propremaining.Location = new System.Drawing.Point(8, 205);
            this.propremaining.Name = "propremaining";
            this.propremaining.Size = new System.Drawing.Size(73, 20);
            this.propremaining.TabIndex = 6;
            this.propremaining.Text = "1.0";
            // 
            // label55
            // 
            this.label55.Location = new System.Drawing.Point(7, 42);
            this.label55.Name = "label55";
            this.label55.Size = new System.Drawing.Size(260, 62);
            this.label55.TabIndex = 5;
            this.label55.Text = "Lateral erosion rules (below). Rc=Radius of curvature/Channel width; Wd = water d" +
                "epth (near bank); T = Tau (near bank); t = time step; Lc = lateral constant; E =" +
                " erosion rate (near bank)";
            // 
            // latbox2
            // 
            this.latbox2.Location = new System.Drawing.Point(7, 132);
            this.latbox2.Name = "latbox2";
            this.latbox2.Size = new System.Drawing.Size(260, 27);
            this.latbox2.TabIndex = 3;
            this.latbox2.Text = "rule 2 = Rc Wd E t Lc";
            // 
            // latbox1
            // 
            this.latbox1.Checked = true;
            this.latbox1.CheckState = System.Windows.Forms.CheckState.Checked;
            this.latbox1.Location = new System.Drawing.Point(7, 104);
            this.latbox1.Name = "latbox1";
            this.latbox1.Size = new System.Drawing.Size(260, 28);
            this.latbox1.TabIndex = 2;
            this.latbox1.Text = "rule 1 = Rc Wd T t Lc";
            // 
            // newlateral
            // 
            this.newlateral.Location = new System.Drawing.Point(22, 72);
            this.newlateral.Name = "newlateral";
            this.newlateral.Size = new System.Drawing.Size(106, 28);
            this.newlateral.TabIndex = 153;
            this.newlateral.Text = "Lateral Erosion";
            this.newlateral.CheckedChanged += new System.EventHandler(this.newlateral_CheckedChanged);
            // 
            // lateralratebox
            // 
            this.lateralratebox.Location = new System.Drawing.Point(255, 60);
            this.lateralratebox.Name = "lateralratebox";
            this.lateralratebox.Size = new System.Drawing.Size(64, 20);
            this.lateralratebox.TabIndex = 150;
            this.lateralratebox.Text = "0.000000";
            // 
            // label7
            // 
            this.label7.Location = new System.Drawing.Point(142, 56);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(95, 24);
            this.label7.TabIndex = 151;
            this.label7.Text = "Lat erosion rate";
            this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.toolTip1.SetToolTip(this.label7, "Lateral erosion constant that is applied to method 1 (old laterla) and method 2 (" +
                    "new lateral)");
            // 
            // NumericalTab
            // 
            this.NumericalTab.Controls.Add(this.label53);
            this.NumericalTab.Controls.Add(this.max_time_step_Box);
            this.NumericalTab.Controls.Add(this.label76);
            this.NumericalTab.Controls.Add(this.Q2box);
            this.NumericalTab.Controls.Add(this.veltaubox);
            this.NumericalTab.Controls.Add(this.label52);
            this.NumericalTab.Controls.Add(this.bedslope_box);
            this.NumericalTab.Controls.Add(this.label3);
            this.NumericalTab.Controls.Add(this.k_evapBox);
            this.NumericalTab.Controls.Add(this.label51);
            this.NumericalTab.Controls.Add(this.label47);
            this.NumericalTab.Controls.Add(this.textBox3);
            this.NumericalTab.Controls.Add(this.textBox2);
            this.NumericalTab.Controls.Add(this.label48);
            this.NumericalTab.Controls.Add(this.label46);
            this.NumericalTab.Controls.Add(this.label50);
            this.NumericalTab.Controls.Add(this.activebox);
            this.NumericalTab.Controls.Add(this.mintimestepbox);
            this.NumericalTab.Controls.Add(this.textBox1);
            this.NumericalTab.Controls.Add(this.smoothbox);
            this.NumericalTab.Controls.Add(this.cyclemaxbox);
            this.NumericalTab.Controls.Add(this.itermaxbox);
            this.NumericalTab.Controls.Add(this.minqbox);
            this.NumericalTab.Controls.Add(this.limitbox);
            this.NumericalTab.Controls.Add(this.erodefactorbox);
            this.NumericalTab.Controls.Add(this.initscansbox);
            this.NumericalTab.Controls.Add(this.label31);
            this.NumericalTab.Controls.Add(this.label35);
            this.NumericalTab.Controls.Add(this.label27);
            this.NumericalTab.Controls.Add(this.label26);
            this.NumericalTab.Controls.Add(this.label12);
            this.NumericalTab.Controls.Add(this.label10);
            this.NumericalTab.Controls.Add(this.label9);
            this.NumericalTab.Controls.Add(this.label5);
            this.NumericalTab.Controls.Add(this.label49);
            this.NumericalTab.Location = new System.Drawing.Point(4, 22);
            this.NumericalTab.Name = "NumericalTab";
            this.NumericalTab.Size = new System.Drawing.Size(907, 243);
            this.NumericalTab.TabIndex = 2;
            this.NumericalTab.Text = "Numerical";
            this.NumericalTab.UseVisualStyleBackColor = true;
            // 
            // label53
            // 
            this.label53.Location = new System.Drawing.Point(56, 229);
            this.label53.Name = "label53";
            this.label53.Size = new System.Drawing.Size(120, 43);
            this.label53.TabIndex = 188;
            this.label53.Text = "Water depth threshold above which erosion will happen (m)";
            this.label53.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.toolTip1.SetToolTip(this.label53, "MinQ is a threshold value, above which CAEASR treats flow as surface flow, it sho" +
                    "uld be scaled to the grid size. Try 0.01 for 10m grids and 0.25 for 50m..");
            // 
            // max_time_step_Box
            // 
            this.max_time_step_Box.Location = new System.Drawing.Point(184, 80);
            this.max_time_step_Box.Name = "max_time_step_Box";
            this.max_time_step_Box.Size = new System.Drawing.Size(64, 20);
            this.max_time_step_Box.TabIndex = 186;
            this.max_time_step_Box.Text = "3600";
            // 
            // label76
            // 
            this.label76.Location = new System.Drawing.Point(40, 80);
            this.label76.Name = "label76";
            this.label76.Size = new System.Drawing.Size(136, 24);
            this.label76.TabIndex = 187;
            this.label76.Text = "Max time step (secs)";
            this.label76.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // Q2box
            // 
            this.Q2box.Location = new System.Drawing.Point(184, 236);
            this.Q2box.Name = "Q2box";
            this.Q2box.Size = new System.Drawing.Size(49, 20);
            this.Q2box.TabIndex = 184;
            this.Q2box.Text = "0.01";
            // 
            // veltaubox
            // 
            this.veltaubox.Location = new System.Drawing.Point(580, 69);
            this.veltaubox.Name = "veltaubox";
            this.veltaubox.Size = new System.Drawing.Size(160, 27);
            this.veltaubox.TabIndex = 183;
            this.veltaubox.Text = "Tau based on velocity";
            this.veltaubox.CheckedChanged += new System.EventHandler(this.veltaubox_CheckedChanged);
            // 
            // label52
            // 
            this.label52.Location = new System.Drawing.Point(580, 19);
            this.label52.Name = "label52";
            this.label52.Size = new System.Drawing.Size(133, 28);
            this.label52.TabIndex = 182;
            this.label52.Text = "Slope used to calc Tau (for erosion)";
            this.toolTip1.SetToolTip(this.label52, "See notes on lateral tab for more. ");
            // 
            // bedslope_box
            // 
            this.bedslope_box.Checked = true;
            this.bedslope_box.CheckState = System.Windows.Forms.CheckState.Checked;
            this.bedslope_box.Location = new System.Drawing.Point(580, 40);
            this.bedslope_box.Name = "bedslope_box";
            this.bedslope_box.Size = new System.Drawing.Size(153, 35);
            this.bedslope_box.TabIndex = 180;
            this.bedslope_box.Text = "Bedslope";
            this.bedslope_box.CheckedChanged += new System.EventHandler(this.bedslope_box_CheckedChanged);
            // 
            // label3
            // 
            this.label3.Location = new System.Drawing.Point(48, 304);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(128, 24);
            this.label3.TabIndex = 179;
            this.label3.Text = "Evaporation rate (m/s)";
            this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // k_evapBox
            // 
            this.k_evapBox.Location = new System.Drawing.Point(184, 307);
            this.k_evapBox.Name = "k_evapBox";
            this.k_evapBox.Size = new System.Drawing.Size(80, 20);
            this.k_evapBox.TabIndex = 178;
            this.k_evapBox.Text = "0.0";
            // 
            // label51
            // 
            this.label51.Location = new System.Drawing.Point(234, 279);
            this.label51.Name = "label51";
            this.label51.Size = new System.Drawing.Size(100, 23);
            this.label51.TabIndex = 177;
            this.label51.Text = "(reach mode)";
            this.label51.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // label47
            // 
            this.label47.Location = new System.Drawing.Point(256, 53);
            this.label47.Name = "label47";
            this.label47.Size = new System.Drawing.Size(66, 23);
            this.label47.TabIndex = 176;
            this.label47.Text = "(caution !)";
            this.label47.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // textBox3
            // 
            this.textBox3.Location = new System.Drawing.Point(465, 227);
            this.textBox3.Name = "textBox3";
            this.textBox3.Size = new System.Drawing.Size(40, 20);
            this.textBox3.TabIndex = 174;
            this.textBox3.Text = "2";
            // 
            // textBox2
            // 
            this.textBox2.Location = new System.Drawing.Point(184, 281);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(40, 20);
            this.textBox2.TabIndex = 172;
            this.textBox2.Text = "60";
            // 
            // label48
            // 
            this.label48.Location = new System.Drawing.Point(307, 227);
            this.label48.Name = "label48";
            this.label48.Size = new System.Drawing.Size(152, 24);
            this.label48.TabIndex = 175;
            this.label48.Text = "flow distribution width (cells)";
            this.label48.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label46
            // 
            this.label46.Location = new System.Drawing.Point(48, 278);
            this.label46.Name = "label46";
            this.label46.Size = new System.Drawing.Size(128, 24);
            this.label46.TabIndex = 173;
            this.label46.Text = "Initial discharge (m3/s)";
            this.label46.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label50
            // 
            this.label50.Location = new System.Drawing.Point(320, 45);
            this.label50.Name = "label50";
            this.label50.Size = new System.Drawing.Size(136, 24);
            this.label50.TabIndex = 169;
            this.label50.Text = "active layer thickness (m)";
            this.label50.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // activebox
            // 
            this.activebox.Location = new System.Drawing.Point(462, 48);
            this.activebox.Name = "activebox";
            this.activebox.Size = new System.Drawing.Size(64, 20);
            this.activebox.TabIndex = 168;
            this.activebox.Text = "0.2";
            // 
            // mintimestepbox
            // 
            this.mintimestepbox.Location = new System.Drawing.Point(184, 53);
            this.mintimestepbox.Name = "mintimestepbox";
            this.mintimestepbox.Size = new System.Drawing.Size(64, 20);
            this.mintimestepbox.TabIndex = 166;
            this.mintimestepbox.Text = "0";
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(184, 118);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(64, 20);
            this.textBox1.TabIndex = 164;
            this.textBox1.Text = "0";
            // 
            // smoothbox
            // 
            this.smoothbox.Location = new System.Drawing.Point(465, 201);
            this.smoothbox.Name = "smoothbox";
            this.smoothbox.Size = new System.Drawing.Size(40, 20);
            this.smoothbox.TabIndex = 160;
            this.smoothbox.Text = "1";
            // 
            // cyclemaxbox
            // 
            this.cyclemaxbox.Location = new System.Drawing.Point(184, 142);
            this.cyclemaxbox.Name = "cyclemaxbox";
            this.cyclemaxbox.Size = new System.Drawing.Size(64, 20);
            this.cyclemaxbox.TabIndex = 155;
            this.cyclemaxbox.Text = "1000";
            // 
            // itermaxbox
            // 
            this.itermaxbox.Location = new System.Drawing.Point(184, 21);
            this.itermaxbox.Name = "itermaxbox";
            this.itermaxbox.Size = new System.Drawing.Size(64, 20);
            this.itermaxbox.TabIndex = 154;
            this.itermaxbox.Text = "100000";
            // 
            // minqbox
            // 
            this.minqbox.Location = new System.Drawing.Point(184, 205);
            this.minqbox.Name = "minqbox";
            this.minqbox.Size = new System.Drawing.Size(49, 20);
            this.minqbox.TabIndex = 145;
            this.minqbox.Text = "0.01";
            // 
            // limitbox
            // 
            this.limitbox.Location = new System.Drawing.Point(462, 133);
            this.limitbox.Name = "limitbox";
            this.limitbox.Size = new System.Drawing.Size(40, 20);
            this.limitbox.TabIndex = 144;
            this.limitbox.Text = "1";
            // 
            // erodefactorbox
            // 
            this.erodefactorbox.Location = new System.Drawing.Point(462, 21);
            this.erodefactorbox.Name = "erodefactorbox";
            this.erodefactorbox.Size = new System.Drawing.Size(40, 20);
            this.erodefactorbox.TabIndex = 143;
            this.erodefactorbox.Text = "0.02";
            // 
            // initscansbox
            // 
            this.initscansbox.Location = new System.Drawing.Point(462, 107);
            this.initscansbox.Name = "initscansbox";
            this.initscansbox.Size = new System.Drawing.Size(40, 20);
            this.initscansbox.TabIndex = 142;
            this.initscansbox.Text = "20";
            // 
            // label31
            // 
            this.label31.Location = new System.Drawing.Point(56, 118);
            this.label31.Name = "label31";
            this.label31.Size = new System.Drawing.Size(120, 24);
            this.label31.TabIndex = 165;
            this.label31.Text = "run start time (h)";
            this.label31.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label35
            // 
            this.label35.Location = new System.Drawing.Point(337, 201);
            this.label35.Name = "label35";
            this.label35.Size = new System.Drawing.Size(120, 24);
            this.label35.TabIndex = 161;
            this.label35.Text = "WS smoothing radius";
            this.label35.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label27
            // 
            this.label27.Location = new System.Drawing.Point(64, 142);
            this.label27.Name = "label27";
            this.label27.Size = new System.Drawing.Size(112, 24);
            this.label27.TabIndex = 157;
            this.label27.Text = "max run duration (h)";
            this.label27.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label26
            // 
            this.label26.Location = new System.Drawing.Point(40, 21);
            this.label26.Name = "label26";
            this.label26.Size = new System.Drawing.Size(136, 24);
            this.label26.TabIndex = 156;
            this.label26.Text = "max # of iterations";
            this.label26.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label12
            // 
            this.label12.Location = new System.Drawing.Point(370, 18);
            this.label12.Name = "label12";
            this.label12.Size = new System.Drawing.Size(87, 24);
            this.label12.TabIndex = 153;
            this.label12.Text = "Max erode limit";
            this.label12.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label10
            // 
            this.label10.Location = new System.Drawing.Point(336, 130);
            this.label10.Name = "label10";
            this.label10.Size = new System.Drawing.Size(120, 24);
            this.label10.TabIndex = 152;
            this.label10.Text = "memory limit";
            this.label10.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label9
            // 
            this.label9.Location = new System.Drawing.Point(56, 205);
            this.label9.Name = "label9";
            this.label9.Size = new System.Drawing.Size(120, 24);
            this.label9.TabIndex = 151;
            this.label9.Text = "Min Q for depth calc";
            this.label9.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.toolTip1.SetToolTip(this.label9, "MinQ is a threshold value, above which CAEASR treats flow as surface flow, it sho" +
                    "uld be scaled to the grid size. Try 0.01 for 10m grids and 0.25 for 50m..");
            // 
            // label5
            // 
            this.label5.Location = new System.Drawing.Point(381, 103);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(73, 26);
            this.label5.TabIndex = 148;
            this.label5.Text = "init # of scans";
            this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label49
            // 
            this.label49.Location = new System.Drawing.Point(40, 53);
            this.label49.Name = "label49";
            this.label49.Size = new System.Drawing.Size(136, 24);
            this.label49.TabIndex = 167;
            this.label49.Text = "Min time step (s)";
            this.label49.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // GrainTab
            // 
            this.GrainTab.Controls.Add(this.einsteinbox);
            this.GrainTab.Controls.Add(this.wilcockbox);
            this.GrainTab.Controls.Add(this.fallGS9box);
            this.GrainTab.Controls.Add(this.fallGS8box);
            this.GrainTab.Controls.Add(this.fallGS7box);
            this.GrainTab.Controls.Add(this.fallGS6box);
            this.GrainTab.Controls.Add(this.fallGS5box);
            this.GrainTab.Controls.Add(this.fallGS4box);
            this.GrainTab.Controls.Add(this.fallGS3box);
            this.GrainTab.Controls.Add(this.gpSumLabel);
            this.GrainTab.Controls.Add(this.gpSumLabel2);
            this.GrainTab.Controls.Add(this.suspGS9box);
            this.GrainTab.Controls.Add(this.suspGS8box);
            this.GrainTab.Controls.Add(this.suspGS7box);
            this.GrainTab.Controls.Add(this.suspGS6box);
            this.GrainTab.Controls.Add(this.suspGS5box);
            this.GrainTab.Controls.Add(this.suspGS4box);
            this.GrainTab.Controls.Add(this.suspGS3box);
            this.GrainTab.Controls.Add(this.suspGS2box);
            this.GrainTab.Controls.Add(this.fallGS2box);
            this.GrainTab.Controls.Add(this.fallGS1box);
            this.GrainTab.Controls.Add(this.label28);
            this.GrainTab.Controls.Add(this.label4);
            this.GrainTab.Controls.Add(this.suspGS1box);
            this.GrainTab.Controls.Add(this.gp3box);
            this.GrainTab.Controls.Add(this.gp4box);
            this.GrainTab.Controls.Add(this.gp5box);
            this.GrainTab.Controls.Add(this.gp6box);
            this.GrainTab.Controls.Add(this.gp7box);
            this.GrainTab.Controls.Add(this.gp8box);
            this.GrainTab.Controls.Add(this.gp9box);
            this.GrainTab.Controls.Add(this.gp2box);
            this.GrainTab.Controls.Add(this.gp1box);
            this.GrainTab.Controls.Add(this.g3box);
            this.GrainTab.Controls.Add(this.g4box);
            this.GrainTab.Controls.Add(this.g5box);
            this.GrainTab.Controls.Add(this.g6box);
            this.GrainTab.Controls.Add(this.g7box);
            this.GrainTab.Controls.Add(this.g8box);
            this.GrainTab.Controls.Add(this.g9box);
            this.GrainTab.Controls.Add(this.g2box);
            this.GrainTab.Controls.Add(this.g1box);
            this.GrainTab.Controls.Add(this.label22);
            this.GrainTab.Controls.Add(this.label21);
            this.GrainTab.Controls.Add(this.label20);
            this.GrainTab.Controls.Add(this.label19);
            this.GrainTab.Controls.Add(this.label18);
            this.GrainTab.Controls.Add(this.label17);
            this.GrainTab.Controls.Add(this.label16);
            this.GrainTab.Controls.Add(this.label15);
            this.GrainTab.Controls.Add(this.label14);
            this.GrainTab.Controls.Add(this.label13);
            this.GrainTab.Controls.Add(this.label6);
            this.GrainTab.Location = new System.Drawing.Point(4, 22);
            this.GrainTab.Name = "GrainTab";
            this.GrainTab.Size = new System.Drawing.Size(907, 243);
            this.GrainTab.TabIndex = 3;
            this.GrainTab.Text = "Sediment";
            this.GrainTab.UseVisualStyleBackColor = true;
            // 
            // einsteinbox
            // 
            this.einsteinbox.AutoSize = true;
            this.einsteinbox.Location = new System.Drawing.Point(605, 76);
            this.einsteinbox.Name = "einsteinbox";
            this.einsteinbox.Size = new System.Drawing.Size(63, 17);
            this.einsteinbox.TabIndex = 107;
            this.einsteinbox.Text = "Einstein";
            this.einsteinbox.UseVisualStyleBackColor = true;
            this.einsteinbox.CheckedChanged += new System.EventHandler(this.einsteinbox_CheckedChanged);
            // 
            // wilcockbox
            // 
            this.wilcockbox.AutoSize = true;
            this.wilcockbox.Checked = true;
            this.wilcockbox.CheckState = System.Windows.Forms.CheckState.Checked;
            this.wilcockbox.Location = new System.Drawing.Point(604, 42);
            this.wilcockbox.Name = "wilcockbox";
            this.wilcockbox.Size = new System.Drawing.Size(119, 17);
            this.wilcockbox.TabIndex = 106;
            this.wilcockbox.Text = "Wilcock and Crowe";
            this.wilcockbox.UseVisualStyleBackColor = true;
            this.wilcockbox.CheckedChanged += new System.EventHandler(this.wilcockbox_CheckedChanged);
            // 
            // fallGS9box
            // 
            this.fallGS9box.Enabled = false;
            this.fallGS9box.Location = new System.Drawing.Point(424, 296);
            this.fallGS9box.Name = "fallGS9box";
            this.fallGS9box.Size = new System.Drawing.Size(100, 20);
            this.fallGS9box.TabIndex = 90;
            this.fallGS9box.Text = "1.357";
            // 
            // fallGS8box
            // 
            this.fallGS8box.Enabled = false;
            this.fallGS8box.Location = new System.Drawing.Point(424, 264);
            this.fallGS8box.Name = "fallGS8box";
            this.fallGS8box.Size = new System.Drawing.Size(100, 20);
            this.fallGS8box.TabIndex = 89;
            this.fallGS8box.Text = "0.959";
            // 
            // fallGS7box
            // 
            this.fallGS7box.Enabled = false;
            this.fallGS7box.Location = new System.Drawing.Point(424, 232);
            this.fallGS7box.Name = "fallGS7box";
            this.fallGS7box.Size = new System.Drawing.Size(100, 20);
            this.fallGS7box.TabIndex = 88;
            this.fallGS7box.Text = "0.678";
            // 
            // fallGS6box
            // 
            this.fallGS6box.Enabled = false;
            this.fallGS6box.Location = new System.Drawing.Point(424, 200);
            this.fallGS6box.Name = "fallGS6box";
            this.fallGS6box.Size = new System.Drawing.Size(100, 20);
            this.fallGS6box.TabIndex = 87;
            this.fallGS6box.Text = "0.479";
            // 
            // fallGS5box
            // 
            this.fallGS5box.Enabled = false;
            this.fallGS5box.Location = new System.Drawing.Point(424, 168);
            this.fallGS5box.Name = "fallGS5box";
            this.fallGS5box.Size = new System.Drawing.Size(100, 20);
            this.fallGS5box.TabIndex = 86;
            this.fallGS5box.Text = "0.338";
            // 
            // fallGS4box
            // 
            this.fallGS4box.Enabled = false;
            this.fallGS4box.Location = new System.Drawing.Point(424, 136);
            this.fallGS4box.Name = "fallGS4box";
            this.fallGS4box.Size = new System.Drawing.Size(100, 20);
            this.fallGS4box.TabIndex = 85;
            this.fallGS4box.Text = "0.237";
            // 
            // fallGS3box
            // 
            this.fallGS3box.Enabled = false;
            this.fallGS3box.Location = new System.Drawing.Point(424, 104);
            this.fallGS3box.Name = "fallGS3box";
            this.fallGS3box.Size = new System.Drawing.Size(100, 20);
            this.fallGS3box.TabIndex = 84;
            this.fallGS3box.Text = "0.164";
            // 
            // gpSumLabel
            // 
            this.gpSumLabel.Location = new System.Drawing.Point(232, 360);
            this.gpSumLabel.Name = "gpSumLabel";
            this.gpSumLabel.Size = new System.Drawing.Size(96, 16);
            this.gpSumLabel.TabIndex = 105;
            this.gpSumLabel.Text = "OK";
            this.gpSumLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // gpSumLabel2
            // 
            this.gpSumLabel2.ForeColor = System.Drawing.SystemColors.ControlText;
            this.gpSumLabel2.Location = new System.Drawing.Point(232, 336);
            this.gpSumLabel2.Name = "gpSumLabel2";
            this.gpSumLabel2.Size = new System.Drawing.Size(112, 16);
            this.gpSumLabel2.TabIndex = 104;
            this.gpSumLabel2.Text = "sum must equal 1.0";
            this.gpSumLabel2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // suspGS9box
            // 
            this.suspGS9box.Location = new System.Drawing.Point(376, 296);
            this.suspGS9box.Name = "suspGS9box";
            this.suspGS9box.Size = new System.Drawing.Size(16, 24);
            this.suspGS9box.TabIndex = 81;
            this.suspGS9box.CheckedChanged += new System.EventHandler(this.suspCheckedChange);
            // 
            // suspGS8box
            // 
            this.suspGS8box.Location = new System.Drawing.Point(376, 264);
            this.suspGS8box.Name = "suspGS8box";
            this.suspGS8box.Size = new System.Drawing.Size(16, 24);
            this.suspGS8box.TabIndex = 80;
            this.suspGS8box.CheckedChanged += new System.EventHandler(this.suspCheckedChange);
            // 
            // suspGS7box
            // 
            this.suspGS7box.Location = new System.Drawing.Point(376, 232);
            this.suspGS7box.Name = "suspGS7box";
            this.suspGS7box.Size = new System.Drawing.Size(16, 24);
            this.suspGS7box.TabIndex = 79;
            this.suspGS7box.CheckedChanged += new System.EventHandler(this.suspCheckedChange);
            // 
            // suspGS6box
            // 
            this.suspGS6box.Location = new System.Drawing.Point(376, 200);
            this.suspGS6box.Name = "suspGS6box";
            this.suspGS6box.Size = new System.Drawing.Size(16, 24);
            this.suspGS6box.TabIndex = 78;
            this.suspGS6box.CheckedChanged += new System.EventHandler(this.suspCheckedChange);
            // 
            // suspGS5box
            // 
            this.suspGS5box.Location = new System.Drawing.Point(376, 168);
            this.suspGS5box.Name = "suspGS5box";
            this.suspGS5box.Size = new System.Drawing.Size(16, 24);
            this.suspGS5box.TabIndex = 77;
            this.suspGS5box.CheckedChanged += new System.EventHandler(this.suspCheckedChange);
            // 
            // suspGS4box
            // 
            this.suspGS4box.Location = new System.Drawing.Point(376, 136);
            this.suspGS4box.Name = "suspGS4box";
            this.suspGS4box.Size = new System.Drawing.Size(16, 24);
            this.suspGS4box.TabIndex = 76;
            this.suspGS4box.CheckedChanged += new System.EventHandler(this.suspCheckedChange);
            // 
            // suspGS3box
            // 
            this.suspGS3box.Location = new System.Drawing.Point(376, 104);
            this.suspGS3box.Name = "suspGS3box";
            this.suspGS3box.Size = new System.Drawing.Size(16, 24);
            this.suspGS3box.TabIndex = 75;
            this.suspGS3box.CheckedChanged += new System.EventHandler(this.suspCheckedChange);
            // 
            // suspGS2box
            // 
            this.suspGS2box.Checked = true;
            this.suspGS2box.CheckState = System.Windows.Forms.CheckState.Checked;
            this.suspGS2box.Location = new System.Drawing.Point(376, 72);
            this.suspGS2box.Name = "suspGS2box";
            this.suspGS2box.Size = new System.Drawing.Size(16, 24);
            this.suspGS2box.TabIndex = 74;
            this.suspGS2box.CheckedChanged += new System.EventHandler(this.suspCheckedChange);
            // 
            // fallGS2box
            // 
            this.fallGS2box.Location = new System.Drawing.Point(424, 72);
            this.fallGS2box.Name = "fallGS2box";
            this.fallGS2box.Size = new System.Drawing.Size(100, 20);
            this.fallGS2box.TabIndex = 83;
            this.fallGS2box.Text = "0.109";
            // 
            // fallGS1box
            // 
            this.fallGS1box.Location = new System.Drawing.Point(424, 40);
            this.fallGS1box.Name = "fallGS1box";
            this.fallGS1box.Size = new System.Drawing.Size(100, 20);
            this.fallGS1box.TabIndex = 82;
            this.fallGS1box.Text = "0.066";
            // 
            // label28
            // 
            this.label28.Location = new System.Drawing.Point(432, 16);
            this.label28.Name = "label28";
            this.label28.Size = new System.Drawing.Size(88, 16);
            this.label28.TabIndex = 95;
            this.label28.Text = "fall velocity (m/s)";
            this.label28.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label4
            // 
            this.label4.Location = new System.Drawing.Point(336, 16);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(96, 16);
            this.label4.TabIndex = 85;
            this.label4.Text = "suspended ?";
            this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // suspGS1box
            // 
            this.suspGS1box.Checked = true;
            this.suspGS1box.CheckState = System.Windows.Forms.CheckState.Checked;
            this.suspGS1box.Location = new System.Drawing.Point(376, 40);
            this.suspGS1box.Name = "suspGS1box";
            this.suspGS1box.Size = new System.Drawing.Size(16, 24);
            this.suspGS1box.TabIndex = 73;
            this.suspGS1box.CheckedChanged += new System.EventHandler(this.suspCheckedChange);
            // 
            // gp3box
            // 
            this.gp3box.Location = new System.Drawing.Point(232, 104);
            this.gp3box.Name = "gp3box";
            this.gp3box.Size = new System.Drawing.Size(100, 20);
            this.gp3box.TabIndex = 66;
            this.gp3box.Text = "0.019";
            this.gp3box.TextChanged += new System.EventHandler(this.fracGSchanged);
            // 
            // gp4box
            // 
            this.gp4box.Location = new System.Drawing.Point(232, 136);
            this.gp4box.Name = "gp4box";
            this.gp4box.Size = new System.Drawing.Size(100, 20);
            this.gp4box.TabIndex = 67;
            this.gp4box.Text = "0.029";
            this.gp4box.TextChanged += new System.EventHandler(this.fracGSchanged);
            // 
            // gp5box
            // 
            this.gp5box.Location = new System.Drawing.Point(232, 168);
            this.gp5box.Name = "gp5box";
            this.gp5box.Size = new System.Drawing.Size(100, 20);
            this.gp5box.TabIndex = 68;
            this.gp5box.Text = "0.068";
            this.gp5box.TextChanged += new System.EventHandler(this.fracGSchanged);
            // 
            // gp6box
            // 
            this.gp6box.Location = new System.Drawing.Point(232, 200);
            this.gp6box.Name = "gp6box";
            this.gp6box.Size = new System.Drawing.Size(100, 20);
            this.gp6box.TabIndex = 69;
            this.gp6box.Text = "0.146";
            this.gp6box.TextChanged += new System.EventHandler(this.fracGSchanged);
            // 
            // gp7box
            // 
            this.gp7box.Location = new System.Drawing.Point(232, 232);
            this.gp7box.Name = "gp7box";
            this.gp7box.Size = new System.Drawing.Size(100, 20);
            this.gp7box.TabIndex = 70;
            this.gp7box.Text = "0.220";
            this.gp7box.TextChanged += new System.EventHandler(this.fracGSchanged);
            // 
            // gp8box
            // 
            this.gp8box.Location = new System.Drawing.Point(232, 264);
            this.gp8box.Name = "gp8box";
            this.gp8box.Size = new System.Drawing.Size(100, 20);
            this.gp8box.TabIndex = 71;
            this.gp8box.Text = "0.231";
            this.gp8box.TextChanged += new System.EventHandler(this.fracGSchanged);
            // 
            // gp9box
            // 
            this.gp9box.Location = new System.Drawing.Point(232, 296);
            this.gp9box.Name = "gp9box";
            this.gp9box.Size = new System.Drawing.Size(100, 20);
            this.gp9box.TabIndex = 72;
            this.gp9box.Text = "0.121";
            this.gp9box.TextChanged += new System.EventHandler(this.fracGSchanged);
            // 
            // gp2box
            // 
            this.gp2box.Location = new System.Drawing.Point(232, 72);
            this.gp2box.Name = "gp2box";
            this.gp2box.Size = new System.Drawing.Size(100, 20);
            this.gp2box.TabIndex = 65;
            this.gp2box.Text = "0.022";
            this.gp2box.TextChanged += new System.EventHandler(this.fracGSchanged);
            // 
            // gp1box
            // 
            this.gp1box.Location = new System.Drawing.Point(232, 40);
            this.gp1box.Name = "gp1box";
            this.gp1box.Size = new System.Drawing.Size(100, 20);
            this.gp1box.TabIndex = 64;
            this.gp1box.Text = "0.144";
            this.gp1box.TextChanged += new System.EventHandler(this.fracGSchanged);
            // 
            // g3box
            // 
            this.g3box.Location = new System.Drawing.Point(96, 104);
            this.g3box.Name = "g3box";
            this.g3box.Size = new System.Drawing.Size(100, 20);
            this.g3box.TabIndex = 57;
            this.g3box.Text = "0.002";
            // 
            // g4box
            // 
            this.g4box.Location = new System.Drawing.Point(96, 136);
            this.g4box.Name = "g4box";
            this.g4box.Size = new System.Drawing.Size(100, 20);
            this.g4box.TabIndex = 58;
            this.g4box.Text = "0.004";
            // 
            // g5box
            // 
            this.g5box.Location = new System.Drawing.Point(96, 168);
            this.g5box.Name = "g5box";
            this.g5box.Size = new System.Drawing.Size(100, 20);
            this.g5box.TabIndex = 59;
            this.g5box.Text = "0.008";
            // 
            // g6box
            // 
            this.g6box.Location = new System.Drawing.Point(96, 200);
            this.g6box.Name = "g6box";
            this.g6box.Size = new System.Drawing.Size(100, 20);
            this.g6box.TabIndex = 60;
            this.g6box.Text = "0.016";
            // 
            // g7box
            // 
            this.g7box.Location = new System.Drawing.Point(96, 232);
            this.g7box.Name = "g7box";
            this.g7box.Size = new System.Drawing.Size(100, 20);
            this.g7box.TabIndex = 61;
            this.g7box.Text = "0.032";
            // 
            // g8box
            // 
            this.g8box.Location = new System.Drawing.Point(96, 264);
            this.g8box.Name = "g8box";
            this.g8box.Size = new System.Drawing.Size(100, 20);
            this.g8box.TabIndex = 62;
            this.g8box.Text = "0.064";
            // 
            // g9box
            // 
            this.g9box.Location = new System.Drawing.Point(96, 296);
            this.g9box.Name = "g9box";
            this.g9box.Size = new System.Drawing.Size(100, 20);
            this.g9box.TabIndex = 63;
            this.g9box.Text = "0.128";
            // 
            // g2box
            // 
            this.g2box.Location = new System.Drawing.Point(96, 72);
            this.g2box.Name = "g2box";
            this.g2box.Size = new System.Drawing.Size(100, 20);
            this.g2box.TabIndex = 56;
            this.g2box.Text = "0.001";
            // 
            // g1box
            // 
            this.g1box.Location = new System.Drawing.Point(96, 40);
            this.g1box.Name = "g1box";
            this.g1box.Size = new System.Drawing.Size(100, 20);
            this.g1box.TabIndex = 55;
            this.g1box.Text = "0.0005";
            // 
            // label22
            // 
            this.label22.Location = new System.Drawing.Point(232, 16);
            this.label22.Name = "label22";
            this.label22.Size = new System.Drawing.Size(96, 16);
            this.label22.TabIndex = 83;
            this.label22.Text = "proportion";
            this.label22.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label21
            // 
            this.label21.Location = new System.Drawing.Point(96, 16);
            this.label21.Name = "label21";
            this.label21.Size = new System.Drawing.Size(96, 16);
            this.label21.TabIndex = 82;
            this.label21.Text = "grain size (m)";
            this.label21.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label20
            // 
            this.label20.Location = new System.Drawing.Point(24, 72);
            this.label20.Name = "label20";
            this.label20.Size = new System.Drawing.Size(40, 24);
            this.label20.TabIndex = 81;
            this.label20.Text = "size2";
            this.label20.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label19
            // 
            this.label19.Location = new System.Drawing.Point(24, 104);
            this.label19.Name = "label19";
            this.label19.Size = new System.Drawing.Size(40, 24);
            this.label19.TabIndex = 80;
            this.label19.Text = "size3";
            this.label19.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label18
            // 
            this.label18.Location = new System.Drawing.Point(24, 136);
            this.label18.Name = "label18";
            this.label18.Size = new System.Drawing.Size(40, 24);
            this.label18.TabIndex = 79;
            this.label18.Text = "size4";
            this.label18.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label17
            // 
            this.label17.Location = new System.Drawing.Point(24, 168);
            this.label17.Name = "label17";
            this.label17.Size = new System.Drawing.Size(40, 24);
            this.label17.TabIndex = 78;
            this.label17.Text = "size5";
            this.label17.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label16
            // 
            this.label16.Location = new System.Drawing.Point(24, 200);
            this.label16.Name = "label16";
            this.label16.Size = new System.Drawing.Size(40, 24);
            this.label16.TabIndex = 77;
            this.label16.Text = "size6";
            this.label16.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label15
            // 
            this.label15.Location = new System.Drawing.Point(24, 232);
            this.label15.Name = "label15";
            this.label15.Size = new System.Drawing.Size(40, 24);
            this.label15.TabIndex = 76;
            this.label15.Text = "size7";
            this.label15.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label14
            // 
            this.label14.Location = new System.Drawing.Point(24, 264);
            this.label14.Name = "label14";
            this.label14.Size = new System.Drawing.Size(40, 24);
            this.label14.TabIndex = 75;
            this.label14.Text = "size8";
            this.label14.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label13
            // 
            this.label13.Location = new System.Drawing.Point(24, 296);
            this.label13.Name = "label13";
            this.label13.Size = new System.Drawing.Size(40, 24);
            this.label13.TabIndex = 74;
            this.label13.Text = "size9";
            this.label13.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label6
            // 
            this.label6.Location = new System.Drawing.Point(24, 40);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(40, 24);
            this.label6.TabIndex = 73;
            this.label6.Text = "size1";
            this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // DescriptionTab
            // 
            this.DescriptionTab.Controls.Add(this.DescBox);
            this.DescriptionTab.Location = new System.Drawing.Point(4, 22);
            this.DescriptionTab.Name = "DescriptionTab";
            this.DescriptionTab.Size = new System.Drawing.Size(907, 243);
            this.DescriptionTab.TabIndex = 5;
            this.DescriptionTab.Text = "Description";
            this.DescriptionTab.UseVisualStyleBackColor = true;
            // 
            // DescBox
            // 
            this.DescBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.DescBox.Location = new System.Drawing.Point(16, 16);
            this.DescBox.Multiline = true;
            this.DescBox.Name = "DescBox";
            this.DescBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.DescBox.Size = new System.Drawing.Size(876, 466);
            this.DescBox.TabIndex = 132;
            // 
            // GridTab
            // 
            this.GridTab.Controls.Add(this.overrideheaderBox);
            this.GridTab.Controls.Add(this.dxbox);
            this.GridTab.Controls.Add(this.label11);
            this.GridTab.Controls.Add(this.ytextbox);
            this.GridTab.Controls.Add(this.xtextbox);
            this.GridTab.Controls.Add(this.label2);
            this.GridTab.Controls.Add(this.label1);
            this.GridTab.Location = new System.Drawing.Point(4, 22);
            this.GridTab.Name = "GridTab";
            this.GridTab.Size = new System.Drawing.Size(907, 243);
            this.GridTab.TabIndex = 1;
            this.GridTab.Text = "Grid";
            this.GridTab.UseVisualStyleBackColor = true;
            // 
            // overrideheaderBox
            // 
            this.overrideheaderBox.Location = new System.Drawing.Point(16, 16);
            this.overrideheaderBox.Name = "overrideheaderBox";
            this.overrideheaderBox.Size = new System.Drawing.Size(200, 24);
            this.overrideheaderBox.TabIndex = 27;
            this.overrideheaderBox.Text = "override header file";
            this.overrideheaderBox.CheckedChanged += new System.EventHandler(this.overrideheaderBox_CheckedChanged);
            // 
            // dxbox
            // 
            this.dxbox.Enabled = false;
            this.dxbox.Location = new System.Drawing.Point(120, 88);
            this.dxbox.Name = "dxbox";
            this.dxbox.Size = new System.Drawing.Size(40, 20);
            this.dxbox.TabIndex = 25;
            this.dxbox.Text = "5";
            // 
            // label11
            // 
            this.label11.Enabled = false;
            this.label11.Location = new System.Drawing.Point(16, 88);
            this.label11.Name = "label11";
            this.label11.Size = new System.Drawing.Size(96, 24);
            this.label11.TabIndex = 26;
            this.label11.Text = "Cell size";
            this.label11.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // ytextbox
            // 
            this.ytextbox.Enabled = false;
            this.ytextbox.Location = new System.Drawing.Point(120, 64);
            this.ytextbox.Name = "ytextbox";
            this.ytextbox.Size = new System.Drawing.Size(56, 20);
            this.ytextbox.TabIndex = 5;
            this.ytextbox.Text = "358";
            // 
            // xtextbox
            // 
            this.xtextbox.Enabled = false;
            this.xtextbox.Location = new System.Drawing.Point(120, 40);
            this.xtextbox.Name = "xtextbox";
            this.xtextbox.Size = new System.Drawing.Size(56, 20);
            this.xtextbox.TabIndex = 4;
            this.xtextbox.Text = "593";
            // 
            // label2
            // 
            this.label2.Enabled = false;
            this.label2.Location = new System.Drawing.Point(16, 64);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(96, 24);
            this.label2.TabIndex = 7;
            this.label2.Text = "Y coordinates";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label1
            // 
            this.label1.Enabled = false;
            this.label1.Location = new System.Drawing.Point(24, 40);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(88, 24);
            this.label1.TabIndex = 6;
            this.label1.Text = "X coordinates";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // HydrologyTab
            // 
            this.HydrologyTab.Controls.Add(this.label83);
            this.HydrologyTab.Controls.Add(this.div_inputs_box);
            this.HydrologyTab.Controls.Add(this.mvaluebox);
            this.HydrologyTab.Controls.Add(this.label37);
            this.HydrologyTab.Controls.Add(this.infile8);
            this.HydrologyTab.Controls.Add(this.ybox8);
            this.HydrologyTab.Controls.Add(this.xbox8);
            this.HydrologyTab.Controls.Add(this.inbox8);
            this.HydrologyTab.Controls.Add(this.infile7);
            this.HydrologyTab.Controls.Add(this.ybox7);
            this.HydrologyTab.Controls.Add(this.xbox7);
            this.HydrologyTab.Controls.Add(this.inbox7);
            this.HydrologyTab.Controls.Add(this.infile6);
            this.HydrologyTab.Controls.Add(this.ybox6);
            this.HydrologyTab.Controls.Add(this.xbox6);
            this.HydrologyTab.Controls.Add(this.inbox6);
            this.HydrologyTab.Controls.Add(this.infile5);
            this.HydrologyTab.Controls.Add(this.ybox5);
            this.HydrologyTab.Controls.Add(this.xbox5);
            this.HydrologyTab.Controls.Add(this.inbox5);
            this.HydrologyTab.Controls.Add(this.input_time_step_box);
            this.HydrologyTab.Controls.Add(this.infile4);
            this.HydrologyTab.Controls.Add(this.infile3);
            this.HydrologyTab.Controls.Add(this.infile2);
            this.HydrologyTab.Controls.Add(this.infile1);
            this.HydrologyTab.Controls.Add(this.ybox1);
            this.HydrologyTab.Controls.Add(this.ybox2);
            this.HydrologyTab.Controls.Add(this.ybox3);
            this.HydrologyTab.Controls.Add(this.ybox4);
            this.HydrologyTab.Controls.Add(this.xbox2);
            this.HydrologyTab.Controls.Add(this.xbox3);
            this.HydrologyTab.Controls.Add(this.xbox4);
            this.HydrologyTab.Controls.Add(this.xbox1);
            this.HydrologyTab.Controls.Add(this.label29);
            this.HydrologyTab.Controls.Add(this.label44);
            this.HydrologyTab.Controls.Add(this.label43);
            this.HydrologyTab.Controls.Add(this.label41);
            this.HydrologyTab.Controls.Add(this.inbox2);
            this.HydrologyTab.Controls.Add(this.inbox3);
            this.HydrologyTab.Controls.Add(this.inbox4);
            this.HydrologyTab.Controls.Add(this.inbox1);
            this.HydrologyTab.Controls.Add(this.label42);
            this.HydrologyTab.Location = new System.Drawing.Point(4, 22);
            this.HydrologyTab.Name = "HydrologyTab";
            this.HydrologyTab.Size = new System.Drawing.Size(907, 243);
            this.HydrologyTab.TabIndex = 4;
            this.HydrologyTab.Text = "Hydrology";
            this.HydrologyTab.UseVisualStyleBackColor = true;
            this.HydrologyTab.Click += new System.EventHandler(this.HydrologyTab_Click);
            // 
            // label83
            // 
            this.label83.Location = new System.Drawing.Point(125, 268);
            this.label83.Name = "label83";
            this.label83.Size = new System.Drawing.Size(100, 32);
            this.label83.TabIndex = 202;
            this.label83.Text = "Divide inputs by..";
            // 
            // div_inputs_box
            // 
            this.div_inputs_box.Location = new System.Drawing.Point(231, 265);
            this.div_inputs_box.Name = "div_inputs_box";
            this.div_inputs_box.Size = new System.Drawing.Size(31, 20);
            this.div_inputs_box.TabIndex = 201;
            this.div_inputs_box.Text = "1";
            // 
            // mvaluebox
            // 
            this.mvaluebox.Location = new System.Drawing.Point(350, 141);
            this.mvaluebox.Name = "mvaluebox";
            this.mvaluebox.Size = new System.Drawing.Size(40, 20);
            this.mvaluebox.TabIndex = 199;
            this.mvaluebox.Text = "0.01";
            // 
            // label37
            // 
            this.label37.Location = new System.Drawing.Point(324, 138);
            this.label37.Name = "label37";
            this.label37.Size = new System.Drawing.Size(128, 24);
            this.label37.TabIndex = 200;
            this.label37.Text = "\'m\' value";
            this.label37.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // infile8
            // 
            this.infile8.Location = new System.Drawing.Point(173, 229);
            this.infile8.Name = "infile8";
            this.infile8.Size = new System.Drawing.Size(120, 20);
            this.infile8.TabIndex = 198;
            // 
            // ybox8
            // 
            this.ybox8.Location = new System.Drawing.Point(127, 229);
            this.ybox8.Name = "ybox8";
            this.ybox8.Size = new System.Drawing.Size(31, 20);
            this.ybox8.TabIndex = 197;
            // 
            // xbox8
            // 
            this.xbox8.Location = new System.Drawing.Point(80, 229);
            this.xbox8.Name = "xbox8";
            this.xbox8.Size = new System.Drawing.Size(32, 20);
            this.xbox8.TabIndex = 196;
            // 
            // inbox8
            // 
            this.inbox8.Location = new System.Drawing.Point(13, 229);
            this.inbox8.Name = "inbox8";
            this.inbox8.Size = new System.Drawing.Size(64, 16);
            this.inbox8.TabIndex = 195;
            this.inbox8.Text = "Input 8";
            // 
            // infile7
            // 
            this.infile7.Location = new System.Drawing.Point(173, 201);
            this.infile7.Name = "infile7";
            this.infile7.Size = new System.Drawing.Size(120, 20);
            this.infile7.TabIndex = 194;
            // 
            // ybox7
            // 
            this.ybox7.Location = new System.Drawing.Point(127, 201);
            this.ybox7.Name = "ybox7";
            this.ybox7.Size = new System.Drawing.Size(31, 20);
            this.ybox7.TabIndex = 193;
            // 
            // xbox7
            // 
            this.xbox7.Location = new System.Drawing.Point(80, 201);
            this.xbox7.Name = "xbox7";
            this.xbox7.Size = new System.Drawing.Size(32, 20);
            this.xbox7.TabIndex = 192;
            // 
            // inbox7
            // 
            this.inbox7.Location = new System.Drawing.Point(13, 201);
            this.inbox7.Name = "inbox7";
            this.inbox7.Size = new System.Drawing.Size(64, 17);
            this.inbox7.TabIndex = 191;
            this.inbox7.Text = "Input 7";
            // 
            // infile6
            // 
            this.infile6.Location = new System.Drawing.Point(173, 173);
            this.infile6.Name = "infile6";
            this.infile6.Size = new System.Drawing.Size(120, 20);
            this.infile6.TabIndex = 190;
            // 
            // ybox6
            // 
            this.ybox6.Location = new System.Drawing.Point(127, 173);
            this.ybox6.Name = "ybox6";
            this.ybox6.Size = new System.Drawing.Size(31, 20);
            this.ybox6.TabIndex = 189;
            // 
            // xbox6
            // 
            this.xbox6.Location = new System.Drawing.Point(80, 173);
            this.xbox6.Name = "xbox6";
            this.xbox6.Size = new System.Drawing.Size(32, 20);
            this.xbox6.TabIndex = 188;
            // 
            // inbox6
            // 
            this.inbox6.Location = new System.Drawing.Point(13, 173);
            this.inbox6.Name = "inbox6";
            this.inbox6.Size = new System.Drawing.Size(64, 17);
            this.inbox6.TabIndex = 187;
            this.inbox6.Text = "Input 6";
            // 
            // infile5
            // 
            this.infile5.Location = new System.Drawing.Point(173, 146);
            this.infile5.Name = "infile5";
            this.infile5.Size = new System.Drawing.Size(120, 20);
            this.infile5.TabIndex = 186;
            // 
            // ybox5
            // 
            this.ybox5.Location = new System.Drawing.Point(127, 146);
            this.ybox5.Name = "ybox5";
            this.ybox5.Size = new System.Drawing.Size(31, 20);
            this.ybox5.TabIndex = 185;
            // 
            // xbox5
            // 
            this.xbox5.Location = new System.Drawing.Point(80, 146);
            this.xbox5.Name = "xbox5";
            this.xbox5.Size = new System.Drawing.Size(32, 20);
            this.xbox5.TabIndex = 184;
            // 
            // inbox5
            // 
            this.inbox5.Location = new System.Drawing.Point(13, 146);
            this.inbox5.Name = "inbox5";
            this.inbox5.Size = new System.Drawing.Size(64, 16);
            this.inbox5.TabIndex = 183;
            this.inbox5.Text = "Input 5";
            // 
            // input_time_step_box
            // 
            this.input_time_step_box.Location = new System.Drawing.Point(327, 83);
            this.input_time_step_box.Name = "input_time_step_box";
            this.input_time_step_box.Size = new System.Drawing.Size(63, 20);
            this.input_time_step_box.TabIndex = 181;
            this.input_time_step_box.Text = "1440";
            // 
            // infile4
            // 
            this.infile4.Location = new System.Drawing.Point(176, 120);
            this.infile4.Name = "infile4";
            this.infile4.Size = new System.Drawing.Size(120, 20);
            this.infile4.TabIndex = 180;
            // 
            // infile3
            // 
            this.infile3.Location = new System.Drawing.Point(176, 96);
            this.infile3.Name = "infile3";
            this.infile3.Size = new System.Drawing.Size(120, 20);
            this.infile3.TabIndex = 179;
            // 
            // infile2
            // 
            this.infile2.Location = new System.Drawing.Point(176, 72);
            this.infile2.Name = "infile2";
            this.infile2.Size = new System.Drawing.Size(120, 20);
            this.infile2.TabIndex = 178;
            // 
            // infile1
            // 
            this.infile1.Location = new System.Drawing.Point(176, 48);
            this.infile1.Name = "infile1";
            this.infile1.Size = new System.Drawing.Size(120, 20);
            this.infile1.TabIndex = 177;
            // 
            // ybox1
            // 
            this.ybox1.Location = new System.Drawing.Point(128, 48);
            this.ybox1.Name = "ybox1";
            this.ybox1.Size = new System.Drawing.Size(32, 20);
            this.ybox1.TabIndex = 175;
            // 
            // ybox2
            // 
            this.ybox2.Location = new System.Drawing.Point(128, 72);
            this.ybox2.Name = "ybox2";
            this.ybox2.Size = new System.Drawing.Size(32, 20);
            this.ybox2.TabIndex = 174;
            // 
            // ybox3
            // 
            this.ybox3.Location = new System.Drawing.Point(128, 96);
            this.ybox3.Name = "ybox3";
            this.ybox3.Size = new System.Drawing.Size(32, 20);
            this.ybox3.TabIndex = 173;
            // 
            // ybox4
            // 
            this.ybox4.Location = new System.Drawing.Point(128, 120);
            this.ybox4.Name = "ybox4";
            this.ybox4.Size = new System.Drawing.Size(32, 20);
            this.ybox4.TabIndex = 172;
            // 
            // xbox2
            // 
            this.xbox2.Location = new System.Drawing.Point(80, 72);
            this.xbox2.Name = "xbox2";
            this.xbox2.Size = new System.Drawing.Size(32, 20);
            this.xbox2.TabIndex = 171;
            // 
            // xbox3
            // 
            this.xbox3.Location = new System.Drawing.Point(80, 96);
            this.xbox3.Name = "xbox3";
            this.xbox3.Size = new System.Drawing.Size(32, 20);
            this.xbox3.TabIndex = 170;
            // 
            // xbox4
            // 
            this.xbox4.Location = new System.Drawing.Point(80, 120);
            this.xbox4.Name = "xbox4";
            this.xbox4.Size = new System.Drawing.Size(32, 20);
            this.xbox4.TabIndex = 169;
            // 
            // xbox1
            // 
            this.xbox1.Location = new System.Drawing.Point(80, 48);
            this.xbox1.Name = "xbox1";
            this.xbox1.Size = new System.Drawing.Size(32, 20);
            this.xbox1.TabIndex = 168;
            // 
            // label29
            // 
            this.label29.Location = new System.Drawing.Point(400, 76);
            this.label29.Name = "label29";
            this.label29.Size = new System.Drawing.Size(100, 32);
            this.label29.TabIndex = 182;
            this.label29.Text = "input data time step (mins)";
            // 
            // label44
            // 
            this.label44.Location = new System.Drawing.Point(176, 24);
            this.label44.Name = "label44";
            this.label44.Size = new System.Drawing.Size(56, 16);
            this.label44.TabIndex = 176;
            this.label44.Text = "File Name";
            // 
            // label43
            // 
            this.label43.Location = new System.Drawing.Point(136, 24);
            this.label43.Name = "label43";
            this.label43.Size = new System.Drawing.Size(16, 16);
            this.label43.TabIndex = 167;
            this.label43.Text = "Y";
            // 
            // label41
            // 
            this.label41.Location = new System.Drawing.Point(88, 24);
            this.label41.Name = "label41";
            this.label41.Size = new System.Drawing.Size(16, 16);
            this.label41.TabIndex = 165;
            this.label41.Text = "X";
            // 
            // inbox2
            // 
            this.inbox2.Location = new System.Drawing.Point(16, 72);
            this.inbox2.Name = "inbox2";
            this.inbox2.Size = new System.Drawing.Size(64, 16);
            this.inbox2.TabIndex = 164;
            this.inbox2.Text = "Input 2";
            // 
            // inbox3
            // 
            this.inbox3.Location = new System.Drawing.Point(16, 96);
            this.inbox3.Name = "inbox3";
            this.inbox3.Size = new System.Drawing.Size(64, 16);
            this.inbox3.TabIndex = 163;
            this.inbox3.Text = "Input 3";
            // 
            // inbox4
            // 
            this.inbox4.Location = new System.Drawing.Point(16, 120);
            this.inbox4.Name = "inbox4";
            this.inbox4.Size = new System.Drawing.Size(64, 16);
            this.inbox4.TabIndex = 162;
            this.inbox4.Text = "Input 4";
            // 
            // inbox1
            // 
            this.inbox1.Location = new System.Drawing.Point(16, 48);
            this.inbox1.Name = "inbox1";
            this.inbox1.Size = new System.Drawing.Size(64, 16);
            this.inbox1.TabIndex = 161;
            this.inbox1.Text = "Input 1";
            // 
            // label42
            // 
            this.label42.Location = new System.Drawing.Point(88, 24);
            this.label42.Name = "label42";
            this.label42.Size = new System.Drawing.Size(16, 16);
            this.label42.TabIndex = 166;
            this.label42.Text = "X";
            // 
            // tabPage2
            // 
            this.tabPage2.Controls.Add(this.grasstextbox);
            this.tabPage2.Controls.Add(this.label40);
            this.tabPage2.Controls.Add(this.label36);
            this.tabPage2.Controls.Add(this.vegTauCritBox);
            this.tabPage2.Location = new System.Drawing.Point(4, 22);
            this.tabPage2.Name = "tabPage2";
            this.tabPage2.Size = new System.Drawing.Size(907, 243);
            this.tabPage2.TabIndex = 7;
            this.tabPage2.Text = "Vegetation";
            this.tabPage2.UseVisualStyleBackColor = true;
            // 
            // grasstextbox
            // 
            this.grasstextbox.Location = new System.Drawing.Point(157, 68);
            this.grasstextbox.Name = "grasstextbox";
            this.grasstextbox.Size = new System.Drawing.Size(40, 20);
            this.grasstextbox.TabIndex = 172;
            this.grasstextbox.Text = "5";
            // 
            // label40
            // 
            this.label40.Location = new System.Drawing.Point(29, 68);
            this.label40.Name = "label40";
            this.label40.Size = new System.Drawing.Size(120, 24);
            this.label40.TabIndex = 173;
            this.label40.Text = "Grass maturity (yrs)";
            this.label40.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label36
            // 
            this.label36.Location = new System.Drawing.Point(13, 28);
            this.label36.Name = "label36";
            this.label36.Size = new System.Drawing.Size(112, 24);
            this.label36.TabIndex = 108;
            this.label36.Text = "vegetation crit shear";
            this.label36.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // vegTauCritBox
            // 
            this.vegTauCritBox.Location = new System.Drawing.Point(127, 35);
            this.vegTauCritBox.Name = "vegTauCritBox";
            this.vegTauCritBox.Size = new System.Drawing.Size(71, 20);
            this.vegTauCritBox.TabIndex = 92;
            this.vegTauCritBox.Text = "180.0";
            // 
            // tabPage3
            // 
            this.tabPage3.Controls.Add(this.mine_input_textBox);
            this.tabPage3.Controls.Add(this.mineY_textBox);
            this.tabPage3.Controls.Add(this.mineX_textBox);
            this.tabPage3.Controls.Add(this.label64);
            this.tabPage3.Controls.Add(this.label65);
            this.tabPage3.Controls.Add(this.label66);
            this.tabPage3.Controls.Add(this.mine_checkBox);
            this.tabPage3.Location = new System.Drawing.Point(4, 22);
            this.tabPage3.Name = "tabPage3";
            this.tabPage3.Size = new System.Drawing.Size(907, 243);
            this.tabPage3.TabIndex = 8;
            this.tabPage3.Text = "Contaminant";
            this.tabPage3.UseVisualStyleBackColor = true;
            // 
            // mine_input_textBox
            // 
            this.mine_input_textBox.Location = new System.Drawing.Point(173, 42);
            this.mine_input_textBox.Name = "mine_input_textBox";
            this.mine_input_textBox.Size = new System.Drawing.Size(120, 20);
            this.mine_input_textBox.TabIndex = 184;
            // 
            // mineY_textBox
            // 
            this.mineY_textBox.Location = new System.Drawing.Point(125, 42);
            this.mineY_textBox.Name = "mineY_textBox";
            this.mineY_textBox.Size = new System.Drawing.Size(32, 20);
            this.mineY_textBox.TabIndex = 182;
            // 
            // mineX_textBox
            // 
            this.mineX_textBox.Location = new System.Drawing.Point(77, 42);
            this.mineX_textBox.Name = "mineX_textBox";
            this.mineX_textBox.Size = new System.Drawing.Size(32, 20);
            this.mineX_textBox.TabIndex = 181;
            // 
            // label64
            // 
            this.label64.Location = new System.Drawing.Point(173, 18);
            this.label64.Name = "label64";
            this.label64.Size = new System.Drawing.Size(56, 16);
            this.label64.TabIndex = 183;
            this.label64.Text = "File Name";
            // 
            // label65
            // 
            this.label65.Location = new System.Drawing.Point(133, 18);
            this.label65.Name = "label65";
            this.label65.Size = new System.Drawing.Size(16, 16);
            this.label65.TabIndex = 180;
            this.label65.Text = "Y";
            // 
            // label66
            // 
            this.label66.Location = new System.Drawing.Point(85, 18);
            this.label66.Name = "label66";
            this.label66.Size = new System.Drawing.Size(16, 16);
            this.label66.TabIndex = 179;
            this.label66.Text = "X";
            // 
            // mine_checkBox
            // 
            this.mine_checkBox.Location = new System.Drawing.Point(13, 42);
            this.mine_checkBox.Name = "mine_checkBox";
            this.mine_checkBox.Size = new System.Drawing.Size(64, 16);
            this.mine_checkBox.TabIndex = 178;
            this.mine_checkBox.Text = "Input 1";
            // 
            // tabPage4
            // 
            this.tabPage4.Controls.Add(this.label75);
            this.tabPage4.Controls.Add(this.label74);
            this.tabPage4.Controls.Add(this.label73);
            this.tabPage4.Controls.Add(this.label72);
            this.tabPage4.Controls.Add(this.label71);
            this.tabPage4.Controls.Add(this.m3Box);
            this.tabPage4.Controls.Add(this.n1Box);
            this.tabPage4.Controls.Add(this.m1Box);
            this.tabPage4.Controls.Add(this.Beta3Box);
            this.tabPage4.Controls.Add(this.Beta1Box);
            this.tabPage4.Controls.Add(this.SiberiaBox);
            this.tabPage4.Controls.Add(this.label70);
            this.tabPage4.Controls.Add(this.label69);
            this.tabPage4.Controls.Add(this.label68);
            this.tabPage4.Controls.Add(this.label67);
            this.tabPage4.Controls.Add(this.soil_ratebox);
            this.tabPage4.Controls.Add(this.slopebox);
            this.tabPage4.Controls.Add(this.creepratebox);
            this.tabPage4.Controls.Add(this.label34);
            this.tabPage4.Controls.Add(this.label8);
            this.tabPage4.Location = new System.Drawing.Point(4, 22);
            this.tabPage4.Name = "tabPage4";
            this.tabPage4.Padding = new System.Windows.Forms.Padding(3);
            this.tabPage4.Size = new System.Drawing.Size(907, 243);
            this.tabPage4.TabIndex = 9;
            this.tabPage4.Text = "Slope Processes";
            this.tabPage4.UseVisualStyleBackColor = true;
            // 
            // label75
            // 
            this.label75.Location = new System.Drawing.Point(53, 296);
            this.label75.Name = "label75";
            this.label75.Size = new System.Drawing.Size(96, 24);
            this.label75.TabIndex = 185;
            this.label75.Text = "n1";
            this.label75.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label74
            // 
            this.label74.Location = new System.Drawing.Point(53, 273);
            this.label74.Name = "label74";
            this.label74.Size = new System.Drawing.Size(96, 24);
            this.label74.TabIndex = 184;
            this.label74.Text = "m3";
            this.label74.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label73
            // 
            this.label73.Location = new System.Drawing.Point(53, 195);
            this.label73.Name = "label73";
            this.label73.Size = new System.Drawing.Size(96, 24);
            this.label73.TabIndex = 183;
            this.label73.Text = "Beta1";
            this.label73.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label72
            // 
            this.label72.Location = new System.Drawing.Point(53, 247);
            this.label72.Name = "label72";
            this.label72.Size = new System.Drawing.Size(96, 24);
            this.label72.TabIndex = 182;
            this.label72.Text = "m1";
            this.label72.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label71
            // 
            this.label71.Location = new System.Drawing.Point(53, 221);
            this.label71.Name = "label71";
            this.label71.Size = new System.Drawing.Size(96, 24);
            this.label71.TabIndex = 181;
            this.label71.Text = "Beta3";
            this.label71.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // m3Box
            // 
            this.m3Box.Location = new System.Drawing.Point(155, 273);
            this.m3Box.Name = "m3Box";
            this.m3Box.Size = new System.Drawing.Size(49, 20);
            this.m3Box.TabIndex = 180;
            this.m3Box.Text = "0.79";
            // 
            // n1Box
            // 
            this.n1Box.Location = new System.Drawing.Point(155, 299);
            this.n1Box.Name = "n1Box";
            this.n1Box.Size = new System.Drawing.Size(49, 20);
            this.n1Box.TabIndex = 179;
            this.n1Box.Text = "0.69";
            this.n1Box.TextChanged += new System.EventHandler(this.n1Box_TextChanged);
            // 
            // m1Box
            // 
            this.m1Box.Location = new System.Drawing.Point(155, 247);
            this.m1Box.Name = "m1Box";
            this.m1Box.Size = new System.Drawing.Size(49, 20);
            this.m1Box.TabIndex = 178;
            this.m1Box.Text = "1.7";
            // 
            // Beta3Box
            // 
            this.Beta3Box.Location = new System.Drawing.Point(155, 221);
            this.Beta3Box.Name = "Beta3Box";
            this.Beta3Box.Size = new System.Drawing.Size(49, 20);
            this.Beta3Box.TabIndex = 177;
            this.Beta3Box.Text = "0.000186";
            // 
            // Beta1Box
            // 
            this.Beta1Box.Location = new System.Drawing.Point(155, 195);
            this.Beta1Box.Name = "Beta1Box";
            this.Beta1Box.Size = new System.Drawing.Size(49, 20);
            this.Beta1Box.TabIndex = 176;
            this.Beta1Box.Text = "1067";
            // 
            // SiberiaBox
            // 
            this.SiberiaBox.Location = new System.Drawing.Point(155, 164);
            this.SiberiaBox.Name = "SiberiaBox";
            this.SiberiaBox.Size = new System.Drawing.Size(147, 34);
            this.SiberiaBox.TabIndex = 175;
            this.SiberiaBox.Text = "SIBERIA sub model?";
            this.toolTip1.SetToolTip(this.SiberiaBox, "CAESAR can run in both catchment and reach mode, but if you have catchment mode c" +
                    "hecked, you should input a rainfall data file");
            // 
            // label70
            // 
            this.label70.AutoSize = true;
            this.label70.Location = new System.Drawing.Point(220, 132);
            this.label70.Name = "label70";
            this.label70.Size = new System.Drawing.Size(246, 13);
            this.label70.TabIndex = 168;
            this.label70.Text = "simply slope * slope length, so replicates wash term";
            // 
            // label69
            // 
            this.label69.AutoSize = true;
            this.label69.Location = new System.Drawing.Point(220, 116);
            this.label69.Name = "label69";
            this.label69.Size = new System.Drawing.Size(357, 13);
            this.label69.TabIndex = 167;
            this.label69.Text = "Slope * Soil erosion rate * (drainage area ^ 0.5) * Time(years) / DX(cellsize)";
            // 
            // label68
            // 
            this.label68.AutoSize = true;
            this.label68.Location = new System.Drawing.Point(220, 42);
            this.label68.Name = "label68";
            this.label68.Size = new System.Drawing.Size(220, 13);
            this.label68.TabIndex = 166;
            this.label68.Text = "Slope * Creeprate * Time(years) / DX(cellsize)";
            // 
            // label67
            // 
            this.label67.Location = new System.Drawing.Point(51, 109);
            this.label67.Name = "label67";
            this.label67.Size = new System.Drawing.Size(96, 24);
            this.label67.TabIndex = 165;
            this.label67.Text = "Soil erosion rate";
            this.label67.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // soil_ratebox
            // 
            this.soil_ratebox.Location = new System.Drawing.Point(155, 113);
            this.soil_ratebox.Name = "soil_ratebox";
            this.soil_ratebox.Size = new System.Drawing.Size(49, 20);
            this.soil_ratebox.TabIndex = 164;
            this.soil_ratebox.Text = "0.0";
            // 
            // slopebox
            // 
            this.slopebox.Location = new System.Drawing.Point(155, 75);
            this.slopebox.Name = "slopebox";
            this.slopebox.Size = new System.Drawing.Size(40, 20);
            this.slopebox.TabIndex = 162;
            this.slopebox.Text = "45";
            // 
            // creepratebox
            // 
            this.creepratebox.Location = new System.Drawing.Point(155, 39);
            this.creepratebox.Name = "creepratebox";
            this.creepratebox.Size = new System.Drawing.Size(49, 20);
            this.creepratebox.TabIndex = 160;
            this.creepratebox.Text = "0.0025";
            // 
            // label34
            // 
            this.label34.Location = new System.Drawing.Point(21, 75);
            this.label34.Name = "label34";
            this.label34.Size = new System.Drawing.Size(128, 24);
            this.label34.TabIndex = 163;
            this.label34.Text = "slope failure threshold";
            this.label34.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label8
            // 
            this.label8.Location = new System.Drawing.Point(51, 39);
            this.label8.Name = "label8";
            this.label8.Size = new System.Drawing.Size(96, 24);
            this.label8.TabIndex = 161;
            this.label8.Text = "Creep rate";
            this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // tabPage5
            // 
            this.tabPage5.Controls.Add(this.label89);
            this.tabPage5.Controls.Add(this.label88);
            this.tabPage5.Controls.Add(this.label87);
            this.tabPage5.Controls.Add(this.label86);
            this.tabPage5.Controls.Add(this.label85);
            this.tabPage5.Controls.Add(this.label84);
            this.tabPage5.Controls.Add(this.slab_depth_box);
            this.tabPage5.Controls.Add(this.shadow_angle_box);
            this.tabPage5.Controls.Add(this.upstream_check_box);
            this.tabPage5.Controls.Add(this.depo_prob_box);
            this.tabPage5.Controls.Add(this.offset_box);
            this.tabPage5.Controls.Add(this.init_depth_box);
            this.tabPage5.Controls.Add(this.DuneBox);
            this.tabPage5.Location = new System.Drawing.Point(4, 22);
            this.tabPage5.Name = "tabPage5";
            this.tabPage5.Padding = new System.Windows.Forms.Padding(3);
            this.tabPage5.Size = new System.Drawing.Size(907, 243);
            this.tabPage5.TabIndex = 10;
            this.tabPage5.Text = "Dune model";
            this.tabPage5.UseVisualStyleBackColor = true;
            this.tabPage5.Click += new System.EventHandler(this.tabPage5_Click);
            // 
            // label89
            // 
            this.label89.AutoSize = true;
            this.label89.Location = new System.Drawing.Point(117, 225);
            this.label89.Name = "label89";
            this.label89.Size = new System.Drawing.Size(270, 13);
            this.label89.TabIndex = 12;
            this.label89.Text = "Downstream offset (travel distance automatically added)";
            // 
            // label88
            // 
            this.label88.AutoSize = true;
            this.label88.Location = new System.Drawing.Point(115, 190);
            this.label88.Name = "label88";
            this.label88.Size = new System.Drawing.Size(124, 13);
            this.label88.TabIndex = 11;
            this.label88.Text = "Deposition probability (%)";
            this.label88.Click += new System.EventHandler(this.label88_Click);
            // 
            // label87
            // 
            this.label87.AutoSize = true;
            this.label87.Location = new System.Drawing.Point(115, 154);
            this.label87.Name = "label87";
            this.label87.Size = new System.Drawing.Size(381, 13);
            this.label87.TabIndex = 10;
            this.label87.Text = "Shadow check distance (cells) - number of cells Upstream it checks for shadow";
            // 
            // label86
            // 
            this.label86.AutoSize = true;
            this.label86.Location = new System.Drawing.Point(115, 118);
            this.label86.Name = "label86";
            this.label86.Size = new System.Drawing.Size(277, 13);
            this.label86.TabIndex = 9;
            this.label86.Text = "Shadow angle (deg) landslip angle in slope processes tab";
            // 
            // label85
            // 
            this.label85.AutoSize = true;
            this.label85.Location = new System.Drawing.Point(117, 83);
            this.label85.Name = "label85";
            this.label85.Size = new System.Drawing.Size(138, 13);
            this.label85.TabIndex = 8;
            this.label85.Text = "Maximum slab thickness (m)";
            // 
            // label84
            // 
            this.label84.AutoSize = true;
            this.label84.Location = new System.Drawing.Point(115, 47);
            this.label84.Name = "label84";
            this.label84.Size = new System.Drawing.Size(185, 13);
            this.label84.TabIndex = 7;
            this.label84.Text = "Initial depth of sand (everywhere in m)";
            // 
            // slab_depth_box
            // 
            this.slab_depth_box.Location = new System.Drawing.Point(26, 80);
            this.slab_depth_box.Name = "slab_depth_box";
            this.slab_depth_box.Size = new System.Drawing.Size(75, 20);
            this.slab_depth_box.TabIndex = 6;
            this.slab_depth_box.Text = "0.5";
            this.slab_depth_box.TextChanged += new System.EventHandler(this.textBox12_TextChanged);
            // 
            // shadow_angle_box
            // 
            this.shadow_angle_box.Location = new System.Drawing.Point(26, 115);
            this.shadow_angle_box.Name = "shadow_angle_box";
            this.shadow_angle_box.Size = new System.Drawing.Size(75, 20);
            this.shadow_angle_box.TabIndex = 5;
            this.shadow_angle_box.Text = "15";
            // 
            // upstream_check_box
            // 
            this.upstream_check_box.Location = new System.Drawing.Point(26, 151);
            this.upstream_check_box.Name = "upstream_check_box";
            this.upstream_check_box.Size = new System.Drawing.Size(75, 20);
            this.upstream_check_box.TabIndex = 4;
            this.upstream_check_box.Text = "40";
            // 
            // depo_prob_box
            // 
            this.depo_prob_box.Location = new System.Drawing.Point(27, 187);
            this.depo_prob_box.Name = "depo_prob_box";
            this.depo_prob_box.Size = new System.Drawing.Size(75, 20);
            this.depo_prob_box.TabIndex = 3;
            this.depo_prob_box.Text = "50";
            // 
            // offset_box
            // 
            this.offset_box.Location = new System.Drawing.Point(26, 222);
            this.offset_box.Name = "offset_box";
            this.offset_box.Size = new System.Drawing.Size(75, 20);
            this.offset_box.TabIndex = 2;
            this.offset_box.Text = "1";
            // 
            // init_depth_box
            // 
            this.init_depth_box.Location = new System.Drawing.Point(27, 44);
            this.init_depth_box.Name = "init_depth_box";
            this.init_depth_box.Size = new System.Drawing.Size(75, 20);
            this.init_depth_box.TabIndex = 1;
            this.init_depth_box.Text = "4";
            // 
            // DuneBox
            // 
            this.DuneBox.AutoSize = true;
            this.DuneBox.Location = new System.Drawing.Point(26, 18);
            this.DuneBox.Name = "DuneBox";
            this.DuneBox.Size = new System.Drawing.Size(108, 17);
            this.DuneBox.TabIndex = 0;
            this.DuneBox.Text = "Run with Dunes?";
            this.DuneBox.UseVisualStyleBackColor = true;
            // 
            // statusBar1
            // 
            this.statusBar1.Location = new System.Drawing.Point(0, 288);
            this.statusBar1.Name = "statusBar1";
            this.statusBar1.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
            this.InfoStatusPanel,
            this.IterationStatusPanel,
            this.TimeStatusPanel,
            this.QwStatusPanel,
            this.QsStatusPanel,
            this.tempStatusPanel});
            this.statusBar1.ShowPanels = true;
            this.statusBar1.Size = new System.Drawing.Size(919, 22);
            this.statusBar1.SizingGrip = false;
            this.statusBar1.TabIndex = 144;
            this.statusBar1.Text = "statusBar1";
            this.statusBar1.PanelClick += new System.Windows.Forms.StatusBarPanelClickEventHandler(this.statusBar1_PanelClick);
            // 
            // InfoStatusPanel
            // 
            this.InfoStatusPanel.Name = "InfoStatusPanel";
            this.InfoStatusPanel.Text = "info";
            this.InfoStatusPanel.Width = 200;
            // 
            // IterationStatusPanel
            // 
            this.IterationStatusPanel.Name = "IterationStatusPanel";
            this.IterationStatusPanel.Text = "iterations";
            this.IterationStatusPanel.Width = 120;
            // 
            // TimeStatusPanel
            // 
            this.TimeStatusPanel.Name = "TimeStatusPanel";
            this.TimeStatusPanel.Text = "time";
            this.TimeStatusPanel.Width = 120;
            // 
            // QwStatusPanel
            // 
            this.QwStatusPanel.Name = "QwStatusPanel";
            this.QwStatusPanel.Text = "Qw";
            this.QwStatusPanel.Width = 120;
            // 
            // QsStatusPanel
            // 
            this.QsStatusPanel.Name = "QsStatusPanel";
            this.QsStatusPanel.Text = "Qs";
            this.QsStatusPanel.Width = 120;
            // 
            // tempStatusPanel
            // 
            this.tempStatusPanel.Name = "tempStatusPanel";
            this.tempStatusPanel.Text = "tempdata";
            // 
            // start_button
            // 
            this.start_button.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.start_button.Enabled = false;
            this.start_button.Location = new System.Drawing.Point(110, 258);
            this.start_button.Name = "start_button";
            this.start_button.Size = new System.Drawing.Size(88, 24);
            this.start_button.TabIndex = 146;
            this.start_button.Text = "Start!";
            this.start_button.Click += new System.EventHandler(this.main_loop);
            // 
            // button1
            // 
            this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.button1.Enabled = false;
            this.button1.Location = new System.Drawing.Point(204, 258);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(100, 24);
            this.button1.TabIndex = 147;
            this.button1.Text = "Quit and save";
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // button4
            // 
            this.button4.Location = new System.Drawing.Point(8, 8);
            this.button4.Name = "button4";
            this.button4.Size = new System.Drawing.Size(112, 40);
            this.button4.TabIndex = 144;
            this.button4.Text = "update graphics";
            this.button4.Click += new System.EventHandler(this.button4_Click_1);
            // 
            // button3
            // 
            this.button3.Font = new System.Drawing.Font("Monotype Corsiva", 8.25F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button3.Location = new System.Drawing.Point(604, 11);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(82, 43);
            this.button3.TabIndex = 99;
            this.button3.Text = "Grass now!";
            this.button3.Click += new System.EventHandler(this.button3_Click);
            // 
            // tempdata1
            // 
            this.tempdata1.Location = new System.Drawing.Point(503, 22);
            this.tempdata1.Name = "tempdata1";
            this.tempdata1.Size = new System.Drawing.Size(39, 20);
            this.tempdata1.TabIndex = 98;
            this.tempdata1.Text = "358";
            // 
            // recirculatebox
            // 
            this.recirculatebox.Location = new System.Drawing.Point(240, 24);
            this.recirculatebox.Name = "recirculatebox";
            this.recirculatebox.Size = new System.Drawing.Size(168, 24);
            this.recirculatebox.TabIndex = 89;
            this.recirculatebox.Text = "recirculate sediment";
            // 
            // checkBox3
            // 
            this.checkBox3.Location = new System.Drawing.Point(240, 8);
            this.checkBox3.Name = "checkBox3";
            this.checkBox3.Size = new System.Drawing.Size(168, 24);
            this.checkBox3.TabIndex = 68;
            this.checkBox3.Text = "water surface smoothing";
            // 
            // Panel1
            // 
            this.Panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.Panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.Panel1.Controls.Add(this.tempdata2);
            this.Panel1.Controls.Add(this.tempdata1);
            this.Panel1.Controls.Add(this.graphicToGoogleEarthButton);
            this.Panel1.Controls.Add(this.label82);
            this.Panel1.Controls.Add(this.label81);
            this.Panel1.Controls.Add(this.label80);
            this.Panel1.Controls.Add(this.button5);
            this.Panel1.Controls.Add(this.button4);
            this.Panel1.Controls.Add(this.button3);
            this.Panel1.Controls.Add(this.recirculatebox);
            this.Panel1.Controls.Add(this.checkBox3);
            this.Panel1.Controls.Add(this.grassbox);
            this.Panel1.Location = new System.Drawing.Point(4, 184);
            this.Panel1.Name = "Panel1";
            this.Panel1.Size = new System.Drawing.Size(823, 69);
            this.Panel1.TabIndex = 145;
            this.Panel1.Visible = false;
            // 
            // tempdata2
            // 
            this.tempdata2.Location = new System.Drawing.Point(548, 22);
            this.tempdata2.Name = "tempdata2";
            this.tempdata2.Size = new System.Drawing.Size(39, 20);
            this.tempdata2.TabIndex = 145;
            this.tempdata2.Text = "358";
            // 
            // graphicToGoogleEarthButton
            // 
            this.graphicToGoogleEarthButton.Location = new System.Drawing.Point(693, 11);
            this.graphicToGoogleEarthButton.Name = "graphicToGoogleEarthButton";
            this.graphicToGoogleEarthButton.Size = new System.Drawing.Size(81, 43);
            this.graphicToGoogleEarthButton.TabIndex = 150;
            this.graphicToGoogleEarthButton.Text = "graphic to google earth";
            this.graphicToGoogleEarthButton.UseVisualStyleBackColor = true;
            this.graphicToGoogleEarthButton.Click += new System.EventHandler(this.graphicToGoogleEarthButton_Click);
            // 
            // label82
            // 
            this.label82.AutoSize = true;
            this.label82.Location = new System.Drawing.Point(560, 6);
            this.label82.Name = "label82";
            this.label82.Size = new System.Drawing.Size(14, 13);
            this.label82.TabIndex = 149;
            this.label82.Text = "Y";
            // 
            // label81
            // 
            this.label81.AutoSize = true;
            this.label81.Location = new System.Drawing.Point(517, 6);
            this.label81.Name = "label81";
            this.label81.Size = new System.Drawing.Size(14, 13);
            this.label81.TabIndex = 148;
            this.label81.Text = "X";
            // 
            // label80
            // 
            this.label80.AutoSize = true;
            this.label80.Location = new System.Drawing.Point(388, 25);
            this.label80.Name = "label80";
            this.label80.Size = new System.Drawing.Size(109, 13);
            this.label80.TabIndex = 147;
            this.label80.Text = "max erode/deposition";
            // 
            // button5
            // 
            this.button5.Location = new System.Drawing.Point(133, 7);
            this.button5.Name = "button5";
            this.button5.Size = new System.Drawing.Size(80, 42);
            this.button5.TabIndex = 146;
            this.button5.Text = "scan";
            this.button5.Click += new System.EventHandler(this.button5_Click_1);
            // 
            // grassbox
            // 
            this.grassbox.Location = new System.Drawing.Point(393, 41);
            this.grassbox.Name = "grassbox";
            this.grassbox.Size = new System.Drawing.Size(104, 24);
            this.grassbox.TabIndex = 97;
            this.grassbox.Text = "grass/sediment";
            this.grassbox.Visible = false;
            // 
            // checkBox1
            // 
            this.checkBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.checkBox1.AutoSize = true;
            this.checkBox1.Checked = true;
            this.checkBox1.CheckState = System.Windows.Forms.CheckState.Checked;
            this.checkBox1.Location = new System.Drawing.Point(450, 263);
            this.checkBox1.Name = "checkBox1";
            this.checkBox1.Size = new System.Drawing.Size(77, 17);
            this.checkBox1.TabIndex = 151;
            this.checkBox1.Text = "view tabs?";
            this.checkBox1.UseVisualStyleBackColor = true;
            this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged_1);
            // 
            // trackBar1
            // 
            this.trackBar1.AutoSize = false;
            this.trackBar1.Location = new System.Drawing.Point(216, 9);
            this.trackBar1.Name = "trackBar1";
            this.trackBar1.Size = new System.Drawing.Size(104, 20);
            this.trackBar1.TabIndex = 149;
            this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll);
            // 
            // label61
            // 
            this.label61.AutoSize = true;
            this.label61.Location = new System.Drawing.Point(6, 14);
            this.label61.Name = "label61";
            this.label61.Size = new System.Drawing.Size(44, 13);
            this.label61.TabIndex = 150;
            this.label61.Text = "Graphic";
            // 
            // groupBox2
            // 
            this.groupBox2.Controls.Add(this.label62);
            this.groupBox2.Controls.Add(this.comboBox1);
            this.groupBox2.Controls.Add(this.trackBar1);
            this.groupBox2.Controls.Add(this.label61);
            this.groupBox2.Location = new System.Drawing.Point(12, -3);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(334, 35);
            this.groupBox2.TabIndex = 151;
            this.groupBox2.TabStop = false;
            this.groupBox2.Visible = false;
            // 
            // label62
            // 
            this.label62.AutoSize = true;
            this.label62.Location = new System.Drawing.Point(170, 14);
            this.label62.Name = "label62";
            this.label62.Size = new System.Drawing.Size(46, 13);
            this.label62.TabIndex = 152;
            this.label62.Text = "Contrast";
            // 
            // comboBox1
            // 
            this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.comboBox1.FormattingEnabled = true;
            this.comboBox1.Location = new System.Drawing.Point(54, 10);
            this.comboBox1.Name = "comboBox1";
            this.comboBox1.Size = new System.Drawing.Size(104, 21);
            this.comboBox1.TabIndex = 151;
            this.comboBox1.SelectedValueChanged += new System.EventHandler(this.comboBox1_SelectedValueChanged);
            // 
            // groupBox3
            // 
            this.groupBox3.Controls.Add(this.label63);
            this.groupBox3.Controls.Add(this.trackBar2);
            this.groupBox3.Location = new System.Drawing.Point(346, -3);
            this.groupBox3.Name = "groupBox3";
            this.groupBox3.Size = new System.Drawing.Size(156, 35);
            this.groupBox3.TabIndex = 152;
            this.groupBox3.TabStop = false;
            this.groupBox3.Visible = false;
            // 
            // label63
            // 
            this.label63.AutoSize = true;
            this.label63.Location = new System.Drawing.Point(6, 13);
            this.label63.Name = "label63";
            this.label63.Size = new System.Drawing.Size(34, 13);
            this.label63.TabIndex = 154;
            this.label63.Text = "Zoom";
            // 
            // trackBar2
            // 
            this.trackBar2.AutoSize = false;
            this.trackBar2.Location = new System.Drawing.Point(42, 9);
            this.trackBar2.Minimum = 1;
            this.trackBar2.Name = "trackBar2";
            this.trackBar2.Size = new System.Drawing.Size(104, 20);
            this.trackBar2.TabIndex = 153;
            this.trackBar2.Value = 5;
            this.trackBar2.Scroll += new System.EventHandler(this.trackBar2_Scroll);
            // 
            // pause
            // 
            this.pause.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.pause.Location = new System.Drawing.Point(310, 258);
            this.pause.Name = "pause";
            this.pause.Size = new System.Drawing.Size(66, 24);
            this.pause.TabIndex = 153;
            this.pause.Text = "pause";
            this.pause.UseVisualStyleBackColor = true;
            this.pause.Click += new System.EventHandler(this.button6_Click_1);
            // 
            // button7
            // 
            this.button7.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.button7.Location = new System.Drawing.Point(382, 259);
            this.button7.Name = "button7";
            this.button7.Size = new System.Drawing.Size(57, 22);
            this.button7.TabIndex = 154;
            this.button7.Text = "resume";
            this.button7.UseVisualStyleBackColor = true;
            this.button7.Click += new System.EventHandler(this.button7_Click);
            // 
            // zoomPanImageBox1
            // 
            this.zoomPanImageBox1.Image = null;
            this.zoomPanImageBox1.Location = new System.Drawing.Point(8, 34);
            this.zoomPanImageBox1.Name = "zoomPanImageBox1";
            this.zoomPanImageBox1.Size = new System.Drawing.Size(824, 220);
            this.zoomPanImageBox1.TabIndex = 148;
            this.zoomPanImageBox1.Visible = false;
            this.zoomPanImageBox1.Load += new System.EventHandler(this.zoomPanImageBox1_Load);
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.AutoScroll = true;
            this.ClientSize = new System.Drawing.Size(919, 310);
            this.Controls.Add(this.button7);
            this.Controls.Add(this.pause);
            this.Controls.Add(this.checkBox1);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.start_button);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.tabControl1);
            this.Controls.Add(this.statusBar1);
            this.Controls.Add(this.zoomPanImageBox1);
            this.Controls.Add(this.Panel1);
            this.Controls.Add(this.groupBox3);
            this.Controls.Add(this.groupBox2);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Menu = this.mainMenu1;
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "CAESAR - Cellular Automaton Evolutionary Slope And River model. version 6.0 (3/6/" +
                "2009)";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.Paint += new System.Windows.Forms.PaintEventHandler(this.paint1);
            this.Resize += new System.EventHandler(this.Form1_Resize);
            this.tabControl1.ResumeLayout(false);
            this.FilesTab.ResumeLayout(false);
            this.FilesTab.PerformLayout();
            this.tabPage1.ResumeLayout(false);
            this.tabPage1.PerformLayout();
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.NumericalTab.ResumeLayout(false);
            this.NumericalTab.PerformLayout();
            this.GrainTab.ResumeLayout(false);
            this.GrainTab.PerformLayout();
            this.DescriptionTab.ResumeLayout(false);
            this.DescriptionTab.PerformLayout();
            this.GridTab.ResumeLayout(false);
            this.GridTab.PerformLayout();
            this.HydrologyTab.ResumeLayout(false);
            this.HydrologyTab.PerformLayout();
            this.tabPage2.ResumeLayout(false);
            this.tabPage2.PerformLayout();
            this.tabPage3.ResumeLayout(false);
            this.tabPage3.PerformLayout();
            this.tabPage4.ResumeLayout(false);
            this.tabPage4.PerformLayout();
            this.tabPage5.ResumeLayout(false);
            this.tabPage5.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.InfoStatusPanel)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.IterationStatusPanel)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.TimeStatusPanel)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.QwStatusPanel)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.QsStatusPanel)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.tempStatusPanel)).EndInit();
            this.Panel1.ResumeLayout(false);
            this.Panel1.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            this.groupBox3.ResumeLayout(false);
            this.groupBox3.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.trackBar2)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}


		private void start_button_Click(object sender, System.EventArgs e)
		{
			xtextbox.Visible=false;
			ytextbox.Visible=false;
			button1.Visible=false;
			button2.Visible=false;
			label1.Visible=false;
			label2.Visible=false;
			
		}


		private void clearforms()
		{
			tabControl1.Visible = false;
            
		}


		// well, in this botched version of CAESAR for C#, main loop replaces main in the 'normal' version.
		private void main_loop(object sender, System.EventArgs e)
		{
            menuItem35.Enabled = true;
			/********* locals ***********/
			int n,x,y;
			double tempflow=baseflow;
			double ince=cycle+60;
			gameClock = new Timer();

//			clearforms();                  // MJ 14/01/05   this is done when load button is clicked
			start_button.Enabled = false;  // MJ 17/01/05
			button1.Enabled = true;        // MJ 17/01/05 
            comboBox1.Items.Add("water depth");
            popComboBox1();
			time_1=1;
			time_factor=60;
			calc_J(1.0);
			time_factor=1;

			save_time=cycle;
			creep_time=cycle;
            soil_erosion_time = cycle;
			time_1=cycle;

			//this.Paint += new PaintEventHandler(paint1);  //JMW

			mygraphics = this.CreateGraphics();

			
            slide_5();
			get_area();

			init_route(TRUE,init_discharge, baseflow);	
			this.InfoStatusPanel.Text="Starting main loop";        // MJ 14/01/05
			//JMW 

			this.InfoStatusPanel.Text="Running";        // MJ 14/01/05
            
            //Googel Earth Animation Directory
            if (googleAnimationCheckbox.Checked)
            {
                Directory.CreateDirectory("animation");
            }
			// <JMW 20041018> 
			if (checkBoxGenerateAVIFile.Checked)
			{
				aw = new AviWriter();

				string fname = textBoxAVIFile.Text; 
			
				//Delete the avi if it already exists, & wait for it to occur
				if (File.Exists(fname))
				{
					File.Delete(fname);

					if (File.Exists(fname)) 
					{
						System.IO.FileSystemWatcher watcher = 
							new System.IO.FileSystemWatcher(fname);
						watcher.WaitForChanged(System.IO.WatcherChangeTypes.Deleted); 
					}
				}

				bmp = aw.Open(fname,25,this.ClientRectangle.Width,
					this.ClientRectangle.Height);  // <JMW 20041018>

			}



			// Here we go into the main loop,
			// not sure why its within a game clock thing, but I copied this bit of code to get
			// the event handler to work - and it seems OK so why change it.
			// so the main loop is really in erodedepo()




			for(n=1;n<=1;n++)
			{
				gameClock.Interval = 1;
				gameClock.Tick += new EventHandler(erodedepo);
				gameClock.Start();
                
			}
		}


		private void erodedepo(Object sender, EventArgs e)
		{
			// remember that this function is called every iteration from main_loop,
			// so have to use global variables, or they get reset every time

			int n,x,y, cit;
            Random xd = new Random();
	        

			
			//has to have erode first - otherwise it draws withoug the water - which is 
			//zero'd after erode.
			
			// Gez code: set previous cycle = to cycle
			previous = cycle;
			old_cycle = cycle%output_file_save_interval;
			// end gez code

			counter++;
			cycle+=time_factor/60;  // cycle in mins, time_factor in seconds..

			// Gez code
			new_cycle = cycle%output_file_save_interval;
		    // end gez code


			// then carry out soil creep. - also growing grass... and dunes...

            if (cycle > creep_time)
            {
                creep_time += 144;// now 10 times a day // now daily..// now weekly //43800;  // do soil creep monthly.
                // also do sand dunes here..

                if (DuneBox.Checked == true)
                {
                    if (xd.Next(1, 100) <= 5000)
                    {
                        dune1(144 * 60);
                    }
                    else
                    {
                        dune2(144 * 60);// passes time that has elapsed in seconds (144 is mins)
                    }
                }

                creep(0.00028);//(0.019);//(0.083);


                if (SiberiaBox.Checked == true)
                {
                    get_area();
                    siberia(0.00028); // the value passed is the time step (in years)

                }
                // next line does grass growing, must change it if changes from monthly update
                if (grow_grass_time > 0) grow_grass(1 / (grow_grass_time * 3650));
            }

            // then soil erosion time
            if (SOIL_RATE > 0 && cycle > soil_erosion_time)
            {
                get_area();
                soil_erosion_time += 1440;// do soil erosion daily
                soilerosion(0.0028);
            }

            erode(); // main fluvial erosion and deposition routine..

            //if(bedslope_box.Checked != true)fill_pits(); // pit filling algorithm - experimental
            
            fill_pits();

            //// line to do uplift at set time....
            //if (cycle > (1440*Convert.ToInt32(textBox5.Text))&&elev[1,1]<100)
            //{
            //    for (x = 1; x <= 175; x++)
            //    {
            //        for (y = 1; y <= ymax; y++)
            //        {
            //            elev[x, y] += Convert.ToInt32(textBox6.Text);
            //        }
            //    }
            //    slide_5();
            //    slide_5();
            //}

            if (newlateral.Checked && Math.IEEERemainder(counter, 10) == 0)
            {
                lateral2();
            }
            else no_lateral(); //TJC 27/1/05
			//if(oldlateral.Checked)lateral();
            if (nolateral.Checked) no_lateral();

			slide_3();
            

			//
			//			This whole section below deals with the water inputs. A separate part for point inputs and 
			//		    a different bit for gradual inputs from the whole of the catchment. (reach or catchment)
			//

			//			carry out an init route every * iterations. normally 1000
			if(Math.IEEERemainder(counter,2000)==0)
			{
                get_area();
				init_route(TRUE,init_discharge, baseflow);
				time_factor=0.00000001;
			}
			
			if(reach_mode_box.Checked==true)
			{
				// if the input type flag is 0 then the discharge inputs are from points
				j_mean=0;
				double totqtemp=0;
				for(n=0;n<=number_of_points-1;n++)
				{
					totqtemp+=inputfile[n,(int)((cycle-init_cycle)/input_time_step),1];
				}

				if(totqtemp>init_discharge)
				{
					init_discharge=init_discharge*2;
					if(init_discharge<totqtemp)init_discharge=totqtemp*1.5;
					Console.Write("scanning up ");
					init_route(TRUE,init_discharge, baseflow);
					time_factor=0.0000000001;
				}

				if(totqtemp<(init_discharge/2)&&init_discharge>80)
				{
					init_discharge=init_discharge/2;
					Console.Write(" scanning down ");
					init_route(TRUE,init_discharge,baseflow);
					time_factor=0.0000000001;
				}

				for(n=0;n<=number_of_points-1;n++)
				{
					x=inpoints[n,0];
					y=inpoints[n,1];
                    discharge[x, y] += inputfile[n, (int)((cycle - init_cycle) / input_time_step), 1] / div_inputs;

                    //left_out[x, y] += discharge[x, y];//extra line to ensure that discharge is counted properly here if vel is used to calc tau.
				}
			}

            
			if(catchment_mode_box.Checked==true)
			{
				// if the input type flag is 1 then the discharge is input from the hydrograph...
				if(cycle>=time_1)
				{
					do
					{
						time_1+=2;
						calc_J(time_1);
						if(time_factor>3600&&new_j_mean>(0.2/(xmax*ymax*DX*DX)))//stops code going too fast when there is actual flow in the channels greater than 0.2cu.
						{
							cycle=time_1+60;
							time_factor=3600;
						}		   
					}while(time_1<cycle);
				}
					
				calchydrograph(time_1-cycle);

                // next line is a dirty fix, so that j_mean can be read directly in from the rainfall file, if the check box is ticked
                // that allows you to calc j_mean direct from a hydrograph.
                if (jmeaninputfilebox.Checked == true) j_mean = ((hourly_rain_data[(int)(cycle / 60)]) / Math.Pow(DX, 2));

				if(j_mean>=baseflow)
				{
					baseflow=baseflow*2;
					Console.Write("going up.. \n");
					get_area();
					init_route(TRUE,init_discharge, baseflow);
					time_factor=0.0000000001;
				}
	
	
				if(baseflow>(j_mean*2)&&baseflow>0.0000005)
				{
					baseflow=j_mean*1.01;
					Console.Write("going down.. \n");
					get_area();
					init_route(TRUE,init_discharge, baseflow);
					time_factor=0.0000000001;
				}
		
			}



			//
			//			Now goes into the four scans for routing water.
			//			Here it actually has 8, sometimes this works better.
			//

			//Console.WriteLine(Convert.ToString(j_mean*DX*DX*nActualGridCells));

			// before scanning adds in pools (filled sinks)
            for(x=1;x<=xmax;x++){for(y=1;y<=ymax;y++){elev[x,y]+=pool_depth[x,y];}}


            route_lr();//drawwater(mygraphics);for(t=1;t<=50000000;t++);
            route_rl();//drawwater(mygraphics);for(t=1;t<=50000000;t++);
            route_down(cycle);//drawwater(mygraphics);for(t=1;t<=50000000;t++);
            route_up();//drawwater(mygraphics);for(t=1;t<=50000000;t++);
            route_lr();//drawwater(mygraphics);for(t=1;t<=50000000;t++);
            route_rl();//drawwater(mygraphics);for(t=1;t<=50000000;t++);
            route_up();//drawwater(mygraphics);for(t=1;t<=50000000;t++);
            route_down(cycle);//drawwater(mygraphics);for(t=1;t<=50000000;t++);

            calc_max_flow_direction();		// calculates flow directions...  discharges in what direction etc...     


            // then removes pools (filled sinks)
            for(x=1;x<=xmax;x++){for(y=1;y<=ymax;y++){elev[x,y]-=pool_depth[x,y];if(water_depth[x,y]>water_depth_erosion_threshold)water_depth[x,y]+=pool_depth[x, y];}}

			// water surface smoothing routine called
			if (checkBox3.Checked == true) smooth(smoothradius); //passes radius for smoothing to smooth function

 
			// then calculate flow direction and velocity and Tau.
			calc_flow_direction();



			// smooths discharges remaining in cells... 
            smooth_discharge(1);


			// this simple for next loop just calcualtes the total discharge that drops off the right end of the map
			
			double temptot=0;
			double erotemp=0;
			for(y=1;y<=ymax;y++)
			{
				if(discharge[xmax+1,y]>0)
				{
					temptot+=discharge[xmax+1,y];
					discharge[xmax+1,y]=0;
				}
					
				for(x=1;x<=xmax;x++)
				{
					erotemp+=init_elevs[x,y]-elev[x,y];			
				}
			}
            //temptot /= 2;// divided by 2 as twice as much water added...
            waterOut = temptot;

			// Gez
			temptotal = temptot;

			// call output routine
			if (checkBoxGenerateTimeSeries.Checked)  // MJ 20/01/05
			{
				output_data();
			}
			// end gez code

			// updates the text boxes with the time and iterationbs elapsed
            this.QwStatusPanel.Text = string.Format("Qw = {0:G}", temptot); // MJ 14/01/05

            this.IterationStatusPanel.Text= "it = " + counter.ToString();  // MJ 14/01/05
			if (cycle <= 1440)	
			{
				this.TimeStatusPanel.Text=string.Format("t = {0:F6} min",cycle);
			} 
			else 
			{
				this.TimeStatusPanel.Text=string.Format("t = {0:F6} day",cycle/1440);
			}


	
			// output of iteration essentials  MJ 19/01/05
			if (checkBoxGenerateIterations.Checked)
			{
				string ITERATION_FILE = IterationOutbox.Text;
				string output = string.Format("{0:G}",counter);
				output = output + string.Format("  {0:F6}",cycle/1440);  // fixed JOE 18/05/05
				output = output + string.Format("  {0:F6}",temptot);
				output = output + string.Format("  {0:F6}",sediQ);
				output = output + string.Format("  {0:F6}",j_mean*DX*DX*nActualGridCells);  // fixed MJ 29/03/05
				StreamWriter sw = File.AppendText(ITERATION_FILE);
				sw.WriteLine(output);
				sw.Close();

			}

			// save data every X times.. passes 0 to save data which means it gets no file extension
			if(Math.IEEERemainder(counter,1000)==0)
			{
				if(menuItem25.Checked==true)save_data(1,0); // save waterdepths
				if(menuItem13.Checked==true)save_data(2,0); // save elevdiff
				if(menuItem12.Checked==true)save_data(3,0); // save elevations
				if(menuItem14.Checked==true)save_data(4,0); // save grainsize
				if(menuItem15.Checked==true)save_data(5,0); // save tracer grainsizes
				if(menuItem16.Checked==true)save_data(6,0); // save tracer surface
				if(menuItem17.Checked==true)save_data(7,0); // save tracer 2
				if(menuItem18.Checked==true)save_data(8,0); // save tracer 3
				if(menuItem19.Checked==true)save_data(9,0); // save tracer 4
				if(menuItem20.Checked==true)save_data(10,0); // save tracer 5
				if(menuItem21.Checked==true)save_data(11,0); // save tracer 6 
				if(menuItem22.Checked==true)save_data(12,0); // save tracer 7
				if(menuItem23.Checked==true)save_data(13,0); // save tracer 8 
				if(menuItem24.Checked==true)save_data(14,0); // save tracer 9
				if(menuItem29.Checked==true)save_data(15,0); // save d50 top layer
				if(menuItem33.Checked==true)save_data(16,0); // save velocity	<JOE 20050605>
				if(menuItem34.Checked==true)save_data(17,0); // save soil_saturation	<JOE 20050605>
				slide_5();

			}

            //Google Earth Animation
            if ((googleAnimationCheckbox.Checked) && (cycle>=save_time2))
            {
                updateClick = 1;
                this.Refresh();
                drawwater(mygraphics);
                if (coordinateDone == 0)
                {
                    //transfrom coordinates
                    point testPoint = new point(xll, yll);
                    testPoint.transformPoint();
                    yurcorner = yll + (System.Convert.ToDouble(ymax) * System.Convert.ToDouble(DX));
                    xurcorner = xll + (System.Convert.ToDouble(xmax) * System.Convert.ToDouble(DX));
                    point testPoint2 = new point(xurcorner, yurcorner);
                    testPoint2.transformPoint();
                    urfinalLati = testPoint2.ycoord;
                    urfinalLongi = testPoint2.xcoord;
                    llfinalLati = testPoint.ycoord;
                    llfinalLongi = testPoint.xcoord;
                    coordinateDone = 1;
                }
                //Save image
                m_objDrawingSurface.MakeTransparent();
                m_objDrawingSurface.Save("animation\\mysavedimage" + imageCount2 + ".png", System.Drawing.Imaging.ImageFormat.Png);
                //update time
                googleTime = googleTime.AddMinutes(save_interval2);
                kmlTime = googleTime.ToString();
                DateArray = kmlTime.Split(new char[] { ' ' });
                DateArray2 = DateArray[0].Split(new char[] { '/' });
                kmlTime = DateArray2[2] + "-" + DateArray2[1] + "-" + DateArray2[0] + "T" + DateArray[1] + "Z";
                
                //create kml file for image
                StreamWriter kmlsr = File.AppendText(KML_FILE_NAME);
                if (imageCount2 == 1)
                {
                    kml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
                         <kml xmlns=""http://earth.google.com/kml/2.1"">";
                    kml = kml + "\n<Folder>"
                        + "\n<name>Animation</name>";
                    kmlsr.WriteLine(kml);
                    kml = "";
                }
                kml = kml + "\n<GroundOverlay>"
                    + "\n<name>Untitled Image Overlay</name>";
                kml = kml + "\n<TimeSpan>"
                       + "\n<begin>" + kmlTime + "</begin>"
                       + "\n<end>" + kmlTime + "</end>"
                       + "\n</TimeSpan>"
                       + "\n<Icon>"
                       + "\n<href>mySavedImage" + imageCount2 + ".png</href>"
                       + "\n</Icon>"
                       + "\n<LatLonBox>";
                kml = kml + "\n<north>" + urfinalLati + "</north>"
                      + "\n<south>" + llfinalLati + "</south>"
                      + "\n<east>" + urfinalLongi + "</east>"
                      + "\n<west>" + llfinalLongi + "</west>\n";
                kml = kml + @"</LatLonBox>
                           </GroundOverlay>";
                kmlsr.WriteLine(kml);
                kml = "";
                kmlsr.Close();
                imageCount2 = imageCount2 + 1;
                save_time2 = save_time2 + save_interval2;
            }
			//JMW 20041110 - Update plots


			// save data every specified interval. Passes the cycle whuch becomes the file extension
			if(cycle>=save_time)
			{
				if(menuItem25.Checked==true)save_data(1,Math.Abs(cycle)); // save waterdepths
				if(menuItem13.Checked==true)save_data(2,Math.Abs(cycle)); // save elevdiff
				if(menuItem12.Checked==true)save_data(3,Math.Abs(cycle)); // save elevations
				if(menuItem14.Checked==true)save_data(4,Math.Abs(cycle)); // save grainsize
				if(menuItem15.Checked==true)save_data(5,Math.Abs(cycle)); // save tracer grainsizes
				if(menuItem16.Checked==true)save_data(6,Math.Abs(cycle)); // save tracer surface
				if(menuItem17.Checked==true)save_data(7,Math.Abs(cycle)); // save tracer 2
				if(menuItem18.Checked==true)save_data(8,Math.Abs(cycle)); // save tracer 3
				if(menuItem19.Checked==true)save_data(9,Math.Abs(cycle)); // save tracer 4
				if(menuItem20.Checked==true)save_data(10,Math.Abs(cycle)); // save tracer 5
				if(menuItem21.Checked==true)save_data(11,Math.Abs(cycle)); // save tracer 6 
				if(menuItem22.Checked==true)save_data(12,Math.Abs(cycle)); // save tracer 7
				if(menuItem23.Checked==true)save_data(13,Math.Abs(cycle)); // save tracer 8 
				if(menuItem24.Checked==true)save_data(14,Math.Abs(cycle)); // save tracer 9
				if(menuItem29.Checked==true)save_data(15,Math.Abs(cycle)); // save d50 top layer
				if(menuItem33.Checked==true)save_data(16,Math.Abs(cycle)); // save velocity			<JOE 20050605>
				if(menuItem34.Checked==true)save_data(17,Math.Abs(cycle)); // save soil saturation	<JOE 20050605>

				//JMW 20041110 - Output frame to avi file
				if (checkBoxGenerateAVIFile.Checked)
				{
					this.Refresh(); // tjc to enable graphics to be drwan before senbding to AVI
					drawwater(mygraphics); // tjc
					Graphics gbmp = Graphics.FromImage(bmp);	
			    

					if (gbmp != null)
					{		

						IntPtr dc1 = mygraphics.GetHdc();
						IntPtr dc2 = gbmp.GetHdc();

						BitBlt(dc2,0,0,this.ClientRectangle.Width,this.ClientRectangle.Height,
							dc1,0,0, 13369376);

					
						mygraphics.ReleaseHdc(dc1);
						gbmp.ReleaseHdc(dc2);


						// need to flip image to get it the correct way up in the avi - not sure why.
						bmp.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipY);


						try 
						{						
							aw.AddFrame();  					
						}
						catch (AviWriter.AviException ex)  // <JMW 20041018>
						{
							aw.Close();
							Console.WriteLine("AVI Exception in: " + ex.ToString());
						}
	                
						//form2.Show();
					 
					}  
				}


				slide_5();
				save_time+=saveinterval;
			}
            if (time_factor > max_time_step) time_factor = max_time_step;// just temp 14400
			

			// if its at the end of the run kill the program
			if(counter>maxiterations||cycle>maxcycle*60)
			{
				gameClock.Stop();
				gameClock.Dispose();

				if ((checkBoxGenerateAVIFile.Checked) & (aw != null))
					aw.Close();  //JMW 20041109
			}
		}



		void calchydrograph(double time)
		{
			j_mean=old_j_mean+(((new_j_mean-old_j_mean)/2)*(2-time));		
		}

 		private void paint1(Object sender, PaintEventArgs e)  
		{
			//graphics = e.Graphics;
			//drawwater(this);

			//if (DoingGraphics)
			//{
			//	Graphics g = e.Graphics;
			//	drawwater(g);  //JMW	
			//}
		}


		void output_data()
		{
			int n;

			// Qw (m3) value at timestep cycle (current
			// Qw_newvol+=temptotal*((cycle-previous)*output_file_save_interval); // replaced by line below MJ 25/01/05
			Qw_newvol+=temptotal*((cycle-previous)*60);  // 60 secs per min
			Jw_newvol += (j_mean*DX*DX*nActualGridCells) * ((cycle-previous)*60);

			//Catch all time steps that pass one or more hour marks 
			if ((new_cycle<old_cycle)||(cycle-previous>=output_file_save_interval))
			{
				while ((tx>previous)&&(cycle>=tx))
				{
					hours++;
			
					// Step1: Calculate hourly total sediment Q (m3)
					Qs_step = globalsediq-old_sediq;
					Qs_over = Qs_step*((cycle-tx)/(cycle-tlastcalc));
					Qs_hour = Qs_step-Qs_over+Qs_last;

					// reset Qs_last and old_sediq for large time steps
					if (cycle>=tx+output_file_save_interval)
					{
						Qs_last = 0;
						old_sediq = globalsediq - Qs_over;
					}

					// reset Qs_last and old_sediq for small time steps
					if (cycle<tx+output_file_save_interval)
					{
						Qs_last = Qs_over;
						old_sediq = globalsediq;
					}

					// Step 2: Calculate grain size Qgs, also calculate contaminated amounts
					for (n=1;n<=G_MAX-1;n++)
					{
						// calculate timestep Qgs
						Qg_step[n] = sum_grain[n]-old_sum_grain[n];
                        Qg_step2[n] = sum_grain2[n] - old_sum_grain2[n];
						// Interpolate Qgs beyond time tx
						Qg_over[n] = Qg_step[n]*((cycle-tx)/(cycle-tlastcalc));
                        Qg_over2[n] = Qg_step2[n] * ((cycle - tx) / (cycle - tlastcalc));
						// and calculate hourly Qgs
						Qg_hour[n] = Qg_step[n]-Qg_over[n]+Qg_last[n];
                        Qg_hour2[n] = Qg_step2[n] - Qg_over2[n] + Qg_last2[n];
						// Reset Qg_last[n] and old_sum_grain[n]for large time steps
						if (cycle>=tx+output_file_save_interval)
						{
							Qg_last[n] = 0;
                            Qg_last2[n] = 0;
							old_sum_grain[n] = sum_grain[n] - Qg_over[n];
                            old_sum_grain2[n] = sum_grain2[n] - Qg_over2[n];
						}
						// Reset Qg_last[n] and old_sum_grain[n] for small time steps
						if (cycle<tx+output_file_save_interval)
						{
							Qg_last[n] = Qg_over[n];
                            Qg_last2[n] = Qg_over2[n];
							old_sum_grain[n] = sum_grain[n];
                            old_sum_grain2[n] = sum_grain2[n];
						}
					}
			
					// Step 3: Calculate hourly mean water discharge
					// Qw_overvol = temptotal*((cycle-tx)*output_file_save_interval); // replaced by line below MJ 25/01/05
					Qw_overvol = temptotal*((cycle-tx)*60);	// 60 secs per min
					Qw_stepvol = Qw_newvol-Qw_oldvol;
					Qw_hourvol = Qw_stepvol-Qw_overvol+Qw_lastvol;
					Qw_hour = Qw_hourvol/(60*output_file_save_interval); // convert hourly water volume to cumecs

					// same for Jw (j_mean contribution)  MJ 14/03/05
					Jw_overvol = (j_mean*DX*DX*nActualGridCells)*((cycle-tx)*60);  // fixed MJ 29/03/05
					Jw_stepvol = Jw_newvol-Jw_oldvol;
					Jw_hourvol = Jw_stepvol-Jw_overvol+Jw_lastvol;
					Jw_hour = Jw_hourvol/(60*output_file_save_interval);


					// reset Qw_lastvol and Qw_oldvol for large time steps
					if (cycle>=tx+output_file_save_interval)
					{
						Qw_lastvol = 0;
						Qw_oldvol = Qw_newvol-Qw_overvol;

						// same for Jw (j_mean contribution)  MJ 14/03/05
						Jw_lastvol = 0;
						Jw_oldvol = Jw_newvol-Jw_overvol;
					}

					// reset Qw_lastvol and Qw_oldvol for small time steps
					if (cycle<tx+output_file_save_interval)
					{
						Qw_lastvol = Qw_overvol;
						Qw_oldvol = Qw_newvol;

						// same for Jw (j_mean contribution)  MJ 14/03/05
						Jw_lastvol = Jw_overvol;
						Jw_oldvol = Jw_newvol;
					}

					Tx = tx;
					tx = Tx+output_file_save_interval;
                  
			
					// Step 4: Output hourly data to file (format for reach model input)
					// changed MJ 18/01/05
					string output = string.Format("{0}",hours);
					output = output	+ string.Format(" {0:F3}",Qw_hour);
					output = output	+ string.Format(" {0:F3}",Jw_hour);
					output = output	+ string.Format(" 0.0");
					output = output	+ string.Format(" {0:F3}",Qs_hour);
					for (n=1;n<=G_MAX-1;n++)
					{
						output = output + string.Format(" {0:F6}",Qg_hour[n]);
						//output = output+" "+Qg_hour[n];
					}
					

					StreamWriter sw = File.AppendText(CATCH_FILE);
					sw.WriteLine(output);
					sw.Close();

                    //output hourly contaminated sediment
                    if (tracerOutcheckBox.Checked == true && TRACERS == 2)
                    {
                        string output2 = string.Format("{0}", hours);
                        for (n = 1; n <= 2; n++)
                        {
                            output2 = output2 + " " + Qg_hour2[n];
                        }
                        StreamWriter sw2 = File.AppendText(CATCH_FILE2);
                        sw2.WriteLine(output2);
                        sw2.Close();
                    }
				}
				tlastcalc = cycle;	
			}													   
		}
		//============================================================================

		private void smooth(int radius)
		{
			int x,y,inc,tot=0,x1,y1;
			double temp_height=0;

			for(x=1;x<=(xmax);x++)
			{	
				inc=1;
	  
				while(cross_scan[x,inc]>0)
				{
					y=cross_scan[x,inc];
					inc++;

					water_depth2[x,y]=water_depth[x,y];

					temp_depth[x,y]=0;
					if(water_depth[x,y]>water_depth_erosion_threshold)
					{
						temp_height=0;
						tot=0;

						double mean_ws_elev=0;
						int tempxmin=-radius;
						int tempxmax=radius;
						int tempymin=-radius;
						int tempymax=radius;
						while(x+tempxmin<1)tempxmin++;
						while(x+tempxmax>xmax)tempxmax--;
						while(y+tempymin<1)tempymin++;
						while(y+tempymax>ymax)tempymax--;
						
						for(x1=tempxmin;x1<=tempxmax;x1++)
						{
							for(y1=tempymin;y1<=tempymax;y1++)
							{
								if(water_depth[x+x1,y+y1]>water_depth_erosion_threshold)
								{
									temp_height+=(water_depth[x+x1,y+y1]+elev[x+x1,y+y1]);
									tot++;
								}
//								if(x1==0&&y1==0) // added to double impact of central cell in the filter
//								{
//									temp_height+=(water_depth[x+x1,y+y1]+elev[x+x1,y+y1]);
//									tot++;
//								}
							}
						}

						mean_ws_elev=temp_height/tot;

                        // if too high
						if((water_depth[x,y]+elev[x,y])>mean_ws_elev)
						{
							if(water_depth[x,y]>((water_depth[x,y]+elev[x,y])-mean_ws_elev))
							{
								temp_depth[x,y]=(mean_ws_elev-(water_depth[x,y]+elev[x,y]));
							}
							if(water_depth[x,y]<((water_depth[x,y]+elev[x,y])-mean_ws_elev))
							{
								temp_depth[x,y]=0.0-water_depth[x,y];
							}

                            // stop it decreasing depths by more than 20%
                            if (((0-temp_depth[x, y]) / water_depth[x, y]) > 0.2)
                            {
                                temp_depth[x, y] = 0-(water_depth[x, y] * 0.2);
                            }

                            // tjc 9/2/05 check to stop above completely removing water from cells so if a cell had a depth of 0.01, then it can not have that depth removed..
							if(temp_depth[x,y]+water_depth[x,y]<water_depth_erosion_threshold)
							{
								temp_depth[x,y]=0;
								water_depth[x,y]=water_depth_erosion_threshold+0.0000001;
							}
                        
						}

                        //if too low (temp depth is +ve)
						if((water_depth[x,y]+elev[x,y])<mean_ws_elev)
						{
							temp_depth[x,y]=mean_ws_elev-(water_depth[x,y]+elev[x,y]);
                            // stop it increasing depths by more than 20%
                            if ((temp_depth[x, y] / water_depth[x, y]) > 0.2)
                            {
                                temp_depth[x, y] = (water_depth[x, y] * 0.2);
                            }


						}

					}

				}
			}

			for(x=1;x<=(xmax);x++)
			{	
				inc=1;
	  
				while(cross_scan[x,inc]>0)
				{
					y=cross_scan[x,inc];
					inc++;
					if(temp_depth[x,y]!=0)
					{
						// check to stop above completely removing water from cells
						
						water_depth[x,y]+=temp_depth[x,y];
						if(water_depth[x,y]<0)water_depth[x,y]=0;
						temp_depth[x,y]=0;
					}
				}
			}

		}

		
		
		private void smooth_discharge(int radius)
		{
			int x,y,inc,x1,y1;
			

			for(x=1;x<=(xmax);x++)
			{	
				inc=1;
	  
				while(cross_scan[x,inc]>0)
				{
					y=cross_scan[x,inc];
					inc++;

					temp_depth[x,y]=0;
				}
			}

	
			for(x=1;x<=(xmax);x++)
			{	
				inc=1;
	  
				while(cross_scan[x,inc]>0)
				{
					y=cross_scan[x,inc];
					inc++;

					if(discharge[x,y]>0)
					{

						int tempnum=0;

						int tempxmin=-radius;
						int tempxmax=radius;
						int tempymin=-radius;
						int tempymax=radius;
						while(x+tempxmin<1)tempxmin++;
						while(x+tempxmax>xmax)tempxmax--;
						while(y+tempymin<1)tempymin++;
						while(y+tempymax>ymax)tempymax--;
						
						for(x1=tempxmin;x1<=tempxmax;x1++)
						{
							for(y1=tempymin;y1<=tempymax;y1++)
							{
								if(water_depth[x+x1,y+y1]>=water_depth_erosion_threshold)tempnum++;
							}
						}


						tempxmin=-radius;
						tempxmax=radius;
						tempymin=-radius;
						tempymax=radius;
						while(x+tempxmin<1)tempxmin++;
						while(x+tempxmax>xmax)tempxmax--;
						while(y+tempymin<1)tempymin++;
						while(y+tempymax>ymax)tempymax--;
						
						for(x1=tempxmin;x1<=tempxmax;x1++)
						{
							for(y1=tempymin;y1<=tempymax;y1++)
							{
								if(water_depth[x+x1,y+y1]>=water_depth_erosion_threshold)
								{
									temp_depth[x+x1,y+y1]+=discharge[x,y]/tempnum;
									temp_depth[x,y]-=discharge[x,y]/tempnum;
								}
							}
						}
						
					}
				}
			}
	
			for(x=1;x<=(xmax);x++)
			{	
				inc=1;
	  
				while(cross_scan[x,inc]>0)
				{
					y=cross_scan[x,inc];
					inc++;

					discharge[x,y]+=temp_depth[x,y];
				}
			}
		}


        private void smooth_tau(int radius)
        {
            int x, y, inc, tot = 0, x1, y1;
            double temp_height = 0;

            for (x = 1; x < (xmax); x++)
            {
                inc = 1;

                while (cross_scan[x, inc] > 0)
                {
                    y = cross_scan[x, inc];
                    inc++;

                    temp_depth[x, y] = 0;
                    if (Tau[x, y] >= 0)
                    {
                        temp_height = 0;
                        tot = 0;

                        double mean_ws_elev = 0;
                        int tempxmin = -radius;
                        int tempxmax = radius;
                        int tempymin = -radius;
                        int tempymax = radius;
                        while (x + tempxmin <= 1) tempxmin++;
                        while (x + tempxmax >= xmax) tempxmax--;
                        while (y + tempymin <= 1) tempymin++;
                        while (y + tempymax >= ymax) tempymax--;

                        for (x1 = tempxmin; x1 <= tempxmax; x1++)
                        {
                            for (y1 = tempymin; y1 <= tempymax; y1++)
                            {
                                if (Tau[x + x1, y + y1] > 0)
                                {
                                    temp_height += Tau[x + x1, y + y1];
                                    tot++;
                                }
                            }
                        }

                        if (tot > 2) temp_depth[x, y] = temp_height / tot; // makes sure dead end cells have no Tau

                    }

                }
            }

            for (x = 1; x <= (xmax); x++)
            {
                inc = 1;

                while (cross_scan[x, inc] > 0)
                {
                    y = cross_scan[x, inc];
                    inc++;
                    if (temp_depth[x, y] != 0)
                    {
                        Tau[x, y] = temp_depth[x, y];
                        temp_depth[x, y] = 0;
                    }
                }
            }

        }







        private void smooth_edge2(int radius) // smoothes only cells with maxflow going into a cell. 
        {
            int x, y, inc, tot = 0, x2, y2, dir;
            double temp_height = 0;

            for (x = 2; x < (xmax); x++)
            {
                inc = 1;

                while (cross_scan[x, inc] > 0)
                {
                    y = cross_scan[x, inc];
                    if (y == ymax) y--;
                    if (y == 1) y++;
                    inc++;

                    temp_depth[x, y] = 0;
                    if (edge2[x, y] >= 0)
                    {
                        temp_height = edge2[x, y];
                        tot = 1;

                        for (dir = 1; dir <= 8; dir++)
                        {

                            x2 = x + deltaX[dir];
                            y2 = y + deltaY[dir];


                            // North
                            if (edge2[x2, y2] > 0 && deltaX[dir] == 0 && deltaY[dir] == -1)
                            {
                                if (calc_max_flow_direction_degrees(x2, y2) > 135 && calc_max_flow_direction_degrees(x2, y2) < 225)
                                {
                                    temp_height += edge2[x2, y2];
                                    tot++;
                                }
                            }

                            //NE
                            if (edge2[x2, y2] > 0 && deltaX[dir] == 1 && deltaY[dir] == -1)
                            {
                                if (calc_max_flow_direction_degrees(x2, y2) > 180 && calc_max_flow_direction_degrees(x2, y2) < 270)
                                {
                                    temp_height += edge2[x2, y2];
                                    tot++;
                                }
                            }

                            //E
                            if (edge2[x2, y2] > 0 && deltaX[dir] == 1 && deltaY[dir] == 0)
                            {
                                if (calc_max_flow_direction_degrees(x2, y2) > 225 && calc_max_flow_direction_degrees(x2, y2) < 315)
                                {
                                    temp_height += edge2[x2, y2];
                                    tot++;
                                }
                            }

                            //SE
                            if (edge2[x2, y2] > 0 && deltaX[dir] == 1 && deltaY[dir] == 1)
                            {
                                if (calc_max_flow_direction_degrees(x2, y2) > 270 && calc_max_flow_direction_degrees(x2, y2) < 360)
                                {
                                    temp_height += edge2[x2, y2];
                                    tot++;
                                }
                            }

                            //S
                            if (edge2[x2, y2] > 0 && deltaX[dir] == 0 && deltaY[dir] == 1)
                            {
                                if (calc_max_flow_direction_degrees(x2, y2) > 315 || calc_max_flow_direction_degrees(x2, y2) < 45)
                                {
                                    temp_height += edge2[x2, y2];
                                    tot++;
                                }
                            }

                            //SW
                            if (edge2[x2, y2] > 0 && deltaX[dir] == -1 && deltaY[dir] == 1)
                            {
                                if (calc_max_flow_direction_degrees(x2, y2) > 0 && calc_max_flow_direction_degrees(x2, y2) < 90)
                                {
                                    temp_height += edge2[x2, y2];
                                    tot++;
                                }
                            }

                            //W
                            if (edge2[x2, y2] > 0 && deltaX[dir] == -1 && deltaY[dir] == 0)
                            {
                                if (calc_max_flow_direction_degrees(x2, y2) > 45 && calc_max_flow_direction_degrees(x2, y2) < 135)
                                {
                                    temp_height += edge2[x2, y2];
                                    tot++;
                                }
                            }

                            //NW
                            if (edge2[x2, y2] > 0 && deltaX[dir] == -1 && deltaY[dir] == -1)
                            {
                                if (calc_max_flow_direction_degrees(x2, y2) > 90 && calc_max_flow_direction_degrees(x2, y2) < 180)
                                {
                                    temp_height += edge2[x2, y2];
                                    tot++;
                                }
                            }




                        }

                        if (tot > 1) temp_depth[x, y] = temp_height / tot; // makes sure dead end cells have no Tau

                    }

                }
            }

            for (x = 1; x <= (xmax); x++)
            {
                inc = 1;

                while (cross_scan[x, inc] > 0)
                {
                    y = cross_scan[x, inc];
                    inc++;
                    if (temp_depth[x, y] != 0)
                    {
                        if (temp_depth[x, y] != 0) edge2[x, y] = temp_depth[x, y];
                        temp_depth[x, y] = 0;
                    }
                }
            }

        }

        private void down_shift(int down) // smoothes only cells with maxflow going into a cell. 
        {
            int x, y, p, inc;
            double[,] edge_temp;
            edge_temp = new Double[xmax + 1, ymax + 1];

            for (x = 1; x <= (xmax); x++)
            {
                inc = 1;

                while (cross_scan[x, inc] > 0)
                {
                    y = cross_scan[x, inc];
                    inc++;
                    if (water_depth[x, y] > water_depth_erosion_threshold)
                    {
                        edge_temp[x, y]=0;
                    }

                }
            }

            for (x = 1; x <= (xmax); x++)
            {
                inc = 1;

                while (cross_scan[x, inc] > 0)
                {
                    y = cross_scan[x, inc];
                    inc++;

                    double tot = 0;
                    int num = 0;

                    if (water_depth[x, y] > water_depth_erosion_threshold)
                    {
                        for (p = 1; p <= 8; p++)
                        {
                            if (max_flow[x, y, p] > 0)
                            {
                                tot += max_flow[x, y, p];
                                num++;
                            }
                        }
                        if (num > 0)
                        {
                            for (p = 1; p <= 8; p++)
                            {
                                if (max_flow[x, y, p] > 0)
                                {
                                    edge_temp[x + deltaX[p], y + deltaY[p]] += Tau[x, y] * (max_flow[x, y, p] / tot);
                                }
                            }
                        }



                    }

                }
            }

            for (x = 1; x <= (xmax); x++)
            {
                inc = 1;

                while (cross_scan[x, inc] > 0)
                {
                    y = cross_scan[x, inc];
                    inc++;
                    if (water_depth[x, y] > water_depth_erosion_threshold)
                    {
                        Tau[x, y] = edge_temp[x, y];
                    }

                }
            }

        }

        private void smooth_tau2(int radius) // smoothes only cells with maxflow going into a cell. 
        {
            int x, y, inc, tot = 0, x2, y2,dir;
            double temp_height = 0;

            for (x = 1; x < (xmax); x++)
            {
                inc = 1;

                while (cross_scan[x, inc] > 0)
                {
                    y = cross_scan[x, inc];
                    inc++;

                    temp_depth[x, y] = 0;
                    if (Tau[x, y] >= 0)
                    {
                        temp_height = Tau[x,y];
                        tot = 1;

                        for (dir = 1; dir <= 8; dir++)
                        {

                            x2 = x + deltaX[dir];
                            y2 = y + deltaY[dir];


                            // North
                            if (Tau[x2, y2] > 0 && deltaX[dir] == 0 && deltaY[dir] == -1)
                            {
                                if (calc_max_flow_direction_degrees(x2, y2) > 135 && calc_max_flow_direction_degrees(x2, y2) < 225)
                                {
                                    temp_height += Tau[x2, y2];
                                    tot++;
                                }
                            }

                            //NE
                            if (Tau[x2, y2] > 0 && deltaX[dir] == 1 && deltaY[dir] == -1)
                            {
                                if (calc_max_flow_direction_degrees(x2, y2) > 180 && calc_max_flow_direction_degrees(x2, y2) < 270)
                                {
                                    temp_height += Tau[x2, y2];
                                    tot++;
                                }
                            }

                            //E
                            if (Tau[x2, y2] > 0 && deltaX[dir] == 1 && deltaY[dir] == 0)
                            {
                                if (calc_max_flow_direction_degrees(x2, y2) > 225 && calc_max_flow_direction_degrees(x2, y2) < 315)
                                {
                                    temp_height += Tau[x2, y2];
                                    tot++;
                                }
                            }

                            //SE
                            if (Tau[x2, y2] > 0 && deltaX[dir] == 1 && deltaY[dir] == 1)
                            {
                                if (calc_max_flow_direction_degrees(x2, y2) > 270 && calc_max_flow_direction_degrees(x2, y2) < 360)
                                {
                                    temp_height += Tau[x2, y2];
                                    tot++;
                                }
                            }

                            //S
                            if (Tau[x2, y2] > 0 && deltaX[dir] == 0 && deltaY[dir] == 1)
                            {
                                if (calc_max_flow_direction_degrees(x2, y2) > 315 || calc_max_flow_direction_degrees(x2, y2) < 45)
                                {
                                    temp_height += Tau[x2, y2];
                                    tot++;
                                }
                            }

                            //SW
                            if (Tau[x2, y2] > 0 && deltaX[dir] == -1 && deltaY[dir] == 1)
                            {
                                if (calc_max_flow_direction_degrees(x2, y2) > 0 && calc_max_flow_direction_degrees(x2, y2) < 90)
                                {
                                    temp_height += Tau[x2, y2];
                                    tot++;
                                }
                            }

                            //W
                            if (Tau[x2, y2] > 0 && deltaX[dir] == -1 && deltaY[dir] == 0)
                            {
                                if (calc_max_flow_direction_degrees(x2, y2) > 45 && calc_max_flow_direction_degrees(x2, y2) < 135)
                                {
                                    temp_height += Tau[x2, y2];
                                    tot++;
                                }
                            }

                            //NW
                            if (Tau[x2, y2] > 0 && deltaX[dir] == -1 && deltaY[dir] == -1)
                            {
                                if (calc_max_flow_direction_degrees(x2, y2) > 90 && calc_max_flow_direction_degrees(x2, y2) < 180)
                                {
                                    temp_height += Tau[x2, y2];
                                    tot++;
                                }
                            }


                            
                           
                        }

                        if (tot > 1) temp_depth[x, y] = temp_height / tot; // makes sure dead end cells have no Tau

                    }

                }
            }

            for (x = 1; x <= (xmax); x++)
            {
                inc = 1;

                while (cross_scan[x, inc] > 0)
                {
                    y = cross_scan[x, inc];
                    inc++;
                    if (temp_depth[x, y] != 0)
                    {
                        if(temp_depth[x,y]!=0)Tau[x, y] = temp_depth[x, y];
                        temp_depth[x, y] = 0;
                    }
                }
            }

        }

        private double return_smoothed_water_height(int x, int y, int radius)
        {
            int tot = 0, x1, y1;
            double temp_height = 0;


            temp_height = 0;
            tot = 0;

            int tempxmin = -radius;
            int tempxmax = radius;
            int tempymin = -radius;
            int tempymax = radius;
            while (x + tempxmin <= 1) tempxmin++;
            while (x + tempxmax >= xmax) tempxmax--;
            while (y + tempymin <= 1) tempymin++;
            while (y + tempymax >= ymax) tempymax--;

            for (x1 = tempxmin; x1 <= tempxmax; x1++)
            {
                for (y1 = tempymin; y1 <= tempymax; y1++)
                {
                    if (water_depth[x+x1, y+y1] >= water_depth_erosion_threshold)
                    {
                        temp_height += water_depth[x+x1, y+y1] + elev[x+x1, y+y1];
                        tot++;
                    }
                }
            }


            if (tot > 0)return (temp_height / tot);
            else return 0;
        }



		int read_header()
		{
			string FILE_NAME;
			int z;
			string[] lineArray2;
			int sp;

			inputheader = new string[6];

			FILE_NAME = this.openfiletextbox.Text;
			if (!File.Exists(FILE_NAME)) 
			{
				MessageBox.Show("No such DEM data file..");
				return 0;
			}

			try
			{

				//read headers
				StreamReader sr = File.OpenText(FILE_NAME);
				for(z = 1; z <= 6; z++)
				{
					inputheader[z-1] = sr.ReadLine();
				}
				sr.Close();

				// get xmax, ymax and DX from input headers

				lineArray2 = inputheader[0].Split(new char[]{' '});
				sp = 1;
				while (lineArray2[sp] == "") sp++;
				xmax = int.Parse(lineArray2[sp]);

				lineArray2 = inputheader[1].Split(new char[]{' '});
				sp = 1;
				while (lineArray2[sp] == "") sp++;
				ymax = int.Parse(lineArray2[sp]);

                lineArray2 = inputheader[2].Split(new char[] { ' ' });
                sp = 1;
                while (lineArray2[sp] == "") sp++;
                xll = double.Parse(lineArray2[sp]);

                lineArray2 = inputheader[3].Split(new char[] { ' ' });
                sp = 1;
                while (lineArray2[sp] == "") sp++;
                yll = double.Parse(lineArray2[sp]);

				lineArray2 = inputheader[4].Split(new char[]{' '});
				sp = 1;
				while (lineArray2[sp] == "") sp++;
				DX = double.Parse(lineArray2[sp]);
                root = (Math.Sqrt(Math.Pow(DX, 2) + Math.Pow(DX, 2))); // imp added 11/07
                fiveroot = (Math.Sqrt(Math.Pow(DX, 2) + Math.Pow(DX, 2))); // imp added 11/07

				
			}			
			catch(Exception ex)
			{
				MessageBox.Show("Theres a problem with the header in the DEM file");
			}

			return 1;
		}


		void load_data()
		{
			int x,y=1,z,xcounter,x1=0,y1=0,n;			
			String input;
			double tttt=0.00;
			
			// load dem

			string FILE_NAME = this.openfiletextbox.Text;
			if (!File.Exists(FILE_NAME)) 
			{
				MessageBox.Show("No such DEM data file..");
				return;
			}

			StreamReader sr = File.OpenText(FILE_NAME);

			//read headers
			for(z=1;z<=6;z++)
			{
				input=sr.ReadLine();
			}
			y=1;

			while ((input=sr.ReadLine())!=null) 
			{
				string[] lineArray;
				lineArray = input.Split(new char[]{' '});
				xcounter=1;
				for (x = 0; x<=(lineArray.Length-1); x++)
				{
					
					if(lineArray[x]!=""&&xcounter<=xmax)
					{
						tttt=double.Parse(lineArray[x]);
						elev[xcounter,y]=tttt;
						//if(xcounter==1)elev[xcounter,y]+=4;
						init_elevs[xcounter,y]=elev[xcounter,y];
						xcounter++;
					}
				}
				y++;

			}
			sr.Close();


			if(this.graindataloadbox.Text!="null")
			{
				FILE_NAME = this.graindataloadbox.Text;
				if(FILE_NAME!="null")
				{
					StreamReader gr = File.OpenText(FILE_NAME);
					y=1;
					grain_array_tot=0;
					while ((input=gr.ReadLine())!=null) 
					{
						string[] lineArray;
						lineArray = input.Split(new char[]{' '});
						xcounter=1;
						grain_array_tot++;
						for (x = 0; x<=(lineArray.Length-1); x++)
						{
							if(lineArray[x]!="")
							{
								if(xcounter==1)x1=int.Parse(lineArray[x]);
								if(xcounter==2)y1=int.Parse(lineArray[x]);
                                if (xcounter == 3) index[x1, y1] = grain_array_tot;// int.Parse(lineArray[x]);
								for(n=0;n<=G_MAX;n++)
								{
									if(xcounter==4+n)
									{
										grain[grain_array_tot,n,0]=double.Parse(lineArray[x]);
									}
								}

								for(z=0;z<=9;z++)
								{
									for(n=0;n<=(G_MAX-2);n++)
									{
										if(xcounter==(4+G_MAX+n+1)+((z)*9))
										{
											strata[grain_array_tot,z,n,0]=double.Parse(lineArray[x]);
										}
									}
								}

								xcounter++;
							}
						}
					}
					gr.Close();
				}
			}
			

			FILE_NAME = this.bedrockbox.Text;
			if(FILE_NAME!="null")
			{

				StreamReader gr = File.OpenText(FILE_NAME);
				//read headers
				for(z=1;z<=6;z++)
				{
					input=gr.ReadLine();
				}
				y=1;

				while ((input=gr.ReadLine())!=null) 
				{
                    string[] lineArray;
                    lineArray = input.Split(new char[] { ' ' });
                    xcounter = 1;
                    for (x = 0; x <= (lineArray.Length - 1); x++)
                    {

                        if (lineArray[x] != "" && xcounter <= xmax)
                        {
                            tttt = double.Parse(lineArray[x]);
                            bedrock[xcounter, y] = tttt;
                            xcounter++;
                        }
                    }
                    y++;

				}
				gr.Close();
			}


            try
            {


                FILE_NAME = this.raindataloadbox.Text;
                if (FILE_NAME != "null")
                {
                    input_type_flag = 1;
                    int inc = 1;
                    //				Random R =new Random();
                    StreamReader gr = File.OpenText(FILE_NAME);
                    while ((input = gr.ReadLine()) != null)
                    {

                        hourly_rain_data[inc] = double.Parse(input);

                        //					// adding random rain bit.
                        //
                        //					if(hourly_rain_data[inc]>0)
                        //					{
                        //						hourly_rain_data[inc]=(R.Next(1,30));
                        //					}

                        //Console.WriteLine(hourly_rain_data[inc]);
                        //					string[] lineArray;
                        //					lineArray = input.Split(new char[]{' '});
                        //					for (x = 0; x<(lineArray.Length-1); x++)
                        //					{
                        //						if(lineArray[x]!="")
                        //						{
                        //							hourly_rain_data[inc]=double.Parse(lineArray[x]);
                        //							Console.WriteLine("loading raindata \n");
                        //							Console.WriteLine(lineArray[x]);
                        //						}
                        //					}
                        inc++;
                    }
                    gr.Close();
                }

            }

            catch (Exception ex)
            {
                MessageBox.Show("There was some type of error loading the input data from the rain data file CAESAR may continue to function but may not be correct");
            }

            try
            {
                FILE_NAME = this.mvalueloadbox.Text;
                if (FILE_NAME != "null")
                {
                    variable_m_value_flag = 1; // sets flag for variable M value to 1 (true)
                    int inc = 1;
                    StreamReader gr = File.OpenText(FILE_NAME);
                    while ((input = gr.ReadLine()) != null)
                    {
                        hourly_m_value[inc] = double.Parse(input);
                        inc++;
                    }
                    gr.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was some type of error loading the m value data from the m value data file CAESAR may continue to function but may not be correct");
            }
            try
            {
                //single mine input "supermine", up to nine grainsizes
                if (mine_checkBox.Checked)
                {
                    mine_inpoints[0, 0] = Convert.ToInt32(mineX_textBox.Text); //input x coordrinate 
                    mine_inpoints[0, 1] = Convert.ToInt32(mineY_textBox.Text); //input y coordinate
                    FILE_NAME = this.mine_input_textBox.Text;
                    if (FILE_NAME != "null")
                    {
                        int lineinc = 1;//number of hours of contamination
                        StreamReader gr = File.OpenText(FILE_NAME);
                        while ((input = gr.ReadLine()) != null)
                        {
                            int inc = 1;//grainsizes 1-9, only two necessary now

                            string[] lineArray;
                            lineArray = input.Split(new char[] { ' ' });
                            for (x = 1; x < (lineArray.Length); x++)
                            {
                                if (lineArray[x] != "")
                                {
                                    if (inc == 1) mineinput[lineinc, inc] = double.Parse(lineArray[x]);//grainsize1
                                    if (inc == 2) mineinput[lineinc, inc] = double.Parse(lineArray[x]);//grainsize2
                                    //if (inc == 3) mineinput[lineinc, inc] = double.Parse(lineArray[x]);//grainsize3
                                    //if (inc == 4) mineinput[lineinc, inc] = double.Parse(lineArray[x]);//grainsize4
                                    //if (inc == 5) mineinput[lineinc, inc] = double.Parse(lineArray[x]);//grainsize5
                                    //if (inc == 6) mineinput[lineinc, inc] = double.Parse(lineArray[x]);//grainsize6
                                    //if (inc == 7) mineinput[lineinc, inc] = double.Parse(lineArray[x]);//grainsize7
                                    //if (inc == 8) mineinput[lineinc, inc] = double.Parse(lineArray[x]);//grainsize8
                                    //if (inc == 9) mineinput[lineinc, inc] = double.Parse(lineArray[x]);//grainsize9
                                    inc++;
                                }
                            }
                            lineinc++;
                        }
                        gr.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was some type of error loading the contaminant input CAESAR may continue to function but may not be correct");
            }
            int tempx=0;

			try
			{
				if(inbox1.Checked)
				{
					FILE_NAME = this.infile1.Text;
					if(FILE_NAME!="null")
					{
						input_type_flag=0;
						StreamReader gr = File.OpenText(FILE_NAME);
						while ((input=gr.ReadLine())!=null) 
						{
							string[] lineArray;
							lineArray = input.Split(new char[]{' '});
							for (x = 0; x<=(lineArray.Length-1); x++)
							{
								if(lineArray[x]!="")
								{
									tempx=int.Parse(lineArray[0]);
									inputfile[0,tempx-(((int)(init_cycle))/input_time_step),x]=double.Parse(lineArray[x]);
								}
							}
						}
						gr.Close();
					}

				}

				if(inbox2.Checked)
				{
					FILE_NAME = this.infile2.Text;
					if(FILE_NAME!="null")
					{
						input_type_flag=0;
						StreamReader gr = File.OpenText(FILE_NAME);
						while ((input=gr.ReadLine())!=null) 
						{
							string[] lineArray;
							lineArray = input.Split(new char[]{' '});
							for (x = 0; x<=(lineArray.Length-1); x++)
							{
								if(lineArray[x]!="")
								{
									tempx=int.Parse(lineArray[0]);
									inputfile[1,tempx-(((int)(init_cycle))/input_time_step),x]=double.Parse(lineArray[x]);
								}
							}
						}
						gr.Close();
					}
				}

				if(inbox3.Checked)
				{
					FILE_NAME = this.infile3.Text;
					if(FILE_NAME!="null")
					{
						input_type_flag=0;
						StreamReader gr = File.OpenText(FILE_NAME);
						while ((input=gr.ReadLine())!=null) 
						{
							string[] lineArray;
							lineArray = input.Split(new char[]{' '});
							for (x = 0; x<=(lineArray.Length-1); x++)
							{
								if(lineArray[x]!="")
								{
									tempx=int.Parse(lineArray[0]);
									inputfile[2,tempx-(((int)(init_cycle))/input_time_step),x]=double.Parse(lineArray[x]);
								}
							}
						}
						gr.Close();
					}
				}

				if(inbox4.Checked)
				{
					FILE_NAME = this.infile4.Text;
					if(FILE_NAME!="null")
					{
						input_type_flag=0;
						StreamReader gr = File.OpenText(FILE_NAME);
						while ((input=gr.ReadLine())!=null) 
						{
							string[] lineArray;
							lineArray = input.Split(new char[]{' '});
							for (x = 0; x<=(lineArray.Length-1); x++)
							{
								if(lineArray[x]!="")
								{
									tempx=int.Parse(lineArray[0]);
									inputfile[3,tempx-(((int)(init_cycle))/input_time_step),x]=double.Parse(lineArray[x]);
								}
							}
						}
						gr.Close();
					}
				}

				if(inbox5.Checked)
				{
					FILE_NAME = this.infile5.Text;
					if(FILE_NAME!="null")
					{
						input_type_flag=0;
						StreamReader gr = File.OpenText(FILE_NAME);
						while ((input=gr.ReadLine())!=null) 
						{
							string[] lineArray;
							lineArray = input.Split(new char[]{' '});
							for (x = 0; x<=(lineArray.Length-1); x++)
							{
								if(lineArray[x]!="")
								{
									tempx=int.Parse(lineArray[0]);
									inputfile[4,tempx-(((int)(init_cycle))/input_time_step),x]=double.Parse(lineArray[x]);
								}
							}
						}
						gr.Close();
					}
				}

				if(inbox6.Checked)
				{
					FILE_NAME = this.infile6.Text;
					if(FILE_NAME!="null")
					{
						input_type_flag=0;
						StreamReader gr = File.OpenText(FILE_NAME);
						while ((input=gr.ReadLine())!=null) 
						{
							string[] lineArray;
							lineArray = input.Split(new char[]{' '});
							for (x = 0; x<=(lineArray.Length-1); x++)
							{
								if(lineArray[x]!="")
								{
									tempx=int.Parse(lineArray[0]);
									inputfile[5,tempx-(((int)(init_cycle))/input_time_step),x]=double.Parse(lineArray[x]);
								}
							}
						}
						gr.Close();
					}
				}

				if(inbox7.Checked)
				{
					FILE_NAME = this.infile7.Text;
					if(FILE_NAME!="null")
					{
						input_type_flag=0;
						StreamReader gr = File.OpenText(FILE_NAME);
						while ((input=gr.ReadLine())!=null) 
						{
							string[] lineArray;
							lineArray = input.Split(new char[]{' '});
							for (x = 0; x<=(lineArray.Length-1); x++)
							{
								if(lineArray[x]!="")
								{
									tempx=int.Parse(lineArray[0]);
									inputfile[6,tempx-(((int)(init_cycle))/input_time_step),x]=double.Parse(lineArray[x]);
								}
							}
						}
						gr.Close();
					}
				}

				if(inbox8.Checked)
				{
					FILE_NAME = this.infile8.Text;
					if(FILE_NAME!="null")
					{
						input_type_flag=0;
						StreamReader gr = File.OpenText(FILE_NAME);
						while ((input=gr.ReadLine())!=null) 
						{
							string[] lineArray;
							lineArray = input.Split(new char[]{' '});
							for (x = 0; x<=(lineArray.Length-1); x++)
							{
								if(lineArray[x]!="")
								{
									tempx=int.Parse(lineArray[0]);
									inputfile[7,tempx-(((int)(init_cycle))/input_time_step),x]=double.Parse(lineArray[x]);
								}
							}
						}
						gr.Close();
					}
				}
			}


			catch(Exception ex)
			{
				MessageBox.Show("There was some type of error loading the input data from "+FILE_NAME+" at line "+Convert.ToString(tempx)+", CAESAR will continue to function but may not be correct");
			}

			FILE_NAME = this.tracerfile.Text;
			if(FILE_NAME!="null")
			{
				int lineinc=1;
				StreamReader gr = File.OpenText(FILE_NAME);
				while ((input=gr.ReadLine())!=null) 
				{
					int inc=1;
					string[] lineArray;
					lineArray = input.Split(new char[]{' '});
					for (x = 0; x<=(lineArray.Length-1); x++)
					{
						if(lineArray[x]!="")
						{
							if(inc==1)tracerinput[lineinc,inc]=double.Parse(lineArray[x]);
							if(inc==2)tracerinput[lineinc,inc]=double.Parse(lineArray[x]);
							if(inc==3)tracerinput[lineinc,inc]=double.Parse(lineArray[x]);
							if(inc==4)tracerinput[lineinc,inc]=double.Parse(lineArray[x]);
							inc++;
						}
					}
					lineinc++;

				}
				gr.Close();
				tot_number_of_tracer_points=lineinc;
			}

			FILE_NAME = this.tracerhydrofile.Text;
			if(FILE_NAME!="null")
			{
				int lineinc=1;
				
				StreamReader gr = File.OpenText(FILE_NAME);
				while ((input=gr.ReadLine())!=null) 
				{
					int temp1=0;
					int inc=1;
					string[] lineArray;
					lineArray = input.Split(new char[]{' '});
					for (x = 0; x<=(lineArray.Length-1); x++)
					{
					if(lineArray[x]!="")
						{
							if(inc==1)temp1=int.Parse(lineArray[x]);
							if(inc==2)tracerhydrograph[temp1,0]=double.Parse(lineArray[x]);
							if(inc==3)tracerhydrograph[temp1,1]=double.Parse(lineArray[x]);
							inc++;
						}
					}
					lineinc++;

				}
				gr.Close();
			}

			if(this.tracergrainbox.Text!="null"&&TRACERS>1)
			{
				FILE_NAME = this.graindataloadbox.Text;
				if(FILE_NAME!="null")
				{
					StreamReader gr = File.OpenText(FILE_NAME);
					y=1;
					grain_array_tot=0;
					while ((input=gr.ReadLine())!=null) 
					{
						string[] lineArray;
						lineArray = input.Split(new char[]{' '});
						xcounter=1;
						grain_array_tot++;
						for (x = 0; x<=(lineArray.Length-1); x++)
						{
							if(lineArray[x]!="")
							{
								if(xcounter==1)x1=int.Parse(lineArray[x]);
								if(xcounter==2)y1=int.Parse(lineArray[x]);
								if(xcounter==3)index[x1,y1]=grain_array_tot;
								for(n=0;n<=G_MAX;n++)
								{
									if(xcounter==4+n)
									{
										grain[grain_array_tot,n,1]=double.Parse(lineArray[x]);
									}
								}

								for(z=0;z<=9;z++)
								{
									for(n=0;n<=(G_MAX-2);n++)
									{
										if(xcounter==(4+G_MAX+n+1)+((z)*9))
										{
											strata[grain_array_tot,z,n,1]=double.Parse(lineArray[x]);
										}
									}
								}
													

								xcounter++;
							}
						}
					}
					gr.Close();
				}
			}

			// MessageBox.Show(Convert.ToString(input_type_flag));
			this.InfoStatusPanel.Text="Loaded: type = " + input_type_flag.ToString();        // MJ 02/02/05			

		}


		void save_data(int typeflag, double tempcycle)
		{
			int x,y,n,z,inc,  p,nn;
			double ztemp;
			string FILENAME = "waterdepth.dat";

			if(uniquefilecheck.Checked==false)tempcycle=0;

			// turns file name into days from mins.
			tempcycle=tempcycle/1440;


			if(typeflag==1&&tempcycle==0) FILENAME = "waterdepth.txt";
			if(typeflag==2&&tempcycle==0) FILENAME = "elevdiff.txt";
			if(typeflag==3&&tempcycle==0) FILENAME = "elev.txt";
            if(typeflag==4&&tempcycle==0) FILENAME = "grain.txt";
			if(typeflag==5&&TRACERS>1&&tempcycle==0) FILENAME = "tracergrain.txt";
            if (typeflag == 6 && (TRACERS==2||mine_checkBox.Checked ==true) && tempcycle == 0) FILENAME = "tracer1.txt";
            if (typeflag == 7 && (TRACERS == 2 || mine_checkBox.Checked == true) && tempcycle == 0) FILENAME = "tracer2.txt";
            if (typeflag == 8 && (TRACERS == 2 || mine_checkBox.Checked == true) && tempcycle == 0) FILENAME = "tracer3.txt";
            if (typeflag == 9 && (TRACERS == 2 || mine_checkBox.Checked == true) && tempcycle == 0) FILENAME = "tracer4.txt";
            if (typeflag == 10 && (TRACERS == 2 || mine_checkBox.Checked == true) && tempcycle == 0) FILENAME = "tracer5.txt";
            if (typeflag == 11 && (TRACERS == 2 || mine_checkBox.Checked == true) && tempcycle == 0) FILENAME = "tracer6.txt";
            if (typeflag == 12 && (TRACERS == 2 || mine_checkBox.Checked == true) && tempcycle == 0) FILENAME = "tracer7.txt";
            if (typeflag == 13 && (TRACERS == 2 || mine_checkBox.Checked == true) && tempcycle == 0) FILENAME = "tracer8.txt";
            if (typeflag == 14 && (TRACERS == 2 || mine_checkBox.Checked == true) && tempcycle == 0) FILENAME = "tracer9.txt";
            if (typeflag == 15 && tempcycle == 0) FILENAME = "d50top.txt";
            if (typeflag == 16 && tempcycle == 0) FILENAME = "velocity.txt";			// <JOE 20050605>
            if (typeflag == 17 && tempcycle == 0) FILENAME = "velocity_vectors.txt";	// <JOE 20050605>

			if(typeflag==1&&tempcycle>0) FILENAME = "waterdepth.dat"+"."+Convert.ToString(Convert.ToInt64(tempcycle));
			if(typeflag==2&&tempcycle>0) FILENAME = "elevdiff.dat"+"."+Convert.ToString(Convert.ToInt64(tempcycle));
			if(typeflag==3&&tempcycle>0) FILENAME = "elev.dat"+"."+Convert.ToString(Convert.ToInt64(tempcycle));
			if(typeflag==4&&tempcycle>0) FILENAME = "grain.dat"+"."+Convert.ToString(Convert.ToInt64(tempcycle));
			if(typeflag==5&&TRACERS>1&&tempcycle>0) FILENAME = "tracergrain.dat"+"."+Convert.ToString(Convert.ToInt64(tempcycle));
			if(typeflag==6&&TRACERS>1&&tempcycle>0) FILENAME = "tracer1.dat"+"."+Convert.ToString(Convert.ToInt64(tempcycle));
			if(typeflag==7&&TRACERS>1&&tempcycle>0) FILENAME = "tracer2.dat"+"."+Convert.ToString(Convert.ToInt64(tempcycle));
			if(typeflag==8&&TRACERS>1&&tempcycle>0) FILENAME = "tracer3.dat"+"."+Convert.ToString(Convert.ToInt64(tempcycle));
			if(typeflag==9&&TRACERS>1&&tempcycle>0) FILENAME = "tracer4.dat"+"."+Convert.ToString(Convert.ToInt64(tempcycle));
			if(typeflag==10&&TRACERS>1&&tempcycle>0) FILENAME = "tracer5.dat"+"."+Convert.ToString(Convert.ToInt64(tempcycle));
			if(typeflag==11&&TRACERS>1&&tempcycle>0) FILENAME = "tracer6.dat"+"."+Convert.ToString(Convert.ToInt64(tempcycle));
			if(typeflag==12&&TRACERS>1&&tempcycle>0) FILENAME = "tracer7.dat"+"."+Convert.ToString(Convert.ToInt64(tempcycle));
			if(typeflag==13&&TRACERS>1&&tempcycle>0) FILENAME = "tracer8.dat"+"."+Convert.ToString(Convert.ToInt64(tempcycle));
			if(typeflag==14&&TRACERS>1&&tempcycle>0) FILENAME = "tracer9.dat"+"."+Convert.ToString(Convert.ToInt64(tempcycle));
			if(typeflag==15&&tempcycle>0) FILENAME = "d50top.dat"+"."+Convert.ToString(Convert.ToInt64(tempcycle));
			if(typeflag==16&&tempcycle>0) FILENAME = "velocity.dat"+"."+Convert.ToString(Convert.ToInt64(tempcycle));			// <JOE 20050605>
			if(typeflag==17&&tempcycle>0) FILENAME = "velocity_vectors.dat"+"."+Convert.ToString(Convert.ToInt64(tempcycle));	// <JOE 20050605>


			if(typeflag>=1&&typeflag<4)
			{
				
				using (StreamWriter sw = new StreamWriter(FILENAME)) 
				{
					sw.Write("ncols         "+xmax);
					sw.Write("\n");
					sw.Write("nrows         "+ymax);
					sw.Write("\n");

					for (nn=2; nn<=5; nn++)
					{
						sw.Write(inputheader[nn]);sw.Write("\n");
					}

					for(y=1;y<=ymax;y++)
					{
						for(x=1;x<=xmax;x++)
						{
							if(typeflag==1)
							{
								if(water_depth[x,y]>0)
								{
									sw.Write(water_depth[x,y]);
                                    
									sw.Write(" ");
								}
								else
								{
									sw.Write("-9999.0"); 
									sw.Write(" ");
								}
							}

							if(typeflag==2)
							{
								sw.Write(init_elevs[x,y]-elev[x,y]);
								sw.Write(" ");
							}
							if(typeflag==3)
							{
								sw.Write(elev[x,y]);
								sw.Write(" ");
							}
						}
						sw.Write("\n");
					}
					

				}
				
			}

			if(typeflag==4)
			{
				
				using (StreamWriter sw = new StreamWriter(FILENAME)) 
				{
					for (y=1;y<=ymax;y++)
					{
						for(x=1;x<=xmax;x++)
						{


							if(index[x,y]!=-9999)
							{
								sw.Write(x);sw.Write(" ");sw.Write(y);sw.Write(" ");sw.Write(index[x,y]);sw.Write(" ");
								for(inc=0;inc<=G_MAX;inc++)
								{
									sw.Write(grain[index[x,y],inc,0]);sw.Write(" ");
								}						
														
								for(z=0;z<=9;z++)
								{
									for(inc=0;inc<=(G_MAX-2);inc++)
									{
										sw.Write(strata[index[x,y],z,inc,0]);sw.Write(" ");
									}
								}
								sw.Write("\n");
							}
						}
					}
				}
			}


			if(typeflag==5&&TRACERS>1)
			{
				
				using (StreamWriter sw = new StreamWriter(FILENAME)) 
				{
					for (y=1;y<=ymax;y++)
					{
						for(x=1;x<=xmax;x++)
						{
							if(index[x,y]!=-9999)
							{
								sw.Write(x);sw.Write(" ");sw.Write(y);sw.Write(" ");sw.Write(index[x,y]);sw.Write(" ");
								for(inc=0;inc<=G_MAX;inc++)
								{
									sw.Write(grain[index[x,y],inc,1]);sw.Write(" ");
								}						
							
								for(z=0;z<=9;z++)
								{
									for(inc=0;inc<=(G_MAX-2);inc++)
									{
										sw.Write(strata[index[x,y],z,inc,1]);sw.Write(" ");
									}
								}
								sw.Write("\n");
							}
						}
					}
				}

			}


			if(typeflag==6&&(TRACERS>1||mine_checkBox.Checked == true))
			{
				
				using (StreamWriter sw = new StreamWriter(FILENAME)) 
				{
					for (nn=0; nn<=5; nn++)
					{
						sw.Write(inputheader[nn]);sw.Write("\n");
					}

					for(y=1;y<=ymax;y++)
					{
						for(x=1;x<=xmax;x++)
						{
							if(index[x,y]!=-9999)
							{
								ztemp=0;
								for(n=1;n<G_MAX;n++)
								{
									ztemp+=(grain[index[x,y],n,1]);
								}

								sw.Write(ztemp);sw.Write(" ");
							}
							else
							{
								sw.Write("-9999.0 ");
							}
						}
						sw.Write("\n");
					}

				}
			}

			for(p=7;p<=14;p++)
			{
                if (typeflag == p && (TRACERS > 1 || mine_checkBox.Checked == true))
				{
				
					using (StreamWriter sw = new StreamWriter(FILENAME)) 
					{
					for (nn=0; nn<=5; nn++)
					{
						sw.Write(inputheader[nn]);sw.Write("\n");
					}

						for(y=1;y<=ymax;y++)
						{
							for(x=1;x<=xmax;x++)
							{
								if(index[x,y]!=-9999)
								{
									ztemp=0.0;
									for(n=1;n<=(G_MAX-2);n++)
									{
										ztemp+=(strata[index[x,y],p-7,n,1]);
									}
									sw.Write(ztemp);sw.Write(" ");
								}
								else
								{
									sw.Write("-9999.0 ");
								}
							}
							sw.Write("\n");
						}

					}
				}
			}

			if(typeflag==15)
			{
				
				using (StreamWriter sw = new StreamWriter(FILENAME)) 
				{
					for (nn=0; nn<=5; nn++)
					{
						sw.Write(inputheader[nn]);sw.Write("\n");
					}

					for(y=1;y<=ymax;y++)
					{
						for(x=1;x<=xmax;x++)
						{
							if(index[x,y] == -9999)
							{
								sw.Write("-9999.0");
								sw.Write(" ");
							}
							else
							{
								sw.Write(d50(index[x,y]));
								sw.Write(" ");
							}
						}
						sw.Write("\n");
					}

				}
			}

			if(typeflag==16)   // <JOE 20050605> Write velocity to a file
			{
				
				using (StreamWriter sw = new StreamWriter(FILENAME)) 
				{
					for (nn=0; nn<=5; nn++)
					{
						sw.Write(inputheader[nn]);sw.Write("\n");
					}

					for(y=1;y<=ymax;y++)
					{
						for(x=1;x<=xmax;x++)
						{
							if(index[x,y] == -9999)
							{
								sw.Write("-9999.0");
								sw.Write(" ");
							}
							else
							{
								sw.Write("0");
								sw.Write(" ");
							}
						}
						sw.Write("\n");
					}

				}
			}

			if(typeflag==17)   // <JOE 20050605> Write soil_saturation to a file
			{
				
				using (StreamWriter sw = new StreamWriter(FILENAME)) 
				{
                    //for (nn=0; nn<=5; nn++)
                    //{
                    //    sw.Write(inputheader[nn]);sw.Write("\n");
                    //}

                    sw.Write("x,y,rot,vel");
                    sw.Write("\n");

					for(y=1;y<=ymax;y++)
					{
						for(x=1;x<=xmax;x++)
						{
                            if (water_depth[x, y] > 0)
                            {
                                sw.Write((xll+(x*DX))+(DX/2)); sw.Write(","); sw.Write(((yll+((ymax-y)*DX)))); sw.Write(","); sw.Write(calc_max_flow_direction_degrees(x, y)); sw.Write(","); sw.Write(max_flow[x,y,0]/(DX*water_depth[x,y]));
                                sw.Write("\n");	
                            }
                            	
						}
						
					}

				}
			}


		}


		private void initialise()
		{

			this.InfoStatusPanel.Text="Initialising..";			// MJ 14/01/05

			if (overrideheaderBox.Checked == true)
			{
				// input xmax, ymax and DX from text boxes  
			xmax=int.Parse(xtextbox.Text);
			ymax=int.Parse(ytextbox.Text);
				DX=double.Parse(dxbox.Text);             // now in read_header()  MJ 24/05/05
			}

            // Create a drawing surface with the same dimensions DEM
            m_objDrawingSurface = new Bitmap(xmax*graphics_scale,
               ymax*graphics_scale, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            save_interval2 = System.Convert.ToInt32(googAnimationSaveInterval.Text);
            save_time2 = save_interval2;
			if(tracerbox.Checked==true)TRACERS=2;
            if (mine_checkBox.Checked == true) TRACERS = 2;
			init_route_number_of_scans=int.Parse(initscansbox.Text);
			ERODEFACTOR=double.Parse(erodefactorbox.Text);
			root=(Math.Sqrt(Math.Pow(DX,2)+Math.Pow(DX,2)));
			fiveroot=(Math.Sqrt(Math.Pow(DX,2)+Math.Pow(DX,2)));
			LIMIT=int.Parse(limitbox.Text);
			MIN_Q=double.Parse(minqbox.Text);
			CREEP_RATE=double.Parse(creepratebox.Text);
            SOIL_RATE = double.Parse(soil_ratebox.Text);
			lateral_constant=double.Parse(lateralratebox.Text);
			maxiterations=int.Parse(itermaxbox.Text);
			cycle=double.Parse(textBox1.Text)*60;
			init_cycle=cycle;
			maxcycle=int.Parse(cyclemaxbox.Text);
			failureangle=double.Parse(slopebox.Text);
			smoothradius=int.Parse(smoothbox.Text);
			saveinterval=double.Parse(saveintervalbox.Text);
			M=double.Parse(mvaluebox.Text);
			grow_grass_time=double.Parse(grasstextbox.Text);
			output_file_save_interval=int.Parse(outputfilesaveintervalbox.Text);
			tx=output_file_save_interval;
			min_time_step=double.Parse(mintimestepbox.Text);
			active=double.Parse(activebox.Text);
			k_evap=double.Parse(k_evapBox.Text);  // added MJ 15/03/05
			vegTauCrit=double.Parse(vegTauCritBox.Text);  // added MJ 10/05/05
            cross_stream_grad_factor = 0;
            max_time_step = int.Parse(max_time_step_Box.Text);	
            water_depth_erosion_threshold = double.Parse(Q2box.Text);
            if (googleAnimationCheckbox.Checked)
            {
                startDate = googleBeginDate.Text;
                googleTime = System.DateTime.Parse(googleBeginDate.Text);
            }
			d1=double.Parse(g1box.Text);
			d2=double.Parse(g2box.Text);
			d3=double.Parse(g3box.Text);
			d4=double.Parse(g4box.Text);
			d5=double.Parse(g5box.Text);
			d6=double.Parse(g6box.Text);
			d7=double.Parse(g7box.Text);
			d8=double.Parse(g8box.Text);
			d9=double.Parse(g9box.Text);

			d1prop=double.Parse(gp1box.Text);
			d2prop=double.Parse(gp2box.Text);
			d3prop=double.Parse(gp3box.Text);
			d4prop=double.Parse(gp4box.Text);
			d5prop=double.Parse(gp5box.Text);
			d6prop=double.Parse(gp6box.Text);
			d7prop=double.Parse(gp7box.Text);
			d8prop=double.Parse(gp8box.Text);
			d9prop=double.Parse(gp9box.Text);

			// new array to deal with suspended sediment   MJ 09/05/05
			isSuspended = new bool[G_MAX+1];
			isSuspended[1] = suspGS1box.Checked;
			isSuspended[2] = suspGS2box.Checked;
			isSuspended[3] = suspGS3box.Checked;
			isSuspended[4] = suspGS4box.Checked;
			isSuspended[5] = suspGS5box.Checked;
			isSuspended[6] = suspGS6box.Checked;
			isSuspended[7] = suspGS7box.Checked;
			isSuspended[8] = suspGS8box.Checked;
			isSuspended[9] = suspGS9box.Checked;

			// new array to deal with suspended sediment   MJ 09/05/05
			fallVelocity = new double[G_MAX+1];
			fallVelocity[1] = double.Parse(fallGS1box.Text);
			fallVelocity[2] = double.Parse(fallGS2box.Text);
			fallVelocity[3] = double.Parse(fallGS3box.Text);
			fallVelocity[4] = double.Parse(fallGS4box.Text);
			fallVelocity[5] = double.Parse(fallGS5box.Text);
			fallVelocity[6] = double.Parse(fallGS6box.Text);
			fallVelocity[7] = double.Parse(fallGS7box.Text);
			fallVelocity[8] = double.Parse(fallGS8box.Text);
			fallVelocity[9] = double.Parse(fallGS9box.Text);


			input_time_step=int.Parse(input_time_step_box.Text);
			init_discharge=double.Parse(textBox2.Text);
			SW=int.Parse(textBox3.Text);

			inpoints=new int[10,2];
            mine_inpoints = new int[1, 2];
			// then intiailise the main arrays
			if(inbox1.Checked)
			{
				number_of_points++;
				inpoints[0,0]=int.Parse(xbox1.Text);
				inpoints[0,1]=int.Parse(ybox1.Text);
			}

			if(inbox2.Checked)
			{
				number_of_points++;
				inpoints[1,0]=int.Parse(xbox2.Text);
				inpoints[1,1]=int.Parse(ybox2.Text);
			}

			if(inbox3.Checked)
			{
				number_of_points++;
				inpoints[2,0]=int.Parse(xbox3.Text);
				inpoints[2,1]=int.Parse(ybox3.Text);
			}

			if(inbox4.Checked)
			{
				number_of_points++;
				inpoints[3,0]=int.Parse(xbox4.Text);
				inpoints[3,1]=int.Parse(ybox4.Text);
			}

			if(inbox5.Checked)
			{
				number_of_points++;
				inpoints[4,0]=int.Parse(xbox5.Text);
				inpoints[4,1]=int.Parse(ybox5.Text);
			}

			if(inbox6.Checked)
			{
				number_of_points++;
				inpoints[5,0]=int.Parse(xbox6.Text);
				inpoints[5,1]=int.Parse(ybox6.Text);
			}

			if(inbox7.Checked)
			{
				number_of_points++;
				inpoints[6,0]=int.Parse(xbox7.Text);
				inpoints[6,1]=int.Parse(ybox7.Text);
			}

			if(inbox8.Checked)
			{
				number_of_points++;
				inpoints[7,0]=int.Parse(xbox8.Text);
				inpoints[7,1]=int.Parse(ybox8.Text);
			}

			inputfile = new double[number_of_points,((maxcycle-((int)(cycle/60)))/(input_time_step/60))+1000,16];
            mineinput = new double[(maxcycle - ((int)(cycle / 60))) + 1000, 3];
			elev = new double[xmax+2,ymax+2];
			discharge = new double[xmax+2,ymax+2];
			water_depth = new double[xmax+2,ymax+2];
			water_depth2 = new double[xmax+2,ymax+2];
			temp_depth = new double[xmax+2,ymax+2];
			area = new double[xmax+2,ymax+2];
			index = new int[xmax+2,ymax+2];
			bedrock = new double[xmax+2,ymax+2];
			tempcreep = new double[xmax+2,ymax+2];
			init_elevs = new double[xmax+2,ymax+2];
			max_flow= new double[xmax+2,ymax+2,9];
			flow_dir=new int[xmax+2,ymax+2,2];
			strata=new double[((xmax+2)*(ymax+2))/LIMIT,10,G_MAX+1,TRACERS];
			grain=new double[((2+xmax)*(ymax+2))/LIMIT,G_MAX+1,TRACERS];
			temp=new double[((xmax+2)*(ymax+2))/LIMIT,G_MAX+1,TRACERS];
			dist=new double[9,G_MAX+1];
			extra_elev=new double[(xmax*ymax)/LIMIT];
			cross_scan=new int[xmax+2,ymax+2];
			down_scan=new int[ymax+2,xmax+2];
			hourly_rain_data=new double[(maxcycle-((int)(cycle/60)))+1000];
            hourly_m_value = new double[(maxcycle-((int)(cycle/60)))+1000];
			bedrock_depth=new double[ymax+5];
			climate_data=new double[10001,3];
			minesites=new int[1001,2];
			temp_grain=new double[G_MAX+1];
			veg=new Double[xmax+1,ymax+1,4]; // 0 is elevation, 1 is level of veg cover (ranging from 0 to 1)
			edge=new double[xmax+1,ymax+1]; // TJC 27/1/05
			edge2=new double[xmax+1,ymax+1]; // TJC 27/4/06
			lat_vol = new double[xmax+2,ymax+2]; // tjc 
			Tau = new double[xmax+2,ymax+2];
			old_water_depth = new double[xmax+2,ymax+2];
			width = new int[xmax+2,ymax+2];
			pool_depth = new double[xmax+2,ymax+2];
			qcounter = new int[xmax+2,ymax+2];
			left_in = new double[xmax+2,ymax+2];
			left_out = new double[xmax+2,ymax+2];
			right_in= new double[xmax+2,ymax+2];
			right_out = new double[xmax+2,ymax+2];
			up_in= new double[xmax+2,ymax+2];
			up_out = new double[xmax+2,ymax+2];
			down_in= new double[xmax+2,ymax+2];
			down_out = new double[xmax+2,ymax+2];
            flowout=new double[xmax+2,ymax+2];
            flowin = new double[xmax + 2, ymax + 2];
            area_depth = new double[xmax + 2, ymax + 2];
            sand = new double[xmax + 2, ymax + 2];
            elev2 = new double[(xmax * dune_mult) + 2, (ymax*dune_mult) + 2];
            sand2 = new double[(xmax * dune_mult) + 2, (ymax * dune_mult) + 2];

            Tau2 = new double[xmax + 2, ymax + 2];
            
			dischargeinput=new double[1000,5];
			tracerinput=new double[1000,5];
			hydrograph=new double[(maxcycle-((int)(cycle/60)))+1000,2];
			tracerhydrograph=new double[(maxcycle-((int)(cycle/60)))+1000,2];

			// MJ arrays 08/02/05
			tempsusp = new double[xmax+2,ymax+2,G_MAX+1,TRACERS];
			tempsusptot = new double[xmax+2,ymax+2];
			Vsusp = new double[xmax+2,ymax+2,G_MAX+1,TRACERS];
			Vsusptot = new double[xmax+2,ymax+2];
			Csusptot = new double[xmax+2,ymax+2];

			// JOE arrays 
			soil_saturation = new double[xmax+2,ymax+2];	// <JOE 20050605>
			slopeAnalysis = new double[xmax+2,ymax+2];		// <JOE 20051605>
			aspect = new double[xmax+2,ymax+2];				// <JOE 20051605>
			hillshade = new double[xmax+2,ymax+2];			// <JOE 20051605>

			//Gez arrays
			sum_grain = new double[G_MAX+1];
            sum_grain2 = new double[G_MAX + 1];
			old_sum_grain = new double[G_MAX+1];
            old_sum_grain2 = new double[G_MAX + 1];
			Qg_step = new double[G_MAX+1];
			Qg_hour = new double[G_MAX+1];
			Qg_over = new double[G_MAX+1];
			Qg_last = new double[G_MAX+1];
            Qg_step2 = new double[G_MAX + 1];
            Qg_hour2 = new double[G_MAX + 1];
            Qg_over2 = new double[G_MAX + 1];
            Qg_last2 = new double[G_MAX + 1];

			CATCH_FILE = TimeseriesOutBox.Text; // MJ 18/01/05
            CATCH_FILE2 = tracerOutputtextBox.Text;

            // siberia data
            Beta1 = double.Parse(Beta1Box.Text);
            Beta3 = double.Parse(Beta3Box.Text);
            m1 = double.Parse(m1Box.Text);
            m3 = double.Parse(m3Box.Text);
            n1 = double.Parse(n1Box.Text);

            // sediment tpt law
            if (einsteinbox.Checked == true) einstein = 1;
            if (wilcockbox.Checked == true) wilcock = 1;

            div_inputs = int.Parse(div_inputs_box.Text);
            fexp = 1;
		}


		void sort_active2(int x,int y)
		{
			int xyindex;
			double total;
			double amount;
			double coeff;
			int n,z,p;
			
	
			if (index[x,y] == -9999) addGS(x,y);  // should not be necessary
			xyindex = index[x,y];

			total = 0.0;
			for (n=0;n<=G_MAX;n++)
			{
				for (p=0;p<=(TRACERS-1);p++)
				{
					total += grain[xyindex,n,p];
				}
			}

			if (total > (active*1.5)) // depositing - create new strata layer and remove bottom one..
			{
				// start from bottom
				// remove bottom active layer
				// then move all from layer above into one below, up to the top layer
				for(z=9;z>=1;z--)
				{
					for(n=0;n<=G_MAX-2;n++)
					{
						for (p=0;p<=(TRACERS-1);p++)
						{
							strata[xyindex,z,n,p]=strata[xyindex,z-1,n,p];
						}
					}
				}

				// then remove strata thickness from grain - and add to top strata layer
				coeff = active / total;
				for (n=1;n<=(G_MAX-1);n++)
				{
					if ((grain_tot(xyindex,n) > 0.0))
					{
						for (p=0;p<=(TRACERS-1);p++)
						{
							amount = coeff * (grain[xyindex,n,p]);
							strata[xyindex,0,n-1,p] = amount;
							grain[xyindex,n,p] -= amount;
						}
					}
				}
			}

			if (total < (active/4)) // eroding - eat into existing strata layer & create new one at bottom
			{
				// Start at top
				// Add top strata to grain
				for (n=1;n<=(G_MAX-1);n++)
				{
					for (p=0;p<=(TRACERS-1);p++)
					{
						grain[xyindex,n,p] += strata[xyindex,0,n-1,p];
					}
				}

				// then from top down add lower strata into upper
				for(z=0;z<=8;z++)
				{
					for(n=0;n<=G_MAX-2;n++)
					{
						for (p=0;p<=(TRACERS-1);p++)
						{
							strata[xyindex,z,n,p] = strata[xyindex,z+1,n,p];
						}
					}
				}

				// add new layer at the bottom
				amount = active;
				p = 0;
				z = 9;
				strata[xyindex,z,0,p] = amount*d1prop; // 0.0;
				strata[xyindex,z,1,p] = amount*d2prop; // + amount*d1prop;
				strata[xyindex,z,2,p] = amount*d3prop;
				strata[xyindex,z,3,p] = amount*d4prop;
				strata[xyindex,z,4,p] = amount*d5prop;
				strata[xyindex,z,5,p] = amount*d6prop;
				strata[xyindex,z,6,p] = amount*d7prop;
				strata[xyindex,z,7,p] = amount*d8prop;
				strata[xyindex,z,8,p] = amount*d9prop;

			}

		}

		
		void sort_active(int x,int y)
		{
			sort_active2(x,y);
		}


		double Fi(int index1, int t)
		{
			int n,z;
			double active_thickness=0;
			double total=0;
			for(n=1;n<=G_MAX;n++)
			{
				for(z=0;z<=(TRACERS-1);z++)
				{
					active_thickness+=(grain[index1,n,z]);
				}
			}
			

			for(z=0;z<=(TRACERS-1);z++)
			{
				total+=(grain[index1,t,z]);
			}

			if(active_thickness<0.0001)
			{
				return(0.0);
			}
			else
			{
				return(total/active_thickness);
			}
		}


		double sand_fraction(int index1)
		{

			int n,z;
			double active_thickness=0;
			double sand_total=0;
			for(n=1;n<=G_MAX;n++)
			{
				for(z=0;z<=(TRACERS-1);z++)
				{
					active_thickness+=(grain[index1,n,z]);
				}
			}

			for(n=1;n<=2;n++) // number of sand fractions...
			{
				for(z=0;z<=(TRACERS-1);z++)
				{
					sand_total+=(grain[index1,n,z]);
				}
			}

			if(active_thickness<0.0001)
			{
				return(0.0);
			}
			else
			{
				return(sand_total/active_thickness);
			}

		}


		double d50(int index1)
		{
			int z,n,i;
			double active_thickness=0;
			double Dfifty=0,max=0,min=0;
			double[] cum_tot;
			cum_tot = new double[20];
            
			for(n=1;n<=G_MAX;n++)
			{
				for(z=0;z<=(0);z++)
				{
					active_thickness+=(grain[index1,n,z]);
					cum_tot[n]+=active_thickness;
				}
			}

			
			

			i=1;
			while(cum_tot[i]<(active_thickness*0.5)&&i<=9)
			{
				i++;
			}
			
			if(i==1){min=Math.Log(d1);max=Math.Log(d1);}
			if(i==2){min=Math.Log(d1);max=Math.Log(d2);}
			if(i==3){min=Math.Log(d2);max=Math.Log(d3);}
			if(i==4){min=Math.Log(d3);max=Math.Log(d4);}
			if(i==5){min=Math.Log(d4);max=Math.Log(d5);}
			if(i==6){min=Math.Log(d5);max=Math.Log(d6);}
			if(i==7){min=Math.Log(d6);max=Math.Log(d7);}
			if(i==8){min=Math.Log(d7);max=Math.Log(d8);}
			if(i==9){min=Math.Log(d8);max=Math.Log(d9);}
			//if(i==9){min=Math.Log(d8);max=Math.Log(d9);}

			Dfifty=Math.Exp(min+((max-min)*((cum_tot[i]-(active_thickness*0.5))/(cum_tot[i]-cum_tot[i-1]))));
			if(active_thickness<0.0000001)Dfifty=0;
			return Dfifty;

		}

		double mean_ws_slope(int x, int y)
		{
			
			double slopesum=0;
			int slopenum=0;
				
			double wd=water_depth_erosion_threshold;

			if(water_depth[x-1,y]>wd&&water_depth[x+1,y]>wd)
			{
				slopesum+=Math.Abs(((elev[x-1,y]+water_depth[x-1,y])-(elev[x+1,y]+water_depth[x+1,y]))/(DX*2));
				slopenum++;
			}

			if(water_depth[x,y-1]>wd&&water_depth[x,y+1]>wd)
			{
				slopesum+=Math.Abs(((elev[x,y-1]+water_depth[x,y-1])-(elev[x,y+1]+water_depth[x,y+1]))/(DX*2));
				slopenum++;
			}

			if(water_depth[x-1,y-1]>wd&&water_depth[x+1,y+1]>wd)
			{
				slopesum+=Math.Abs(((elev[x-1,y-1]+water_depth[x-1,y-1])-(elev[x+1,y+1]+water_depth[x+1,y+1]))/(root*2));
				slopenum++;
			}

			if(water_depth[x-1,y+1]>wd&&water_depth[x+1,y-1]>wd)
			{
				slopesum+=Math.Abs(((elev[x-1,y+1]+water_depth[x-1,y+1])-(elev[x+1,y-1]+water_depth[x+1,y-1]))/(root*2));
				slopenum++;
			}

			if(slopenum<1)slopenum=1;
			//if(slopesum==0)slopesum=mean_old_ws_slope(x,y);
			return(slopesum/slopenum);

		}


		double mean_old_ws_slope(int x, int y)
		{
			
			double slopesum=0;
			int slopenum=0;
				
			double wd=water_depth_erosion_threshold;

			if(old_water_depth[x-1,y]>wd&&old_water_depth[x+1,y]>wd)
			{
				slopesum+=Math.Abs(((elev[x-1,y]+old_water_depth[x-1,y])-(elev[x+1,y]+old_water_depth[x+1,y]))/(DX*2));
				slopenum++;
			}

			if(old_water_depth[x,y-1]>wd&&old_water_depth[x,y+1]>wd)
			{
				slopesum+=Math.Abs(((elev[x,y-1]+old_water_depth[x,y-1])-(elev[x,y+1]+old_water_depth[x,y+1]))/(DX*2));
				slopenum++;
			}

			if(old_water_depth[x-1,y-1]>wd&&old_water_depth[x+1,y+1]>wd)
			{
				slopesum+=Math.Abs(((elev[x-1,y-1]+old_water_depth[x-1,y-1])-(elev[x+1,y+1]+old_water_depth[x+1,y+1]))/(root*2));
				slopenum++;
			}

			if(old_water_depth[x-1,y+1]>wd&&old_water_depth[x+1,y-1]>wd)
			{
				slopesum+=Math.Abs(((elev[x-1,y+1]+old_water_depth[x-1,y+1])-(elev[x+1,y-1]+old_water_depth[x+1,y-1]))/(root*2));
				slopenum++;
			}

			if(slopenum<1)slopenum=1;
			//if(slopesum==0)slopesum=mean_old_ws_slope2(x,y);
			return(slopesum/slopenum);

		}


		double mean_ws_slope2(int x, int y) // 
		{


			int x2,y2,dir;
			double tempelev=0;//(water_depth[x,y]+elev[x,y]);
			int tempinc=0;
		
			double wd=water_depth_erosion_threshold;
											
			for (dir=1;dir<=8;dir++)
			{
				x2 = x + deltaX[dir];
				y2 = y + deltaY[dir];
			
				if(water_depth[x2,y2]>wd)
				{
					if((water_depth[x,y]+elev[x,y])>(water_depth[x2,y2]+elev[x2,y2]))
					{
						tempelev+=((water_depth[x,y]+elev[x,y])-(water_depth[x2,y2]+elev[x2,y2]))/DX;
						tempinc++;
					}
				}
			}
			if(tempinc<1)tempinc=1;			
			return(tempelev/tempinc);
			

		}

		double mean_old_ws_slope2(int x, int y) // 
		{


			int x2,y2,dir;
			double tempelev=0;//(water_depth[x,y]+elev[x,y]);
			int tempinc=0;
			
			double wd=water_depth_erosion_threshold;
											
			for (dir=1;dir<=8;dir++)
			{
				x2 = x + deltaX[dir];
				y2 = y + deltaY[dir];
			
				if(old_water_depth[x2,y2]>wd)
				{
					if((old_water_depth[x,y]+elev[x,y])>(old_water_depth[x2,y2]+elev[x2,y2]))
					{
						tempelev+=((old_water_depth[x,y]+elev[x,y])-(old_water_depth[x2,y2]+elev[x2,y2]))/DX;
						tempinc++;
					}
				}
			}
			if(tempinc<1)tempinc=1;			
			return(tempelev/tempinc);
			

		}

		double max_ws_slope(int x, int y)
		{
			double slopemax=0;
			double slopesum=0;
			
				
			double wd=water_depth_erosion_threshold;

			if(water_depth[x-1,y]>wd&&water_depth[x+1,y]>wd)
			{
				slopesum=Math.Abs(((elev[x-1,y]+water_depth[x-1,y])-(elev[x+1,y]+water_depth[x+1,y]))/(DX*2));
				if(slopesum>slopemax)slopemax=slopesum;
			}

			if(water_depth[x,y-1]>wd&&water_depth[x,y+1]>wd)
			{
				slopesum=Math.Abs(((elev[x,y-1]+water_depth[x,y-1])-(elev[x,y+1]+water_depth[x,y+1]))/(DX*2));
				if(slopesum>slopemax)slopemax=slopesum;
			}

			if(water_depth[x-1,y-1]>wd&&water_depth[x+1,y+1]>wd)
			{
				slopesum=Math.Abs(((elev[x-1,y-1]+water_depth[x-1,y-1])-(elev[x+1,y+1]+water_depth[x+1,y+1]))/(root*2));
				if(slopesum>slopemax)slopemax=slopesum;
			}

			if(water_depth[x-1,y+1]>wd&&water_depth[x+1,y-1]>wd)
			{
				slopesum=Math.Abs(((elev[x-1,y+1]+water_depth[x-1,y+1])-(elev[x+1,y-1]+water_depth[x+1,y-1]))/(root*2));
				if(slopesum>slopemax)slopemax=slopesum;
			}

			return(slopemax);

		}

		double max_bed_slope(int x, int y)
		{

			double slope=0;
			int slopetot=0;
			double slopemax=0;
	
			if(elev[x,y]>elev[x,y-1])
			{
				slope=Math.Pow((elev[x,y]-elev[x,y-1])/DX,1);
				if(slope>slopemax)slopemax=slope;
				slopetot++;
			}
			if(elev[x,y]>elev[x+1,y-1])
			{
				slope=Math.Pow((elev[x,y]-elev[x+1,y-1])/root,1);
				if(slope>slopemax)slopemax=slope;
				slopetot++;
			}
			if(elev[x,y]>elev[x+1,y])
			{
				slope=Math.Pow((elev[x,y]-elev[x+1,y])/DX,1);
				if(slope>slopemax)slopemax=slope;
				slopetot++;
			}
			if(elev[x,y]>elev[x+1,y+1])
			{
				slope=Math.Pow((elev[x,y]-elev[x+1,y+1])/root,1);
				if(slope>slopemax)slopemax=slope;
				slopetot++;
			}
			if(elev[x,y]>elev[x,y+1])
			{
				slope=Math.Pow((elev[x,y]-elev[x,y+1])/DX,1);
				if(slope>slopemax)slopemax=slope;
				slopetot++;
			}
			if(elev[x,y]>elev[x-1,y+1])
			{
				slope=Math.Pow((elev[x,y]-elev[x-1,y+1])/root,1);
				if(slope>slopemax)slopemax=slope;
				slopetot++;
			}
			if(elev[x,y]>elev[x-1,y])
			{
				slope=Math.Pow((elev[x,y]-elev[x-1,y])/DX,1);
				if(slope>slopemax)slopemax=slope;
				slopetot++;
			}
			if(elev[x,y]>elev[x-1,y-1])
			{
				slope=Math.Pow((elev[x,y]-elev[x-1,y-1])/root,1);
				if(slope>slopemax)slopemax=slope;
				slopetot++;
			}
			if(slope>0)slope=(slope/slopetot);


			//return(slopemax);
			//if(slopemax<0.001)slopemax=0.001;
            if (slopemax > 0.01) slopemax = 0.01;
			return(slopemax);
		}

        double max_bed_slope2(int x, int y)
        {

            double slope = 0;
            int slopetot = 0;
            double slopemax = 0;

            if (elev[x, y] > elev[x, y - 1])
            {
                slope = Math.Pow((elev[x, y] - elev[x, y - 1]) / DX, 1);
                if (slope > slopemax) slopemax = slope;
                slopetot++;
            }
            if (elev[x, y] > elev[x + 1, y - 1])
            {
                slope = Math.Pow((elev[x, y] - elev[x + 1, y - 1]) / root, 1);
                if (slope > slopemax) slopemax = slope;
                slopetot++;
            }
            if (elev[x, y] > elev[x + 1, y])
            {
                slope = Math.Pow((elev[x, y] - elev[x + 1, y]) / DX, 1);
                if (slope > slopemax) slopemax = slope;
                slopetot++;
            }
            if (elev[x, y] > elev[x + 1, y + 1])
            {
                slope = Math.Pow((elev[x, y] - elev[x + 1, y + 1]) / root, 1);
                if (slope > slopemax) slopemax = slope;
                slopetot++;
            }
            if (elev[x, y] > elev[x, y + 1])
            {
                slope = Math.Pow((elev[x, y] - elev[x, y + 1]) / DX, 1);
                if (slope > slopemax) slopemax = slope;
                slopetot++;
            }
            if (elev[x, y] > elev[x - 1, y + 1])
            {
                slope = Math.Pow((elev[x, y] - elev[x - 1, y + 1]) / root, 1);
                if (slope > slopemax) slopemax = slope;
                slopetot++;
            }
            if (elev[x, y] > elev[x - 1, y])
            {
                slope = Math.Pow((elev[x, y] - elev[x - 1, y]) / DX, 1);
                if (slope > slopemax) slopemax = slope;
                slopetot++;
            }
            if (elev[x, y] > elev[x - 1, y - 1])
            {
                slope = Math.Pow((elev[x, y] - elev[x - 1, y - 1]) / root, 1);
                if (slope > slopemax) slopemax = slope;
                slopetot++;
            }
            //if (slope > 0) slope = (slope / slopetot);


            //return(slopemax);
            //if(slopemax<0.001)slopemax=0.001;
            //if (slopemax > 0.01) slopemax = 0.01;
            return (slopemax);
        }

        double max_neg_bed_slope(int x, int y)
        {

            double slope = 0;
            int slopetot = 0;
            double slopemax = 0;

            if (elev[x, y] < elev[x, y - 1])
            {
                slope = Math.Pow((elev[x, y-1] - elev[x, y ]) / DX, 1);
                if (slope > slopemax) slopemax += slope;
                slopetot++;
            }
            //if (elev[x, y] < elev[x + 1, y - 1])
            //{
            //    slope = Math.Pow((elev[x+1, y-1] - elev[x, y]) / DX, 1);
            //    if (slope > slopemax) slopemax = slope;
            //    slopetot++;
            //}
            if (elev[x, y] < elev[x + 1, y])
            {
                slope = Math.Pow((elev[x+1, y] - elev[x, y]) / DX, 1);
                if (slope > slopemax) slopemax += slope;
                slopetot++;
            }
            //if (elev[x, y] < elev[x + 1, y + 1])
            //{
            //    slope = Math.Pow((elev[x+1, y+1] - elev[x, y ]) / root, 1);
            //    if (slope > slopemax) slopemax = slope;
            //    slopetot++;
            //}
            if (elev[x, y] < elev[x, y + 1])
            {
                slope = Math.Pow((elev[x, y+1] - elev[x, y]) / DX, 1);
                if (slope > slopemax) slopemax += slope;
                slopetot++;
            }
            //if (elev[x, y] < elev[x - 1, y + 1])
            //{
            //    slope = Math.Pow((elev[x-1, y+1] - elev[x, y]) / root, 1);
            //    if (slope > slopemax) slopemax = slope;
            //    slopetot++;
            //}
            if (elev[x, y] < elev[x - 1, y])
            {
                slope = Math.Pow((elev[x-1, y] - elev[x, y]) / DX, 1);
                if (slope > slopemax) slopemax += slope;
                slopetot++;
            }
            //if (elev[x-1, y-1] > elev[x - 1, y - 1])
            //{
            //    slope = Math.Pow((elev[x-1, y-1] - elev[x, y]) / DX, 1);
            //    if (slope > slopemax) slopemax = slope;
            //    slopetot++;
            //}
            //if (slope < 0) slope = (slope / slopetot);

            //return(slopemax);
            //if(slopemax<0.001)slopemax=0.001;
            return (slopemax);
        }


		double mean_bed_slope(int x, int y)
		{
            return (max_bed_slope(x, y));


			double slope=0;
			int slopetot=0;
			double slopemax=0;
	
			if(elev[x,y]>elev[x,y-1]&&elev[x,y-1]>0)
			{
				slope=Math.Pow((elev[x,y]-elev[x,y-1])/DX,1);
				slopemax+=slope;
				slopetot++;
			}
			if(elev[x,y]>elev[x+1,y-1])
			{
				slope=Math.Pow((elev[x,y]-elev[x+1,y-1])/root,1);
				slopemax+=slope;
				slopetot++;
			}
			if(elev[x,y]>elev[x+1,y])
			{
				slope=Math.Pow((elev[x,y]-elev[x+1,y])/DX,1);
				slopemax+=slope;
				slopetot++;
			}
			if(elev[x,y]>elev[x+1,y+1])
			{
				slope=Math.Pow((elev[x,y]-elev[x+1,y+1])/root,1);
				slopemax+=slope;
				slopetot++;
			}
			if(elev[x,y]>elev[x,y+1])
			{
				slope=Math.Pow((elev[x,y]-elev[x,y+1])/DX,1);
				slopemax+=slope;
				slopetot++;
			}
			if(elev[x,y]>elev[x-1,y+1])
			{
				slope=Math.Pow((elev[x,y]-elev[x-1,y+1])/root,1);
				slopemax+=slope;
				slopetot++;
			}
			if(elev[x,y]>elev[x-1,y])
			{
				slope=Math.Pow((elev[x,y]-elev[x-1,y])/DX,1);
				slopemax+=slope;
				slopetot++;
			}
			if(elev[x,y]>elev[x-1,y-1])
			{
				slope=Math.Pow((elev[x,y]-elev[x-1,y-1])/root,1);
				slopemax+=slope;
				slopetot++;
			}
			if(slopemax>0)slope=(slopemax/slopetot);
			//if(slope<0.001)slope=0.01;
            //if (slope > 0.1) slope = 0.1;
            //slope = 0.01;
			return(slope);
		}


		double grain_tot(int cent,int fract)
		{
			int n;
			double total=0;
			//if(cent==-9999)return total;
			for(n=0;n<=(TRACERS-1);n++)
			{
				total+=grain[cent,fract,n];
			}
			return total;
		}


		double temp_tot(int cent,int fract)
		{
			int n;
			double total=0;
			for(n=0;n<=(TRACERS-1);n++)
			{
				total+=temp[cent,fract,n];
			}
			return total;
		}


		double strata_tot(int cent,int z,int fract)
		{
			int n;
			double total=0;
			for(n=0;n<=(TRACERS-1);n++)
			{
				total+=strata[cent,z,fract,n];
			}
			return total;
		}

		
		void addGS(int x,int y)
		{

			int n,z,q;

			grain_array_tot++;
			index[x,y]=grain_array_tot;
			for(n=0;n<=G_MAX;n++)temp[grain_array_tot,n,0]=0;

			z=0;
			/*if(x>203&&x<430&&y>24&&y<101)z=1;*/


            //if (grassbox.Checked == true)
            //{
            //    grain[grain_array_tot, 0, z] = 0;
            //    grain[grain_array_tot, 1, z] = active/2;
            //    grain[grain_array_tot, 2, z] = active / 2;// 0;//+(active*d1prop);
            //    grain[grain_array_tot, 3, z] = 0;
            //    grain[grain_array_tot, 4, z] = 0;
            //    grain[grain_array_tot, 5, z] = 0;
            //    grain[grain_array_tot, 6, z] = 0;
            //    grain[grain_array_tot, 7, z] = 0;
            //    grain[grain_array_tot, 8, z] = 0;
            //    grain[grain_array_tot, 9, z] = 0;
            //    grain[grain_array_tot, 10, z] = 0;


            //    for (n = 0; n <= 9; n++)
            //    {
            //        strata[grain_array_tot, n, 0, z] = (active)/2;					// TJ xx/03/05
            //        strata[grain_array_tot, n, 1, z] = active/2;//+(active*d1prop);  // TJ xx/03/05
            //        strata[grain_array_tot, n, 2, z] = 0;
            //        strata[grain_array_tot, n, 3, z] = 0;
            //        strata[grain_array_tot, n, 4, z] = 0;
            //        strata[grain_array_tot, n, 5, z] = 0;
            //        strata[grain_array_tot, n, 6, z] = 0;
            //        strata[grain_array_tot, n, 7, z] = 0;
            //        strata[grain_array_tot, n, 8, z] = 0;

            //        if (elev[x, y] - (active * (n + 1)) < (bedrock[x, y] - active))
            //        {
            //            for (q = 0; q <= (G_MAX - 2); q++)
            //            {
            //                strata[grain_array_tot, n, q, z] = 0;
            //            }
            //        }
            //    }
            //    for (n = 9; n <= 9; n++)
            //    {
            //        strata[grain_array_tot, n, 0, z] = (active) * d1prop;					// TJ xx/03/05
            //        strata[grain_array_tot, n, 1, z] = (active * d2prop);//+(active*d1prop);  // TJ xx/03/05
            //        strata[grain_array_tot, n, 2, z] = (active) * d3prop;
            //        strata[grain_array_tot, n, 3, z] = (active) * d4prop;
            //        strata[grain_array_tot, n, 4, z] = (active) * d5prop;
            //        strata[grain_array_tot, n, 5, z] = (active) * d6prop;
            //        strata[grain_array_tot, n, 6, z] = (active) * d7prop;
            //        strata[grain_array_tot, n, 7, z] = (active) * d8prop;
            //        strata[grain_array_tot, n, 8, z] = (active) * d9prop;

            //        if (elev[x, y] - (active * (n + 1)) < (bedrock[x, y] - active))
            //        {
            //            for (q = 0; q <= (G_MAX - 2); q++)
            //            {
            //                strata[grain_array_tot, n, q, z] = 0;
            //            }
            //        }
            //    }
            //}

            grassbox.Checked = false;
            if (grassbox.Checked == false)
			{
				grain[grain_array_tot,0,z]=0; 	
				grain[grain_array_tot,1,z]=active*d1prop;
				grain[grain_array_tot,2,z]=active*d2prop;//+(active*d1prop);
				grain[grain_array_tot,3,z]=active*d3prop;
				grain[grain_array_tot,4,z]=active*d4prop;
				grain[grain_array_tot,5,z]=active*d5prop;
				grain[grain_array_tot,6,z]=active*d6prop;
				grain[grain_array_tot,7,z]=active*d7prop;
				grain[grain_array_tot,8,z]=active*d8prop;
				grain[grain_array_tot,9,z]=active*d9prop;
				grain[grain_array_tot,10,z]=0;


				for(n=0;n<=9;n++)
				{
					strata[grain_array_tot,n,0,z]=(active)*d1prop;					// TJ xx/03/05
					strata[grain_array_tot,n,1,z]=(active*d2prop);//+(active*d1prop);  // TJ xx/03/05
					strata[grain_array_tot,n,2,z]=(active)*d3prop;
					strata[grain_array_tot,n,3,z]=(active)*d4prop;
					strata[grain_array_tot,n,4,z]=(active)*d5prop;
					strata[grain_array_tot,n,5,z]=(active)*d6prop;
					strata[grain_array_tot,n,6,z]=(active)*d7prop;
					strata[grain_array_tot,n,7,z]=(active)*d8prop;
					strata[grain_array_tot,n,8,z]=(active)*d9prop;

					if(elev[x,y]-(active*(n+1))<(bedrock[x,y]-active))
					{
						for(q=0;q<=(G_MAX-2);q++)
						{
							strata[grain_array_tot,n,q,z]=0;
						}
					}
				}
            }

			sort_active(x,y);


		}

		// calc roughtness on Srickler relationship
		double strickler(int x, int y)
		{
			double temp=0;
			double temp_d50=1;

			if (index[x,y] != -9999)temp_d50=d50(index[x,y]); 
			temp =0.034*Math.Pow(temp_d50,0.167);
			//Console.WriteLine(Convert.ToString(strickler(x,y)));
			temp+=0.012;
			return temp;

		}


		//Calculate roughness - Added JMW 20051122
		//Based on Baptist, 2005
		double chezy(int x, int y)
		{
			double Cr;
			double Cb;
			double temp_d50=30;

			double temp_depth=old_water_depth[x,y];
			
			if(temp_depth<=0)temp_depth=0.1;
			

			// just to save it when there is no grain file
			if (index[x,y] != -9999)temp_d50=d50(index[x,y]); 
			
            

			// Grain roughness (strickler formulation)
			Cb = (26.4*Math.Pow(temp_depth/temp_d50,0.167));
			Cr=Cb;

            // veg influencing roughness is commented out at the moment...
            //if (veg[x,y,1]>0.01)// if there is any veg..
            //{
            //    // Applying vegetation
            //    if (veg[x,y,3] < temp_depth)
            //    {
            //        Cr = (Math.Pow(1/(1/(Cb*Cb) + veg[x,y,2]*veg[x,y,3]/(2*g)),0.5)
            //            + Math.Pow(g,0.5)/kappa*Math.Log(temp_depth/veg[x,y,3]));
            //    }
            //    else
            //    {                 
            //        Cr = (Math.Pow(1/(1/(Cb*Cb) + veg[x,y,2]*temp_depth/(2*g)),0.5));
            //    }
            //}

			return Cr;
		}


		double chezytomanning(double chezyc, double depth)
		{
			return (Math.Pow(depth,0.167))/chezyc;
		}


		double calc_manning(int x, int y)
		{ 
			double temp_depth=old_water_depth[x,y];
			if(temp_depth<=0)temp_depth=0.1;
			//return chezytomanning(chezy(x,y), temp_depth)+0.012;
            return 0.03;
		}


		void grow_grass(double amount3)
		{

            int x, y;
			for(x=1;x<=xmax;x++)
			{
				for(y=1;y<=ymax;y++)
				{
                    //first check if veg is at 0.. not sure if this is needed now..
                    if (veg[x, y, 0] == 0)
                    {
                        veg[x, y, 0] = elev[x, y];
                    }

					// first check if under water or not..
					if(water_depth[x,y]<water_depth_erosion_threshold)
					{
                        // if not then it
                        // now adds to the amount of veg there.. 
						veg[x,y,1]+=amount3;
						if(veg[x,y,1]>1)veg[x,y,1]=1;
					}

                    // check if veg below elev! if so raise to elev
                    if (veg[x, y, 0] < elev[x, y]) // raises the veg level if it gets buried.. but only by a certain amount (0.001m day...)
                    {
                        veg[x, y, 0] += 0.001; // this is an arbitrary amount..
                    }

					// trying to see now, if veg is above elev - so if lateral erosion happens - more than 0.1m the veg gets wiped..

                    if (veg[x, y, 0] - elev[x, y] > 0.1)
                    {
                        veg[x, y, 1] = 0;
                        veg[x, y, 0] = elev[x, y];
                    }


					// now see if veg under water - if so let it die back a bit..
					if(water_depth[x,y]>=water_depth_erosion_threshold&&veg[x,y,1]>0)
					{
						veg[x,y,1]-=(amount3*2);
                        if (veg[x, y, 1] < 0)
                        {
                            veg[x, y, 1] = 0;
                            veg[x, y, 0] = elev[x, y]; // resets elev if veg amt is 0
                        }
					}

                    // also if it is under sediment - then dies back a bit too...
                    if (veg[x, y, 0] < elev[x, y]) 
                    {
                        veg[x, y, 1] -= (amount3 * 2);
                        if (veg[x, y, 1] < 0)
                        {
                            veg[x, y, 1] = 0;
                            veg[x, y, 0] = elev[x, y]; // resets elev if veg amt is 0
                        }
                        
                    }

                    // but if it is under sediment, has died back to nearly 0 (0.05) then it resets the elevation 
                    // to the surface elev.
                    if (veg[x, y, 0] < elev[x, y]&&veg[x,y,1]<0.05)
                    {
                        veg[x, y, 0] = elev[x, y];
                    }


				}
			}



//			/****** this has to have its own version of sort active not removing grass ***/
//
//
//			int x,y,n,z,temp_centre,q,p;
//			double total,total2,sub_tot;
//			//double amount3=0.000961;
//			double amount2;
//			double amount=0;
//
//			for(x=1;x<=xmax;x++)
//			{
//				for(y=1;y<=ymax;y++)
//				{
//					if(index[x,y]!=-9999&&water_depth[x,y]<=MIN_Q)
//					{
//
//
//						/** 0.000057 is adding grass to 0.1 at ten hourly steps
//						  so its 0.01 from 0 in 2 years **/
//
//						//						if((grain[index[x,y],0,0]+amount3)>active)amount3=active-grain[index[x,y],0,0];
//						//						grain[index[x,y],0,0]+=amount3;
//						//						sort_active(x,y);
//						//					}
//						//				}
//						//			}
//						//		}
//
//
//
//						sort_active(x,y);
//
//						grain[index[x,y],0,0]+=amount3;
//						if(grain[index[x,y],0,0]>active)grain[index[x,y],0,0]=active;
// 	  
//						temp_centre=index[x,y];
//						/** has to run from n=1 */
//
//						//total=active+amount3;
//						amount=amount3;
//						//if(amount<0)printf("asdasd %f\n",(amount*1000000));
//						// doing the bedrock..
//						if(grain[temp_centre,G_MAX,0]>0)
//						{
//							if((grain[temp_centre,G_MAX,0]+amount)>active)
//							{
//								amount=active-grain[temp_centre,G_MAX,0];
//							}
//
//						}
//
//						total=0;
//						for(n=1;n<=G_MAX-1;n++)
//						{
//							for(q=0;q<=(TRACERS-1);q++)
//							{
//	
//								total+=grain[temp_centre,n,q];
//							}
//						}
//
//						for(n=1;n<=(G_MAX-1);n++)
//						{
//							if(grain_tot(temp_centre,n)>0)
//							{
//								amount2=(grain_tot(temp_centre,n)/total)*amount;
//								if(n>0&&n<G_MAX)
//								{
//									sub_tot=grain_tot(temp_centre,n);
//									if(sub_tot>0)
//									{
//										for(q=0;q<=(TRACERS-1);q++)
//										{
//											strata[temp_centre,0,n-1,q]+=amount2*(grain[temp_centre,n,q]/sub_tot);
//										}
//									}
//								}
//								sub_tot=grain_tot(temp_centre,n);
//								if(sub_tot>0)
//								{
//									for(q=0;q<=(TRACERS-1);q++)
//									{
//										grain[temp_centre,n,q]-=amount2*(grain[temp_centre,n,q]/sub_tot);
//									}
//								}
//							}
//						}
//		       	
//						/* then workk down through the strata **/
//
//						for(z=0;z<=9;z++)
//						{
//							total2=0;
//							for(n=0;n<=(G_MAX-2);n++)total2+=strata_tot(temp_centre,z,n);
//							amount=(total2-(active));
//							for(n=0;n<=(G_MAX-2);n++)
//							{
//								if(strata_tot(temp_centre,z,n)>0&&amount>0)
//								{
//									if(z<9)
//									{
//										sub_tot=strata_tot(temp_centre,z,n);
//										for(q=0;q<=(TRACERS-1);q++)
//										{
//											strata[temp_centre,z+1,n,q]+=(strata[temp_centre,z,n,q]/sub_tot)*((sub_tot/total2)*amount);
//										}
//									}
//									sub_tot=strata_tot(temp_centre,z,n);
//									for(q=0;q<=(TRACERS-1);q++)
//									{
//										strata[temp_centre,z,n,q]-=(strata[temp_centre,z,n,q]/sub_tot)*((sub_tot/total2)*amount);
//									}
//								}	
//							}		
//						}
//  
//		
//
//	  
//						sort_active(x,y);
//						
//					}
//				}
//			}

		}


		void creep(double time)
		{

			/** creep rate is 10*-2 * slope per year, so inputs time jump in years*/
			/** very important differnece here is that slide_GS() is called only if
				BOTH cells are not -9999 therfore if both have grainsize then do additions.
				this is to stop the progressive spread of selected cells upslope */

		

			int x,y;
			double temp;


			for(x=1;x<=xmax;x++)
			{
				for(y=1;y<=ymax;y++)
				{
					tempcreep[x,y]=0;
				}
			}

	
			for(x=2;x<xmax;x++)
			{
				for(y=2;y<ymax;y++)
				{
					if(elev[x,y]>bedrock[x,y])
					{
						if(elev[x,y-1]<elev[x,y]&&elev[x,y-1]>0)
						{
							temp=((elev[x,y]-elev[x,y-1])/DX)*CREEP_RATE*time/DX;
							if((elev[x,y]-temp)<bedrock[x,y])temp=elev[x,y]-bedrock[x,y];
							if(temp<0)temp=0;				
							tempcreep[x,y]-=temp;
							tempcreep[x,y-1]+=temp;
							if(index[x,y]!=-9999)
							{
                                slide_GS(x, y, temp, x, y - 1);
							}
						}
						if(elev[x+1,y-1]<elev[x,y]&&elev[x+1,y-1]>0)
						{
							temp=((elev[x,y]-elev[x+1,y-1])/root)*CREEP_RATE*time/root;
							if((elev[x,y]-temp)<bedrock[x,y])temp=elev[x,y]-bedrock[x,y];
							if(temp<0)temp=0;
							tempcreep[x,y]-=temp;
							tempcreep[x+1,y-1]+=temp;
							if(index[x,y]!=-9999)
							{
                                slide_GS(x, y, temp, x+1, y - 1);
							}
			
						}
						if(elev[x+1,y]<elev[x,y]&&elev[x+1,y]>0)
						{
							temp=((elev[x,y]-elev[x+1,y])/DX)*CREEP_RATE*time/DX;
							if((elev[x,y]-temp)<bedrock[x,y])temp=elev[x,y]-bedrock[x,y];
							if(temp<0)temp=0;
							tempcreep[x,y]-=temp;
							tempcreep[x+1,y]+=temp;
							if(index[x,y]!=-9999)
							{
                                slide_GS(x, y, temp, x+1, y);
							}
						}
						if(elev[x+1,y+1]<elev[x,y]&&elev[x+1,y+1]>0)
						{
							temp=((elev[x,y]-elev[x+1,y+1])/root)*CREEP_RATE*time/root;
							if((elev[x,y]-temp)<bedrock[x,y])temp=elev[x,y]-bedrock[x,y];
							if(temp<0)temp=0;
							tempcreep[x,y]-=temp;
							tempcreep[x+1,y+1]+=temp;
							if(index[x,y]!=-9999)
							{
                                slide_GS(x, y, temp, x+1, y + 1);
							}
						}
						if(elev[x,y+1]<elev[x,y]&&elev[x,y+1]>0)
						{
							temp=((elev[x,y]-elev[x,y+1])/DX)*CREEP_RATE*time/DX;
							if((elev[x,y]-temp)<bedrock[x,y])temp=elev[x,y]-bedrock[x,y];
							if(temp<0)temp=0;
							tempcreep[x,y]-=temp;
							tempcreep[x,y+1]+=temp;
							if(index[x,y]!=-9999)
							{
                                slide_GS(x, y, temp, x, y + 1);
							}
						}
						if(elev[x-1,y+1]<elev[x,y]&&elev[x-1,y+1]>0)
						{
							temp=((elev[x,y]-elev[x-1,y+1])/root)*CREEP_RATE*time/root;
							if((elev[x,y]-temp)<bedrock[x,y])temp=elev[x,y]-bedrock[x,y];
							if(temp<0)temp=0;
							tempcreep[x,y]-=temp;
							tempcreep[x-1,y+1]+=temp;
							if(index[x,y]!=-9999)
							{
                                slide_GS(x, y, temp, x-1, y + 1);
							}
						}
						if(elev[x-1,y]<elev[x,y]&&elev[x-1,y]>0)
						{
							temp=((elev[x,y]-elev[x-1,y])/DX)*CREEP_RATE*time/DX;
							if((elev[x,y]-temp)<bedrock[x,y])temp=elev[x,y]-bedrock[x,y];
							if(temp<0)temp=0;
							tempcreep[x,y]-=temp;
							tempcreep[x-1,y]+=temp;
							if(index[x,y]!=-9999)
							{
                                slide_GS(x, y, temp, x-1, y );
							}
						}
						if(elev[x-1,y-1]<elev[x,y]&&elev[x-1,y-1]>0)
						{
							temp=((elev[x,y]-elev[x-1,y-1])/root)*CREEP_RATE*time/root;
							if((elev[x,y]-temp)<bedrock[x,y])temp=elev[x,y]-bedrock[x,y];
							if(temp<0)temp=0;
							tempcreep[x,y]-=temp;
							tempcreep[x-1,y-1]+=temp;
							if(index[x,y]!=-9999)
							{
                                slide_GS(x, y, temp, x-1, y - 1);
							}
						}
					}
				}
			}
	
			for(x=1;x<=xmax;x++)
			{
				for(y=1;y<=ymax;y++)
				{
					elev[x,y]+=tempcreep[x,y];
				}
			}

		}

        void siberia(double time)
        {
            int x, y;
            double temp;
            double SibQ = 0;
            double SibQsf = 0;

                        

            for (x = 1; x <= xmax; x++)
            {
                for (y = 1; y <= ymax; y++)
                {
                    tempcreep[x, y] = 0;
                }
            }


            for (x = 2; x <= xmax; x++)
            {
                for (y = 2; y < ymax; y++)
                {
                    if (elev[x, y] > bedrock[x, y])
                    {
                        SibQ = Beta3 * Math.Pow(area[x, y] * DX * DX, m3);
                        SibQsf= Beta1*Math.Pow((SibQ/DX),m1)*Math.Pow(max_bed_slope2(x,y),n1)*time;
                        double max_slope = max_bed_slope2(x, y);
                        if (max_slope == 0) max_slope = 10; // catch line to stop erosion if there is no slope
                        //if (max_slope > 0) max_slope *= 0.99;

                        if ((elev[x, y]-elev[x, y - 1] )/DX >= max_slope && elev[x, y - 1] > 0)
                        {
                            temp = SibQsf;
                            if ((elev[x, y] - temp) < bedrock[x, y]) temp = elev[x, y] - bedrock[x, y];
                            if (temp < 0) temp = 0;
                            tempcreep[x, y] -= temp;
                            tempcreep[x, y - 1] += temp;
                            if (index[x, y] != -9999)
                            {
                                slide_GS(x, y, temp, x, y - 1);
                            }
                        }
                        if ((elev[x, y] - elev[x + 1, y - 1]) / root >= max_slope && (elev[x + 1, y - 1] > 0 || x == xmax))
                        {
                            temp = SibQsf;
                            if ((elev[x, y] - temp) < bedrock[x, y]) temp = elev[x, y] - bedrock[x, y];
                            if (temp < 0) temp = 0;
                            tempcreep[x, y] -= temp;
                            tempcreep[x + 1, y - 1] += temp;
                            if (index[x, y] != -9999)
                            {
                                slide_GS(x, y, temp, x + 1, y - 1);
                            }

                        }
                        if ((elev[x, y] - elev[x + 1, y]) / DX >= max_slope && (elev[x + 1, y] > 0 || x == xmax))
                        {
                            temp = SibQsf;
                            if ((elev[x, y] - temp) < bedrock[x, y]) temp = elev[x, y] - bedrock[x, y];
                            if (temp < 0) temp = 0;
                            tempcreep[x, y] -= temp;
                            tempcreep[x + 1, y] += temp;
                            if (index[x, y] != -9999)
                            {
                                slide_GS(x, y, temp, x + 1, y);
                            }
                        }
                        if ((elev[x, y] - elev[x + 1, y + 1]) / root >= max_slope && (elev[x + 1, y + 1] > 0 || x == xmax))
                        {
                            temp = SibQsf;
                            if ((elev[x, y] - temp) < bedrock[x, y]) temp = elev[x, y] - bedrock[x, y];
                            if (temp < 0) temp = 0;
                            tempcreep[x, y] -= temp;
                            tempcreep[x + 1, y + 1] += temp;
                            if (index[x, y] != -9999)
                            {
                                slide_GS(x, y, temp, x + 1, y + 1);
                            }
                        }
                        if ((elev[x, y] - elev[x, y + 1]) / DX >= max_slope && elev[x, y + 1] > 0 )
                        {
                            temp = SibQsf;
                            if ((elev[x, y] - temp) < bedrock[x, y]) temp = elev[x, y] - bedrock[x, y];
                            if (temp < 0) temp = 0;
                            tempcreep[x, y] -= temp;
                            tempcreep[x, y + 1] += temp;
                            if (index[x, y] != -9999)
                            {
                                slide_GS(x, y, temp, x, y + 1);
                            }
                        }
                        if ((elev[x, y] - elev[x - 1, y + 1]) / root >= max_slope && elev[x - 1, y + 1] > 0 )
                        {
                            temp = SibQsf;
                            if ((elev[x, y] - temp) < bedrock[x, y]) temp = elev[x, y] - bedrock[x, y];
                            if (temp < 0) temp = 0;
                            tempcreep[x, y] -= temp;
                            tempcreep[x - 1, y + 1] += temp;
                            if (index[x, y] != -9999)
                            {
                                slide_GS(x, y, temp, x - 1, y + 1);
                            }
                        }
                        if ((elev[x, y] - elev[x - 1, y]) / DX >= max_slope && elev[x - 1, y] > 0 )
                        {
                            temp = SibQsf;
                            if ((elev[x, y] - temp) < bedrock[x, y]) temp = elev[x, y] - bedrock[x, y];
                            if (temp < 0) temp = 0;
                            tempcreep[x, y] -= temp;
                            tempcreep[x - 1, y] += temp;
                            if (index[x, y] != -9999)
                            {
                                slide_GS(x, y, temp, x - 1, y);
                            }
                        }
                        if ((elev[x, y] - elev[x - 1, y - 1]) / root >= max_slope && elev[x - 1, y - 1] > 0 )
                        {
                            temp = SibQsf;
                            if ((elev[x, y] - temp) < bedrock[x, y]) temp = elev[x, y] - bedrock[x, y];
                            if (temp < 0) temp = 0;
                            tempcreep[x, y] -= temp;
                            tempcreep[x - 1, y - 1] += temp;
                            if (index[x, y] != -9999)
                            {
                                slide_GS(x, y, temp, x - 1, y - 1);
                            }
                        }

                    }
                }
            }

            for (x = 1; x <= xmax; x++)
            {
                for (y = 1; y <= ymax; y++)
                {
                    elev[x, y] += tempcreep[x, y];
                }
            }

        }


        void soilerosion(double time)
        {

            /** creep rate is 10*-2 * slope per year, so inputs time jump in years*/
            /** very important differnece here is that slide_GS() is called only if
                BOTH cells are not -9999 therfore if both have grainsize then do additions.
                this is to stop the progressive spread of selected cells upslope */



            int x, y;
            double temp;


            for (x = 1; x <= xmax; x++)
            {
                for (y = 1; y <= ymax; y++)
                {
                    tempcreep[x, y] = 0;
                }
            }


            for (x = 2; x < xmax; x++)
            {
                for (y = 2; y < ymax; y++)
                {
                    if (elev[x, y] > bedrock[x, y])
                    {
                        if (elev[x, y - 1] < elev[x, y] && elev[x, y - 1] > 0)
                        {
                            temp = ((elev[x, y] - elev[x, y - 1]) / DX) * SOIL_RATE * time / DX * Math.Pow(area[x,y]*DX*DX,0.5);
                            if ((elev[x, y] - temp) < bedrock[x, y]) temp = elev[x, y] - bedrock[x, y];
                            if (temp < 0) temp = 0;
                            tempcreep[x, y] -= temp;
                            tempcreep[x, y - 1] += temp;
                            if (index[x, y] != -9999)
                            {
                                slide_GS(x, y, temp, x, y - 1);
                            }
                        }
                        if (elev[x + 1, y - 1] < elev[x, y] && elev[x + 1, y - 1] > 0)
                        {
                            temp = ((elev[x, y] - elev[x + 1, y - 1]) / root) * SOIL_RATE * time / root * Math.Pow(area[x, y] * DX * DX, 0.5);
                            if ((elev[x, y] - temp) < bedrock[x, y]) temp = elev[x, y] - bedrock[x, y];
                            if (temp < 0) temp = 0;
                            tempcreep[x, y] -= temp;
                            tempcreep[x + 1, y - 1] += temp;
                            if (index[x, y] != -9999)
                            {
                                slide_GS(x, y, temp, x + 1, y - 1);
                            }

                        }
                        if (elev[x + 1, y] < elev[x, y] && elev[x + 1, y] > 0)
                        {
                            temp = ((elev[x, y] - elev[x + 1, y]) / DX) * SOIL_RATE * time / DX * Math.Pow(area[x, y] * DX * DX, 0.5);
                            if ((elev[x, y] - temp) < bedrock[x, y]) temp = elev[x, y] - bedrock[x, y];
                            if (temp < 0) temp = 0;
                            tempcreep[x, y] -= temp;
                            tempcreep[x + 1, y] += temp;
                            if (index[x, y] != -9999)
                            {
                                slide_GS(x, y, temp, x + 1, y);
                            }
                        }
                        if (elev[x + 1, y + 1] < elev[x, y] && elev[x + 1, y + 1] > 0)
                        {
                            temp = ((elev[x, y] - elev[x + 1, y + 1]) / root) * SOIL_RATE * time / root * Math.Pow(area[x, y] * DX * DX, 0.5);
                            if ((elev[x, y] - temp) < bedrock[x, y]) temp = elev[x, y] - bedrock[x, y];
                            if (temp < 0) temp = 0;
                            tempcreep[x, y] -= temp;
                            tempcreep[x + 1, y + 1] += temp;
                            if (index[x, y] != -9999)
                            {
                                slide_GS(x, y, temp, x + 1, y + 1);
                            }
                        }
                        if (elev[x, y + 1] < elev[x, y] && elev[x, y + 1] > 0)
                        {
                            temp = ((elev[x, y] - elev[x, y + 1]) / DX) * SOIL_RATE * time / DX * Math.Pow(area[x, y] * DX * DX, 0.5);
                            if ((elev[x, y] - temp) < bedrock[x, y]) temp = elev[x, y] - bedrock[x, y];
                            if (temp < 0) temp = 0;
                            tempcreep[x, y] -= temp;
                            tempcreep[x, y + 1] += temp;
                            if (index[x, y] != -9999)
                            {
                                slide_GS(x, y, temp, x, y + 1);
                            }
                        }
                        if (elev[x - 1, y + 1] < elev[x, y] && elev[x - 1, y + 1] > 0)
                        {
                            temp = ((elev[x, y] - elev[x - 1, y + 1]) / root) * SOIL_RATE * time / root * Math.Pow(area[x, y] * DX * DX, 0.5);
                            if ((elev[x, y] - temp) < bedrock[x, y]) temp = elev[x, y] - bedrock[x, y];
                            if (temp < 0) temp = 0;
                            tempcreep[x, y] -= temp;
                            tempcreep[x - 1, y + 1] += temp;
                            if (index[x, y] != -9999)
                            {
                                slide_GS(x, y, temp, x - 1, y + 1);
                            }
                        }
                        if (elev[x - 1, y] < elev[x, y] && elev[x - 1, y] > 0)
                        {
                            temp = ((elev[x, y] - elev[x - 1, y]) / DX) * SOIL_RATE * time / DX * Math.Pow(area[x, y] * DX * DX, 0.5);
                            if ((elev[x, y] - temp) < bedrock[x, y]) temp = elev[x, y] - bedrock[x, y];
                            if (temp < 0) temp = 0;
                            tempcreep[x, y] -= temp;
                            tempcreep[x - 1, y] += temp;
                            if (index[x, y] != -9999)
                            {
                                slide_GS(x, y, temp, x - 1, y);
                            }
                        }
                        if (elev[x - 1, y - 1] < elev[x, y] && elev[x - 1, y - 1] > 0)
                        {
                            temp = ((elev[x, y] - elev[x - 1, y - 1]) / root) * SOIL_RATE * time / root * Math.Pow(area[x, y] * DX * DX, 0.5);
                            if ((elev[x, y] - temp) < bedrock[x, y]) temp = elev[x, y] - bedrock[x, y];
                            if (temp < 0) temp = 0;
                            tempcreep[x, y] -= temp;
                            tempcreep[x - 1, y - 1] += temp;
                            if (index[x, y] != -9999)
                            {
                                slide_GS(x, y, temp, x - 1, y - 1);
                            }
                        }
                    }
                }
            }

            for (x = 1; x <= xmax; x++)
            {
                for (y = 1; y <= ymax; y++)
                {
                    elev[x, y] += tempcreep[x, y];
                }
            }

        }


		void get_area()
		{
			int x,y;

			for(x=1;x<=xmax;x++)
			{
				for(y=1;y<=ymax;y++)
				{
					area_depth[x,y]=1;
					if(elev[x,y]==-9999)area_depth[x,y]=0.0;
					area[x,y]=0;
				}
			}
			get_area2();
  
		}


		void get_area2()
		{

            int x, y;
			double ht, tot_q;
			double q_out;
			double temp_a;
			y_min=1;



            /*   route down  ********/

            for (y = 2; y < ymax; y++)
            {
                for (x = 2; x < xmax; x++)
                {


                    ht = elev[x, y];
                    if (elev[x, y] == -9999)
                    {
                        area_depth[x, y] = 0;
                        area[x, y] = 0;
                    }

                    if (elev[x - 1, y + 1] <= ht || elev[x, y + 1] <= ht || elev[x + 1, y + 1] <= ht)
                    {

                        //ht += 0.00000001;

                        tot_q = 0;
                        temp_a = 0;

                        q_out = area_depth[x, y];
                        if (area_depth[x, y] > area[x, y]) area[x, y] = area_depth[x, y];


                        if (elev[x - 1, y + 1] < ht && elev[x - 1, y + 1] > -9999)
                            tot_q += ((ht - elev[x - 1, y + 1]) / root);
                        if (elev[x, y + 1] < ht && elev[x, y + 1] > -9999)
                            tot_q += (ht - elev[x, y + 1]) / DX;
                        if (elev[x + 1, y + 1] < ht && elev[x + 1, y + 1] > -9999)
                            tot_q += ((ht - elev[x + 1, y + 1]) / root);

                        if (elev[x - 1, y + 1] < ht && elev[x - 1, y + 1] > -9999)
                        {
                            area_depth[x - 1, y + 1] += q_out * (((ht - elev[x - 1, y + 1]) / root) / tot_q);
                            temp_a += q_out * (((ht - elev[x - 1, y + 1]) / root) / tot_q);
                        }

                        if (elev[x, y + 1] < ht && elev[x, y + 1] > -9999)
                        {
                            area_depth[x, y + 1] += q_out * (((ht - elev[x, y + 1]) / DX) / tot_q);
                            temp_a += q_out * (((ht - elev[x, y + 1]) / DX) / tot_q);
                        }

                        if (elev[x + 1, y + 1] < ht && elev[x + 1, y + 1] > -9999)
                        {
                            area_depth[x + 1, y + 1] += q_out * (((ht - elev[x + 1, y + 1]) / root) / tot_q);
                            temp_a += q_out * (((ht - elev[x + 1, y + 1]) / root) / tot_q);
                        }

                        area_depth[x, y] -= temp_a;

                    }

                }

            }

 


            /*   route up  ********/

            for (y = ymax; y > 1; y--)
            {
                for (x = xmax; x > 1; x--)
                {

                    if (elev[x, y] == -9999)
                    {
                        area_depth[x, y] = 0;
                        area[x, y] = 0;
                    }

                    ht = elev[x, y];

                    if (elev[x - 1, y - 1] <= ht || elev[x, y - 1] <= ht || elev[x + 1, y - 1] <= ht)
                    {

                        //ht += 0.00000001;

                        tot_q = 0;
                        temp_a = 0;

                        q_out = area_depth[x, y];
                        if (area_depth[x, y] > area[x, y]) area[x, y] = area_depth[x, y];


                        if (elev[x - 1, y - 1] < ht)
                            tot_q += ((ht - elev[x - 1, y - 1]) / root);
                        if (elev[x, y - 1] < ht)
                            tot_q += (ht - elev[x, y - 1]) / DX;
                        if (elev[x + 1, y - 1] < ht)
                            tot_q += ((ht - elev[x + 1, y - 1]) / root);

                        if (elev[x - 1, y - 1] < ht)
                        {
                            area_depth[x - 1, y - 1] += q_out * (((ht - elev[x - 1, y - 1]) / root) / tot_q);
                            temp_a += q_out * (((ht - elev[x - 1, y - 1]) / root) / tot_q);
                        }

                        if (elev[x, y - 1] < ht)
                        {
                            area_depth[x, y - 1] += q_out * (((ht - elev[x, y - 1]) / DX) / tot_q);
                            temp_a += q_out * (((ht - elev[x, y - 1]) / DX) / tot_q);
                        }

                        if (elev[x + 1, y - 1] < ht)
                        {
                            area_depth[x + 1, y - 1] += q_out * (((ht - elev[x + 1, y - 1]) / root) / tot_q);
                            temp_a += q_out * (((ht - elev[x + 1, y - 1]) / root) / tot_q);
                        }

                        area_depth[x, y] -= temp_a;

                    }

                }

            }



            
			/****** route rl *******/

			for(x=xmax;x>1;x--)
			{
				for(y=ymax;y>1;y--)
				{

	
					ht=elev[x,y];
					if(elev[x,y]==-9999)
					{
						area_depth[x,y]=0;
						area[x,y]=0;
					}

					if(elev[x-1,y-1]<=ht||elev[x-1,y]<=ht||elev[x-1,y+1]<=ht)
					{

						//ht+=0.00000001;

						temp_a=0;
						tot_q=0;
						q_out=area_depth[x,y];
						if(area_depth[x,y]>area[x,y])area[x,y]=area_depth[x,y];



						if(elev[x-1,y-1]<ht)
							tot_q+=((ht-elev[x-1,y-1])/root);
						if(elev[x-1,y]<ht)
							tot_q+=(ht-elev[x-1,y])/DX;
						if(elev[x-1,y+1]<ht)
							tot_q+=((ht-elev[x-1,y+1])/root);

						if(elev[x-1,y-1]<ht)
						{
							area_depth[x-1,y-1]+=q_out*(((ht-elev[x-1,y-1])/root)/tot_q);
							temp_a+=q_out*(((ht-elev[x-1,y-1])/root)/tot_q);
						}

						if(elev[x-1,y]<ht)
						{
							area_depth[x-1,y]+=q_out*(((ht-elev[x-1,y])/DX)/tot_q);
							temp_a+=q_out*(((ht-elev[x-1,y])/DX)/tot_q);
						}

						if(elev[x-1,y+1]<ht)
						{
							area_depth[x-1,y+1]+=q_out*(((ht-elev[x-1,y+1])/root)/tot_q);
							temp_a+=q_out*(((ht-elev[x-1,y+1])/root)/tot_q); 
						}
						area_depth[x,y]-=temp_a;
					}
				}
			}

            /****** route lr *****/


            for (x = 1; x < xmax; x++)
            {
                for (y = 1; y < ymax; y++)
                {

                    ht = elev[x, y];
                    if (elev[x, y] == -9999)
                    {
                        area_depth[x, y] = 0;
                        area[x, y] = 0;
                    }

                    if (elev[x + 1, y - 1] <= ht || elev[x + 1, y] <= ht || elev[x + 1, y + 1] <= ht)
                    {

                        //ht += 0.00000001;

                        temp_a = 0;
                        tot_q = 0;
                        q_out = area_depth[x, y];
                        if (area_depth[x, y] > area[x, y]) area[x, y] = area_depth[x, y];


                        if (elev[x + 1, y - 1] < ht)
                            tot_q += ((ht - elev[x + 1, y - 1]) / root);
                        if (elev[x + 1, y] < ht)
                            tot_q += (ht - elev[x + 1, y]) / DX;
                        if (elev[x + 1, y + 1] < ht)
                            tot_q += ((ht - elev[x + 1, y + 1]) / root);

                        if (elev[x + 1, y - 1] < ht)
                        {
                            area_depth[x + 1, y - 1] += q_out * (((ht - elev[x + 1, y - 1]) / root) / tot_q);
                            temp_a += q_out * (((ht - elev[x + 1, y - 1]) / root) / tot_q);
                        }

                        if (elev[x + 1, y] < ht)
                        {
                            area_depth[x + 1, y] += q_out * (((ht - elev[x + 1, y]) / DX) / tot_q);
                            temp_a += q_out * (((ht - elev[x + 1, y]) / DX) / tot_q);
                        }

                        if (elev[x + 1, y + 1] < ht)
                        {
                            area_depth[x + 1, y + 1] += q_out * (((ht - elev[x + 1, y + 1]) / root) / tot_q);
                            temp_a += q_out * (((ht - elev[x + 1, y + 1]) / root) / tot_q);
                        }
                        area_depth[x, y] -= temp_a;

                    }
                }
            }


 		}


		void init_route(int flag,double reach_input_amount, double catchment_input_amount)
		{
			int x,y,n,inc,dan,x1,y1,tempxmin,tempxmax,tempymin,tempymax,waterflag;
			
			double temp_j_mean;
			double w = water_depth_erosion_threshold;

			this.InfoStatusPanel.Text="Determining scan area";		// MJ 14/01/05

			y_min=1;
			/* w is the water threshold, above which it recognises etc */

			temp_j_mean=j_mean;

			/****** 0 mins and max's ******/


			if(flag==TRUE)
			{
				for(x=1;x<=xmax;x++)
				{
					for(y=1;y<=ymax;y++)
					{
						//discharge[x,y]+=input_amount*Math.Pow(DX,2);
						water_depth[x,y]=0;
						cross_scan[x,y]=y;
						down_scan[y,x]=x;
						for(n=0;n<=8;n++)max_flow[x,y,n]=0;
						for(n=0;n<=1;n++)flow_dir[x,y,n]=0;
					}
				}
			}


			/*printf("\n");*/
			if(catchment_mode_box.Checked==true)j_mean=catchment_input_amount;

			if(flag==TRUE)
			{

				for(dan=1;dan<=init_route_number_of_scans;dan++)
				{
					for(x=1;x<=xmax;x++)
					{
						for(y=1;y<=ymax;y++)
						{
							water_depth[x,y]=0;
							lat_vol[x,y]=0;
							if(catchment_mode_box.Checked==true)discharge[x,y]+=catchment_input_amount*Math.Pow(DX,2);
							
							//discharge[x,y]+=.001; //un comment to make model scan everywhere...
						}
					}
					


					if(reach_mode_box.Checked==true)
					{
						// if the input type flag is 0 then the discharge inputs are from points
						//j_mean=0;
				
						for(n=0;n<=number_of_points-1;n++)
						{
							x=inpoints[n,0];
							y=inpoints[n,1];			
							discharge[x,y]+=reach_input_amount/number_of_points;
						}
					}
                    //add sinks
                    for (x = 1; x <= xmax; x++) { for (y = 1; y <= ymax; y++) { elev[x, y] += pool_depth[x, y]; } }

					route_lr();
					route_up();	
					route_rl();
					route_down(cycle);	
					route_rl();	
					route_up();
					route_lr();
					route_down(cycle);

                    //remove sinks
                    for (x = 1; x <= xmax; x++){ for (y = 1; y <= ymax; y++) {
                            elev[x, y] -= pool_depth[x, y]; if (water_depth[x, y] > 0) water_depth[x, y] += pool_depth[x, y]; } }

				}
			}



			/*******************************/
	
			for(x=1;x<=xmax;x++)
			{
				for(y=1;y<=ymax;y++)
				{
					cross_scan[x,y]=0;
					down_scan[y,x]=0;
					if(water_depth[x,y]==-9999)water_depth[x,y]=0;
				}
			}
			

			for(x=1;(x<=xmax);x++)
			{
				for(y=1;y<=(ymax);y++)
				{
					tempxmin=-3;
					tempxmax=3;
					tempymin=-3;
					tempymax=3;
					while(x+tempxmin<1)tempxmin++;
					while(x+tempxmax>xmax)tempxmax--;
					while(y+tempymin<1)tempymin++;
					while(y+tempymax>ymax)tempymax--;
					waterflag=FALSE;
					for(x1=tempxmin;x1<=tempxmax;x1++)
					{
						for(y1=tempymin;y1<=tempymax;y1++)
						{
							if(water_depth[x+x1,y+y1]>=w)
							{
								waterflag=TRUE;
							}
						}
					}
					if(waterflag==FALSE)
						water_depth[x,y]=-9999;
					if(elev[x,y]==-9999)water_depth[x,y]=-9999;
				}
			}

			

			for(x=1;x<=xmax;x++)
			{
				inc=1;
				for(y=1;y<=ymax;y++)
				{
					discharge[x,y]=0;
					max_flow[x,y,0]=0;
					water_depth2[x,y]=0;
					if(water_depth[x,y]>-9999)
					{
						cross_scan[x,inc]=y;
						inc++;
					}	
					//discharge[x,y]=0;			
				}
			}	

			for(y=1;y<=ymax;y++)
			{
				inc=1;
				for(x=xmax;x>=1;x--)
				{
					if(water_depth[x,y]>-9999)
					{
						down_scan[y,inc]=x;
						inc++;
					}
					//if(input_type_flag==1)discharge[x,y]=0;
				}
			}
	
			for(y=1;y<=ymax;y++)
			{

				// line added to remove excess Qw values from far RH column
				if(discharge[xmax+1,y]>0)
				{
					discharge[xmax+1,y]=0;
				}
				// end of addition

				inc=1;
				while(down_scan[y,inc]>0)
				{
					x=down_scan[y,inc];
					inc++;	
					water_depth[x,y]=0;

				}
			}
			j_mean=temp_j_mean;





//			//** these lines have been added in attempt to remove discharge spikes  MJ 25/01/05
//			for(x=1;(x<=xmax);x++)
//			{
//				for(y=1;y<=(ymax);y++)
//				{
//					discharge[x,y] = 0.0;
//				}
//			}
//
//			for(int ccc=1;ccc<=5*init_route_number_of_scans;ccc++)
//			{
//				if(input_type_flag==0)
//				{
//					// if the input type flag is 0 then the discharge inputs are from points
//					j_mean=0;
//					double totqtemp=0;
//					for(n=0;n<=number_of_points-1;n++)
//					{
//						totqtemp+=inputfile[n,(int)((cycle-init_cycle)/input_time_step),1];
//					}
//	
//					if(totqtemp>init_discharge)
//					{
//						init_discharge=init_discharge*2;
//						if(init_discharge<totqtemp)init_discharge=totqtemp*1.5;
//						Console.Write("scanning up ");
//						init_route(TRUE,init_discharge);
//						time_factor=0.0000000001;
//					}
//
//					if(totqtemp<(init_discharge/2)&&init_discharge>80)
//					{
//						init_discharge=init_discharge/2;
//						Console.Write(" scanning down ");
//						init_route(TRUE,init_discharge);
//						time_factor=0.0000000001;
//					}
//
//					for(n=0;n<=number_of_points-1;n++)
//					{
//						x=inpoints[n,0];
//						y=inpoints[n,1];		
//						discharge[x,y]+=inputfile[n,(int)((cycle-init_cycle)/input_time_step),1];
//					}
//				}
//
//				else if(input_type_flag==1)
//				{
//					// if the input type flag is 1 then the discharge is input from the hydrograph...
//					if(cycle>=time_1)
//					{
//						do
//						{
//							time_1+=2;
//							calc_J(time_1);
//							if(time_factor>3600&&new_j_mean>(0.2/3000000))
//							{
//								cycle=time_1+60;
//								time_factor=3600;
//							}		   
//						}while(time_1<cycle);
//					}
//	
//					calchydrograph(time_1-cycle);
//	
//					if(j_mean>=baseflow)
//					{
//						baseflow=baseflow*2;
//						Console.Write("goig up.. \n");
//						get_area();
//						init_route(TRUE,baseflow);
//						time_factor=0.0000000001;
//					}
//	
//	
//					if(baseflow>(j_mean*2)&&baseflow>0.0000005)
//					{
//						baseflow=j_mean*1.01;
//						Console.Write("going down.. \n");
//						get_area();
//						init_route(TRUE,baseflow);
//						time_factor=0.0000000001;
//					}
//			
//					//discharge[20,300]+=j_mean*10000000; commented out, if entered allows flow to be entered at a point as well. 
//				}
//
//				route_lr();
//				route_up();	
//				route_rl();
//				route_down(cycle);	
//				route_rl();	
//				route_up();
//				route_lr();
//				route_down(cycle);
//			}
//			for(y=1;y<=ymax;y++)
//			{
//				discharge[xmax+1,y]=0;
//			}
//
//			//** end of discharge spike removal attempt

			this.InfoStatusPanel.Text="Running";		// MJ 14/01/05

		}

		private void calc_width(int x, int y)
		{
			int z1;
			int inside=0;
			int outside=0;

            if (x < 6 || x > (xmax - 5) || y < 6 || y > (ymax - 5))
            {
                width[x, y] = 10;
                return;
            }

			for(z1=1;z1<=5;z1++)
			{
				if(edge[x+z1,y]>=0)outside=z1;
				if(edge[x+z1,y+z1]>=0)outside=z1;
				if(edge[x+z1,y-z1]>=0)outside=z1;
				if(edge[x,y-z1]>=0)outside=z1;
				if(edge[x,y+z1]>=0)outside=z1;
				if(edge[x-z1,y]>=0)outside=z1;
				if(edge[x-z1,y+z1]>=0)outside=z1;
				if(edge[x-z1,y-z1]>=0)outside=z1;
				if(outside>0)z1=5;
			}
			for(z1=1;z1<=5;z1++)
			{
				if(edge[x+z1,y]<=0&&edge[x+z1,y]>-9999)inside=z1;
				if(edge[x+z1,y+z1]<=0&&edge[x+z1,y+z1]>-9999)inside=z1;
				if(edge[x+z1,y-z1]<=0&&edge[x+z1,y-z1]>-9999)inside=z1;
				if(edge[x,y-z1]<=0&&edge[x,y-z1]>-9999)inside=z1;
				if(edge[x,y+z1]<=0&&edge[x,y+z1]>-9999)inside=z1;
				if(edge[x-z1,y]<=0&&edge[x-z1,y]>-9999)inside=z1;
				if(edge[x-z1,y+z1]<=0&&edge[x-z1,y+z1]>-9999)inside=z1;
				if(edge[x-z1,y-z1]<=0&&edge[x-z1,y-z1]>-9999)inside=z1;
				if(inside>0)z1=5;
			}

			width[x,y]=inside+outside;
		}


		
		private void calc_J(double cycle)
		{

			double local_rain_fall_rate; /** in m/second **/
			double local_time_step=120; /** in secs */
			old_j_mean=new_j_mean;
			jo=j;

            /* Get The M Value From File If One Is Specified */
            if (variable_m_value_flag == 1)
            {
                M = hourly_m_value[1 + (int)(cycle / 60)];
            }

			local_rain_fall_rate=0;
			if(hourly_rain_data[(int)(cycle/60)]>0)
			{
				local_rain_fall_rate=rain_factor*((hourly_rain_data[(int)(cycle/60)]/1000)/3600); /** divide by 1000 to make m/hr, then by 3600 for m/sec */
			}

			if (local_rain_fall_rate==0)
			{
				j=jo/(1+((jo*local_time_step)/M));
				new_j_mean=M/local_time_step*Math.Log(1+((jo*local_time_step)/M));		
			}

			if (local_rain_fall_rate>0)
			{
				j=local_rain_fall_rate/(((local_rain_fall_rate-jo)/jo)*Math.Exp((0-local_rain_fall_rate)*local_time_step/M)+1);
				new_j_mean=(M/local_time_step)*Math.Log(((local_rain_fall_rate-jo)+jo*Math.Exp((local_rain_fall_rate*local_time_step)/M))/local_rain_fall_rate);
			}
			if(new_j_mean<0)new_j_mean=0;
			/**printf("new J mean = %f\n",(new_j_mean*1000));*/ 

		}

		
		void route_up()
		{
			int x,y,inc, n,i;
			double slope=0, depth=0,lowest , tot_ht, tot_q, temp_a, q_out, ht;
			double manning=0.03;
			double factor=1;
			double threshold=MIN_Q;
			
			inc=1;
			
  
			//this.InfoStatusPanel.Text="Up";
			for(y=ymax;y>=1;y--)
			{
				inc=1;    
				//drawwater(mygraphics);
				while(down_scan[y,inc]>0)
				{
					x=down_scan[y,inc];
					inc++;
            
					ht=elev[x,y];
      
					/** inputting water from the edges **/
      
					if(water_depth[x,y+1]==-9999&&water_depth[x,y]!=-99)
					{
						/** get slope **/
						discharge[x,y]=(area[x,y]*j_mean)*Math.Pow(DX,2);
						water_depth[x,y]=-99;
					}
					else
					{
						discharge[x,y]+=((j_mean*Math.Pow(DX,2))/4);     // 4 to 8    19/01/05
					}
      
					/* determine average slope */

					if(discharge[x,y]>MIN_Q)
					{
	
						slope=mean_bed_slope(x,y);
						if(slope<0.002)slope=0.002;
                        if (slope > 0.01) slope = 0.01;
	
						threshold=K*slope*DX;
						if(threshold<MIN_Q)threshold=MIN_Q;
	
						if(y==1)slope=0.001;
						//depth=discharge[x,y]/(Math.Pow(DX,1));
	
						/*** now calc depth. *****/

						//slope=0.005;
						
						depth=0;
						//						depth=(Math.Pow((((discharge[x,y]/Math.Pow(DX,1))*manning)/
						//								Math.Pow(slope,0.5)),0.6));

						depth=(Math.Pow((((discharge[x,y]/Math.Pow(DX,1))*calc_manning(x,y))/
							Math.Pow(slope,0.5)),0.6));
                        

						//if(depth>discharge[x,y])depth=discharge[x,y];
					
	
						/***** depth added if greater than that there. **/
	
			
						if(depth>water_depth[x,y])
						{
							water_depth[x,y]=depth;
							lat_vol[x,y]=discharge[x,y];
						}

	
	
					}
      

      
					/* then do surface routing */
      
      
					if(x>1&&x<(xmax)&&discharge[x,y]>threshold&&water_depth[x-1,y-1]!=-9999&&water_depth[x,y-1]!=-9999&&water_depth[x+1,y-1]!=-9999)
					{
	
						tot_q=0;
						temp_a=0;
						
	
						/********* first sort out wet height *****/
						/* starting with d/s slopes ****/
						discharge[x,y]-=threshold;


						/***** now to route discharge d/s ***************/
						tot_ht=elev[x,y]+depth;
	
						//
						// start of main routing bit
						//

						if(elev[x,y-1]<tot_ht||elev[x-1,y-1]<tot_ht||elev[x+1,y-1]<tot_ht)
						{
							/**** check to see if base is lower *******/
							/* if not then leave some discharge       */
		
							q_out=discharge[x,y];
							lowest=1000;
		
							if(elev[x-1,y-1]>elev[x,y]&&
								elev[x,y-1]>elev[x,y]&&
								elev[x+1,y-1]>elev[x,y])
							{
								if(elev[x-1,y-1]<lowest)lowest=elev[x-1,y-1];
								if(elev[x,y-1]<lowest)lowest=elev[x,y-1];
								if(elev[x+1,y-1]<lowest)lowest=elev[x+1,y-1];
                                q_out = q_out * ((tot_ht - lowest) / water_depth[x, y]);
								if(q_out>discharge[x,y])q_out=0; // line to prevent very very small depths increasing q_out disproportionaltely
								if(lowest>tot_ht)q_out=0;
							}
		

							n=x;
							while((x-n)<SW&&tot_ht>elev[n-1,y-1]&&(n-1)>0&&water_depth[n-1,y-1]!=-9999)//&&q_out>lat_vol[n-1,y-1])
							{
								tot_q+=Math.Pow(((tot_ht-elev[n-1,y-1])/root),fexp);
								n--;
							}

							if(tot_ht>elev[x,y-1]&&water_depth[x,y-1]!=-9999)
							{
								tot_q+=Math.Pow(((tot_ht-elev[x,y-1])/DX),fexp);
							}
							
							n=x;
							while((n-x)<SW&&tot_ht>elev[n+1,y-1]&&(n+1)<xmax&&water_depth[n+1,y-1]!=-9999)//&&q_out>lat_vol[n+1,y-1])
							{
								tot_q+=Math.Pow(((tot_ht-elev[n+1,y-1])/root),fexp);
								n++;
							}

						
							n=x;

							double tt=0; // temp variable
							while((x-n)<SW&&tot_ht>elev[n-1,y-1]&&(n-1)>0&&water_depth[n-1,y-1]!=-9999)//&&q_out>lat_vol[n-1,y-1])
							{
								tt=q_out*(Math.Pow(((tot_ht-elev[n-1,y-1])/root),fexp)/tot_q);

                                discharge[n - 1, y - 1] += tt;
                                up_in[n - 1, y - 1] += tt;
                                //right_in[n - 1, y - 1] += tt;

                                for (i = n; i < x; i++)
                                {
                                    //up_in[i, y - 1] += tt;
                                    right_in[i - 1, y - 1] += tt;

                                    right_out[i, y - 1] += tt;
                                }
                                temp_a += tt;

								n--;
							}
							if(n<x)qcounter[x-1,y-1]++;

							if(tot_ht>elev[x,y-1]&&water_depth[x,y-1]!=-9999)
							{
								tt=q_out*(Math.Pow(((tot_ht-elev[x,y-1])/DX),fexp)/tot_q);

                                discharge[x, y - 1] += tt;
                                up_in[x, y - 1] += tt;

                                temp_a += tt;

							}

							n=x;
							while((n-x)<SW&&tot_ht>elev[n+1,y-1]&&(n+1)<xmax&&water_depth[n+1,y-1]!=-9999)//&&q_out>lat_vol[n+1,y-1])
							{
								tt=q_out*(Math.Pow(((tot_ht-elev[n+1,y-1])/root),fexp)/tot_q);
                                discharge[n + 1, y - 1] += tt;
                                up_in[n + 1, y - 1] += tt;
                                //left_in[n + 1, y - 1] += tt;

                                for (i = n; i > x; i--)
                                {

                                    left_in[i + 1, y - 1] += tt;
                                    left_out[i, y - 1] += tt;
                                }
                                temp_a += tt;

								n++;
							}


							discharge[x,y]=discharge[x,y]-temp_a;
							up_out[x,y]+=temp_a;
                            flowout[x, y] += temp_a;
						}
	

						/* add subsurface flow back in **/
						discharge[x,y]+=threshold;
					}
      
					/* then route subsurface flow...*/

					if(discharge[x,y]>0&&water_depth[x-1,y-1]!=-9999&&water_depth[x,y-1]!=-9999&&water_depth[x+1,y-1]!=-9999)
					{
						if(elev[x-1,y-1]<=ht||elev[x,y-1]<=ht||elev[x+1,y-1]<=ht)
						{
	  
	  
							tot_q=0;
							temp_a=0;
							q_out=discharge[x,y];
							if(q_out>MIN_Q)q_out=MIN_Q;
	  
							if(elev[x-1,y-1]<ht)
								tot_q+=Math.Pow(((ht-elev[x-1,y-1])/root),factor);
							if(elev[x,y-1]<ht)
								tot_q+=Math.Pow(((ht-elev[x,y-1])/DX),factor);
							if(elev[x+1,y-1]<ht)
								tot_q+=Math.Pow(((ht-elev[x+1,y-1])/root),factor);
	  
							if(elev[x-1,y-1]<ht)
							{
								discharge[x-1,y-1]+=q_out*(((ht-elev[x-1,y-1])/root)/tot_q);
								//up_in[x-1,y-1]+=q_out*(((ht-elev[x-1,y-1])/root)/tot_q);
								temp_a+=q_out*(((ht-elev[x-1,y-1])/root)/tot_q);
							}
	  
							if(elev[x,y-1]<ht)
							{
								discharge[x,y-1]+=q_out*(((ht-elev[x,y-1])/DX)/tot_q);
								//up_in[x,y-1]+=q_out*(((ht-elev[x,y-1])/DX)/tot_q);
								temp_a+=q_out*(((ht-elev[x,y-1])/DX)/tot_q);
							}
	  
							if(elev[x+1,y-1]<ht)
							{
								discharge[x+1,y-1]+=q_out*(((ht-elev[x+1,y-1])/root)/tot_q);
								//up_in[x+1,y-1]+=q_out*(((ht-elev[x+1,y-1])/root)/tot_q);
								temp_a+=q_out*(((ht-elev[x+1,y-1])/root)/tot_q);
							}
	  
							//up_out[x,y]+=temp_a;
							discharge[x,y]=discharge[x,y]-temp_a;



	  
						}
					}   
				}
			}
		}


		void route_down(double cycle)
		{
			int x,y,inc, inctot,n,i;
			double slope=0, depth=0,lowest , tot_ht, tot_q, temp_a, q_out, ht;
			double manning=0.03;
			double factor=1;
			double threshold=MIN_Q;
			
            inc=1;
			inctot=0;

			//if(checkBox1.Checked==true)this.InfoStatusPanel.Text="Down";
			for(y=1;y<=ymax;y++)
			{
    
				inctot+=inc;
				inc=1;
				//if(checkBox1.Checked==true)drawwater(mygraphics);
    
				while(down_scan[y,inc]>0)
				{
					x=down_scan[y,inc];
					inc++;
      
      
					ht=elev[x,y];
      
      
					/* route water if not enough to flow */
      
					if(water_depth[x,y-1]==-9999&&water_depth[x,y]!=-99)
					{

						discharge[x,y]=(area[x,y]*j_mean)*Math.Pow(DX,2);
						water_depth[x,y]=-99;
	
					}
					else
					{
						discharge[x,y]+=((j_mean*Math.Pow(DX,2))/4);    
					}
      

					if(discharge[x,y]>MIN_Q)
					{
	
						slope=mean_bed_slope(x,y);
						if(slope<0.002)slope=0.002;
                        if (slope > 0.01) slope = 0.01;
							
						threshold=K*slope*DX;
						if(threshold<MIN_Q)threshold=MIN_Q;

						if(y==ymax)slope=0.001;
	
						depth=0;
						//depth=(Math.Pow((((discharge[x,y]/Math.Pow(DX,1))*manning)/
						//Math.Pow(slope,0.5)),0.6));
						depth=(Math.Pow((((discharge[x,y]/Math.Pow(DX,1))*calc_manning(x,y))/
							Math.Pow(slope,0.5)),0.6));
                        
						/***** depth added if greater than that there. **/
	
						if(depth>water_depth[x,y])
						{
							water_depth[x,y]=depth;
							lat_vol[x,y]=discharge[x,y];
						}

					}

				
      
					
					/* then do surface routing */
      
      
					if(x>1&&x<(xmax)&&discharge[x,y]>threshold&&water_depth[x-1,y+1]!=-9999&&water_depth[x,y+1]!=-9999&&water_depth[x+1,y+1]!=-9999)
					{
	
						
						tot_q=0;
	
						temp_a=0;
						
	
						/********* first sort out wet height *****/	
	


	
						discharge[x,y]-=threshold;


						/***** now to route discharge d/s ***************/
	
						tot_ht=elev[x,y]+depth;
						//
						// start of main routing bit
						//

						if(elev[x,y+1]<tot_ht||elev[x-1,y+1]<tot_ht||elev[x+1,y+1]<tot_ht)
						{
							
							q_out=discharge[x,y];

							/**** check to see if base is lower *******/
							/* if not then leave some discharge       */
		
							lowest=1000;
		
							if(	elev[x-1,y+1]>elev[x,y]&&
								elev[x,y+1]>elev[x,y]&&
								elev[x+1,y+1]>elev[x,y])
							{
								
								if(elev[x-1,y+1]<lowest)lowest=elev[x-1,y+1];
								if(elev[x,y+1]<lowest)lowest=elev[x,y+1];
								if(elev[x+1,y+1]<lowest)lowest=elev[x+1,y+1];
								q_out=q_out*((tot_ht-lowest)/water_depth[x,y]);
								if(q_out>discharge[x,y])q_out=0; // line to prevent very very small depths increasing q_out disproportionaltely
								if(lowest>tot_ht)q_out=0;
							}

						

							
							n=x;
							while((x-n)<SW&&tot_ht>elev[n-1,y+1]&&(n-1)>0&&water_depth[n-1,y+1]!=-9999)//&&q_out>lat_vol[n-1,y+1])
							{
								tot_q+=Math.Pow(((tot_ht-elev[n-1,y+1])/root),fexp);
								n--;
							}

							if(tot_ht>elev[x,y+1]&&water_depth[x,y+1]!=-9999)
							{
								tot_q+=Math.Pow(((tot_ht-elev[x,y+1])/DX),fexp);
							}

							n=x;
							while((n-x)<SW&&tot_ht>elev[n+1,y+1]&&(n+1)<xmax&&water_depth[n+1,y+1]!=-9999)//&&q_out>lat_vol[n+1,y+1])
							{
								tot_q+=Math.Pow(((tot_ht-elev[n+1,y+1])/root),fexp);
								n++;
							}


							n=x;
							double tt=0; //temp variable
							while((x-n)<SW&&tot_ht>elev[n-1,y+1]&&(n-1)>0&&water_depth[n-1,y+1]!=-9999)//&&q_out>lat_vol[n-1,y+1])
							{
								tt=q_out*(Math.Pow(((tot_ht-elev[n-1,y+1])/root),fexp)/tot_q);

                                discharge[n - 1, y + 1] += tt;
                                down_in[n - 1, y + 1] += tt;
                                //right_in[n - 1, y + 1] += tt;

                                for (i = n; i < x; i++)
                                {
                                    //down_in[i, y + 1] += tt;
                                    right_in[i - 1, y + 1] += tt;
                                    right_out[i, y + 1] += tt;
                                }
                                temp_a += tt;

								n--;
							}


							if(tot_ht>elev[x,y+1]&&water_depth[x,y+1]!=-9999)
							{
								tt=q_out*(Math.Pow(((tot_ht-elev[x,y+1])/DX),fexp)/tot_q);

                                discharge[x, y + 1] += tt;
                                down_in[x, y + 1] += tt;

                                temp_a += tt;						
									

							}

							n=x;
							while((n-x)<SW&&tot_ht>elev[n+1,y+1]&&(n+1)<xmax&&water_depth[n+1,y+1]!=-9999)//&&q_out>lat_vol[n+1,y+1])
							{
								tt=q_out*(Math.Pow(((tot_ht-elev[n+1,y+1])/root),fexp)/tot_q);

                                discharge[n + 1, y + 1] += tt;
                                down_in[n + 1, y + 1] += tt;
                                //left_in[n + 1, y + 1] += tt;

                                for (i = n; i > x; i--)
                                {
                                    //down_in[i, y + 1] += tt;
                                    left_in[i + 1, y + 1] += tt;
                                    left_out[i, y + 1] += tt;
                                }
                                temp_a += tt;

								n++;
							}



							discharge[x,y]=discharge[x,y]-temp_a;
							down_out[x,y]+=temp_a;
                            flowout[x, y] += temp_a;
						}
						discharge[x,y]+=threshold;
	
					}
      
					if(discharge[x,y]>0&&water_depth[x-1,y+1]!=-9999&&water_depth[x,y+1]!=-9999&&water_depth[x+1,y+1]!=-9999)
					{
						if(elev[x-1,y+1]<=ht||elev[x,y+1]<=ht||elev[x+1,y+1]<=ht)
						{
	  
	  
							tot_q=0;
							temp_a=0;
							q_out=discharge[x,y];
							if(q_out>MIN_Q)q_out=MIN_Q;
	  
							if(elev[x-1,y+1]<ht)
								tot_q+=Math.Pow(((ht-elev[x-1,y+1])/root),factor);
							if(elev[x,y+1]<ht)
								tot_q+=Math.Pow(((ht-elev[x,y+1])/DX),factor);
							if(elev[x+1,y+1]<ht)
								tot_q+=Math.Pow(((ht-elev[x+1,y+1])/root),factor);
	  
							if(elev[x-1,y+1]<ht)
							{
								discharge[x-1,y+1]+=q_out*(((ht-elev[x-1,y+1])/root)/tot_q);
								//down_in[x-1,y+1]+=q_out*(((ht-elev[x-1,y+1])/root)/tot_q);
								temp_a+=q_out*(((ht-elev[x-1,y+1])/root)/tot_q);
							}
	  
							if(elev[x,y+1]<ht)
							{
								discharge[x,y+1]+=q_out*(((ht-elev[x,y+1])/DX)/tot_q);
								//down_in[x,y+1]+=q_out*(((ht-elev[x,y+1])/DX)/tot_q);
								temp_a+=q_out*(((ht-elev[x,y+1])/DX)/tot_q);
							}
	  
							if(elev[x+1,y+1]<ht)
							{
								discharge[x+1,y+1]+=q_out*(((ht-elev[x+1,y+1])/root)/tot_q);
								//down_in[x+1,y+1]+=q_out*(((ht-elev[x+1,y+1])/root)/tot_q);
								temp_a+=q_out*(((ht-elev[x+1,y+1])/root)/tot_q);
							}
							/*	if(y==ymax-150)totty+=temp_a;*/
							//down_out[x,y]+=temp_a;
							discharge[x,y]=discharge[x,y]-temp_a;

							  
						}
					}
      
      
				}
			}

		}


		double route_lr()
		{
			int x,y,inc, inctot,n,i;
			double jsat, q, ht, slope=0, depth=0,lowest , tot_ht, tot_q, temp_a, q_out, slopetot;
			double manning=0.03;
			double factor=1;
			double totty=0;
			double threshold=MIN_Q, slopemax;
			y=y_min;
			inctot=0;
			inc=1;
        
			//this.InfoStatusPanel.Text="left-right";
			for(x=1;x<=(xmax);x++)
			{

				inctot+=inc;
				inc=1;
				//drawwater(mygraphics);
				while(cross_scan[x,inc]>0)
				{
	    
					y=cross_scan[x,inc];
					inc++;
	   	    
					ht=elev[x,y];	    
	    
					if(water_depth[x-1,y]==-9999&&water_depth[x,y]!=-99)
					{
						discharge[x,y]=(area[x,y]*j_mean)*Math.Pow(DX,2);
						water_depth[x,y]=-99;
					}
					else
					{
						discharge[x,y]+=((j_mean*Math.Pow(DX,2))/4);     // 4 to 8    19/01/05
					}
					if(discharge[x,y]>MIN_Q)
					{
	      
						slope=mean_bed_slope(x,y);
						if(slope<0.002)slope=0.002;
                        if (slope > 0.01) slope = 0.01;
	      
						threshold=K*slope*DX;
						if(threshold<MIN_Q)threshold=MIN_Q;
						/*** now calc depth. *****/
	      
						if(x==xmax)slope=0.001;
	      
						depth=0;
						//						depth=(Math.Pow((((discharge[x,y]/Math.Pow(DX,1))*manning)/
						//								Math.Pow(slope,0.5)),0.6));
						
						depth=(Math.Pow((((discharge[x,y]/Math.Pow(DX,1))*calc_manning(x,y))/
							Math.Pow(slope,0.5)),0.6));
                        

						//if(y==50)Console.WriteLine(Convert.ToString(calc_manning(x,y)));

						/***** depth added if greater than that there. **/
	      
						if(depth>water_depth[x,y])
						{
							water_depth[x,y]=depth;
							lat_vol[x,y]=discharge[x,y];
						}

		      
					}
	    

					//double totalal=0; int x1,y1;for(x1=1;x1<=xmax;x1++){for(y1=1;y1<=ymax;y1++){totalal+=discharge[x,y];}}if(totalal>100)Console.WriteLine("now9");

	    
					/* route water if not enough to flow */
	    
					/* then do surface routing */
	    
					if(y>1&&y<(ymax)&&discharge[x,y]>threshold&&water_depth[x+1,y-1]!=-9999&&water_depth[x+1,y]!=-9999&&water_depth[x+1,y+1]!=-9999)
					{
						      
						tot_q=0;
	      
						temp_a=0;
	      
			
						discharge[x,y]-=threshold;

	      
						/***** now to route discharge d/s ***************/
	      
						tot_ht=elev[x,y]+depth;

						//
						// start of main routing bit
						//

						if(elev[x+1,y-1]<tot_ht||elev[x+1,y]<tot_ht||elev[x+1,y+1]<tot_ht)
						{

							/**** check to see if base is lower *******/
							/* if not then leave some discharge       */

							q_out=discharge[x,y];
							lowest=1000;
		
							if(	elev[x+1,y-1]>elev[x,y]&&
								elev[x+1,y]>elev[x,y]&&
								elev[x+1,y+1]>elev[x,y])
							{
								if(elev[x+1,y-1]<lowest)lowest=elev[x+1,y-1];
								if(elev[x+1,y]<lowest)lowest=elev[x+1,y];
								if(elev[x+1,y+1]<lowest)lowest=elev[x+1,y+1];
                                q_out = q_out * ((tot_ht - lowest) / water_depth[x, y]);
								if(q_out>discharge[x,y])q_out=0; // line to prevent very very small depths increasing q_out disproportionaltely
								if(lowest>tot_ht)q_out=0;
							}


							//max_flow[x,y,0]+=q_out;

							
							n=y;
							while((y-n)<SW&&tot_ht>elev[x+1,n-1]&&(n-1)>0&&water_depth[x+1,n-1]!=-9999)//&&q_out>lat_vol[x+1,n-1])
							{
								tot_q+=Math.Pow(((tot_ht-elev[x+1,n-1])/root),fexp);
								n--;
							}

							if(tot_ht>elev[x+1,y]&&water_depth[x+1,y]!=-9999)
							{
								tot_q+=Math.Pow(((tot_ht-elev[x+1,y])/DX),fexp);
							}

							n=y;
							while((n-y)<SW&&tot_ht>elev[x+1,n+1]&&(n+1)<ymax&&water_depth[x+1,n+1]!=-9999)//&&q_out>lat_vol[x+1,n+1])
							{
								tot_q+=Math.Pow(((tot_ht-elev[x+1,n+1])/root),fexp);
								n++;
							}


							n=y;

							double tt=0; // temp variable
							while((y-n)<SW&&tot_ht>elev[x+1,n-1]&&(n-1)>0&&water_depth[x+1,n-1]!=-9999)//&&q_out>lat_vol[x+1,n-1])
							{
								tt=q_out*(Math.Pow(((tot_ht-elev[x+1,n-1])/root),fexp)/tot_q);

                                discharge[x + 1, n - 1] += tt;
                                left_in[x + 1, n - 1] += tt;
                                //up_in[x + 1, n - 1] += tt;

                                for (i = n; i < y; i++)
                                {
                                    //left_in[x + 1, i] += tt;
                                    up_in[x + 1, i - 1] += tt;
                                    up_out[x + 1, i] += tt;
                                }
                                temp_a += tt;

								n--;
							}

							if(tot_ht>elev[x+1,y]&&water_depth[x+1,y]!=-9999)
							{
								tt=q_out*(Math.Pow(((tot_ht-elev[x+1,y])/DX),fexp)/tot_q);

                                discharge[x + 1, y] += tt;
                                left_in[x + 1, y] += tt;

                                temp_a += tt;


							}

							n=y;
							while((n-y)<SW&&tot_ht>elev[x+1,n+1]&&(n+1)<ymax&&water_depth[x+1,n+1]!=-9999)//&&q_out>lat_vol[x+1,n+1])
							{
								tt=q_out*(Math.Pow(((tot_ht-elev[x+1,n+1])/root),fexp)/tot_q);

                                discharge[x + 1, n + 1] += tt;
                                left_in[x + 1, n + 1] += tt;
                                //down_in[x + 1, n + 1] += tt;

                                for (i = n; i > y; i--)
                                {
                                    //left_in[x + 1, i] += tt;
                                    down_in[x + 1, i + 1] += tt;
                                    down_out[x + 1, i] += tt;
                                }
                                temp_a += tt;

								n++;
							}



							if(x==xmax)totty+=temp_a;
							discharge[x,y]=discharge[x,y]-temp_a;
							left_out[x,y]+=temp_a;
                            
						}
	      
						discharge[x,y]+=threshold;
	      
					}
	    
					if(discharge[x,y]>0&&water_depth[x+1,y-1]!=-9999&&water_depth[x+1,y]!=-9999&&water_depth[x+1,y+1]!=-9999)
					{
						if(elev[x+1,y-1]<=ht||elev[x+1,y]<=ht||elev[x+1,y+1]<=ht)
						{
		
							tot_q=0;
							temp_a=0;
							q_out=discharge[x,y];
							if(q_out>MIN_Q)q_out=MIN_Q;
		
							if(elev[x+1,y-1]<ht)
								tot_q+=((ht-elev[x+1,y-1])/root);
							if(elev[x+1,y]<ht)
								tot_q+=(ht-elev[x+1,y])/DX;
							if(elev[x+1,y+1]<ht)
								tot_q+=((ht-elev[x+1,y+1])/root);
		
							if(elev[x+1,y-1]<ht)
							{
								discharge[x+1,y-1]+=q_out*(((ht-elev[x+1,y-1])/root)/tot_q);
								//left_in[x+1,y-1]+=q_out*(((ht-elev[x+1,y-1])/root)/tot_q);
								temp_a+=q_out*(((ht-elev[x+1,y-1])/root)/tot_q);
							}
		
							if(elev[x+1,y]<ht)
							{
								discharge[x+1,y]+=q_out*(((ht-elev[x+1,y])/DX)/tot_q);
								//left_in[x+1,y]+=q_out*(((ht-elev[x+1,y])/DX)/tot_q);
								temp_a+=q_out*(((ht-elev[x+1,y])/DX)/tot_q);
							}
		
							if(elev[x+1,y+1]<ht)
							{
								discharge[x+1,y+1]+=q_out*(((ht-elev[x+1,y+1])/root)/tot_q);
								//left_in[x+1,y+1]+=q_out*(((ht-elev[x+1,y+1])/root)/tot_q);
								temp_a+=q_out*(((ht-elev[x+1,y+1])/root)/tot_q);
							}
							if(x==xmax)totty+=temp_a;
							//left_out[x,y]+=temp_a;
							discharge[x,y]=discharge[x,y]-temp_a;

									
						}
					}
	    
				}
			}
			return totty;
		}


		void route_rl()
		{
  
			int x,y,inc,n,i;
			double jsat, q, ht, slope=0, depth=0,lowest , tot_ht, tot_q, temp_a, q_out, slopetot;
			double manning=0.03;
			double factor=1;
			double threshold=MIN_Q, slopemax;
			y=y_min+1;
  
			//this.InfoStatusPanel.Text="Right-left";
			for(x=xmax;x>=1;x--)
			{
    
				inc=1;
				//drawwater(mygraphics);
				while(cross_scan[x,inc]>0)
				{
					y=cross_scan[x,inc];
					inc++;
      
					ht=elev[x,y];
      
					if(water_depth[x+1,y]==-9999&&water_depth[x,y]!=-99)
					{
						discharge[x,y]=(area[x,y]*j_mean)*Math.Pow(DX,2);
						water_depth[x,y]=-99;
					}
					else
					{
						discharge[x,y]+=((j_mean*Math.Pow(DX,2))/4);     // 4 to 8    19/01/05
					}
      
					if(discharge[x,y]>MIN_Q)
					{
	
						slope=mean_bed_slope(x,y);
						if(slope<0.002)slope=0.002;
                        if (slope > 0.01) slope = 0.01;
	
						threshold=K*slope*DX;
						if(threshold<MIN_Q)threshold=MIN_Q;

						/*** now calc depth. *****/
	
						if(x==1)slope=0.001;
	
						depth=0;
						//						depth=(Math.Pow((((discharge[x,y]/Math.Pow(DX,1))*manning)/
						//								Math.Pow(slope,0.5)),0.6));

						depth=(Math.Pow((((discharge[x,y]/Math.Pow(DX,1))*calc_manning(x,y))/
							Math.Pow(slope,0.5)),0.6));
                        

						/***** depth added if greater than that there. **/
	
						
						if(depth>water_depth[x,y])
						{
							water_depth[x,y]=depth;
							lat_vol[x,y]=discharge[x,y];
						}


					}
      
      
					/* route water if not enough to flow */
      
					/* then do surface routing */
      
					if(y>1&&y<(ymax)&&discharge[x,y]>threshold&&water_depth[x-1,y-1]!=-9999&&water_depth[x-1,y]!=-9999&&water_depth[x-1,y+1]!=-9999)
					{
	
					
						tot_q=0;
	
						temp_a=0;
	
						/********* first sort out wet height *****/
						/* starting with d/s slopes ****/
	
	
						/***** now to route discharge d/s ***************/
	
						discharge[x,y]-=threshold;


						tot_ht=elev[x,y]+depth;
	
						//
						// start of main routing bit
						//

						if(elev[x-1,y-1]<tot_ht||elev[x-1,y]<tot_ht||elev[x-1,y+1]<tot_ht)
						{
							/**** check to see if base is lower *******/
							/* if not then leave some discharge       */
		
							q_out=discharge[x,y];
							lowest=1000;

							if(	elev[x-1,y-1]>elev[x,y]&&
								elev[x-1,y]>elev[x,y]&&
								elev[x-1,y+1]>elev[x,y])
							{
								if(elev[x-1,y-1]<lowest)lowest=elev[x-1,y-1];
								if(elev[x-1,y]<lowest)lowest=elev[x-1,y];
								if(elev[x-1,y+1]<lowest)lowest=elev[x-1,y+1];
                                q_out = q_out * ((tot_ht - lowest) / water_depth[x, y]);
								if(q_out>discharge[x,y])q_out=0; // line to prevent very very small depths increasing q_out disproportionaltely
								if(lowest>tot_ht)q_out=0;
							}		



							n=y;
							while((y-n)<SW&&tot_ht>elev[x-1,n-1]&&(n-1)>0&&water_depth[x-1,n-1]!=-9999)//&&q_out>lat_vol[x-1,n-1])
							{
								tot_q+=Math.Pow(((tot_ht-elev[x-1,n-1])/root),fexp);
								n--;
							}

							if(tot_ht>elev[x-1,y]&&water_depth[x-1,y]!=-9999)
							{
								tot_q+=Math.Pow(((tot_ht-elev[x-1,y])/DX),fexp);
							}

							n=y;
							while((n-y)<SW&&tot_ht>elev[x-1,n+1]&&(n+1)<ymax&&water_depth[x-1,n+1]!=-9999)//&&q_out>lat_vol[x-1,n+1])
							{
								tot_q+=Math.Pow(((tot_ht-elev[x-1,n+1])/root),fexp);
								n++;
							}
						
							n=y;

							double tt=0; // temp variable
							while((y-n)<SW&&tot_ht>elev[x-1,n-1]&&(n-1)>0&&water_depth[x-1,n-1]!=-9999)//&&q_out>lat_vol[x-1,n-1])
							{
								tt=q_out*(Math.Pow(((tot_ht-elev[x-1,n-1])/root),fexp)/tot_q);
                                discharge[x - 1, n - 1] += tt;
                                right_in[x - 1, n - 1] += tt;
                                //up_in[x - 1, n - 1] += tt;

                                for (i = n; i < y; i++)
                                {
                                    //right_in[x - 1, i] += tt;
                                    up_in[x - 1, i - 1] += tt;
                                    up_out[x - 1, i] += tt;
                                }
                                temp_a += tt;
								n--;
							}
							
							if(tot_ht>elev[x-1,y]&&water_depth[x-1,y]!=-9999)
							{
								tt=q_out*(Math.Pow(((tot_ht-elev[x-1,y])/DX),fexp)/tot_q);

                                discharge[x - 1, y] += tt;
                                right_in[x - 1, y] += tt;

                                temp_a += tt;

							}

							n=y;
							while((n-y)<SW&&tot_ht>elev[x-1,n+1]&&(n+1)<ymax&&water_depth[x-1,n+1]!=-9999)//&&q_out>lat_vol[x-1,n+1])
							{
								tt=q_out*(Math.Pow(((tot_ht-elev[x-1,n+1])/root),fexp)/tot_q);

                                discharge[x - 1, n + 1] += tt;
                                right_in[x - 1, n + 1] += tt;
                                //down_in[x - 1, n + 1] += tt;

                                for (i = n; i > y; i--)
                                {
                                    //right_in[x - 1, i] += tt;
                                    down_in[x - 1, i + 1] += tt;
                                    down_out[x - 1, i] += tt;
                                }
                                temp_a += tt;

								n++;
							}

							discharge[x,y]=discharge[x,y]-temp_a;
							right_out[x,y]+=temp_a;
                            flowout[x, y] += temp_a;
						}
	
						discharge[x,y]+=threshold;
	
					}
					if(discharge[x,y]>0&&water_depth[x-1,y-1]!=-9999&&water_depth[x-1,y]!=-9999&&water_depth[x-1,y+1]!=-9999)
					{
						if(elev[x-1,y-1]<=ht||elev[x-1,y]<=ht||elev[x-1,y+1]<=ht)
						{
	  
	  
							tot_q=0;
							temp_a=0;
							q_out=discharge[x,y];
							if(q_out>MIN_Q)q_out=MIN_Q;
	  
							if(elev[x-1,y-1]<ht)
								tot_q+=((ht-elev[x-1,y-1])/root);
							if(elev[x-1,y]<ht)
								tot_q+=((ht-elev[x-1,y])/DX);
							if(elev[x-1,y+1]<ht)
								tot_q+=((ht-elev[x-1,y+1])/root);
	  
							if(elev[x-1,y-1]<ht)
							{
								discharge[x-1,y-1]+=q_out*(((ht-elev[x-1,y-1])/root)/tot_q);
								//right_in[x-1,y-1]+=q_out*(((ht-elev[x-1,y-1])/root)/tot_q);
								temp_a+=q_out*(((ht-elev[x-1,y-1])/root)/tot_q);
							}
	  
							if(elev[x-1,y]<ht)
							{
								discharge[x-1,y]+=q_out*(((ht-elev[x-1,y])/DX)/tot_q);
								//right_in[x-1,y]+=q_out*(((ht-elev[x-1,y])/DX)/tot_q);
								temp_a+=q_out*(((ht-elev[x-1,y])/DX)/tot_q);
							}
	  
							if(elev[x-1,y+1]<ht)
							{
								discharge[x-1,y+1]+=q_out*(((ht-elev[x-1,y+1])/root)/tot_q);
								//right_in[x-1,y+1]+=q_out*(((ht-elev[x-1,y+1])/root)/tot_q);
								temp_a+=q_out*(((ht-elev[x-1,y+1])/root)/tot_q);
							}
	  
							//right_out[x,y]+=temp_a;
							discharge[x,y]=discharge[x,y]-temp_a;

	  
	  
						}
					}
      
      
				}
			}
		}


        double calc_max_flow_direction_degrees(int x, int y)
        {
            double deg = 0;
            if (water_depth[x, y] > water_depth_erosion_threshold)
            {
                double xplus = (left_out[x, y] - right_in[x, y]);
                double xminus = (right_out[x, y] - left_in[x, y]);
                double yplus = (up_out[x, y] - down_in[x, y]);
                double yminus = (down_out[x, y] - up_in[x, y]);
                if (xplus < 0) xplus = 0;
                if (xminus < 0) xminus = 0;
                if (yplus < 0) yplus = 0;
                if (yminus < 0) yminus = 0;
                double xbalance = xplus - xminus;
                double ybalance = yminus - yplus;



                //working out max_flow for 12-3pm

                if (xbalance > 0 && ybalance<0)
                {

                    deg = (Math.Atan(xbalance / Math.Abs(ybalance))*(180/3.142));

                }

                // for 3pm to 6pm
                if (xbalance > 0 && ybalance > 0)
                {
                    deg = 90+(Math.Atan(ybalance / xbalance) * (180 / 3.142));
                }

                // for 6 - 9 
                if (xbalance < 0 && ybalance > 0)
                {
                    deg = 180+(Math.Atan(Math.Abs(xbalance) / Math.Abs(ybalance)) * (180 / 3.142));
                }

                // for 9-12
                if (xbalance < 0 && ybalance < 0)
                {
                    deg = 270 + (Math.Atan(Math.Abs(ybalance) / Math.Abs(xbalance)) * (180 / 3.142));
                }

                if (xbalance > 0 && ybalance == 0) deg = 90;
                if (xbalance < 0 && ybalance == 0) deg = 270;
                if (ybalance > 0 && xbalance == 0) deg = 180;
                if (ybalance < 0 && xbalance == 0) deg = 0;

                return (deg);

            }
            else
            {
                return -9999.0;
            }
            

        }


        void calc_max_flow_direction()
        {
            int x, y, n, inc, valz = 1;
            double tot;

            for (x = 1; x <= xmax; x++)
            {
                for(y=1;y<=ymax;y++)
                {



                    if(water_depth[x,y]>water_depth_erosion_threshold)
                    {

                        //first calc max flow in any direction..
                        double tot2 = 0;
                        double tot3 = 0;

                        if (up_out[x, y] - down_in[x, y] > 0) tot2 += up_out[x, y] - down_in[x, y];
                        if (down_out[x, y] - up_in[x, y] > 0) tot2 -= down_out[x, y] - up_in[x, y];
                        if (left_out[x, y] - right_in[x, y] > 0) tot3 += left_out[x, y] - right_in[x, y];
                        if (right_out[x, y] - left_in[x, y] > 0) tot3 -= right_out[x, y] - left_in[x, y];

                        if (tot2 < 0) tot2 = 0 - tot2;
                        if (tot3 < 0) tot3 = 0 - tot3;

                        if (water_depth[x, y] > water_depth_erosion_threshold)
                        {
                            max_flow[x, y, 0] = Math.Sqrt(Math.Pow(tot2, 2) + Math.Pow(tot3, 2));
                        }




                        // calc balance of flow out vs in,
                        double xplus = (left_out[x, y] - right_in[x, y]);
                        double xminus = (right_out[x, y] - left_in[x, y]);
                        double yplus = (up_out[x, y] - down_in[x, y]);
                        double yminus = (down_out[x, y] - up_in[x, y]);
                        if (xplus < 0) xplus = 0;
                        if (xminus < 0) xminus = 0;
                        if (yplus < 0) yplus = 0;
                        if (yminus < 0) yminus = 0;

                        if (xplus > xminus)
                        {
                            xplus -= xminus;
                            xminus = 0;
                        }
                        if (xminus > xplus)
                        {
                            xminus -= xplus;
                            xplus = 0;
                        }
                        if (yplus > yminus)
                        {
                            yplus -= yminus;
                            yminus = 0;
                        }
                        if (yminus > yplus)
                        {
                            yminus -= yplus;
                            yplus = 0;
                        }


                        //working out max_flow here now...

                        if (xplus > 0)
                        {
                            double wtot = 0;
                            if (water_depth[x + 1, y - 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x + 1, y - 1])) wtot += Math.Pow(((water_depth[x, y] + elev[x, y]) - elev[x + 1, y - 1]) / root,2);
                            if (water_depth[x + 1, y] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x + 1, y])) wtot += Math.Pow(((water_depth[x, y] + elev[x, y]) - elev[x + 1, y]) / DX,2);
                            if (water_depth[x + 1, y + 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x + 1, y + 1])) wtot += Math.Pow(((water_depth[x, y] + elev[x, y]) - elev[x + 1, y + 1]) / root, 2);

                            if (water_depth[x + 1, y - 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x + 1, y - 1]))
                            {
                                
                                max_flow[x, y, 2] += xplus * (Math.Pow((((water_depth[x, y] + elev[x, y]) - elev[x + 1, y - 1]) / root),2) / wtot);
                            }
                            if (water_depth[x + 1, y] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x + 1, y]))
                            {
                               
                                max_flow[x, y, 3] += xplus * (Math.Pow((((water_depth[x, y] + elev[x, y]) - elev[x + 1, y]) / DX),2) / wtot);
                            }
                            if (water_depth[x + 1, y + 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x + 1, y + 1]))
                            {

                                max_flow[x, y, 4] += xplus * (Math.Pow((((water_depth[x, y] + elev[x, y]) - elev[x + 1, y + 1]) / root), 2) / wtot);
                            }
                        }

                        if (xminus > 0)
                        {
                            double wtot = 0;
                            if (water_depth[x - 1, y - 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x - 1, y - 1])) wtot += Math.Pow(((water_depth[x, y] + elev[x, y]) - elev[x - 1, y - 1]) / root,2);
                            if (water_depth[x - 1, y] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x - 1, y])) wtot += Math.Pow(((water_depth[x, y] + elev[x, y]) - elev[x - 1, y]) / DX,2);
                            if (water_depth[x - 1, y + 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x - 1, y + 1])) wtot += Math.Pow(((water_depth[x, y] + elev[x, y]) - elev[x - 1, y + 1]) / root,2);

                            if (water_depth[x - 1, y - 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x - 1, y - 1]))
                            {
                                
                                max_flow[x, y, 8] += xminus * (Math.Pow((((water_depth[x, y] + elev[x, y]) - elev[x - 1, y - 1]) / root),2) / wtot);
                            }
                            if (water_depth[x - 1, y] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x - 1, y]))
                            {
                                
                                max_flow[x, y, 7] += xminus * (Math.Pow((((water_depth[x, y] + elev[x, y]) - elev[x - 1, y]) / DX),2) / wtot);
                            }
                            if (water_depth[x - 1, y + 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x - 1, y + 1]))
                            {
                                
                                max_flow[x, y, 6] += xminus * (Math.Pow((((water_depth[x, y] + elev[x, y]) - elev[x - 1, y + 1]) / root),2) / wtot);
                            }
                        }

                        if (yplus > 0)
                        {
                            double wtot = 0;
                            if (water_depth[x - 1, y - 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x - 1, y - 1])) wtot += Math.Pow(((water_depth[x, y] + elev[x, y]) - elev[x - 1, y - 1]) / root,2);
                            if (water_depth[x, y - 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x, y - 1])) wtot += Math.Pow(((water_depth[x, y] + elev[x, y]) - elev[x, y - 1]) / DX,2);
                            if (water_depth[x + 1, y - 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x + 1, y - 1])) wtot += Math.Pow(((water_depth[x, y] + elev[x, y]) - elev[x + 1, y - 1]) / root,2);

                            if (water_depth[x - 1, y - 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x - 1, y - 1]))
                            {
                                
                                max_flow[x, y, 8] += yplus * (Math.Pow((((water_depth[x, y] + elev[x, y]) - elev[x - 1, y - 1]) / root),2) / wtot);
                            }
                            if (water_depth[x, y - 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x, y - 1]))
                            {

                                max_flow[x, y, 1] += yplus * (Math.Pow((((water_depth[x, y] + elev[x, y]) - elev[x, y - 1]) / DX), 2) / wtot);
                            }
                            if (water_depth[x + 1, y - 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x + 1, y - 1]))
                            {
                                
                                max_flow[x, y, 2] += yplus * (Math.Pow((((water_depth[x, y] + elev[x, y]) - elev[x + 1, y - 1]) / root),2) / wtot);
                            }
                        }

                        if (yminus > 0)
                        {
                            double wtot = 0;
                            if (water_depth[x - 1, y + 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x - 1, y + 1])) wtot += Math.Pow(((water_depth[x, y] + elev[x, y]) - elev[x - 1, y + 1]) / root,2);
                            if (water_depth[x, y + 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x, y + 1])) wtot += Math.Pow(((water_depth[x, y] + elev[x, y]) - elev[x, y + 1]) / DX,2);
                            if (water_depth[x + 1, y + 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x + 1, y + 1])) wtot += Math.Pow(((water_depth[x, y] + elev[x, y]) - elev[x + 1, y + 1]) / root,2);

                            if (water_depth[x - 1, y + 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x - 1, y + 1]))
                            {
                              
                                max_flow[x, y, 6] += yminus * (Math.Pow((((water_depth[x, y] + elev[x, y]) - elev[x - 1, y + 1]) / root),2) / wtot);
                            }
                            if (water_depth[x, y + 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x, y + 1]))
                            {
                               
                                max_flow[x, y, 5] += yminus * (Math.Pow((((water_depth[x, y] + elev[x, y]) - elev[x, y + 1]) / DX),2) / wtot);
                            }
                            if (water_depth[x + 1, y + 1] > water_depth_erosion_threshold && ((water_depth[x, y] + elev[x, y]) > elev[x + 1, y + 1]))
                            {
                                
                                max_flow[x, y, 4] += yminus * (Math.Pow((((water_depth[x, y] + elev[x, y]) - elev[x + 1, y + 1]) / root),2) / wtot);
                            }
                        }         
                    }
                    //for (n = 1; n <= 8; n++)
                    //{
                    //    if (max_flow[x, y, n] < 0) max_flow[x, y, n] = 0;
                    //}
                }
            }
        }



		void calc_flow_direction()
		{
			int x,y,n,inc,valz=1;
			double tot;
  
			for(y=ymax;y>=1;y--)
			{
				inc=1;    
				while(down_scan[y,inc]>0)
				{
					x=down_scan[y,inc];
					inc++;

                    
					/** calculate max flow out direction **/
					tot=0;
					for(n=1;n<=8;n++)
					{
						if(max_flow[x,y,n]>tot)
						{
							valz=n;
							tot=max_flow[x,y,n];
							//max_flow[x,y,0]=tot; /* stores max discharge out in 0 of max_flow array. - now carried out in route routines*/
						}
					}
					if(tot>0)flow_dir[x,y,1]=valz;

					/** calculate flow in direction  **/

					tot=0;

					if(max_flow[x,y-1,5]>tot)
					{
						valz=1;
						tot=max_flow[x,y-1,5];
					}
				

					if(max_flow[x+1,y-1,6]>tot)
					{
						valz=2;
						tot=max_flow[x+1,y-1,6];
					}

					if(max_flow[x+1,y,7]>tot)
					{
						valz=3;
						tot=max_flow[x+1,y,7];
					}

					if(max_flow[x+1,y+1,8]>tot)
					{
						valz=4;
						tot=max_flow[x+1,y+1,8];
					}

					if(max_flow[x,y+1,1]>tot)
					{
						valz=5;
						tot=max_flow[x,y+1,1];
					}

					if(max_flow[x-1,y+1,2]>tot)
					{
						valz=6;
						tot=max_flow[x-1,y+1,2];
					}

					if(max_flow[x-1,y,3]>tot)
					{
						valz=7;
						tot=max_flow[x-1,y,3];
					}

					if(max_flow[x-1,y-1,4]>tot)
					{
						valz=8;
						tot=max_flow[x-1,y-1,4];
					}


					if(tot>0)flow_dir[x,y,0]=valz;

                    				

					// next section calculates Tau

					// next line to make sure that if no water smoothing, then water_depth2 us updated with correct water depths
					if (checkBox3.Checked == false)water_depth2[x,y]=water_depth[x,y];

                    //if(water_depth[x,y]>water_depth_erosion_threshold)
                    //{
                    //    // re- calcualate discharge (max_flow[x,y,0]) accounting for pool depths..
                    //    //if(pool_depth[x,y]>water_depth[x,y])pool_depth[x,y]=water_depth[x,y];
                    //    if(qcounter[x,y]==0)qcounter[x,y]=1;

                    //    if(max_flow[x,y,0]<0)max_flow[x,y,0]=0;//Console.WriteLine(Convert.ToString(max_flow[x,y,0]));

                    //    double slope=0;
                    //    if(wslope_box.Checked==true)//&&mean_bed_slope(x,y)>0)
                    //    {
                    //        slope=mean_ws_slope(x,y);
                    //        //if(slope==0)slope=mean_ws_slope2(x,y);
                            
                    //    }
						
                    //    if(bedslope_box.Checked==true)slope=max_bed_slope(x,y);
                    //    //if(slope>0.01)slope=0.01; // to get rid of too steep slopes
                        
                        
                    //    Tau[x,y]=(water_depth[x,y]-pool_depth[x,y])*slope*1000*9.8;

                    //    if(veltaubox.Checked==true)
                    //    {
                    //        double vel;

                    //        vel = (max_flow[x, y, 0] / (DX * water_depth[x, y]));
                    //        // calculating velocity

                    //        double ci=9.81*Math.Pow(calc_manning(x,y),2)*Math.Pow(water_depth[x,y],-0.33);// calcualting drag coeffiecuent
                    //        if (ci > 0.04) ci = 0.04;
                    //        if(vel>2)vel=2; // if vel too high cut it
                    //        //ci = 0.01;
                    //        Tau[x, y] = 1000 * ci * Math.Pow(vel, 2);
                    //        //Tau[x, y] = 10* vel;
                            
                    //        // OK how is tau calculated. Is it done by 

                    //    }
                        
                    //}
                    //else
                    //{
                    //    Tau[x,y]=-9999;
                    //}




				}
			}
		}



		private void zero_values()
		{
			int x,y,z,n;
			double act=0.5;
			for(y=0;y<=ymax;y++)
			{
				for(x=0;x<=xmax;x++)
				{
					area[x,y]=0;
					elev[x,y]=0;
					bedrock[x,y]=0;
					init_elevs[x,y]=elev[x,y];
					discharge[x,y]=0;
					water_depth[x,y]=0;
					index[x,y]=-9999;
                    veg[x, y, 0] = 0;// elevation
                    veg[x, y, 1] = 0; // density
					veg[x,y,2]=0; // jw density
					veg[x,y,3]=0; // height
					lat_vol[x,y]=0;
					edge[x,y]=0;
					edge2[x,y]=0;
					pool_depth[x,y]=0;
					qcounter[x,y]=0;
					lat_vol[x,y]=0;
                    sand[x, y] = 0;


					for(n=0;n<=8;n++)max_flow[x,y,n]=0;
					for(n=0;n<=1;n++)flow_dir[x,y,n]=0;
				}
			}

			for(x=1;x<((xmax*ymax)/LIMIT);x++)
			{
				for(y=0;y<=G_MAX;y++)
				{
					for(n=0;n<=(TRACERS-1);n++)
					{
						grain[x,y,n]=0;
						temp[x,y,n]=0;
						extra_elev[x]=0;
					}
				}
				for(z=0;z<=9;z++)
				{
					for(y=0;y<=G_MAX-2;y++)
					{
						for(n=0;n<=(TRACERS-1);n++)
						{
							strata[x,z,y,n]=0;
						}
					}
				}
			}
			for(x=0;x<=1000;x++)
			{
				minesites[x,0]=0;
				minesites[x,1]=0;
			}

		}

        void dune1(double time) // does dune things from top to bottom
        {
            int x, y, n, prob, counter1 = 1, xtemp, ytemp, ytemp2,x2,y2;
            int t, checkup = int.Parse(upstream_check_box.Text);
            int flag = 1;

            double slabdepth = 0.0003 * time;
            double maxslabdepth = double.Parse(slab_depth_box.Text); 
            int dep_probability= int.Parse(depo_prob_box.Text);
            int downstream_offset = int.Parse(offset_box.Text);
            double initial_sand_depth = double.Parse(init_depth_box.Text);
            double angle = double.Parse(shadow_angle_box.Text); 

            if (slabdepth > maxslabdepth) slabdepth = maxslabdepth;
            double factor = Math.Tan((angle * (3.141592654 / 180))) * (DX/dune_mult);
            Random xr = new Random();

            for (x = 1; x < xmax; x++)
            {
                for (y = 1; y <= ymax; y++)
                {
                    // subtract eleev from sand so splitting into sand and elev for dune part...
                    elev[x, y] -= sand[x, y];


                    // check to add to sand from grain (if no water)
                    // if so then update sand and sand2 (and elev if subtracting from grain and
                    // adding to sand

                    if (water_depth[x, y] < water_depth_erosion_threshold)
                    {
                        if (elev[x, y] - init_elevs[x, y] >= slabdepth)
                        {
                            sand[x, y] += slabdepth;
                            elev[x, y] -= slabdepth;

                            // now also update sand2 values... averaged across cell.
                            for (x2 = 0; x2 < dune_mult; x2++)
                            {
                                for (y2 = 0; y2 < dune_mult; y2++)
                                {
                                    sand2[(x * dune_mult) - x2, (y * dune_mult) - y2] += slabdepth;
                                }
                            }

                        }

                    }

                    //update elev2 from elev
                    for (x2 = 0; x2 < dune_mult; x2++)
                    {
                        for (y2 = 0; y2 < dune_mult; y2++)
                        {
                            elev2[(x * dune_mult) - x2, (y * dune_mult) - y2] = elev[x, y];
                        }
                    }

                }
            }


            // adding new sand in a strip at the base: does this in the first iteration (when counter <2)
            //if (counter < 200000000000)
            //{
            //    for (x = 1; x <= /*(xmax*dune_mult)-10*/100; x++)
            //    {
            //        for (y = 1; y <= 1/*(ymax * dune_mult)*/; y++)
            //        {
            //            //sand[x, 25] += 0.6;
            //            sand2[x, y] += initial_sand_depth/10;
            //        }
            //        //sand2[x, 1] += initial_sand_depth / 20;
            //    }
            //}

            if (counter < 2)
            {
                for (x = 1; x <= /*(xmax*dune_mult)-10*/500; x++)
                {
                    for (y = 1; y <= (ymax * dune_mult); y++)
                    {
                        //sand[x, 25] += 0.6;
                        sand2[x, y] += initial_sand_depth;
                    }
                    //sand2[x, 1] += initial_sand_depth / 20;
                }
            }


            // check everywhere for sand landslides
            for (x = 1; x <= xmax*dune_mult; x++)
            {
                for (y = 1; y <= ymax*dune_mult; y++)
                {
                    slide_4(x, y);
                }
            }


            for (n = 1; n <= (xmax*dune_mult) * (ymax*dune_mult); n++)
            {

                // creating random x and y co-ords to check...
                x = xr.Next(1, (xmax*dune_mult) + 1);
                y = xr.Next(1, (ymax*dune_mult) + 1);
                prob = 100;
                counter1 = 0;
                flag = 1;

                if (sand2[x, y] >= slabdepth)
                {
                    // to see if should be entrained or not...
                    for (t = 1; t <= checkup; t++)
                    {
                        ytemp = y - t;
                        if (ytemp < 1) ytemp = (ymax * dune_mult) + ytemp;
                        if (((sand2[x, ytemp] + elev2[x, ytemp]) - (sand2[x, y] + elev2[x, y])) > (factor * (t)))
                        {
                            flag = 0;
                            t = checkup;
                        }

                    }


                    // now having decided it can be eroded, now see if it can be moved
                    if (flag == 1)
                    {
                        // while random number greater than prob then move on one if poss..
                        while (prob > dep_probability)
                        {
                            counter1++; // shift down one cell...
                            prob = xr.Next(1, 100); // new random number

                            // now adding in the downsrtream offset if needed done by ensuring prob is 100
                            if (counter1 < downstream_offset) prob = 100;

                            // seeing if in shadow or not...
                            for (t = 1; t < checkup; t++)
                            {
                                ytemp = (y + counter1) - t;
                                ytemp2 = (y + counter1);
                                if (ytemp < 1) ytemp = (ymax * dune_mult) + ytemp;
                                if (ytemp > (ymax * dune_mult)) ytemp = 0 + (ytemp - (ymax * dune_mult));
                                if (ytemp2 > (ymax * dune_mult)) ytemp2 = 0 + (ytemp2 - (ymax * dune_mult));
                                if (((sand2[x, ytemp] + elev2[x, ytemp]) - (sand2[x, ytemp2] + elev2[x, ytemp2])) > (factor * t))
                                {
                                    t = checkup;
                                    prob = 0;
                                }
                            }
                            //if (elev[x, ytemp - 1] - elev[x, y] > factor) break;
                        }

                        double tempmax = sand2[x, y];
                        if (tempmax < 0) tempmax = 0;



                        // now erode sand if there is enough there in the sand layer
                        if (slabdepth < tempmax) tempmax = slabdepth;
                        if (tempmax < 0) tempmax = 0;
                        sand2[x, y] -= tempmax;
                        // do landslides for just that cell and ones around.
                        slide_4(x, y);

                        ytemp = y + counter1;
                        if (ytemp > (ymax * dune_mult))
                        {
                            ytemp = ytemp - (ymax * dune_mult);
                        }

                        // now deposit sand
                        //if(y+counter1<ymax*dune_mult)sand2[x, ytemp] += tempmax;

                        sand2[x, ytemp] += tempmax;

                        // do landslides for just that cell and ones around.
                        slide_4(x, ytemp);
                        // and add it to elev and remove from sand if water present...

                    }
                }

            }




            // now do landslides everywhere 5 times... just to make sure..
            for (t = 1; t <= 5; t++)
            {
                for (x = 1; x <= xmax*dune_mult; x++)
                {
                    for (y = 1; y <= ymax*dune_mult; y++)
                    {
                        if(sand2[x,y]>0)slide_4(x, y);
                    }
                }
            }

            // sand = mean sand2

            for (x = 1; x <= (xmax); x++)
            {
                for (y = 1; y <= (ymax); y++)
                {

                    double sandsum = 0;
                    for (x2 = 0; x2 < dune_mult; x2++)
                    {
                        for (y2 = 0; y2 < dune_mult; y2++)
                        {
                            if (sand2[(x * dune_mult) - x2, (y * dune_mult) - y2] > 0)
                            {
                                sandsum += sand2[(x * dune_mult) - x2, (y * dune_mult) - y2];
                            }

                        }
                    }
                    sand[x,y]=sandsum/(dune_mult*dune_mult);

                    
                     //if waterdepth >0 then sand > elev and grain (at a rate)
                     //then also reduce sand 2 by same amount transferred.

                    if (water_depth[x, y] > water_depth_erosion_threshold)
                    {
                        if (sand[x, y] > 0)
                        {
                            double tempsandvol = sand[x, y];
                            if (tempsandvol > 0.1) tempsandvol = 0.1;
                            sand[x, y] -=tempsandvol;
                            elev[x, y] += tempsandvol;
                            if (index[x, y] == -9999) addGS(x, y);
                            grain[index[x, y], 1, 0] += tempsandvol;
                            sort_active2(x, y);

                            // now has to reduce sand vol..
                            double sand2tot = 0;
                            int sand2num = 0;
                            for (x2 = 0; x2 < dune_mult; x2++)
                            {
                                for (y2 = 0; y2 < dune_mult; y2++)
                                {
                                    if (sand2[(x * dune_mult) - x2, (y * dune_mult) - y2] > 0)
                                    {
                                        sand2tot += sand2[(x * dune_mult) - x2, (y * dune_mult) - y2];
                                        sand2num++;
                                    }

                                }
                            }
                            for (x2 = 0; x2 < dune_mult; x2++)
                            {
                                for (y2 = 0; y2 < dune_mult; y2++)
                                {
                                    if (sand2[(x * dune_mult) - x2, (y * dune_mult) - y2] > 0)
                                    {
                                        sand2[(x * dune_mult) - x2, (y * dune_mult) - y2]-=(tempsandvol*dune_mult*dune_mult)*
                                            (sand2[(x * dune_mult) - x2, (y * dune_mult) - y2]/sand2tot);
                                        
                                    }

                                }
                            }


                        }

                    }

                    //sandsum = 0;
                    //for (x2 = 0; x2 < dune_mult; x2++)
                    //{
                    //    for (y2 = 0; y2 < dune_mult; y2++)
                    //    {
                    //        if (sand2[(x * dune_mult) - x2, (y * dune_mult) - y2] > 0)
                    //        {
                    //            sandsum += sand2[(x * dune_mult) - x2, (y * dune_mult) - y2];
                    //        }

                    //    }
                    //}
                    //sand[x, y] = sandsum / (dune_mult * dune_mult);


                    // now add sand array back onto elev
                    elev[x, y] += sand[x, y];

                }

            }



        }


        void dune2(double time) //Does dune things from L-R
        {
            int x, y, n, prob, counter1 = 1, xtemp, xtemp2, ytemp, ytemp2;
            int t, checkup = int.Parse(upstream_check_box.Text);
            int flag = 1;

            double slabdepth = 0.0003 * time;
            double maxslabdepth = double.Parse(slab_depth_box.Text);
            int dep_probability = int.Parse(depo_prob_box.Text);
            int downstream_offset = int.Parse(offset_box.Text);
            double initial_sand_depth = double.Parse(init_depth_box.Text);
            double angle = double.Parse(shadow_angle_box.Text);

            if (slabdepth > maxslabdepth) slabdepth = maxslabdepth;
            double factor = Math.Tan((angle * (3.141592654 / 180))) * DX;
            Random xr = new Random();

            // subtract eleev from sand so splitting into sand and elev for dune part...
            for (x = 1; x < xmax; x++)
            {
                for (y = 1; y <= ymax; y++)
                {
                    elev[x, y] -= sand[x, y];
                }
            }

            // adding new sand in a strip at the base: does this in the first iteration (when counter <2)
            if (counter < 2)
            {
                for (x = 20; x <= 180; x++)
                {
                    for (y = 1; y <= ymax; y++)
                    {
                        //sand[x, 25] += 0.6;
                        sand[x, y] += initial_sand_depth;
                    }

                }
            }


            // check everywhere for sand landslides
            for (x = 1; x <= xmax; x++)
            {
                for (y = 1; y <= ymax; y++)
                {
                    slide_4(x, y);
                }
            }


            for (n = 1; n <= xmax * ymax; n++)
            {

                // creating random x and y co-ords to check...
                x = xr.Next(1, xmax + 1);
                y = xr.Next(1, ymax + 1);
                prob = 100;
                counter1 = 0;
                flag = 1;

                // to see if should be entrained or not...
                for (t = 1; t <= checkup; t++)
                {
                    xtemp = x - t;
                    if (xtemp < 1) xtemp = xmax + xtemp;
                    if (((sand[xtemp, y] + elev[xtemp, y]) - (sand[x, y] + elev[x, y])) > (factor * (t)))
                    {
                        flag = 0;
                        t = checkup;
                    }

                }


                // now having decided it can be eroded, now see if it can be moved
                if (flag == 1 && water_depth[x, y] < water_depth_erosion_threshold)
                {
                    // while random number greater than prob then move on one if poss..
                    while (prob > dep_probability)
                    {
                        counter1++; // shift down one cell...
                        prob = xr.Next(1, 100); // new random number

                        // now adding in the downsrtream offset if needed done by ensuring prob is 100
                        if (counter1 < downstream_offset) prob = 100;

                        // seeing if in shadow or not...
                        for (t = 1; t < checkup; t++)
                        {
                            xtemp = (x + counter1) - t;
                            xtemp2 = (x + counter1);
                            if (xtemp < 1) xtemp = xmax + xtemp;
                            if (xtemp > xmax) xtemp = 0 + (xtemp - xmax);
                            if (xtemp2 > xmax) xtemp2 = 0 + (xtemp2 - xmax);
                            if (((sand[xtemp, y] + elev[xtemp, y]) - (sand[xtemp2, y] + elev[xtemp2, y])) > (factor * t))
                            {
                                t = checkup;
                                prob = 0;
                            }
                        }
                        
                    }

                    double tempmax = sand[x, y];
                    if (tempmax < 0) tempmax = 0;

                    // bit to re-entrain sand... if its been added to elev by water part
                    if (slabdepth > tempmax && water_depth[x, y] < water_depth_erosion_threshold)
                    {
                        if (elev[x, y] - init_elevs[x, y] > slabdepth)
                        {
                            sand[x, y] += slabdepth;
                            elev[x, y] -= slabdepth;
                            tempmax = sand[x, y];
                        }
                    }


                    // now erode sand if there is enough there in the sand layer
                    if (slabdepth < tempmax) tempmax = slabdepth;
                    if (tempmax < 0) tempmax = 0;
                    sand[x, y] -= tempmax;
                    // do landslides for just that cell and ones around.
                    slide_4(x, y);

                    xtemp = x + counter1;
                    if (xtemp > xmax)
                    {
                        xtemp = xtemp - xmax;
                    }

                    // now deposit sand
                    sand[xtemp, y] += tempmax;
                    // do landslides for just that cell and ones around.
                    slide_4(xtemp, y);
                    // and add it to elev and remove from sand if water present...
                    if (water_depth[xtemp, y] > water_depth_erosion_threshold)
                    {
                        if (index[xtemp, y] == -9999) addGS(xtemp, y);
                        grain[index[xtemp, y], 1, 0] += tempmax;
                        elev[xtemp, y] += tempmax;
                        sand[xtemp, y] -= tempmax; // having updated elev have to remove from sand
                        sort_active(xtemp, y);
                    }



                }

            }

            // now do landslides everywhere 5 times... just to make sure..
            for (t = 1; t <= 5; t++)
            {
                for (x = 1; x <= xmax; x++)
                {
                    for (y = 1; y <= ymax; y++)
                    {
                        slide_4(x, y);
                    }
                }
            }

            // now add sand array back onto elev
            for (x = 1; x < xmax; x++)
            {
                for (y = 1; y <= ymax; y++)
                {
                    elev[x, y] += sand[x, y];
                }
            }
        }


		void calc_soil_saturation() // <JOE 20050605>
		{
			int x,y,n,inc;
			double coeff,Qsum;
  
			for (y=1; y<=ymax; y++)
			{
				inc = 1;    

				while (down_scan[y,inc] > 0) 
				{
					x = down_scan[y,inc];
					inc++;
					soil_saturation[x,y] = area[x,y] * j_mean;
					
				}
			}		
		}		


		void calc_hillshade() // <JOE 20051605- begin>
		{
			//Local variables
			int x, y;
		
			double slopemax;
			double slope;
			int slopetot;
			double local_Illumination;
			
			// Initialize Hillshade Paramaters
			double azimuth = 315 * (3.141592654/180); // Default of 315 degrees converted to radians
			double altitude = 45 * (3.141592654/180); // Default of 45 degrees converted to radians



			for(x=1;x<=xmax;x++)
			{
				for(y=1;y<=ymax;y++)
				{
					if(elev[x,y] != -9999 && elev[x,y] > 0)
					{
						slopemax=0.0;
						slope=0.0;
						slopetot=0;

						// Do slope analysis and Aspect Calculation first
						if(elev[x,y] > elev[x,y-1] && elev[x,y-1] != -9999) // North 0
						{
							slope = Math.Pow((elev[x,y]-elev[x,y-1])/root,1);
							if(slope > slopemax)
							{
								slopemax=slope;
								slopetot++;
								aspect[x,y] = 0 * (3.141592654/180);
							}	
							
						}
						if(elev[x,y] > elev[x+1,y-1] && elev[x+1,y-1] != -9999) // Northeast 45
						{
							slope = Math.Pow((elev[x,y]-elev[x+1,y-1])/DX,1);
							if(slope > slopemax)
							{
								slopemax=slope;
								slopetot++;
								aspect[x,y] = 45 * (3.141592654/180);
							}
						}
						if(elev[x,y] > elev[x+1,y] && elev[x+1,y] != -9999) // East 90
						{
							slope = Math.Pow((elev[x,y]-elev[x+1,y])/root,1);
							if(slope > slopemax)
							{
								slopemax=slope;
								slopetot++;
								aspect[x,y] = 90 * (3.141592654/180);
							}
						}
						if(elev[x,y] > elev[x+1,y+1] && elev[x+1,y+1] != -9999) // SouthEast 135
						{
							slope = Math.Pow((elev[x,y]-elev[x+1,y+1])/root,1);
							if(slope > slopemax)
							{
								slopemax=slope;
								slopetot++;
								aspect[x,y] = 135 * (3.141592654/180);
							}
							
						}
						if(elev[x,y] > elev[x,y+1] && elev[x,y+1] != -9999) // South 180
						{
							slope = Math.Pow((elev[x,y]-elev[x,y+1])/DX,1);
							if(slope > slopemax)
							{
								slopemax=slope;
								slopetot++;
								aspect[x,y] = 180 * (3.141592654/180);
							}
						}
						if(elev[x,y] > elev[x-1,y+1] && elev[x-1,y+1] != -9999) // SouthWest 225
						{
							slope = Math.Pow((elev[x,y]-elev[x-1,y+1])/root,1);
							if(slope > slopemax)
							{
								slopemax=slope;
								slopetot++;
								aspect[x,y] = 225 * (3.141592654/180);
							}
						}
						if(elev[x,y] > elev[x-1,y] && elev[x-1,y] != -9999) // West 270
						{
							slope = Math.Pow((elev[x,y]-elev[x-1,y])/root,1);
							if(slope > slopemax)
							{
								slopemax=slope;
								slopetot++;
								aspect[x,y] = 270;
							}
						}
						if(elev[x,y] > elev[x-1,y-1] && elev[x-1,y-1] != -9999) // Northwest 315
						{
							slope = Math.Pow((elev[x,y]-elev[x-1,y-1])/DX,1);
							if(slope > slopemax)
							{
								slopemax=slope;
								slopetot++;
								aspect[x,y] = 315 * (3.141592654/180);
							}
						}
						
						if (slope > 0) slopeAnalysis[x,y] = slopemax;// Tom's: (slope/slopetot); ?

						// Convert slope to radians
						slopeAnalysis[x,y] = System.Math.Atan(slopeAnalysis[x,y]);


						// Do Hillshade Calculation
						local_Illumination = 255 * ((System.Math.Cos(azimuth)
												     * System.Math.Sin(slopeAnalysis[x,y])
												     * System.Math.Cos(aspect[x,y] - azimuth)) 
                            					   + (System.Math.Sin(altitude)
													 * System.Math.Cos(slopeAnalysis[x,y])));
						
						hillshade[x,y] = System.Math.Abs(local_Illumination);
					}
				}
			}

		}		// End calc_hillshade() <JOE 20051605- end>



		void Color_HSVtoRGB()	// <JOE 20051605>
		{
			// Convert HSV to RGB.
			// Made this a seperate function as it is called multiple times in drawwater().

			if (sat == 0) 
			{
				// If sat is 0, all colors are the same.
				// This is some flavor of gray.
				red = val;
				green = val;
				blue = val;
			} 
			else 
			{
				double pFactor;
				double qFactor;
				double tFactor;

				double fractionalSector;
				int sectorNumber;
				double sectorPos;

				// The color wheel consists of six 60 degree sectors.
				// Figure out which sector you are in.
				sectorPos = hue / 60;
				sectorNumber = (int)(Math.Floor(sectorPos));

				// get the fractional part of the sector.
				// That is, how many degrees into the sector are you?
				fractionalSector = sectorPos - sectorNumber;

				// Calculate values for the three axes
				// of the color. 
				pFactor = val * (1 - sat);
				qFactor = val * (1 - (sat * fractionalSector));
				tFactor = val * (1 - (sat * (1 - fractionalSector)));

				// Assign the fractional colors to r, g, and b based on the sector the angle is in.
				switch (sectorNumber) 
				{
					case 0:
						red = val;
						green = tFactor;
						blue = pFactor;
						break;
					case 1:
						red = qFactor;
						green = val;
						blue = pFactor;
						break;
					case 2:
						red = pFactor;
						green = val;
						blue = tFactor;
						break;
					case 3:
						red = pFactor;
						green = qFactor;
						blue = val;
						break;
					case 4:
						red = tFactor;
						green = pFactor;
						blue = val;
						break;
					case 5:
						red = val;
						green = pFactor;
						blue = qFactor;
						break;
				}
			}
		}


		void drawwater(System.Drawing.Graphics graphics)// <JMW 20041018>
		{
            Graphics objGraphics;
            objGraphics = Graphics.FromImage(m_objDrawingSurface);
            objGraphics.Clear(SystemColors.Control);

			int x, y, z, n, n1, tot;
			int redcol = 0, greencol = 0, bluecol = 0, alphacol = 255;
			int t=0, t_y=0;
			double tot_max, ztemp, erotemp = 0, tomsedi = 0;
			Pen waterpen, grainpen;
			
			// Set Graphics Display Size
			if (xmax <= 0) xmax = 1;

            //set scaling of graphics - so X bmp pixels to every model pixel.
            t = graphics_scale;

			// These loop through the entire grid
			// DEM <JOE 20050905>
			if (menuItem30.Checked == true)	
			{
				double zDEM;
				double zCalc, zMin = 100000.0, zMax = 0.0, zRange, hsMin = 0, hsMax = 255, hsRange, hs;
				double valMin = 0.0;
				double valMax = 1.0;



				calc_hillshade();		// Call up routine 
				
				// First, find max, min and range of DEM and Hillshade
				for(x=1;x<=xmax;x++)
				{
					for(y=1;y<=ymax;y++)
					{
						zCalc = elev[x,y];
						if(zCalc != -9999)
						{
							if (zCalc < zMin) zMin = zCalc;
							if (zCalc > zMax) zMax = zCalc;
							hs = hillshade[x,y];
							if (hs < hsMin) hsMin = hs;
							if (hs > hsMax) hsMax = hs;
						}
					}
				}
				zRange = zMax - zMin;
				hsRange = hsMax - hsMin;
				
				for(x=1;x<=xmax;x++)
				{
					for(y=1;y<=ymax;y++)
					{
						if (elev[x,y] > 0.0)
						{
							// HILLSHADE: Draw first underneath
							
							// set gray scale intensity
							hue = 360.0;	// hue doesn't matter for gray shade
							sat = 0.0;		// ensures gray shade
							valMin = 0.0;
							valMax = 1.0;
							val = ((hillshade[x,y]/255) * (valMax - valMin)) + valMin; // uses maximum contrast
//							val = (((hillshade[x,y] - hsMin)/(zRange)) * (valMax - valMin)) + valMin; // lower contrast

							Color_HSVtoRGB();	// Call up color conversion
							redcol = System.Convert.ToInt32(red*255);
							greencol = System.Convert.ToInt32(green*255);
							bluecol = System.Convert.ToInt32(blue*255);
							alphacol = 255;
							
							SolidBrush brush2 = new SolidBrush(Color.FromArgb(alphacol,redcol,greencol,bluecol));
							objGraphics.FillRectangle(brush2,(x-1)*t,(y-1)*t,t,t);
							
							// DEM	
							zDEM = (elev[x,y]);
							// Sets hue based on desired color range (in decimal degrees; max 360)
							double hueMin = 30.0;
							double hueMax = 85.0;
//							hue = (((zDEM - zMin)/(zRange)) * (hueMax - hueMin)) + hueMin; // Forward
							hue = hueMax -(((zDEM - zMin)/(zRange)) * (hueMax - hueMin)); // Reverse
				
							// Set saturation based on desired range
							double satMin = 0.50;
							double satMax = 0.95;
							sat = (((zDEM - zMin)/(zRange)) * (satMax - satMin)) + satMin;
//							sat = 0; // Use for grey-scale DEM only!
							 
							// Set value based on desired range
							valMin = 0.40;
							valMax = 0.80;
							val = (((zDEM - zMin)/(zRange)) * (valMax - valMin)) + valMin;
//							val = valMax - (((zDEM - zMin)/(zRange)) * (valMax - valMin));
						 			
							Color_HSVtoRGB();	// Call up color conversion
							redcol = System.Convert.ToInt32(red*255);
							greencol = System.Convert.ToInt32(green*255);
							bluecol = System.Convert.ToInt32(blue*255);
							alphacol = 125;
							
							SolidBrush brush = new SolidBrush(Color.FromArgb(alphacol,redcol,greencol,bluecol));
                            objGraphics.FillRectangle(brush, (x-1) * t, (y-1) * t, t, t);

						}	// Close of Entire Grid Mask
					}		// Close of Column Loop 
				}			// Close of Row Loop

			}				// Close of DEM check box (menuitem34) 
			
            
	// Find Ranges for those in Active Area
			// Water Depth Range:
			double wdCalc, wdMin = 100000.0, wdMax =-10.0, wdRange;
							
			// Find Water Depth Ranges
			for(x=1;x<xmax;x++)
			{
				for(y=1;y<=ymax;y++)
				{
					wdCalc = Tau[x,y];
					if(wdCalc>0)
					{
						if(wdCalc<wdMin)wdMin=wdCalc;
						if(wdCalc>wdMax)wdMax=wdCalc;
					}
				}
			}
			wdRange = wdMax - wdMin;



			// All these loop through just the 'Active Area'
			for(x=1;x<=xmax;x++)
			{
				for(y=1;y<=ymax;y++)
				{
					if (1>0) // Index masks out so only 'active cells' shown	was if(index[x,y]>-9999)		
					{
						// Water Depth
						if(menuItem3.Checked==true&&water_depth[x,y]>water_depth_erosion_threshold)//MIN_Q)//||discharge[x,y]>0)
						{

							z=0;
                            if (comboBox1.Text == "water depth")
                            {
                                z = (int)(water_depth[x, y] * 125 * contrastMultiplier);
                            }
                            else
                            {
                                z = (int)(water_depth[x, y] * 125);
                            }
							//z=(int)((width[x,y]/(1/edge2[x,y]))*256);
							//z=(int)((2/(((2.131*Math.Pow(edge2[x,y],-1.0794))*DX)/(DX*width[x,y])))*1250);
							//z=(int)(edge[x,y]*1000);
							//z=(int)((max_flow[x,y,0]/DX)*1);
							//if(max_flow[x,y,0]<(0.5))z=255;
							//z=(int)(max_flow[x,y,3]*10);
                            //z = 0; z = (int)(Math.Pow(edge2[x, y], 0.7) * 2 * 256);

                            
                            //z = (int)(return_mean_vel_diff(x, y) * 125);                           
                            if(z<0)z=0;
							if(z>254)z=254;
							
							greencol=255-z;
							redcol=z;
							bluecol = 255;


							alphacol = 255;

							SolidBrush brush = new SolidBrush(Color.FromArgb(alphacol,redcol,greencol,bluecol));
                            objGraphics.FillRectangle(brush, (x-1) * t, (y-1) * t, t, t);
												
						}
					
						// DoD Erosion/ Depostion
						if(menuItem4.Checked==true)
						{
							tomsedi+=(init_elevs[x,y]-elev[x,y]);
							tomsedi-=(Vsusptot[x,y])/(DX*DX);
							if(init_elevs[x,y]-elev[x,y]>=0.001) //eroding
							{
                                if (comboBox1.Text == "erosion/dep")
                                {
                                    z = (int)((init_elevs[x, y] - elev[x, y]) * 256 * contrastMultiplier);
                                }
                                else
                                {
                                    z = (int)((init_elevs[x, y] - elev[x, y]) * 256);
                                }
								if(z<0)z=0;
								if(z>254)z=254;
								greencol=255-z;
								redcol=z;
								// red green blue

								SolidBrush brush = new SolidBrush(Color.FromArgb(255,greencol,greencol));
                                objGraphics.FillRectangle(brush, (x-1) * t, (y-1) * t, t, t);
							}

							if(init_elevs[x,y]-elev[x,y]<=-0.001) //depositing
							{
								z=(int)((elev[x,y]-init_elevs[x,y])*256);
								if(z<0)z=0;
								if(z>254)z=254;
								greencol=z;
								redcol=255-z;

								SolidBrush brush = new SolidBrush(Color.FromArgb(redcol,255,redcol));
                                objGraphics.FillRectangle(brush, (x-1) * t, (y-1) * t, t, t);
							}

							//						if(init_elevs[x,y]-elev[x,y]>0.0001&&init_elevs[x,y]-elev[x,y]<0.1)graphics.DrawRectangle(Pens.Yellow,x*t,y*t,t,t);
							//						if(init_elevs[x,y]-elev[x,y]>0.1&&init_elevs[x,y]-elev[x,y]<0.2)graphics.DrawRectangle(Pens.Orange,x*t,y*t,t,t);
							//						if(init_elevs[x,y]-elev[x,y]>0.2&&init_elevs[x,y]-elev[x,y]<10)graphics.DrawRectangle(Pens.Red,x*t,y*t,t,t);
							//						if(init_elevs[x,y]-elev[x,y]<-0.0001&&init_elevs[x,y]-elev[x,y]>-0.1)graphics.DrawRectangle(Pens.LightGreen,x*t,y*t,t,t);
							//						if(init_elevs[x,y]-elev[x,y]<-0.1&&init_elevs[x,y]-elev[x,y]>-0.2)graphics.DrawRectangle(Pens.Green,x*t,y*t,t,t);
							//						if(init_elevs[x,y]-elev[x,y]<-0.2&&init_elevs[x,y]-elev[x,y]>-10)graphics.DrawRectangle(Pens.DarkGreen,x*t,y*t,t,t);

						
						}
					
						if(menuItem5.Checked==true)
						{
							if(1>0)//if(index[x,y]!=-9999)
							{
							    z=(int)(veg[x,y,1]*256);
                                //z = (int)((Tau[x,y]-(Tau2[x,y]*2)) * 256);
                                z = (int)(max_flow[x, y, 0] * 20);

                                if (z < 0) z = 0;
                                if (z > 254) z = 254;
                                greencol = z;
                                redcol = 255 - z;

                                SolidBrush brush = new SolidBrush(Color.FromArgb(redcol, 255, redcol));
                                objGraphics.FillRectangle(brush, (x-1) * t, (y-1) * t, t, t);

							}
						}
					
						// Tracer Concentration
						if(menuItem6.Checked==true)//&&TRACERS>1)
						{
							if(water_depth[x,y]>0)
							{
								double temptot=0;
								int dir;



								z=(int)(temptot*30000000);

								z=(int)((lat_vol[x,y]-discharge[x,y])*25);
								z=(int)((pool_depth[x,y])*256);
                                //z = (int)((width[x, y]) * 25);
                                //z = (int)((edge2[x, y]) * 1000);
                                //z = (int)(max_flow[x, y, 0] * 25);
                                //z=(int) (calc_manning(x,y)*3000);
                                //Console.WriteLine(Convert.ToString(temptot*10000));
								if(z<0)z=0;
								if(z>254)z=254;
								greencol=255-z;
								redcol=z;
								
								
								SolidBrush brush = new SolidBrush(Color.FromArgb(255,greencol,redcol));
                                objGraphics.FillRectangle(brush, (x-1) * t, (y-1) * t, t, t);
								 


							}
								


						}



						// now to draw second teir


					if(menuItem7.Checked==true&&edge[x,y]>-9999)
					{

						if(edge[x,y]>=0) //inside
						{
							z=0;
							z=(int)((edge[x,y])*1000);
							
							if(z<0)z=0;
//							z=(int)((2.131*Math.Pow(edge[x,y],-1.0794))*DX);
//							z=254-z;
							if(z>254)z=254;
							if(z<0)z=0;
							greencol=255-z;
							redcol=z;
							// red green blue

							SolidBrush brush = new SolidBrush(Color.FromArgb(255,greencol,greencol));
                            objGraphics.FillRectangle(brush, (x-1) * t, (y-1) * t, t, t);
						}

						if(edge[x,y]<0) //outside
						{
							z=(int)((0-edge[x,y])*1000);
							if(z<0)z=0;
							if(z>254)z=254;
//							z=(int)((2.131*Math.Pow(edge[x,y],-1.0794))*DX);
//							z=254+z;
//							if(z>254)z=254;
//							if(z<0)z=0;
							greencol=z;
							redcol=255-z;

							SolidBrush brush = new SolidBrush(Color.FromArgb(redcol,255,redcol));
                            objGraphics.FillRectangle(brush, (x-1) * t, (y-1) * t, t, t);
						}

				
					}

						if(menuItem8.Checked==true)


						{
						
							if(Tau[x,y]>0)
							{
                                if (comboBox1.Text == "Bed sheer stress")
                                {
                                    z = (int)((Tau[x, y]) * (4)*contrastMultiplier);
                                }
                                else
                                {
                                    z = (int)((Tau[x, y]) * (255 / wdRange));
                                    //z = (int)(Tau[x, y] * (4));
                                }
								//Console.WriteLine(Convert.ToString(Tau[x,y]));
								if(z<0)z=0;
								if(z>254)z=254;
								//if(z>100)z=254;
								greencol=255-z;
								redcol=z;

								SolidBrush brush = new SolidBrush(Color.FromArgb(redcol,greencol,255));
                                objGraphics.FillRectangle(brush, (x-1) * t, (y-1) * t, t, t);

							}
						
						}
					
						// D50
						if(menuItem9.Checked==true)
						{
							if(index[x,y]!=-9999)
							{
                                if (comboBox1.Text == "grainsize")
                                {
                                    tot_max = d50(index[x, y]) * 2000*contrastMultiplier;
                                }
                                else
                                {
                                    tot_max = d50(index[x, y]) * 2000;
                                }
								//Console.WriteLine((Convert.ToString(tot_max)));
						
								tot=(int)tot_max;
								if(tot>255)tot=255;
								if(tot<0)tot=0;

								SolidBrush brush = new SolidBrush(Color.FromArgb(255-(tot*1),255-(tot*1),255-(tot*1)));
                                objGraphics.FillRectangle(brush, (x-1) * t, (y-1) * t, t, t);

							}
						}
					
						// Tracer
                        if (menuItem10.Checked == true && (TRACERS > 1 || mine_checkBox.Checked == true))
						{
							if(index[x,y]!=-9999&&grain[index[x,y],1,1]>0)
							{
								ztemp=0;
								for(n=1;n<G_MAX;n++)
								{
									ztemp+=(grain[index[x,y],n,1]*2550);
								}
                                if (comboBox1.Text == "tracer")
                                {
                                    z = (int)(ztemp*contrastMultiplier*100);
                                }
                                else
                                {
                                    z = (int)(ztemp);
                                }
								if(z<0)z=0;
								if(z>254)z=254;
								greencol=255-z;
								redcol=z;

								SolidBrush brush = new SolidBrush(Color.FromArgb(255,greencol,redcol));
                                objGraphics.FillRectangle(brush, (x-1) * t, (y-1) * t, t, t);
							}
						}
					
						// area drained
						if(menuItem26.Checked==true)
						{
							if(1==1)
							{
									z=(int)area[x,y];
								
								
									if(z<0)z=0;
									if(z>254)z=254;

									greencol=255-z;
									redcol=z;

									SolidBrush brush = new SolidBrush(Color.FromArgb(redcol,greencol,255));
                                    objGraphics.FillRectangle(brush, (x-1) * t, (y-1) * t, t, t);

							}
						}
					
						// Suspended Sediment Concentration
						if(menuItem27.Checked==true)
						{
							if(index[x,y]!=-9999)
							{
								if (Csusptot[x,y] > 0.0)
								{
                                    if (comboBox1.Text == "susp conc")
                                    {
                                        z = (int)(Csusptot[x, y] * 25600*contrastMultiplier);
                                    }
                                    else
                                    {
                                        z = (int)(Csusptot[x, y] * 25600);
                                    }
									if(z<0)z=0;
									if(z>254)z=254;

									greencol=255-z;
									redcol=z;

									SolidBrush brush = new SolidBrush(Color.FromArgb(redcol,greencol,255));
                                    objGraphics.FillRectangle(brush, (x-1) * t, (y-1) * t, t, t);
								}
							}
						}

						// Suspended Sediment Volume
						if(menuItem28.Checked==true)
						{
							if(index[x,y]!=-9999)
							{
								if (Vsusptot[x,y] > 0.0)
								{
                                    if (comboBox1.Text == "susp vol")
                                    {
                                        z = (int)(Vsusptot[x, y] * 50*contrastMultiplier);
                                    }
                                    else
                                    {
                                        z = (int)(Vsusptot[x, y] * 50);
                                    }
									if(z<0)z=0;
									if(z>254)z=254;
									greencol=255-z;
									redcol=z;
									SolidBrush brush = new SolidBrush(Color.FromArgb(redcol,greencol,255));
                                    objGraphics.FillRectangle(brush, (x-1) * t, (y-1) * t, t, t);
								}
							}
						}
	
						// Flow Velocity
						if (menuItem31.Checked == true)	// <JOE 20050605>
						{
							if (index[x,y] != -9999)
							{
								if (max_flow[x,y,0] > 0.0)
								{
									z=0;
                                    if (comboBox1.Text == "flow velocity")
                                    {
                                        z = (int)((max_flow[x, y, 0]/(DX*water_depth[x,y])) * 51*contrastMultiplier * (1+(edge[x,y]*4)));
                                    }
                                    else
                                    {
                                        z = (int)((max_flow[x, y, 0] / (DX * water_depth[x, y])) * 51+(1 + (1+edge[x, y] * 4)));
                                    }
									//if(yyy>0.25)z=254;
									if (z < 0) z = 0;
									if (z > 254) z = 254;
									greencol = 255-z;
									redcol = z;
									SolidBrush brush = new SolidBrush(Color.FromArgb(redcol,greencol,255));
                                    objGraphics.FillRectangle(brush, (x-1) * t, (y-1) * t, t, t);
								}
							}
						}

						// Soil Saturation
						if (menuItem32.Checked == true)	// <JOE 20050605>
						{
							if (index[x,y] != -9999)
							{
								if (soil_saturation[x,y] > 0.0)
								{
									z = (int)(soil_saturation[x,y] * 10);
									if (z < 0) z = 0;
									if (z > 254) z = 254;
									greencol = 255-z;
									redcol = z;
									SolidBrush brush = new SolidBrush(Color.FromArgb(redcol,greencol,255));
                                    objGraphics.FillRectangle(brush, (x-1) * t, (y-1) * t, t, t);
								}
							}
			
						}
					}			// Close of nodata check for 'active' grid only
				}				// Close of Collumn Loop
			}					// Close of Row Loop
            
           
			this.QsStatusPanel.Text=string.Format("Qs = {0:F8}",tomsedi*DX*DX);
            
            objGraphics.Dispose();
            zoomPanImageBox1.Image = m_objDrawingSurface;
            
		}	// Close of drawwater() // <JOE 20051605- end>




		void fill_pits()
		{
			int x,y,dir,x2=0,y2=0, inc;
			double lowest=10000, highest=0;
            double pit_fill_amount = ERODEFACTOR;

            if (pit_fill_amount > 0.01) pit_fill_amount = 0.01; // prevents pits getting over filled if high erodefactor is allowed

			double[,] pool_temp;

			pool_temp=new Double[xmax+1,ymax+1];
			
			for(x=1;x<(xmax);x++)
			{	
				inc=1;
	  
                //while(cross_scan[x,inc]>0)
                //{
                //    y=cross_scan[x,inc];
                //    inc++;
                for(y=2;y<ymax;y++)
                {

                    if (1==1)//(water_depth[x, y] > water_depth_erosion_threshold)
					{
						pool_temp[x,y]=0;
						lowest=10000;
						highest=0;
						for (dir=1;dir<=8;dir++)
						{
							x2 = x + deltaX[dir];
							y2 = y + deltaY[dir];

							if(elev[x,y]+pool_depth[x,y]<elev[x2,y2]+pool_depth[x2,y2])
							{
								if(elev[x2,y2]+pool_depth[x2,y2]<lowest)lowest=elev[x2,y2]+pool_depth[x2,y2];
							}
							if(elev[x,y]+pool_depth[x,y]>elev[x2,y2]+pool_depth[x2,y2])
							{
								if(elev[x2,y2]+pool_depth[x2,y2]>highest)highest=elev[x2,y2]+pool_depth[x2,y2];
							}
						}
                        // amount that pits should be filled or lowered by (always more loweredby) should be same/more than the erode/depo limit, otherwuse you can get pits eroded faster than they can be filled in
                        if (lowest != 10000 && lowest > (elev[x, y] + pool_depth[x, y])) pool_temp[x, y] += pit_fill_amount;// lowest - (elev[x, y] + pool_depth[x, y]);
                        if (highest != 0 && highest < (elev[x, y] + pool_depth[x, y])) pool_temp[x, y] -= pit_fill_amount*1.02;// highest - (elev[x, y] + pool_depth[x, y]);
						
					}
				}
			}
			for(x=1;x<(xmax);x++)
			{	
				inc=1;
	  
				while(cross_scan[x,inc]>0)
				{
					y=cross_scan[x,inc];
					inc++;

                    if (1==1)//(water_depth[x, y] > water_depth_erosion_threshold)
					{
						pool_depth[x,y]+=pool_temp[x,y];
						if(pool_depth[x,y]<0)pool_depth[x,y]=0;
						
					}
                    
				}
                
			}
		}

		void erode()
		{
			double tot_ht, ht, factor=0, slopemax=0,slopesum=0, amount_to_add=0, depth, tempb, tempbmax=0;
            int x = 0, y, n, inc, loopinc, q, xtemp, ytemp, temp_centre, p, slopenum, contamGrain;
			double depth_threshold=water_depth_erosion_threshold; // was 0.001
            double[] gtot, gtot2, gtot3;
			gtot = new Double[20];
			gtot2 = new Double[20];
            gtot3 = new Double[20];//amount of tracer at outlet, for each grainsize
			/** additional suspended sediment variables (MJ 16/02/05) **/  
			int dir,x2,y2;
			int xyindex;
			int Ucount;
			double Usum,Umax;
			double coeff;
			double Vouttot,Voutcoeff;
			double[] U = new Double[9];
			double Csuspmax = 0.1; // max concentration  of SS allowed in a cell (proportion)
			double Vsusptemp,Vsuspmax;
			double Vdir,Vpdir,Vpdrop,Vsurplus;
			double gsusptot;
            double old_time_factor = 0;
			/** end of additional suspended sediment variables **/


//			WriteSedFile("Start_erode()");

			tempb=0;
  
			for(n=0;n<=G_MAX;n++)
			{
				gtot[n]=0;
				gtot2[n]=0;
                gtot3[n] = 0;
			}
  



			double tempbsubtotal=0;

            

			do
			{
				//time_factor=60;
				tempb=0;
				tempbmax=0;

                time_factor = time_factor * 1.5;
                if (time_factor > max_time_step) time_factor = max_time_step; // copied from erodedepo();
                

				for(x=0;x<=grain_array_tot;x++)
				{
					for(y=0;y<=G_MAX;y++)
					{
						for(p=0;p<=(TRACERS-1);p++)
						{
							temp[x,y,p]=0;
						}
					}
				}


				/**
				 ** START of additional suspended sediment code **
				 ** 
				 ** The following lines are used to initialize the temporary suspended
				 ** seds arrays. They are used later to temporarily store sediment volumes,
				 ** before updating the official arrays Vsusp and Vsupstot.
				 **
				 ** Added by MJ 16/02/05
				 ** Latest change by MJ 09/05/05
				 **/ 

				for (y=1; y<=ymax; y++)
				{
					for (x=1; x<=xmax; x++)
					{
						//Tau[x,y] = 0.0;
						tempsusptot[x,y] = 0.0;
						for (n=0; n<=G_MAX; n++)
						{
							if (isSuspended[n])
							{
								for (p=0; p<=(TRACERS-1); p++)
								{
									tempsusp[x,y,n,p] = 0.0;
								}
							}
						}

                        // also used for updating dunes - if water runs over some sand it gets incorporated into the 
                        // fluvial part

                        if (sand[x, y] > 0 && water_depth[x, y] > water_depth_erosion_threshold)
                        {
                            //////////////////////////////////
                            double tempsandvol = sand[x, y];
                            if (tempsandvol > 0.1) tempsandvol = 0.1;
                            sand[x, y] -= tempsandvol;

                            if (index[x, y] == -9999) addGS(x, y);
                            grain[index[x, y], 1, 0] += tempsandvol;
                            sort_active2(x, y);

                            // now has to reduce sand vol..
                            double sand2tot = 0;
                            int sand2num = 0;
                            for (x2 = 0; x2 < dune_mult; x2++)
                            {
                                for (y2 = 0; y2 < dune_mult; y2++)
                                {
                                    if (sand2[(x * dune_mult) - x2, (y * dune_mult) - y2] > 0)
                                    {
                                        sand2tot += sand2[(x * dune_mult) - x2, (y * dune_mult) - y2];
                                        sand2num++;
                                    }

                                }
                            }
                            for (x2 = 0; x2 < dune_mult; x2++)
                            {
                                for (y2 = 0; y2 < dune_mult; y2++)
                                {
                                    if (sand2[(x * dune_mult) - x2, (y * dune_mult) - y2] > 0)
                                    {
                                        sand2[(x * dune_mult) - x2, (y * dune_mult) - y2] -= (tempsandvol * dune_mult * dune_mult) *
                                            (sand2[(x * dune_mult) - x2, (y * dune_mult) - y2] / sand2tot);

                                    }

                                }
                            }

                        }
					}
				}

                
				/** end of additional suspended sediment code **/


//				WriteSedFile("after_initialize");

				// adding material in here...
				// reorganized MJ 09/05/05
				//

				if (reach_mode_box.Checked==true)
				{
					for (n=0; n<=number_of_points-1; n++)
					{
						x = inpoints[n,0];
						y = inpoints[n,1];			

						int tempn,n2;
						for (tempn=5; tempn<=13; tempn++)
						{
							if (index[x,y] == -9999) addGS(x,y);
                            amount_to_add = (Math.Abs(inputfile[n, (int)((cycle - init_cycle) / input_time_step), tempn])) / div_inputs;
							amount_to_add = amount_to_add / (DX*DX); // divide by grid cell size
							amount_to_add /= (input_time_step*60); // turn from days to secs
							amount_to_add = amount_to_add*time_factor; // convert rate into volume
							//Console.WriteLine(Convert.ToString(amount_to_add));
                            //n2 = tempn - 4;
                            //temp[index[x, y], n2, 0] += amount_to_add;

// commented out these lines about suspended sediment. Still not sure how to add it correctly... 13/3/07
                            n2 = tempn - 4;
                            if (isSuspended[n2])
                            {
                                //								Vsusp[x,y,n2,0] += amount_to_add*(DX*DX);
                                //								Vsusptot[x,y] += amount_to_add*(DX*DX);
                                tempsusp[x, y, n2, 0] += amount_to_add * (DX * DX);
                                tempsusptot[x, y] += amount_to_add * (DX * DX);
                            }
                            else
                            {
                                temp[index[x, y], n2, 0] += amount_to_add;
                            }
						}
					}
				}

                // new contaminant adding part
                if (tracerbox.Checked == true)
                {
                    for (n = 1; n <= tot_number_of_tracer_points; n++)
                    {
                        // same as above but adding tracer material
                        amount_to_add = 0;
                        x = Convert.ToInt32(tracerinput[n, 1]);
                        y = Convert.ToInt32(tracerinput[n, 2]);
                        factor = tracerinput[n, 3];
                        amount_to_add = tracerhydrograph[(int)(cycle / 60), 1] * factor;
                        amount_to_add = amount_to_add / (DX * DX);
                        amount_to_add = amount_to_add / 3600; // turning in to secs
                        if (index[x, y] == -9999) addGS(x, y);
                        temp[index[x, y], Convert.ToInt32(tracerinput[n, 4]), 1] += amount_to_add * time_factor;
                    }
                }
                    if (mine_checkBox.Checked == true)
                    {
                        // adding contamination at "super mine", all nine grainsizes, just two now
                        for (contamGrain = 1; contamGrain < 3; contamGrain++)
                        {
                            amount_to_add = 0;
                            x = mine_inpoints[0, 0];
                            y = mine_inpoints[0, 1];
                            amount_to_add = mineinput[(int)(cycle / 60), contamGrain];
                            amount_to_add = amount_to_add / (DX * DX);
                            amount_to_add = amount_to_add / 3600; // turning in to secs
                            if (index[x, y] == -9999) addGS(x, y);
                            temp[index[x, y], contamGrain, 1] += amount_to_add * time_factor;
                        }
                     }


//				WriteSedFile("after_influx");

                    // add in recirculating sediment.
                    if (recirculatebox.Checked == true && reach_mode_box.Checked == true)
                    {
                        int tempn;
                        for (n = 0; n <= number_of_points - 1; n++)
                        {
                            x = inpoints[n, 0];
                            y = inpoints[n, 1];

                            for (tempn = 5; tempn <= 13; tempn++)
                            {
                                if (index[x, y] == -9999) addGS(x, y);
                                if (isSuspended[tempn - 4])
                                {

                                    tempsusp[x, y, tempn - 4, 0] += (DX * DX) * ((temp_grain[tempn - 4]*time_factor) / number_of_points) * double.Parse(propremaining.Text);
                                    tempsusptot[x, y] += (DX * DX) * ((temp_grain[tempn - 4]*time_factor) / number_of_points) * double.Parse(propremaining.Text);
                                }
                                else
                                {
                                    temp[index[x, y], tempn - 4, 0] += ((temp_grain[tempn - 4]*time_factor) / number_of_points) * double.Parse(propremaining.Text);
                                }
                                //temp[index[x, y], tempn - 4, 0] += (temp_grain[tempn - 4] / number_of_points)*double.Parse(propremaining.Text);
                            }
                        }
                        for (tempn = 5; tempn <= 13; tempn++)
                        {
                            temp_grain[tempn - 4] = 0;
                        }
                    }

                    //			WriteSedFile("after_recirculate");


				//max=0;
				
				tempbsubtotal=0;
    
				for(y=1;y<ymax;y++)
				{
      
					inc=1;
					while(down_scan[y,inc]>0)
					{
						x=down_scan[y,inc];
						inc++;	
	
						/** check to see if under water **/
	
						if(water_depth[x,y]>depth_threshold&&x>1&&x<xmax)
						{
	  
							tot_ht=elev[x,y]+water_depth[x,y];
							depth=water_depth[x,y];
							ht=elev[x,y];
							tempb=0;
                            if (index[x, y] == -9999) addGS(x, y);

                            // dune parts...
                            //if (sand[x, y] > 0.01)
                            //{
                            //    grain[index[x, y], 1, 0] += 0.01;
                            //    sand[x, y] -= 0.01; // 
                            //    sort_active2(x, y);
                            //}
	  
							for(n=1;n<=8;n++)
							{
								for(loopinc=0;loopinc<=G_MAX;loopinc++)
								{
									dist[n,loopinc]=0;
								}
							}



							/*************** then incision/depo ************/
	  
							slopemax=0;
							slopesum=1;
							slopenum=0;

                            
							if(max_bed_slope(x,y)>0&&elev[x,y]>bedrock[x,y])erode_w3(x,y,water_depth[x,y],1,slopesum); 
	  
							/************************************************************************************************/
	  
							/* calls erode 3, with amount, dist category, grid category (for grain sizes) and x+y's */
							erode3(0,3,x,y);
							erode3(1,4,x,y);
							erode3(2,5,x,y);
							erode3(3,6,x,y);
							erode3(4,7,x,y);
							erode3(5,8,x,y);
							erode3(6,9,x,y);
							erode3(7,10,x,y);
							erode3(8,11,x,y);
							erode3(9,12,x,y);
							erode3(10,13,x,y);

							 
	  
							/*** try new tempb approach....  *******************************************/
	  
                            //tempb=0;
                            //if(index[x,y]!=-9999)
                            //{
                            //    for(loopinc=1;loopinc<=G_MAX;loopinc++)
                            //    {
                            //        for(p=0;p<=(TRACERS-1);p++)
                            //        {
                            //            tempb+=temp[index[x,y],loopinc,p];
                            //            tempbsubtotal+=temp[index[x,y],loopinc,p];
                            //        }
                            //    }
                            //}
                            //tempbcounter++;
                            //if(tempb>0.2||tempb<-0.2)Console.WriteLine(tempb);
                            //if(tempb<0)tempb=0-tempb;
                            //if(tempb>tempbmax)							
                            //{
                            //    if(tempbmax>ERODEFACTOR)this.tempdata1.Text=Convert.ToString(x);
                            //    if(tempbmax>ERODEFACTOR)this.tempdata2.Text=Convert.ToString(y);
                            //    if (tempbmax > ERODEFACTOR) y = ymax;
                            //    tempbmax=tempb;
                            //}
						}
					}
				}


    
				//IMPORTANT - trying to increase time step here..
                old_time_factor = time_factor;
                
                //this.tempdata1.Text = Convert.ToString(time_factor);
                //this.tempdata2.Text = Convert.ToString(tempbmax);

				// or trying to decrease it too!

                tempbmax = 0;
                for (y = 1; y < ymax; y++)
                {

                    inc = 1;
                    while (down_scan[y, inc] > 0)
                    {
                        x = down_scan[y, inc];
                        inc++;

                        tempb = 0;
                        if (index[x, y] != -9999)
                        {
                            for (loopinc = 1; loopinc <= G_MAX; loopinc++)
                            {
                                for (p = 0; p <= (TRACERS - 1); p++)
                                {
                                    tempb += temp[index[x, y], loopinc, p];
                                    tempbsubtotal += temp[index[x, y], loopinc, p];
                                }
                            }
                        }
                        if (tempb < 0) tempb = 0 - tempb;
                        if (tempb > ERODEFACTOR) this.tempdata1.Text = Convert.ToString(x);
                        if (tempb > ERODEFACTOR) this.tempdata2.Text = Convert.ToString(max_flow[x, y, 0]);
                        //if (tempb > ERODEFACTOR) Console.WriteLine(Tau[x,y]+" "+max_flow[x, y, 0]);
                        if (tempb > tempbmax) tempbmax = tempb;

                    }
                }

                if (tempbmax > ERODEFACTOR && time_factor > min_time_step)
                {
                    time_factor = time_factor / 2;
                    
                    
                }
                    


			} while (tempbmax>ERODEFACTOR&&time_factor>min_time_step);
			
           



//			WriteSedFile("after_entrainment");


			
			
			

            if (tracerbox.Checked == true)
            {
                for (n = 1; n <= tot_number_of_tracer_points; n++)
                {
                    x=Convert.ToInt32(tracerinput[n,1]);
                    y=Convert.ToInt32(tracerinput[n,2]);
                    grain[index[x, y], Convert.ToInt32(tracerinput[n, 4]), 1] += temp[index[x, y], Convert.ToInt32(tracerinput[n, 4]), 1];
                    if (x < xmax) elev[x, y] += temp[index[x, y], Convert.ToInt32(tracerinput[n, 4]), 1];
                    if (x == xmax) gtot2[Convert.ToInt32(tracerinput[n, 4])] += temp[index[x, y], Convert.ToInt32(tracerinput[n, 4]), 1];
                    temp[index[x, y], Convert.ToInt32(tracerinput[n, 4]), 1] = 0;
                    sort_active(x, y);
                }
            }
            if (mine_checkBox.Checked == true)
            {
                //sorting of contaminted material at "super mine", just two grainsizes now
                for (contamGrain = 1; contamGrain < 3; contamGrain++)
                {
                    x = mine_inpoints[0, 0];
                    y = mine_inpoints[0, 1];
                    grain[index[x, y], contamGrain, 1] += temp[index[x, y], contamGrain, 1];
                    if (x < xmax) elev[x, y] += temp[index[x, y], contamGrain, 1];
                    if (x == xmax) gtot2[contamGrain] += temp[index[x, y], contamGrain, 1];
                    temp[index[x, y], contamGrain, 1] = 0;
                    sort_active(x, y);
                    //Console.WriteLine("Hour:" + (int)(cycle / 60));
                    //Console.WriteLine("grainsize" + contamGrain + ", layer1:" + grain[index[x, y], contamGrain, 1]);
                    //Console.WriteLine("grainsize" + contamGrain + ", layer2:" + strata[index[x, y], 0, contamGrain - 1, 1]);
                    //Console.WriteLine("grainsize" + contamGrain + ", layer3:" + strata[index[x, y], 1, contamGrain - 1, 1]);
                    //Console.WriteLine("grainsize" + contamGrain + ", layer4:" + strata[index[x, y], 2, contamGrain - 1, 1]);
                    //Console.WriteLine("grainsize" + contamGrain + ", layer5:" + strata[index[x, y], 3, contamGrain - 1, 1]);
                    //Console.WriteLine("grainsize" + contamGrain + ", layer6:" + strata[index[x, y], 4, contamGrain - 1, 1]);
                    //Console.WriteLine("grainsize" + contamGrain + ", layer7:" + strata[index[x, y], 5, contamGrain - 1, 1]);
                    //Console.WriteLine("grainsize" + contamGrain + ", layer8:" + strata[index[x, y], 6, contamGrain - 1, 1]);
                    //Console.WriteLine("grainsize" + contamGrain + ", layer9:" + strata[index[x, y], 7, contamGrain - 1, 1]);
                }
            }


//			WriteSedFile("after_tracers");



			/**
			 ** START of additional suspended sediment code **
			 ** 
			 ** The following lines are used to move the suspended seds around
			 ** with flow, and have (some of) them drop out of the flow.
			 ** Tempsusp[,,] and tempsusptot[,] have been initialized earlier on 
			 ** and record entrainment of suspended sediment as per erode4().
			 ** Vsusp[,,] and Vsusptot store suspended sediments in transport,
			 ** to be carried over to next timestep.
			 **
			 ** Added by MJ 16/02/05
			 ** Changed by MJ 19/05/05
			 **/ 


			// update Vsusp to account for susp entrainment
			for (y=1;y<=ymax;y++)
			{
				inc = 1;
				while (down_scan[y,inc] > 0)
				{
					x = down_scan[y,inc];

                    //if ((veg[x, y, 1] > 0) && (Tau[x,y] > vegTauCrit))
                    //{
                    //    // now to remove from veg layer..
                    //    //Console.WriteLine(Convert.ToString(temp_dist[0]));
                    //    veg[x, y, 1] -= time_factor * Math.Pow(Tau[x, y] - vegTauCrit, 1) * 0.00005;
                    //    if (veg[x, y, 1] < 0) veg[x, y, 1] = 0;
                    //}

					if (tempsusptot[x,y] > 0.0)
					{
						Vsusptot[x,y] += tempsusptot[x,y];
						tempsusptot[x,y] = 0.0;			// clear for re-use
						for (n=0; n<=G_MAX; n++)
						{
							if (isSuspended[n])
							{
								for (p=0; p<=(TRACERS-1); p++)
								{
									Vsusp[x,y,n,p] += tempsusp[x,y,n,p];
									tempsusp[x,y,n,p] = 0.0;		// clear for re-use
								}
							}
						}
					}
					inc++;  // go to next element in downscan[y,inc]
				}
			}
			    
//			WriteSedFile("after_update_Vsusp_1");
			
    
			// distribute susp seds
			for (y=1;y<=ymax;y++)
			{
				inc = 1;
				while (down_scan[y,inc] > 0)
				{
					x = down_scan[y,inc];
					if ((x < xmax) && (water_depth[x,y] > depth_threshold) && (Vsusptot[x,y] > 0))
					{
						// determine velocities
						coeff = water_depth[x,y] * DX;
						Umax = 0.0;
						Usum = 0.0;
						Ucount = 0;
						for (dir=1;dir<=8;dir++)
						{
							x2 = x + deltaX[dir];
							y2 = y + deltaY[dir];
							if (  (max_flow[x,y,dir] > 0.00000000001)								// check that there is maxflow in that dir
							   && (water_depth[x2,y2] > depth_threshold)							// and there is water depth
							   //&& (Vsusptot[x2,y2] < (Csuspmax * water_depth[x2,y2] * DX * DX)) // and not too concentrated in recieving cell
								)
							{
								Ucount++;
								U[dir] = max_flow[x,y,dir] / coeff;
  								if (U[dir] > Umax)  Umax = U[dir];
	  							Usum += U[dir];
	  						}
	  						else  U[dir] = 0;
						}

						if (Usum > 0.000000000001)
						{
							// determine volume to be moved out
  							Voutcoeff = (Usum*time_factor) / DX;
							if (Voutcoeff > 0.9999)  Voutcoeff = 0.9999;  // MJ 23/03/05 to avoid problems later on
				    
							// distribute according to velocities
							for (dir=1;dir<=8;dir++)
							{
								if (U[dir] > 0.000000000000001)
								{
									x2 = x + deltaX[dir];
									y2 = y + deltaY[dir];
									if ((x2 > 0) && (y2 > 0) && (y2 <= ymax))
									{
										if (index[x2,y2] == -9999)  addGS(x2,y2);
										coeff =  U[dir] / Usum;
										Vdir = coeff * Voutcoeff * Vsusptot[x,y];
                                        
                                        // changes to prevent too much ss being moved in to recieving cells
                                        if ((Vdir + Vsusptot[x2, y2]) > (Csuspmax * water_depth[x2, y2] * DX * DX))
                                        {
                                            Vdir = (Csuspmax * water_depth[x2, y2] * DX * DX) - Vsusptot[x2, y2];
                                            if (Vdir < 0) Vdir = 0;
                                        }
                                        
										tempsusptot[x,y] -= Vdir;
										tempsusptot[x2,y2] += Vdir; 
										for (n=0; n<=G_MAX; n++)
										{
											if (isSuspended[n])
											{
												for (p=0; p<=(TRACERS-1); p++)
												{
													Vpdir = coeff * Voutcoeff * Vsusp[x,y,n,p];
													tempsusp[x,y,n,p] -= Vpdir;
													tempsusp[x2,y2,n,p] += Vpdir;
												}
											}
										}
									}
								}
							}
			  			}
			  		}
					inc++;  // go to next element in downscan[y,inc]
				}
			}

//			WriteSedFile("after_distribute");

			// update Vsusp to account for susp movement
			for (y=1;y<=ymax;y++)
			{
				inc = 1;
				while (down_scan[y,inc] > 0)
				{
					x = down_scan[y,inc];
					if ((x < xmax) && (tempsusptot[x,y] != 0))
					{
						Vsusptot[x,y] += tempsusptot[x,y];
						for (n=0; n<=G_MAX; n++)
						{
							if (isSuspended[n])
							{
								for (p=0; p<=(TRACERS-1); p++)
								{
									Vsusp[x,y,n,p] += tempsusp[x,y,n,p];
								}
							}
						}
					}
					if (Vsusptot[x,y] < 0.0)  
					{
						// needed for numerical stability
						// Vsusptot can sometimes be - 1.0 x 10-15
						// MJ 23/03/05 : extra note : this issue is solved when Voutcoeff < 1.0
						Vsusptot[x,y] = 0.0;
						for (n=0; n<=G_MAX; n++)
						{
							if (isSuspended[n])
							{
								for (p=0; p<=(TRACERS-1); p++)
								{
									Vsusp[x,y,n,p] = 0;
								}
							}
						}
					}
					inc++;  // go to next element in downscan[y,inc]
				}
			}

//			WriteSedFile("after_update_Vsusp_2");

			// add up susp seds at outflow  (adjusted MJ 04/07/2005)
			gsusptot = 0;
			for (y=1;y<=ymax;y++)
			{
				if (tempsusptot[xmax,y] > 0)
				{
					gsusptot += tempsusptot[xmax,y];
					for(n=0;n<=G_MAX;n++)
					{
						if (isSuspended[n])
						{
							for (p=0; p<=(TRACERS-1); p++)
							{
								gtot2[n] += tempsusp[xmax,y,n,p]/(DX*DX);
                                if (tracerOutcheckBox.Checked == true && TRACERS == 2)
                                {
                                    gtot3[n] += tempsusp[xmax, y, n, 1] / (DX * DX);//suspended sediment at outlet
                                }
							}
						}
					}
				}
			}
			this.tempStatusPanel.Text=string.Format("Qss = {0:F8}",gsusptot/time_factor);


//			WriteSedFile("after_update_outflow");


			// drop susp sediments according to fall velocity
            // also is called globally every 10 iterations in order to allow sediment outside of the 
            // scanned area to be deposited

            if (Math.IEEERemainder(counter, 10) == 0)
            {
                for (y = 1; y <= ymax; y++)
                {
                    for(x=1;x<=xmax;x++)
                    {
                        
                        if (Vsusptot[x, y] > 0.000000000001)
                        {
                            if (index[x, y] == -9999) addGS(x, y);
                            xyindex = index[x, y];
                            if (water_depth[x, y] > depth_threshold)
                            {
                                for (n = 0; n <= G_MAX; n++)
                                {
                                    if (isSuspended[n])
                                    {
                                        coeff = (fallVelocity[n] * time_factor) / water_depth[x, y];
                                        //if (max_flow[x, y, 0] / (DX * water_depth[x, y]) > 0.25) coeff = 0; // TJC - 10/1/06 this part is so that it can only drop sediment if the velocity is below a threshold)
                                        if (coeff > 1) coeff = 1;
                                        for (p = 0; p <= (TRACERS - 1); p++)
                                        {
                                            Vpdrop = Vsusp[x, y, n, p] * coeff;
                                            if (Vpdrop / (DX * DX) > 0.001) Vpdrop = 0.001 * (DX * DX); //only allow 1mm to be deposited per iteration
                                            temp[xyindex, n, p] += Vpdrop / (DX * DX);  // bug fix MJ 06/07/05
                                            Vsusp[x, y, n, p] -= Vpdrop;
                                            Vsusptot[x, y] -= Vpdrop;
                                        }
                                    }
                                }
                                Csusptot[x, y] = Vsusptot[x, y] / (water_depth[x, y] * DX * DX);
                            }
                            else
                            // restructured this bit  (MJ 07/06/05)
                            // previous version contained a bug here
                            // bug: Vsusptot[x,y] != sum Vsusp[x,y,n,p]
                            // don't why previous routine was wrong, nor why this works
                            // seems like it does exactly the same, but this one works
                            {
                                for (n = 0; n <= G_MAX; n++)
                                {
                                    if (isSuspended[n])
                                    {
                                        for (p = 0; p <= (TRACERS - 1); p++)
                                        {
                                            Vpdrop = Vsusp[x, y, n, p];
                                            if (Vpdrop / (DX * DX) > 0.001) Vpdrop = 0.001 * (DX * DX);
                                            temp[xyindex, n, p] += Vpdrop / (DX * DX);  // bug fix MJ 06/07/05
                                            Vsusp[x, y, n, p] -= Vpdrop;
                                            Vsusptot[x, y] -= Vpdrop;
                                        }
                                    }
                                }
                                if (water_depth[x, y] > 0.0)
                                {
                                    Csusptot[x, y] = Vsusptot[x, y] / (water_depth[x, y] * DX * DX);
                                }
                                else
                                {
                                    Csusptot[x, y] = 0.0;
                                }
                            }

                        }
                    }
                }
            }
            else
            {
                for (y = 1; y <= ymax; y++)
                {
                    inc = 1;
                    while (down_scan[y, inc] > 0)
                    {
                        x = down_scan[y, inc];
                        if (Vsusptot[x, y] > 0.000000000001)
                        {
                            if (index[x, y] == -9999) addGS(x, y);
                            xyindex = index[x, y];
                            if (water_depth[x, y] > depth_threshold)
                            {
                                for (n = 0; n <= G_MAX; n++)
                                {
                                    if (isSuspended[n])
                                    {
                                        coeff = (fallVelocity[n] * time_factor) / water_depth[x, y];
                                        //if (max_flow[x, y, 0] / (DX * water_depth[x, y]) > 0.25) coeff = 0; // TJC - 10/1/06 this part is so that it can only drop sediment if the velocity is below a threshold)
                                        if (coeff > 1) coeff = 1;
                                        for (p = 0; p <= (TRACERS - 1); p++)
                                        {
                                            Vpdrop = Vsusp[x, y, n, p] * coeff;
                                            if (Vpdrop / (DX * DX) > 0.001) Vpdrop = 0.001 * (DX * DX); //only allow 1mm to be deposited per iteration
                                            temp[xyindex, n, p] += Vpdrop / (DX * DX);  // bug fix MJ 06/07/05
                                            Vsusp[x, y, n, p] -= Vpdrop;
                                            Vsusptot[x, y] -= Vpdrop;
                                        }
                                    }
                                }
                                Csusptot[x, y] = Vsusptot[x, y] / (water_depth[x, y] * DX * DX);
                            }
                            else
                            // restructured this bit  (MJ 07/06/05)
                            // previous version contained a bug here
                            // bug: Vsusptot[x,y] != sum Vsusp[x,y,n,p]
                            // don't why previous routine was wrong, nor why this works
                            // seems like it does exactly the same, but this one works
                            {
                                for (n = 0; n <= G_MAX; n++)
                                {
                                    if (isSuspended[n])
                                    {
                                        for (p = 0; p <= (TRACERS - 1); p++)
                                        {
                                            Vpdrop = Vsusp[x, y, n, p];
                                            if (Vpdrop / (DX * DX) > 0.001) Vpdrop = 0.001 * (DX * DX);
                                            temp[xyindex, n, p] += Vpdrop / (DX * DX);  // bug fix MJ 06/07/05
                                            Vsusp[x, y, n, p] -= Vpdrop;
                                            Vsusptot[x, y] -= Vpdrop;
                                        }
                                    }
                                }
                                if (water_depth[x, y] > 0.0)
                                {
                                    Csusptot[x, y] = Vsusptot[x, y] / (water_depth[x, y] * DX * DX);
                                }
                                else
                                {
                                    Csusptot[x, y] = 0.0;
                                }
                            }

                        }
                        inc++;  // go to next element in downscan[y,inc]
                    }
                }
            }

//			WriteSedFile("after_drop_susp");

			/** end of additional suspended sediment code **/
			

			
			/* from here on is really only an update the values routine...*/
			// restructured  MJ 25/03/05
			bool need_sorting;
			for(y=1;y<=ymax;y++)
			{
				inc=1;
				while(down_scan[y,inc]>0)
				{
					x=down_scan[y,inc];
					if(index[x,y]!=-9999&&y<=ymax&&y>=1&&x>=1&&x<=xmax)
					{
						temp_centre=index[x,y];
						need_sorting = false;
						for(n=0;n<=G_MAX;n++)
						{
							for(p=0;p<=(TRACERS-1);p++)
							{
								if (temp[temp_centre,n,p] != 0.0) 
								{
									grain[temp_centre,n,p]+=temp[temp_centre,n,p];
									if(x<xmax)elev[x,y]+=temp[temp_centre,n,p];
									if(x<xmax&&n>0&&p==0)gtot[n]+=temp[temp_centre,n,p];

                                    if (x == xmax)
                                    {
                                        gtot2[n] += temp[temp_centre, n, p];//bug fix p was 0 always
                                        if (tracerOutcheckBox.Checked == true && TRACERS == 2)
                                        {
                                            gtot3[n] += temp[temp_centre, n, 1];//bedload contaminated sediment
                                        }
                                    }

									//temp[temp_centre,n,p]=0; commented out on 18/7/05 - to allow temp to be used in lateral2
									need_sorting = true;
								}
							}
						}
						if (need_sorting) sort_active2(x,y);
					}
					inc++;  // go to next element in downscan[y,inc]
				}
			}

//			WriteSedFile("after_sorting");

            // now to ensure that elevations at the input point do not change...
            // not sure if to keep in or not...
            //for (n = 0; n <= number_of_points - 1; n++)
            //{
            //    x = inpoints[n, 0];
            //    y = inpoints[n, 1];
            //    if (elev[x, y] != init_elevs[x, y]) elev[x, y] = init_elevs[x, y];
            //}


			// update output fluxes
			sediQ=0;
			for(n=1;n<=G_MAX;n++)
			{
				temp_grain[n]=gtot2[n]/time_factor; // important to divide input by time factor, so it can be reduced if re-circulating too much...
				sediQ+=gtot2[n]*DX*DX;
				globalsediq+=gtot2[n]*DX*DX;
				sum_grain[n]+=gtot2[n]*DX*DX; // Gez
                sum_grain2[n] += gtot3[n] * DX * DX;//used in output data calc
			}
            sedOut = sediQ;
			// now display sedi out bottom..
			if(menuItem4.Checked==false)this.QsStatusPanel.Text=string.Format("Qs = {0:F8}",sediQ); // MJ 14/01/05
            
//			WriteSedFile("End_erode()");

		}



        void erode_w2(int x, int y, double depth, double slope, double slopesum)
        // restructured by MJ 02/02/05
        {
            int n;

            if (water_depth[x, y] > water_depth_erosion_threshold)
            {
                int p;
                double[] temp_dist;
                temp_dist = new Double[11];

                double rho = 1000.0;
                double gravity = 9.8;
                double tau = 0;

                if (index[x, y] == -9999) addGS(x, y);
                if (slope > 0.01) slope = 0.01; // dubious line.. maybee review..

                double Di = 0.0;


                double U_star=0; 
                double tau_ri = 0.0;
                double Wi_star = 0.0;
                double d_50 = d50(index[x, y]);
                double Fs = sand_fraction(index[x, y]);
                double Qbi = 0;

                Tau[x, y] = 0;
                Tau2[x, y] = 0;

                double temptot2 = 0;
                int lat_dir = 10;
                for (p = 1; p <= 8; p++)
                {
                    if (edge[x, y] - edge[x + deltaX[p], y + deltaY[p]] > temptot2)
                    {
                        temptot2 = edge[x, y] - edge[x + deltaX[p], y + deltaY[p]];
                        lat_dir = p;
                    }

                }

                for (p = 1; p <= 8; p++)
                {

                    tau = 0;
                    double vel;
                    vel = (max_flow[x, y, p] / (DX * water_depth[x, y]));

                    double ci = 9.81 * Math.Pow(calc_manning(x, y), 2) * Math.Pow(water_depth[x, y], -0.33);// calcualting drag coeffiecuent
                    if (ci > 0.04) ci = 0.04;

                    if (vel > 2) vel = 2; // if vel too high cut it

                    tau = 1000 * ci * Math.Pow(vel, 2);


                    if (lat_dir==p&&x > 0 && water_depth[x + deltaX[p], y + deltaY[p]] > water_depth_erosion_threshold && edge[x, y] > edge[x + deltaX[p], y + deltaY[p]])
                    {
                        double tempvel = max_flow[x, y, 0] / (DX * water_depth[x, y]);
                        if (tempvel > 2) tempvel = 2;
                        tau += (50/(DX * 2.13 * Math.Pow(edge2[x, y], -1.08))) * 1000 * ci * Math.Pow(tempvel, 2);//(edge[x, y] - edge[x + deltaX[p], y + deltaY[p]]) * 10;
                        Tau2[x, y] += (50 / (DX * 2.13 * Math.Pow(edge2[x, y], -1.08))) * 1000 * ci * Math.Pow(tempvel, 2); //(edge[x, y] - edge[x + deltaX[p], y + deltaY[p]]) * 10;
                    }


                    //if (water_depth[x + deltaX[p], y + deltaY[p]] > water_depth_erosion_threshold &&
                    //    elev[x + deltaX[p], y + deltaY[p]] < elev[x, y])
                    //{
                    //    tau = water_depth[x, y] * 1000 * 9.8 * (elev[x, y] - elev[x + deltaX[p], y + deltaY[p]]);
                    //}

                    if (tau > 0)
                    {
                        Tau[x, y] += tau;
                    }

                    if(tau<0)tau=0;

                    
          
                    // works out how much should be eroded from the cell according to max slope & depth.
                    if (tau > 0)
                    {
                        
                        for (n = 1; n <= 9; n++)
                        {
                            if (n == 0) Di = d0;
                            if (n == 1) Di = d1;
                            if (n == 2) Di = d2;
                            if (n == 3) Di = d3;
                            if (n == 4) Di = d4;
                            if (n == 5) Di = d5;
                            if (n == 6) Di = d6;
                            if (n == 7) Di = d7;
                            if (n == 8) Di = d8;
                            if (n == 9) Di = d9;

                            // Wilcock and Crowe/Curran

                            if (wilcock == 1)
                            {
                                tau_ri = (0.021 + (0.015 * Math.Exp(-20 * Fs))) * (rho * gravity * d_50) * Math.Pow((Di / d_50), (0.67 / (1 + Math.Exp(1.5 - (Di / d_50)))));
                                U_star = Math.Pow(tau / rho, 0.5);
                                if ((tau / tau_ri) < 1.35)
                                {
                                    Wi_star = 0.002 * Math.Pow(tau / tau_ri, 7.5);

                                }
                                else
                                {
                                    Wi_star = 14 * Math.Pow(1 - (0.894 / Math.Pow(tau / tau_ri, 0.5)), 4.5);
                                }
                                Qbi = ((Fi(index[x, y], n) * Math.Pow(U_star, 3)) / ((2.65 - 1) * gravity)) * Wi_star;
                            }

                            if (einstein == 1)
                            {
                                // changed einstein exponent to 20 instead of 40... 
                                Qbi = (40 * Math.Pow((1 / (((2250 - 1000) * Di) / (tau / 9.8))), 3))
                                    / Math.Sqrt(1000 / ((2250 - 1000) * 9.8 * Math.Pow(Di, 3)));
                            }
                            if (veg[x, y, 1] > 0.5) Qbi = 0;



                            temp_dist[n] = Qbi * time_factor; // not sure if it should have a *DX here..
                            //temp_dist[n] = Qbi * time_factor * DX; // I think it should  MJ 05/02/05
                            // well it isnt!! TJC 05/04/05
                            if (temp_dist[n] < 0.0000000000001) temp_dist[n] = 0;
                            // here where check to see if greater than suspended sediment total in a cell...
                            //

                            if (isSuspended[n])
                            {
                                double Vsuspmax, Csuspmax = 0.05, Vsusptemp, susptemp = 0;
                                Vsuspmax = Csuspmax * (water_depth[x, y] * DX * DX);
                                Vsusptemp = Vsusptot[x, y] + tempsusptot[x, y];
                                if ((Vsusptemp + (temp_dist[n] * DX * DX)) > Vsuspmax)
                                {
                                    //Console.WriteLine(Convert.ToString(Vsusptemp) + Convert.ToString((temp_dist[n] * DX * DX)));
                                    if (Vsusptemp < Vsuspmax)
                                    {
                                        susptemp = (Vsuspmax - Vsusptemp);
                                        if ((susptemp / (DX * DX)) > temp_dist[n]) Console.WriteLine(Convert.ToString(Vsusptemp) + Convert.ToString((temp_dist[n] * DX * DX)));
                                        temp_dist[n] = susptemp / (DX * DX);
                                    }
                                    else
                                    {
                                        temp_dist[n] = 0;
                                    }
                                }
                            }
                        }

                        // here to remove from veg layer..
                        //if ((veg[x, y, 1] > 0) && (tau > vegTauCrit))
                        //{
                        //    temp_dist[0] = time_factor * Math.Pow(tau - vegTauCrit, 1) * 0.00000005;
                        //    // now to remove from veg layer..
                        //    //Console.WriteLine(Convert.ToString(temp_dist[0]));
                        //    veg[x, y, 1] -= temp_dist[0];
                        //    if (veg[x, y, 1] < 0) veg[x, y, 1] = 0;
                        //}


                        // now to determine if movement should be restricted due to veg...
                        //if (veg[x, y, 1] > 0.5)
                        //{
                        //    temptot = 0;
                        //    elevdiff = 0;
                        //    // adds up total of material to be removed.. including calculating how much is there to be moved
                        //    for (n = 1; n <= 9; n++)
                        //    {
                        //        if (grain_tot(index[x, y], n) - temp_dist[n] < 0)
                        //        {
                        //            temp_dist[n] = grain_tot(index[x, y], n);
                        //        }
                        //        temptot += temp_dist[n];

                        //    }
                        //    // now checks if this removed from the cell would put it below the veg layer..
                        //    if (elev[x, y] - temptot <= veg[x, y, 0])
                        //    {
                        //        // now remove from proportion that can be eroded..
                        //        // we can do this as we have the prop (in temptot) that is there to be eroded.
                        //        elevdiff = elev[x, y] - veg[x, y, 0];
                        //        for (n = 1; n <= 9; n++)
                        //        {
                        //            temp_dist[n] = elevdiff * (temp_dist[n] / temptot);
                        //            if (elev[x, y] <= veg[x, y, 0]) temp_dist[n] = 0;
                        //        }
                        //    }

                        //}

                        for (n = 1; n <= 9; n++)
                        {
                            if (p < 8) dist[p + 1, n] += temp_dist[n];
                            if (p == 8) dist[1, n] += temp_dist[n];
                        }
                        temp_dist[10] = 0;
                       
                    }
                }

            }
        }



        void erode_w3(int x, int y, double depth, double slope, double slopesum)
        
        {
            int n;

            if (water_depth[x, y] > water_depth_erosion_threshold)
            {
                int p;
                double[] temp_dist;
                temp_dist = new Double[11];

                double rho = 1000.0;
                double gravity = 9.8;
                double tau = 0;

                if (index[x, y] == -9999) addGS(x, y);
                if (slope > 0.01) slope = 0.01; // dubious line.. maybee review..

                double Di = 0.0;


                double U_star = 0;
                double tau_ri = 0.0;
                double Wi_star = 0.0;
                double d_50 = d50(index[x, y]);
                double Fs = sand_fraction(index[x, y]);
                double Qbi = 0;

                Tau[x, y] = 0;
                Tau2[x, y] = 0;

                double temptot2 = 0;
                double edgetemp=0;
                int lat_dir = 10;
                double vel=0;
                double temptautot = 0;
                double temptaumaxtot = 0;
                int max_tau_dir = 0;

                double ci = 9.81 * Math.Pow(calc_manning(x, y), 2) * Math.Pow(water_depth[x, y], -0.33);// calcualting drag coeffiecuent
                if (ci > 0.04) ci = 0.04;

                for (p = 1; p <= 8; p++)
                {
                    if (edge[x, y] - edge[x + deltaX[p], y + deltaY[p]] > temptot2)
                    {
                        temptot2 = edge[x, y] - edge[x + deltaX[p], y + deltaY[p]];
                        lat_dir = p;
                    }
                    if (water_depth[x + deltaX[p], y + deltaY[p]] < water_depth_erosion_threshold)
                    {
                        if(edge[x + deltaX[p], y + deltaY[p]]>-9999)edgetemp += edge[x + deltaX[p], y + deltaY[p]];
                    }
                    if (max_flow[x, y, p] > 0)
                    {
                        if (vel > 2) vel = 2;
                        vel = (max_flow[x, y, p] / (DX * water_depth[x, y]));
                        temptautot += 1000 * ci * Math.Pow(vel, 2);
                        if (max_flow[x, y, p] > temptaumaxtot)
                        {
                            temptaumaxtot = max_flow[x, y, p];
                            max_tau_dir = p;
                        }
                        
                    }
                    
                }

                for (p = 1; p <= 8; p++)
                {

                    tau = 0;
                    vel=0;
                    vel = (max_flow[x, y, p] / (DX * water_depth[x, y]));

                    //if (edgetemp > 0) vel *= 1.25;
                    //if (edgetemp < 0) vel *= 0.75;

                    //if(edge[x,y]>-9999)vel *= 1 + (edge[x, y] * 10);
                    
                    if (vel > 2) vel = 2; // if vel too high cut it

                    tau = 1000 * ci * Math.Pow(vel, 2);

                    //if (edgetemp > 0) tau *= 1.25;
                    //if (edgetemp < 0) tau *= 0.75;

                    //if (lat_dir == p && x > 0 && water_depth[x + deltaX[p], y + deltaY[p]] > water_depth_erosion_threshold && edge[x, y] > edge[x + deltaX[p], y + deltaY[p]])
                    //{
                    //    tau += temptautot / 4;
                    //}

                    if (lat_dir == p && x > 0 && water_depth[x + deltaX[p], y + deltaY[p]] > water_depth_erosion_threshold && edge[x, y] > edge[x + deltaX[p], y + deltaY[p]])
                    {
                        double tempvel = max_flow[x, y, 0] / (DX * water_depth[x, y]);
                        if (tempvel > 2) tempvel = 2;
                        tau += (50 / (DX * 2.13 * Math.Pow(edge2[x, y], -1.08))) * 1000 * ci * Math.Pow(tempvel, 2);//(edge[x, y] - edge[x + deltaX[p], y + deltaY[p]]) * 10;
                        Tau2[x, y] += (50 / (DX * 2.13 * Math.Pow(edge2[x, y], -1.08))) * 1000 * ci * Math.Pow(tempvel, 2); //(edge[x, y] - edge[x + deltaX[p], y + deltaY[p]]) * 10;
                    }


                    //if (water_depth[x + deltaX[p], y + deltaY[p]] > water_depth_erosion_threshold &&
                    //    elev[x + deltaX[p], y + deltaY[p]] < elev[x, y])
                    //{
                    //    tau = water_depth[x, y] * 1000 * 9.8 * (elev[x, y] - elev[x + deltaX[p], y + deltaY[p]]);
                    //}

                    if (tau > 0)
                    {
                        Tau[x, y] += tau;
                    }

                    if (tau < 0) tau = 0;



                    // works out how much should be eroded from the cell according to max slope & depth.
                    if (tau > 0)
                    {

                        for (n = 1; n <= 9; n++)
                        {
                            if (n == 0) Di = d0;
                            if (n == 1) Di = d1;
                            if (n == 2) Di = d2;
                            if (n == 3) Di = d3;
                            if (n == 4) Di = d4;
                            if (n == 5) Di = d5;
                            if (n == 6) Di = d6;
                            if (n == 7) Di = d7;
                            if (n == 8) Di = d8;
                            if (n == 9) Di = d9;

                            // Wilcock and Crowe/Curran

                            if (wilcock == 1)
                            {
                                tau_ri = (0.021 + (0.015 * Math.Exp(-20 * Fs))) * (rho * gravity * d_50) * Math.Pow((Di / d_50), (0.67 / (1 + Math.Exp(1.5 - (Di / d_50)))));
                                U_star = Math.Pow(tau / rho, 0.5);
                                if ((tau / tau_ri) < 1.35)
                                {
                                    Wi_star = 0.002 * Math.Pow(tau / tau_ri, 7.5);

                                }
                                else
                                {
                                    Wi_star = 14 * Math.Pow(1 - (0.894 / Math.Pow(tau / tau_ri, 0.5)), 4.5);
                                }
                                Qbi = ((Fi(index[x, y], n) * Math.Pow(U_star, 3)) / ((2.65 - 1) * gravity)) * Wi_star;
                            }

                            if (einstein == 1)
                            {
                                // changed einstein exponent to 20 instead of 40... 
                                Qbi = (40 * Math.Pow((1 / (((2250 - 1000) * Di) / (tau / 9.8))), 3))
                                    / Math.Sqrt(1000 / ((2250 - 1000) * 9.8 * Math.Pow(Di, 3)));
                            }
                            if (veg[x, y, 1] > 0.5) Qbi = 0;



                            temp_dist[n] = Qbi * time_factor; // not sure if it should have a *DX here..
                            //temp_dist[n] = Qbi * time_factor * DX; // I think it should  MJ 05/02/05
                            // well it isnt!! TJC 05/04/05
                            if (temp_dist[n] < 0.0000000000001) temp_dist[n] = 0;
                            // here where check to see if greater than suspended sediment total in a cell...
                            //

                            if (isSuspended[n])
                            {
                                double Vsuspmax, Csuspmax = 0.05, Vsusptemp, susptemp = 0;
                                Vsuspmax = Csuspmax * (water_depth[x, y] * DX * DX);
                                Vsusptemp = Vsusptot[x, y] + tempsusptot[x, y];
                                if ((Vsusptemp + (temp_dist[n] * DX * DX)) > Vsuspmax)
                                {
                                    //Console.WriteLine(Convert.ToString(Vsusptemp) + Convert.ToString((temp_dist[n] * DX * DX)));
                                    if (Vsusptemp < Vsuspmax)
                                    {
                                        susptemp = (Vsuspmax - Vsusptemp);
                                        if ((susptemp / (DX * DX)) > temp_dist[n]) Console.WriteLine(Convert.ToString(Vsusptemp) + Convert.ToString((temp_dist[n] * DX * DX)));
                                        temp_dist[n] = susptemp / (DX * DX);
                                    }
                                    else
                                    {
                                        temp_dist[n] = 0;
                                    }
                                }
                            }
                        }

                        // here to remove from veg layer..
                        //if ((veg[x, y, 1] > 0) && (tau > vegTauCrit))
                        //{
                        //    temp_dist[0] = time_factor * Math.Pow(tau - vegTauCrit, 1) * 0.00000005;
                        //    // now to remove from veg layer..
                        //    //Console.WriteLine(Convert.ToString(temp_dist[0]));
                        //    veg[x, y, 1] -= temp_dist[0];
                        //    if (veg[x, y, 1] < 0) veg[x, y, 1] = 0;
                        //}


                        // now to determine if movement should be restricted due to veg...
                        //if (veg[x, y, 1] > 0.5)
                        //{
                        //    temptot = 0;
                        //    elevdiff = 0;
                        //    // adds up total of material to be removed.. including calculating how much is there to be moved
                        //    for (n = 1; n <= 9; n++)
                        //    {
                        //        if (grain_tot(index[x, y], n) - temp_dist[n] < 0)
                        //        {
                        //            temp_dist[n] = grain_tot(index[x, y], n);
                        //        }
                        //        temptot += temp_dist[n];

                        //    }
                        //    // now checks if this removed from the cell would put it below the veg layer..
                        //    if (elev[x, y] - temptot <= veg[x, y, 0])
                        //    {
                        //        // now remove from proportion that can be eroded..
                        //        // we can do this as we have the prop (in temptot) that is there to be eroded.
                        //        elevdiff = elev[x, y] - veg[x, y, 0];
                        //        for (n = 1; n <= 9; n++)
                        //        {
                        //            temp_dist[n] = elevdiff * (temp_dist[n] / temptot);
                        //            if (elev[x, y] <= veg[x, y, 0]) temp_dist[n] = 0;
                        //        }
                        //    }

                        //}

                        for (n = 1; n <= 9; n++)
                        {
                            if (p < 8) dist[p + 1, n] += temp_dist[n];
                            if (p == 8) dist[1, n] += temp_dist[n];
                        }
                        temp_dist[10] = 0;

                    }
                }

            }
        }




		void erode2(int p, double t, double depth, double slope)
		{
			/* here, forme erode, the x,y co-ords of the cell to be eroded from are passed.
			along with the direction to be eroded to, xinc, yinc, as wellas the pow er (t)
			I've set the active layer, as a fixed size, (2*d84) or for this case approx
			50cm. This aslways remains fixed (depth) and if depositing, any excess is moved down,
			if eroding moved up into active layer. updating etc is going to be complex. can assume,
			that as program will only allow 10% of depth eroded, 50cm means 5m deep flow, will probably never
			happen */

			/* this const, muller is Richards def, not other which is 0.4063 */

			double amt0=0;
			double amt1=0;
			double amt2=0;
			double amt3=0;
			double amt4=0;
			double amt5=0;
			double amt6=0;
			double amt7=0;
			double amt8=0;
			double amt9=0;
			double amt10=0;

			double devils_fork0=0;
			double devils_fork1=0;
			double devils_fork2=0;
			double devils_fork3=0;
			double devils_fork4=0;
			double devils_fork5=0;
			double devils_fork6=0;
			double devils_fork7=0;
			double devils_fork8=0;
			double devils_fork9=0;
			double devils_fork10=0;

			double omega0=0;
			double omega1=0;
			double omega2=0;
			double omega3=0;
			double omega4=0;
			double omega5=0;
			double omega6=0;
			double omega7=0;
			double omega8=0;
			double omega9=0;
			double omega10=0;

			/********* using einstein brown 1950 *********/
			/* assuming depth = R */
			/* all taken from steves fluid book */

			devils_fork0=((2250-1000)*d0)/(1000*depth*slope);	
			devils_fork1=((2250-1000)*d1)/(1000*depth*slope);
			devils_fork2=((2250-1000)*d2)/(1000*depth*slope);	
			devils_fork3=((2250-1000)*d3)/(1000*depth*slope);
			devils_fork4=((2250-1000)*d4)/(1000*depth*slope);
			devils_fork5=((2250-1000)*d5)/(1000*depth*slope);
			devils_fork6=((2250-1000)*d6)/(1000*depth*slope);
			devils_fork7=((2250-1000)*d7)/(1000*depth*slope);
			devils_fork8=((2250-1000)*d8)/(1000*depth*slope);
			devils_fork9=((2250-1000)*d9)/(1000*depth*slope);
			devils_fork10=((2250-1000)*d10)/(1000*depth*slope);

			omega0=40*Math.Pow((1/devils_fork0),3);
			omega1=40*Math.Pow((1/devils_fork1),3);
			omega2=40*Math.Pow((1/devils_fork2),3);    
			omega3=40*Math.Pow((1/devils_fork3),3);
			omega4=40*Math.Pow((1/devils_fork4),3);
			omega5=40*Math.Pow((1/devils_fork5),3);
			omega6=40*Math.Pow((1/devils_fork6),3);
			omega7=40*Math.Pow((1/devils_fork7),3);
			omega8=40*Math.Pow((1/devils_fork8),3);
			omega9=40*Math.Pow((1/devils_fork9),3);
			omega10=40*Math.Pow((1/devils_fork10),3);

            

			amt0=omega0/Math.Sqrt(1000/((2250-1000)*9.8*Math.Pow(d0,3)));	
			amt1=omega1/Math.Sqrt(1000/((2250-1000)*9.8*Math.Pow(d1,3)));
			amt2=omega2/Math.Sqrt(1000/((2250-1000)*9.8*Math.Pow(d2,3)));
			amt3=omega3/Math.Sqrt(1000/((2250-1000)*9.8*Math.Pow(d3,3)));
			amt4=omega4/Math.Sqrt(1000/((2250-1000)*9.8*Math.Pow(d4,3)));
			amt5=omega5/Math.Sqrt(1000/((2250-1000)*9.8*Math.Pow(d5,3)));
			amt6=omega6/Math.Sqrt(1000/((2250-1000)*9.8*Math.Pow(d6,3)));
			amt7=omega7/Math.Sqrt(1000/((2250-1000)*9.8*Math.Pow(d7,3)));
			amt8=omega8/Math.Sqrt(1000/((2250-1000)*9.8*Math.Pow(d8,3)));
			amt9=omega9/Math.Sqrt(1000/((2250-1000)*9.8*Math.Pow(d9,3)));
			amt10=omega10/Math.Sqrt(1000/((2250-1000)*9.8*Math.Pow(d10,3)));

			dist[p,0]=amt0*time_factor;
			dist[p,1]=amt1*time_factor;
			dist[p,2]=amt2*time_factor;
			dist[p,3]=amt3*time_factor;
			dist[p,4]=amt4*time_factor;
			dist[p,5]=amt5*time_factor;
			dist[p,6]=amt6*time_factor;
			dist[p,7]=amt7*time_factor;
			dist[p,8]=amt8*time_factor;
			dist[p,9]=amt9*time_factor;
			dist[p,10]=0; /*amt10*time_factor;*/

		} // erode2


		void erode3(int fract, int grid_val, int x,int y)
		{

			int n,temp_centre;
			double tempb=0;
			double tempamt=0;
			double total=0;
			double total2=0;


			if(index[x,y]==-9999)addGS(x,y);
			temp_centre=index[x,y];

	
			for(n=1;n<=8;n++)
			{
				total+=dist[n,fract];
			}

			/******* lines like the next one, are assential to ensure that it adds new eroded sqaures to the list. **/
			if(grain_tot(temp_centre,fract)>0.0001)
			{


				if(index[x,y]==-9999)addGS(x,y);
				
				
      
				if(total>=grain_tot(temp_centre,fract))
				{
					total2=0;
					for(n=1;n<=8;n++)
					{
						dist[n,fract]=dist[n,fract]*(grain_tot(temp_centre,fract)/total)*0.99999;
						total2+=dist[n,fract];
					}
				}
								 
										 
				if(dist[1,fract]>0.0000)
				{
					if(index[x-1,y-1]==-9999)addGS(x-1,y-1);
					erode4(x,y,temp_centre,fract,dist[1,fract],index[x-1,y-1]);
					
				}
				if(dist[2,fract]>0.0000)
				{
					if(index[x,y-1]==-9999)addGS(x,y-1);
					erode4(x,y,temp_centre,fract,dist[2,fract],index[x,y-1]);
				
				}
				if(dist[3,fract]>0.0000)
				{
					if(index[x+1,y-1]==-9999)addGS(x+1,y-1);
					erode4(x,y,temp_centre,fract,dist[3,fract],index[x+1,y-1]);

				}
				if(dist[4,fract]>0.0000)
				{
					if(index[x+1,y]==-9999)addGS(x+1,y);
					erode4(x,y,temp_centre,fract,dist[4,fract],index[x+1,y]);
				}
				if(dist[5,fract]>0.0000)
				{
					if(index[x+1,y+1]==-9999)addGS(x+1,y+1);
					erode4(x,y,temp_centre,fract,dist[5,fract],index[x+1,y+1]);
				}
				if(dist[6,fract]>0.0000)
				{
					if(index[x,y+1]==-9999)addGS(x,y+1);
					erode4(x,y,temp_centre,fract,dist[6,fract],index[x,y+1]);
				}
				if(dist[7,fract]>0.0000)
				{
					if(index[x-1,y+1]==-9999)addGS(x-1,y+1);
					erode4(x,y,temp_centre,fract,dist[7,fract],index[x-1,y+1]);
				}
				if(dist[8,fract]>0.0000)
				{
					if(index[x-1,y]==-9999)addGS(x-1,y);
					erode4(x,y,temp_centre,fract,dist[8,fract],index[x-1,y]);
				}
			
			}

		} // erode3


		void erode4(int x,int y,int cent_from,int fract,double amount,int cent_to)
		{
			int p;
			double total,sub;
			total = 0.0;

			for (p=0; p<=(TRACERS-1); p++)
			{
				total += grain[cent_from,fract,p];
			}

			if (total > 0.0)
			{
				if (isSuspended[fract])
				{
					for (p=0; p<=(TRACERS-1); p++)
					{
						sub = amount*(grain[cent_from,fract,p]/total)/* *0.999999 */;
						temp[cent_from,fract,p] -= sub;
						sub = sub * DX *DX;								
						tempsusp[x,y,fract,p] += sub;					  
						tempsusptot[x,y] += sub;						
					}
				}
				else
				{
					for (p=0; p<=(TRACERS-1); p++)
					{
						sub = amount * (grain[cent_from,fract,p]/total)/* *0.999999 */;
						temp[cent_from,fract,p] -= sub;
						temp[cent_to,fract,p] += sub;
					}
				}
			}
		}


		void slide(int scan)
		{

			double diff,main_crit_ht, crit_ht, wet_crit_ht;
			double slide_tot=0;
			int tot,n, x;
			main_crit_ht=Math.Tan((failureangle*(3.141592654/180)))*DX;
            crit_ht=main_crit_ht;
			wet_crit_ht=crit_ht/2;
			/*  printf("  Landslide module 1!!! \n");*/


			for (scan=1;scan<ymax;scan++)
			{

				x=0;

				do
				{
					tot=0;
					for(n=xmax;n>1;n--)
					{
						if(elev[n,scan]>0&&elev[n-1,scan]>0)
						{
							if(elev[n,scan]<=(bedrock[n,scan]+active))
								crit_ht=10*DX;
							else
								crit_ht=main_crit_ht;

							if((elev[n,scan]-elev[n-1,scan])>crit_ht)
							{
								diff=(elev[n,scan]-elev[n-1,scan])-crit_ht;
								if((elev[n,scan]-diff)<(bedrock[n,scan]+active))diff=(elev[n,scan]-(bedrock[n,scan]+active));
                                if (diff > 0.001) diff = 0.001; // this makes large landslides happen more slowly..
								slide_tot=slide_tot+diff;
								elev[n,scan]=elev[n,scan]-diff;
								elev[n-1,scan]=elev[n-1,scan]+diff;
								if(index[n,scan]!=-9999||index[n-1,scan]!=-9999)slide_GS(n,scan,diff,n-1,scan);
								tot++;
							}
						}
					}

					for(n=2;n<xmax;n++)
					{
						if(elev[n,scan]>0&&elev[n-1,scan]>0)
						{
							if(elev[n-1,scan]<=(bedrock[n-1,scan]+active))
								crit_ht=10*DX;
							else
								crit_ht=main_crit_ht;

							if((elev[n-1,scan]-elev[n,scan])>crit_ht)
							{
								diff=(elev[n-1,scan]-elev[n,scan])-crit_ht;
								if((elev[n-1,scan]-diff)<(bedrock[n-1,scan]+active))diff=(elev[n-1,scan]-(bedrock[n-1,scan]+active));
                                if (diff > 0.001) diff = 0.001; // this makes large landslides happen more slowly..
								slide_tot=slide_tot+diff;
								elev[n-1,scan]=elev[n-1,scan]-diff;
								elev[n,scan]=elev[n,scan]+diff;
								if(index[n,scan]!=-9999||index[n-1,scan]!=-9999)slide_GS(n-1,scan,diff,n,scan);
								tot++;
							}
						}
					}

					x++;
				}while(tot>0&&x<2000);
			}

			for (n=1;n<=xmax;n++)
			{

				x=0;

				do
				{
					tot=0;
					for(scan=ymax-1;scan>1;scan--)
					{
						if(elev[n,scan]>0&&elev[n,scan-1]>0)
						{
							if(elev[n,scan]<=(bedrock[n,scan]+active))
								crit_ht=10*DX;
							else
								crit_ht=main_crit_ht;

							if((elev[n,scan]-elev[n,scan-1])>crit_ht)
							{
								diff=(elev[n,scan]-elev[n,scan-1])-crit_ht;
								if((elev[n,scan]-diff)<(bedrock[n,scan]+active))diff=(elev[n,scan]-(bedrock[n,scan]+active));
                                if (diff > 0.001) diff = 0.001; // this makes large landslides happen more slowly..
								slide_tot=slide_tot+diff;
								elev[n,scan]=elev[n,scan]-diff;
								elev[n,scan-1]=elev[n,scan-1]+diff;
								if(index[n,scan-1]!=-9999||index[n,scan]!=-9999)slide_GS(n,scan,diff,n,scan-1);
								tot++;
							}
						}
					}

					for(scan=2;scan<ymax;scan++)
					{
						if(elev[n,scan]>0&&elev[n,scan-1]>0)
						{
							if(bedrock[n,scan-1]<=(bedrock[n,scan-1]+active))
								crit_ht=10*DX;
							else
								crit_ht=main_crit_ht;

							if((elev[n,scan-1]-elev[n,scan])>crit_ht)
							{
								diff=(elev[n,scan-1]-elev[n,scan])-crit_ht;
								if((elev[n,scan-1]-diff)<(bedrock[n,scan-1]+active))diff=(elev[n,scan-1]-(bedrock[n,scan-1]+active));
                                if (diff > 0.001) diff = 0.001; // this makes large landslides happen more slowly..
								slide_tot=slide_tot+diff;
								elev[n,scan-1]=elev[n,scan-1]-diff;
								elev[n,scan]=elev[n,scan]+diff;
								if(index[n,scan]!=-9999||index[n,scan-1]!=-9999)slide_GS(n,scan-1,diff,n,scan);	      
								tot++;
							}
						}
					}

					x++;
				}while(tot>0&&x<2000);
			}


		}


		void slide_3()
		{
			int x,y,inc;
			double wet_factor;
			double factor=Math.Tan((failureangle*(3.141592654/180)))*DX;
			double diff=0;

			for(y=2;y<ymax;y++)
			{
				inc=1;
				while(down_scan[y,inc]>0)
				{
					x=down_scan[y,inc];
					if(x==xmax)x=xmax-1;
					if(x==1)x=2;

					inc++;	

					water_depth[x,y]=0;
					/** check to see if under water **/
					wet_factor=factor;
					//if(water_depth[x,y]>0.01)wet_factor=factor/2;
					if(elev[x,y]<=(bedrock[x,y]+active))wet_factor=10*DX;

					/** chexk landslides in channel slowly */

					if(((elev[x,y]-elev[x+1,y+1])/1.41)>wet_factor&&elev[x+1,y+1]>0&&water_depth[x+1,y+1]!=-9999)
					{
						diff=((elev[x,y]-elev[x+1,y+1])/1.41)-wet_factor;
						if((elev[x,y]-diff)<(bedrock[x,y]+active))diff=(elev[x,y]-(bedrock[x,y]+active));
						elev[x,y]-=diff;
						elev[x+1,y+1]+=diff;
						slide_GS(x,y,diff,x+1,y+1);
					}
					if((elev[x,y]-elev[x,y+1])>wet_factor&&elev[x,y+1]>0&&water_depth[x,y+1]!=-9999)
					{
						diff=(elev[x,y]-elev[x,y+1])-wet_factor;
						if((elev[x,y]-diff)<(bedrock[x,y]+active))diff=(elev[x,y]-(bedrock[x,y]+active));
						elev[x,y]-=diff;
						elev[x,y+1]+=diff;
						slide_GS(x,y,diff,x,y+1);
					}
					if(((elev[x,y]-elev[x-1,y+1])/1.41)>wet_factor&&elev[x-1,y+1]>0&&water_depth[x-1,y+1]!=-9999)
					{
						diff=((elev[x,y]-elev[x-1,y+1])/1.41)-wet_factor;
						if((elev[x,y]-diff)<(bedrock[x,y]+active))diff=(elev[x,y]-(bedrock[x,y]+active));
						elev[x,y]-=diff;
						elev[x-1,y+1]+=diff;
						slide_GS(x,y,diff,x-1,y+1);
					}
					if((elev[x,y]-elev[x-1,y])>wet_factor&&elev[x-1,y]>0&&water_depth[x-1,y]!=-9999)
					{
						diff=(elev[x,y]-elev[x-1,y])-wet_factor;
						if((elev[x,y]-diff)<(bedrock[x,y]+active))diff=(elev[x,y]-(bedrock[x,y]+active));
						elev[x,y]-=diff;
						elev[x-1,y]+=diff;
						slide_GS(x,y,diff,x-1,y);
					}	

					if(((elev[x,y]-elev[x-1,y-1])/1.41)>wet_factor&&elev[x-1,y-1]>0&&water_depth[x-1,y-1]!=-9999)
					{
						diff=((elev[x,y]-elev[x-1,y-1])/1.41)-wet_factor;
						if((elev[x,y]-diff)<(bedrock[x,y]+active))diff=(elev[x,y]-(bedrock[x,y]+active));
						elev[x,y]-=diff;
						elev[x-1,y-1]+=diff;
						slide_GS(x,y,diff,x-1,y-1);
					}
					if((elev[x,y]-elev[x,y-1])>wet_factor&&elev[x,y-1]>0&&water_depth[x,y-1]!=-9999)
					{
						diff=(elev[x,y]-elev[x,y-1])-wet_factor;
						if((elev[x,y]-diff)<(bedrock[x,y]+active))diff=(elev[x,y]-(bedrock[x,y]+active));
						elev[x,y]-=diff;
						elev[x,y-1]+=diff;
						slide_GS(x,y,diff,x,y-1);
					}
					if(((elev[x,y]-elev[x+1,y-1])/1.41)>wet_factor&&elev[x+1,y-1]>0&&water_depth[x+1,y-1]!=-9999)
					{
						diff=((elev[x,y]-elev[x+1,y-1])/1.41)-wet_factor;
						if((elev[x,y]-diff)<(bedrock[x,y]+active))diff=(elev[x,y]-(bedrock[x,y]+active));
						elev[x,y]-=diff;
						elev[x+1,y-1]+=diff;
						slide_GS(x,y,diff,x+1,y-1);
					}


					/* if(dist[n,fract]<0.000001)dist[n,fract]=0;*/
                    if ((elev[x, y] - elev[x + 1, y]) > wet_factor && elev[x + 1, y] > 0 && water_depth[x + 1, y] != -9999)
                    {
                        diff = (elev[x, y] - elev[x + 1, y]) - wet_factor;
                        if ((elev[x, y] - diff) < (bedrock[x, y] + active)) diff = (elev[x, y] - (bedrock[x, y] + active));
                        elev[x, y] -= diff;
                        elev[x + 1, y] += diff;
                        slide_GS(x, y, diff, x + 1, y);
                    }
			
				}
			}

		}

        void slide_5()
        {
            int x, y, inc=0;
            double wet_factor;
            double factor = Math.Tan((failureangle * (3.141592654 / 180))) * DX;
            double diff = 0;
            double total = 0;

            do
            {
                total = 0;
                inc++;
                for (y = 2; y < ymax; y++)
                {
                    for (x = 2; x < xmax; x++)
                    {

                        wet_factor = factor;
                        //if(water_depth[x,y]>0.01)wet_factor=factor/2;
                        if (elev[x, y] <= (bedrock[x, y] + active)) wet_factor = 10 * DX;

                        /** chexk landslides in channel slowly */

                        if (((elev[x, y] - elev[x + 1, y + 1]) / 1.41) > wet_factor && elev[x + 1, y + 1] > 0)
                        {
                            diff = ((elev[x, y] - elev[x + 1, y + 1]) / 1.41) - wet_factor;
                            if ((elev[x, y] - diff) < (bedrock[x, y] + active)) diff = (elev[x, y] - (bedrock[x, y] + active));
                            elev[x, y] -= diff;
                            elev[x + 1, y + 1] += diff;
                            total += diff;
                        }
                        if ((elev[x, y] - elev[x, y + 1]) > wet_factor && elev[x, y + 1] > 0)
                        {
                            diff = (elev[x, y] - elev[x, y + 1]) - wet_factor;
                            if ((elev[x, y] - diff) < (bedrock[x, y] + active)) diff = (elev[x, y] - (bedrock[x, y] + active));
                            elev[x, y] -= diff;
                            elev[x, y + 1] += diff;
                            total += diff;
                        }
                        if (((elev[x, y] - elev[x - 1, y + 1]) / 1.41) > wet_factor && elev[x - 1, y + 1] > 0)
                        {
                            diff = ((elev[x, y] - elev[x - 1, y + 1]) / 1.41) - wet_factor;
                            if ((elev[x, y] - diff) < (bedrock[x, y] + active)) diff = (elev[x, y] - (bedrock[x, y] + active));
                            elev[x, y] -= diff;
                            elev[x - 1, y + 1] += diff;
                            total += diff;
                        }
                        if ((elev[x, y] - elev[x - 1, y]) > wet_factor && elev[x - 1, y] > 0)
                        {
                            diff = (elev[x, y] - elev[x - 1, y]) - wet_factor;
                            if ((elev[x, y] - diff) < (bedrock[x, y] + active)) diff = (elev[x, y] - (bedrock[x, y] + active));
                            elev[x, y] -= diff;
                            elev[x - 1, y] += diff;
                            total += diff;
                        }

                        if (((elev[x, y] - elev[x - 1, y - 1]) / 1.41) > wet_factor && elev[x - 1, y - 1] > 0)
                        {
                            diff = ((elev[x, y] - elev[x - 1, y - 1]) / 1.41) - wet_factor;
                            if ((elev[x, y] - diff) < (bedrock[x, y] + active)) diff = (elev[x, y] - (bedrock[x, y] + active));
                            elev[x, y] -= diff;
                            elev[x - 1, y - 1] += diff;
                            total += diff;
                        }
                        if ((elev[x, y] - elev[x, y - 1]) > wet_factor && elev[x, y - 1] > 0)
                        {
                            diff = (elev[x, y] - elev[x, y - 1]) - wet_factor;
                            if ((elev[x, y] - diff) < (bedrock[x, y] + active)) diff = (elev[x, y] - (bedrock[x, y] + active));
                            elev[x, y] -= diff;
                            elev[x, y - 1] += diff;
                            total += diff;
                        }
                        if (((elev[x, y] - elev[x + 1, y - 1]) / 1.41) > wet_factor && elev[x + 1, y - 1] > 0)
                        {
                            diff = ((elev[x, y] - elev[x + 1, y - 1]) / 1.41) - wet_factor;
                            if ((elev[x, y] - diff) < (bedrock[x, y] + active)) diff = (elev[x, y] - (bedrock[x, y] + active));
                            elev[x, y] -= diff;
                            elev[x + 1, y - 1] += diff;
                            total += diff;
                        }



                        if ((elev[x, y] - elev[x + 1, y]) > wet_factor && elev[x + 1, y] > 0)
                        {
                            diff = (elev[x, y] - elev[x + 1, y]) - wet_factor;
                            if ((elev[x, y] - diff) < (bedrock[x, y] + active)) diff = (elev[x, y] - (bedrock[x, y] + active));
                            elev[x, y] -= diff;
                            elev[x + 1, y] += diff;
                            total += diff;
                        }

                    }
                }
            } while (total > 0&&inc<200);

        }

        void slide_4(int x, int y) // landslides from sand dunes...
        {
            int inc;
            double wet_factor;
            double factor = Math.Tan((failureangle * (3.141592654 / 180))) * (DX/dune_mult);
            double diff = 0;

            wet_factor = factor;


                if ((((elev2[x, y] + sand2[x, y]) - (elev2[x + 1, y + 1] + sand2[x + 1, y + 1])) / 1.41) > wet_factor && (elev2[x + 1, y + 1] + sand2[x + 1, y + 1]) > 0)
                {
                    diff = (((elev2[x, y] + sand2[x, y]) - (elev2[x + 1, y + 1] + sand2[x + 1, y + 1])) / 1.41) - wet_factor;
                    if (diff > sand2[x, y]) diff = sand2[x, y];
                    //if (((elev2[x, y] + sand2[x, y]) - diff) < (bedrock[x, y] + active)) diff = ((elev2[x, y] + sand2[x, y]) - (bedrock[x, y] + active));
                    sand2[x, y] -= diff;
                    sand2[x + 1, y + 1] += diff;
                }
                if (((elev2[x, y] + sand2[x, y]) - (elev2[x, y + 1] + sand2[x, y + 1])) > wet_factor && (elev2[x, y + 1] + sand2[x, y + 1]) > 0)
                {
                    diff = ((elev2[x, y] + sand2[x, y]) - (elev2[x, y + 1] + sand2[x, y + 1])) - wet_factor;
                    if (diff > sand2[x, y]) diff = sand2[x, y];
                    //if (((elev2[x, y] + sand2[x, y]) - diff) < (bedrock[x, y] + active)) diff = ((elev2[x, y] + sand2[x, y]) - (bedrock[x, y] + active));
                    sand2[x, y] -= diff;
                    sand2[x, y + 1] += diff;
                }
                if ((((elev2[x, y] + sand2[x, y]) - (elev2[x - 1, y + 1] + sand2[x - 1, y + 1])) / 1.41) > wet_factor && (elev2[x - 1, y + 1] + sand2[x - 1, y + 1]) > 0)
                {
                    diff = (((elev2[x, y] + sand2[x, y]) - (elev2[x - 1, y + 1] + sand2[x - 1, y + 1])) / 1.41) - wet_factor;
                    if (diff > sand2[x, y]) diff = sand2[x, y];
                   // if (((elev2[x, y] + sand2[x, y]) - diff) < (bedrock[x, y] + active)) diff = ((elev2[x, y] + sand2[x, y]) - (bedrock[x, y] + active));
                    sand2[x, y] -= diff;
                    sand2[x - 1, y + 1] += diff;
                 }
                if (((elev2[x, y] + sand2[x, y]) - (elev2[x - 1, y] + sand2[x - 1, y])) > wet_factor && (elev2[x - 1, y] + sand2[x - 1, y]) > 0)
                {
                    diff = ((elev2[x, y] + sand2[x, y]) - (elev2[x - 1, y] + sand2[x - 1, y])) - wet_factor;
                    if (diff > sand2[x, y]) diff = sand2[x, y];
                    //if (((elev2[x, y] + sand2[x, y]) - diff) < (bedrock[x, y] + active)) diff = ((elev2[x, y] + sand2[x, y]) - (bedrock[x, y] + active));
                    sand2[x, y] -= diff;
                    sand2[x - 1, y] += diff;
                }

                if ((((elev2[x, y] + sand2[x, y]) - (elev2[x - 1, y - 1] + sand2[x - 1, y - 1])) / 1.41) > wet_factor && (elev2[x - 1, y - 1] + sand2[x - 1, y - 1]) > 0)
                {
                    diff = (((elev2[x, y] + sand2[x, y]) - (elev2[x - 1, y - 1] + sand2[x - 1, y - 1])) / 1.41) - wet_factor;
                    if (diff > sand2[x, y]) diff = sand2[x, y];
                    //if (((elev2[x, y] + sand2[x, y]) - diff) < (bedrock[x, y] + active)) diff = ((elev2[x, y] + sand2[x, y]) - (bedrock[x, y] + active));
                    sand2[x, y] -= diff;
                    sand2[x - 1, y - 1] += diff;
                    

                }
                if (((elev2[x, y] + sand2[x, y]) - (elev2[x, y - 1] + sand2[x, y - 1])) > wet_factor && (elev2[x, y - 1] + sand2[x, y - 1]) > 0)
                {
                    diff = ((elev2[x, y] + sand2[x, y]) - (elev2[x, y - 1] + sand2[x, y - 1])) - wet_factor;
                    if (diff > sand2[x, y]) diff = sand2[x, y];
                    //if (((elev2[x, y] + sand2[x, y]) - diff) < (bedrock[x, y] + active)) diff = ((elev2[x, y] + sand2[x, y]) - (bedrock[x, y] + active));
                    sand2[x, y] -= diff;
                    sand2[x, y - 1] += diff;
                    

                }
                if ((((elev2[x, y] + sand2[x, y]) - (elev2[x + 1, y - 1] + sand2[x + 1, y - 1])) / 1.41) > wet_factor && (elev2[x + 1, y - 1] + sand2[x + 1, y - 1]) > 0)
                {
                    diff = (((elev2[x, y] + sand2[x, y]) - (elev2[x + 1, y - 1] + sand2[x + 1, y - 1])) / 1.41) - wet_factor;
                    if (diff > sand2[x, y]) diff = sand2[x, y];
                    //if (((elev2[x, y] + sand2[x, y]) - diff) < (bedrock[x, y] + active)) diff = ((elev2[x, y] + sand2[x, y]) - (bedrock[x, y] + active));
                    sand2[x, y] -= diff;
                    sand2[x + 1, y - 1] += diff;
                    
                }


                if (((elev2[x, y] + sand2[x, y]) - (elev2[x + 1, y] + sand2[x + 1, y])) > wet_factor && (elev2[x + 1, y] + sand2[x + 1, y]) > 0)
                {
                    diff = ((elev2[x, y] + sand2[x, y]) - (elev2[x + 1, y] + sand2[x + 1, y])) - wet_factor;
                    if (diff > sand2[x, y]) diff = sand2[x, y];
                    //if (((elev2[x, y] + sand2[x, y]) - diff) < (bedrock[x, y] + active)) diff = ((elev2[x, y] + sand2[x, y]) - (bedrock[x, y] + active));
                    sand2[x, y] -= diff;
                    sand2[x + 1, y] += diff;
                    
                }
            

        }


		void slide_GS(int x,int y,double amount,int x2,int y2)
		{

			/** Ok, heres how it works, x and y are ones material moved from,
			  x2 and y2 are ones material moved to...
			  amd amount is the amount shifted. */

			int n,z;
			double total=0;

               // do only for cells where both have grainsize..
	
			if(index[x,y]!=-9999&&index[x2,y2]!=-9999)
			{
				z=0;
				if(amount>active)
				{


					grain[index[x2,y2],1,z]+=(amount-active)*d1prop;
					grain[index[x2,y2],2,z]+=(amount-active)*d2prop;
					grain[index[x2,y2],3,z]+=(amount-active)*d3prop;
					grain[index[x2,y2],4,z]+=(amount-active)*d4prop;
					grain[index[x2,y2],5,z]+=(amount-active)*d5prop;
					grain[index[x2,y2],6,z]+=(amount-active)*d6prop;
					grain[index[x2,y2],7,z]+=(amount-active)*d7prop;
					grain[index[x2,y2],8,z]+=(amount-active)*d8prop;
					grain[index[x2,y2],9,z]+=(amount-active)*d9prop;

					amount=active;
				}
	

				for(n=1;n<=(G_MAX-1);n++)
				{
					if(grain_tot(index[x,y],n)>0.000)total+=grain_tot(index[x,y],n);
				}

				for(n=1;n<=(G_MAX-1);n++)
				{
					for(z=0;z<=(TRACERS-1);z++)
					{
						if(total>0)
						{
							grain[index[x2,y2],n,z]+=amount*(grain[index[x,y],n,z]/total);
							if(grain[index[x,y],n,z]>0.0001)grain[index[x,y],n,z]-=amount*(grain[index[x,y],n,z]/total);
							if(grain[index[x,y],n,z]<0)grain[index[x,y],n,z]=0;
						}
					}
				}

                /* then to set active layer to correct depth before erosion, */
                sort_active(x, y);
                sort_active(x2, y2);
			}

            //now do for cells where only recieving cells have grainsize
            // just adds amount to reviving cells of normal..
            if (index[x, y] == -9999 && index[x2, y2] != -9999)
            {
                z = 0;

                // if lateral erode thing..
                    grain[index[x2, y2], 1, z] += (amount) * d1prop;
                    grain[index[x2, y2], 2, z] += (amount) * d2prop;
                    grain[index[x2, y2], 3, z] += (amount) * d3prop;
                    grain[index[x2, y2], 4, z] += (amount) * d4prop;
                    grain[index[x2, y2], 5, z] += (amount) * d5prop;
                    grain[index[x2, y2], 6, z] += (amount) * d6prop;
                    grain[index[x2, y2], 7, z] += (amount) * d7prop;
                    grain[index[x2, y2], 8, z] += (amount) * d8prop;
                    grain[index[x2, y2], 9, z] += (amount) * d9prop;
                
                /* then to set active layer to correct depth before erosion, */
                sort_active(x2, y2);
            }

            // now for cells whre dontaing cell has grainsize
            if (index[x, y] != -9999 && index[x2, y2] == -9999)
            {
                z = 0;

                addGS(x2, y2); // add grainsize array for recieving cell..

                if (amount > active)
                {

                    grain[index[x2, y2], 1, z] += (amount - active) * d1prop;
                    grain[index[x2, y2], 2, z] += (amount - active) * d2prop;
                    grain[index[x2, y2], 3, z] += (amount - active) * d3prop;
                    grain[index[x2, y2], 4, z] += (amount - active) * d4prop;
                    grain[index[x2, y2], 5, z] += (amount - active) * d5prop;
                    grain[index[x2, y2], 6, z] += (amount - active) * d6prop;
                    grain[index[x2, y2], 7, z] += (amount - active) * d7prop;
                    grain[index[x2, y2], 8, z] += (amount - active) * d8prop;
                    grain[index[x2, y2], 9, z] += (amount - active) * d9prop;

                    amount = active;
                }


                for (n = 1; n <= (G_MAX - 1); n++)
                {
                    if (grain_tot(index[x, y], n) > 0.000) total += grain_tot(index[x, y], n);
                }

                for (n = 1; n <= (G_MAX - 1); n++)
                {
                    for (z = 0; z <= (TRACERS - 1); z++)
                    {
                        if (total > 0)
                        {
                            grain[index[x2, y2], n, z] += amount * (grain[index[x, y], n, z] / total);
                            if (grain[index[x, y], n, z] > 0.0001) grain[index[x, y], n, z] -= amount * (grain[index[x, y], n, z] / total);
                            if (grain[index[x, y], n, z] < 0) grain[index[x, y], n, z] = 0;
                        }
                    }
                }

                /* then to set active layer to correct depth before erosion, */
                sort_active(x, y);
                sort_active(x2, y2);
            }

		}



        void lateral2()
        {

            int x, y, n, inc, dir;
            double[,] edge_temp, edge_temp2, meanwselev;
            int[,] upscale, upscale_edge;

            edge_temp = new Double[xmax + 1, ymax + 1];
            edge_temp2 = new Double[xmax + 1, ymax + 1];
            meanwselev = new Double[xmax + 1, ymax + 1];
            upscale = new int[(xmax + 1) * 2, (ymax + 1) * 2];
            upscale_edge = new int[(xmax + 1) * 2, (ymax + 1) * 2];

            double mft = water_depth_erosion_threshold;//MIN_Q;// max_flow threshold

            double temp;
            //			double[,]tempgs;
            //			tempgs = new double[xmax*ymax*8,5];


            // First remove spurious wet cells.  

            for (x = 1; x <= (xmax); x++)
            {
                inc = 1;

                while (cross_scan[x, inc] > 0)
                {
                    y = cross_scan[x, inc];
                    inc++;

                    meanwselev[x, y] = water_depth[x, y] + elev[x, y];
                    if (water_depth[x,y] > mft)
                    {
                        int tempcounter = 0;
                        for (dir = 1; dir <= 8; dir++)
                        {
                            int x2, y2;
                            x2 = x + deltaX[dir];
                            y2 = y + deltaY[dir];
                            if (water_depth[x2,y2] < mft) tempcounter++;
                        }
                        if (tempcounter > 6) water_depth[x, y] = 0;
                    }
                }
            }

            // first determine which cells are at the edge of the channel

            for (y = 2; y < ymax; y++)
            {

                for (x = 2; x < xmax; x++)
                {



                    edge[x, y] = -9999;

                    if (water_depth[x,y] < mft)
                    {
                        if (water_depth[x, y - 1] > mft ||
                            water_depth[x - 1, y] > mft ||
                            water_depth[x + 1, y] > mft ||
                            water_depth[x, y + 1] > mft)
                        {
                            edge[x, y] = 0;
                        }

                    }
                    if (water_depth[x,y] < mft)
                    {
                        if (water_depth[x, y - 1] > mft &&
                            water_depth[x - 1, y] > mft &&
                            water_depth[x + 1, y] > mft &&
                            water_depth[x, y + 1] > mft)
                        {
                            edge[x, y] = -9999;
                            edge2[x, y] = -9999;
                        }

                    }

                }
            }

            // new upscaling code
            // first determine wet and dry cells on the new grid
            for (x = 1; x <= xmax; x++)
            {
                for (y = 1; y <= ymax; y++)
                {
                    if (water_depth[x,y] < mft)
                    {
                        upscale[(x * 2), (y * 2)] = 0; // if dry
                        upscale[(x * 2), (y * 2) - 1] = 0;
                        upscale[(x * 2) - 1, (y * 2)] = 0;
                        upscale[(x * 2) - 1, (y * 2) - 1] = 0;
                    }
                    if (water_depth[x,y] >= mft)
                    {
                        upscale[(x * 2), (y * 2)] = 1; // if wet
                        upscale[(x * 2), (y * 2) - 1] = 1;
                        upscale[(x * 2) - 1, (y * 2)] = 1;
                        upscale[(x * 2) - 1, (y * 2) - 1] = 1;
                    }

                }
            }

            // now determine edge cells on the new grid..

            for (y = 2; y < ymax * 2; y++)
            {
                for (x = 2; x < xmax * 2; x++)
                {
                    upscale_edge[x, y] = 0;
                    if (upscale[x, y] == 0)
                    {
                        if (upscale[x, y - 1] == 1 ||
                            upscale[x - 1, y] == 1 ||
                            upscale[x + 1, y] == 1 ||
                            upscale[x, y + 1] == 1)
                        {
                            upscale[x, y] = 2;
                        }

                    }

                }
            }

            // now tall up inside and outside on upscaled grid


            for (y = 2; y < ymax * 2; y++)
            {
                for (x = 2; x < xmax * 2; x++)
                {
                    if (upscale[x, y] == 2)
                    {
                        int wetcells = 0;
                        int drycells = 0;
                        int water = 0;
                        int edge_cell_counter = 1;

                        // sum up dry cells and edge cells - 
                        // now manhattan neighbors
                        for (dir = 1; dir <= 7; dir += 2)
                        {
                            int x2, y2;
                            x2 = x + deltaX[dir];
                            y2 = y + deltaY[dir];

                            if (upscale[x2, y2] == 1) wetcells += 1;
                            if (upscale[x2, y2] == 0) drycells += 1;
                            if (upscale[x2, y2] == 2) edge_cell_counter += 1;

                        }

                        if (edge_cell_counter > 3) drycells += edge_cell_counter - 2;
                        //						

                        water = wetcells - drycells;
                        upscale_edge[x, y] = water;

                    }

                }
            }

            // now update normal edge array..

            for (x = 1; x <= xmax; x++)
            {
                for (y = 1; y <= ymax; y++)
                {
                    if (edge[x, y] == 0)
                    {
                        edge[x, y] = (double)(upscale_edge[(x * 2), (y * 2)] +
                        upscale_edge[(x * 2), (y * 2) - 1] +
                        upscale_edge[(x * 2) - 1, (y * 2)] +
                        upscale_edge[(x * 2) - 1, (y * 2) - 1]);
                        if (edge[x, y] > 2) edge[x, y] = 2; // important line to stop too great inside bends...
                        if (edge[x, y] < -2) edge[x, y] = -2;
                        //if (edge[x, y] > 0) edge[x, y] *= 1.1;
                        //edge[31, 32] = 5;
                    }
                }
            }


            //then apply a smoothing filter over the top of this. here its done three times - 


            for (n = 1; n <= double.Parse(avge_smoothbox.Text); n++)
            {
                for (y = 2; y < ymax; y++)
                {

                    inc = 1;
                    while (down_scan[y, inc] > 0)
                    {
                        x = down_scan[y, inc];

                        edge_temp[x, y] = 0;
                        if (x == 1) x++;
                        if (x == xmax) x--;
                        inc++;

                        if (edge[x, y] > -9999)
                        {
                            double mean = 0;
                            double num = 0;
                            double water_flag = 0;


                            // add in cell itself..
                            mean += edge[x, y];
                            num++;


                            for (dir = 1; dir <= 8; dir++)
                            {
                                int x2, y2;
                                x2 = x + deltaX[dir];
                                y2 = y + deltaY[dir];

                                if (water_depth[x2, y2] > mft) water_flag++;

                                if (edge[x2, y2] > -9999 && water_depth[x2, y2] < mft)
                                {

                                    //now to mean manhattan neighbours - only if they share a wet diagonal neighbour
                                    if ((Math.Abs(deltaX[dir]) + Math.Abs(deltaY[dir])) != 2)
                                    {
                                        if (deltaX[dir] == 1 && deltaY[dir] == 0 &&
                                            (water_depth[x + 1, y - 1] > mft ||
                                            water_depth[x + 1, y + 1] > mft))
                                        {
                                            mean += (edge[x + deltaX[dir], y + deltaY[dir]]);
                                            num++;
                                        }
                                        if (deltaX[dir] == 0 && deltaY[dir] == 1 &&
                                            (water_depth[x + 1, y + 1] > mft ||
                                            water_depth[x - 1, y + 1] > mft))
                                        {
                                            mean += (edge[x + deltaX[dir], y + deltaY[dir]]);
                                            num++;
                                        }
                                        if (deltaX[dir] == -1 && deltaY[dir] == 0 &&
                                            (water_depth[x - 1, y - 1] > mft ||
                                            water_depth[x - 1, y + 1] > mft))
                                        {
                                            mean += (edge[x + deltaX[dir], y + deltaY[dir]]);
                                            num++;
                                        }
                                        if (deltaX[dir] == 0 && deltaY[dir] == -1 &&
                                            (water_depth[x - 1, y - 1] > mft ||
                                            water_depth[x + 1, y - 1] > mft))
                                        {
                                            mean += (edge[x + deltaX[dir], y + deltaY[dir]]);
                                            num++;
                                        }
                                        //										mean+=(edge[x2,y2]);
                                        //										num++;
                                    }
                                    //now non manahttan neighbours, with concected by a dry cell checked..
                                    else
                                    {
                                        if (deltaX[dir] == -1 && deltaY[dir] == -1 &&
                                            (water_depth[x, y - 1] < mft ||
                                            water_depth[x - 1, y] < mft))
                                        {
                                            mean += (edge[x + deltaX[dir], y + deltaY[dir]]);
                                            num++;
                                        }
                                        if (deltaX[dir] == 1 && deltaY[dir] == -1 &&
                                            (water_depth[x, y - 1] < mft ||
                                            water_depth[x + 1, y] < mft))
                                        {
                                            mean += (edge[x + deltaX[dir], y + deltaY[dir]]);
                                            num++;
                                        }
                                        if (deltaX[dir] == 1 && deltaY[dir] == 1 &&
                                            (water_depth[x + 1, y] < mft ||
                                            water_depth[x, y + 1] < mft))
                                        {
                                            mean += (edge[x + deltaX[dir], y + deltaY[dir]]);
                                            num++;
                                        }
                                        if (deltaX[dir] == -1 && deltaY[dir] == 1 &&
                                            (water_depth[x, y + 1] < mft ||
                                            water_depth[x - 1, y] < mft))
                                        {
                                            mean += (edge[x + deltaX[dir], y + deltaY[dir]]);
                                            num++;
                                        }
                                    }


                                }


                            }

                            if (mean != 0) edge_temp[x, y] = mean / num;



                            // removes too many cells - islands etc..

                            //if(num>5&&edge[x,y]>0)edge_temp[x,y]=0;
                            //if(num+water_flag>7&&edge[x,y]>0)edge_temp[x,y]=0;

                            // remove edge effects
                            //if (x < 3 || x > (xmax - 2)) edge_temp[x, y] = 0;
                            //if (y < 3 || y > (ymax - 2)) edge_temp[x, y] = 0;

                        }
                    }
                }


                for (y = 2; y < ymax; y++)
                {
                    inc = 1;
                    while (down_scan[y, inc] > 0)
                    {
                        x = down_scan[y, inc];
                        if (x == 1) x++;
                        if (x == xmax) x--;
                        inc++;
                        if (edge[x, y] > -9999)
                        {
                            edge[x, y] = edge_temp[x, y];

                            //if(edge[x,y]<-1)edge[x,y]=-1;
                            //if(edge[x,y]>1)edge[x,y]=1;


                        }

                    }
                }
            }



            // trial line to remove too high inside bends,,
            for (x = 1; x <= xmax; x++)
            {
                for (y = 1; y <= ymax; y++)
                {
                    //if (edge[x, y] > 0) edge[x, y] *= 2;
                    //if (edge[x, y] > -9999) edge[x, y] *= 0.5;
                    if (edge[x, y] > -9999 && edge[x, y] > 0.25) edge[x, y] = 0.25;
                    if (edge[x, y] > -9999 && edge[x, y] < -0.25) edge[x, y] = -0.25;
                    width[x, y] = 0;
                    edge2[x, y] = 0;
                    if (edge[x, y] > -9999) edge2[x, y] = Math.Abs(edge[x, y]);
                    if (water_depth[x, y] >= mft) calc_width(x, y);
                    //if(water_depth[x,y]>0.1)calc_width(x,y);
                }
            }



            //// now smooth across the channel..

            double tempdiff = 0;
            do
            {
                for (y = 2; y < ymax; y++)
                {

                    inc = 1;
                    while (down_scan[y, inc] > 0)
                    {
                        x = down_scan[y, inc];

                        edge_temp[x, y] = 0;
                        edge_temp2[x, y] = 0;
                        if (x == 1) x++;
                        if (x == xmax) x--;
                        inc++;
                        if (water_depth[x, y] > mft && edge[x, y] == -9999) edge[x, y] = 0;

                        if (edge[x, y] > -9999 && water_depth[x, y] > mft)
                        {
                            double mean = 0, mean2 = 0;
                            int num = 0, num2 = 0;
                            mean2 += edge2[x, y]; num2++;
                            for (dir = 1; dir <= 8; dir++)
                            {
                                int x2, y2;
                                x2 = x + deltaX[dir];
                                y2 = y + deltaY[dir];

                                if (water_depth[x2, y2] > mft && edge[x2, y2] == -9999) edge[x2, y2] = 0;

                                if (edge[x2, y2] > -9999)
                                {

                                    mean += (edge[x2, y2]);
                                    num++;

                                    mean2 += Math.Abs(edge2[x2, y2]);
                                    num2++;
                                }
                            }
                            edge_temp[x, y] = mean / num;
                            edge_temp2[x, y] = mean2 / num2;
                        }
                    }
                }


                tempdiff = 0;
                for (y = 2; y < ymax; y++)
                {
                    inc = 1;
                    while (down_scan[y, inc] > 0)
                    {
                        x = down_scan[y, inc];
                        if (x == 1) x++;
                        if (x == xmax) x--;
                        inc++;
                        if (edge[x, y] > -9999 && water_depth[x, y] > mft)
                        {
                            if (Math.Abs(edge[x, y] - edge_temp[x, y]) > tempdiff) tempdiff = Math.Abs(edge[x, y] - edge_temp[x, y]);
                            edge[x, y] = edge_temp[x, y];
                            edge2[x, y] = edge_temp2[x, y];

                        }

                    }
                }
            } while (tempdiff > 0.0001); //this makes it loop until the averaging across the stream stabilises
            // so that the difference between the old and new values are < 0.0001




            for (x = 1; x <= xmax; x++)
            {
                for (y = 1; y <= ymax; y++)
                {
                    tempcreep[x, y] = 0;
                    if (edge[x, y] > -9999) edge[x, y] = 0 - edge[x, y];
                    if (edge[x, y] > -9999 && edge[x, y] > 0.1) edge[x, y] = 0.1;
                    if (edge[x, y] > -9999 && edge[x, y] < -0.1) edge[x, y] = -0.1;
                    //if (edge[x, y] > -9999 && (x < 3 || x > (xmax - 3))) edge[x, y] = 0;
                }
            }
 

            // now do actual lateral eroding... - remember that tau is now edge2 * tau.. and shifted downstream... 
            n = 0;
            for (x = 2; x < xmax; x++)
            {
                for (y = 2; y < ymax; y++)
                {
                    if (edge[x, y] > -9999)
                    {
                        for (dir = 1; dir <= 8; dir+=1)//was 1 to 8 +=2
                        {
                            int x2, y2;
                            x2 = x + deltaX[dir];
                            y2 = y + deltaY[dir];
                            temp = 0;
                            double temp3 = 0;
                            if (x2 >= xmax) x2--;

                            if (edge[x2, y2] > -9999)
                            {

                                if (water_depth[x,y] < mft
                                    && water_depth[x2,y2] > mft
                                    && elev[x, y] > 0
                                    && elev[x, y] > elev[x2, y2]
                                    && veg[x2, y2, 1]<0.5) // this last line is to stop lateral erosion from vegetated onto vegetati
                                {

                                    if(edge[x,y]>-0.01)
                                    {
                                        //temp3 = 0;
                                        //if(index[x2,y2]!=-9999)for (n = 1; n <= G_MAX; n++) temp3 += temp_tot(index[x2, y2], n);
                                        //if (temp3 < 0) temp3 = 0;
                                        
                                        if (latbox1.Checked == true && max_flow[x2, y2,0] > 0)
                                        {
                                            double temptau = max_flow[x2,y2,0]/(DX*water_depth[x2,y2]);
                                            //if (temptau > 20) temptau = 20;
                                            double tempedge = edge[x2, y2];
                                            //if(tempedge>0.05)tempedge=0.05;
                                            
                                            //temp = edge2[x2, y2] * temptau * 0.1 * time_factor * lateral_constant*water_depth[x2,y2];// *(max_flow[x2, y2, 0] / (DX * water_depth2[x2, y2])) * water_depth[x2, y2];
                                            temp = tempedge * temptau * 0.1 * time_factor * lateral_constant * water_depth[x2, y2];// *(max_flow[x2, y2, 0] / (DX * water_depth2[x2, y2])) * water_depth[x2, y2];
                                            //temp = temp3 * tempedge * temptau * time_factor * lateral_constant * water_depth[x2, y2];
                                            // interesting, depends on whether or not you use the edge2 or edge function
                                            // is edge2 a better representation as it includes some of the fuzzines created
                                            // in effect introducing some of the effects of width??
                                            //Console.WriteLine(temp);
                                        }

                                        if (latbox2.Checked == true && max_flow[x2, y2, 0] > 0)
                                        {
                                            double tempvel = max_flow[x2, y2, 0] / (DX * water_depth[x2, y2]);
                                            double tempedge = (1 / (DX * 2.13 * Math.Pow(edge2[x, y], -1.08)));
                                            temp = tempedge * tempvel * 0.1 * time_factor * lateral_constant * water_depth[x2, y2];// *(max_flow[x2, y2, 0] / (DX * water_depth2[x2, y2])) * water_depth[x2, y2];                                           
                                            
                                        }



                                    }
                                   

                                }

                                if (temp > 0)// needed to ensure that it doesnt do temp and add gs things if no lat erosion/dep
                                {
                                    temp = temp / DX; // imporant scaling term, links temp to grid cell size - as temp change here is lateral rate..
                                    if (Math.IEEERemainder(dir, 2) == 0) temp = temp / 2;
                                    //
                                    // next line stops it laterlaly erodiing ffrom bedrock..
                                    if ((elev[x, y] - temp) <= bedrock[x, y]) temp = 0;

                                    // next line to stop too much being eroded or deposited...
                                    if(temp>ERODEFACTOR/2)temp=ERODEFACTOR/2;
                       
                                    if (index[x, y] == -9999) addGS(x, y);
                                    tempcreep[x, y] -= temp;
                                    tempcreep[x2, y2] += temp*double.Parse(propremaining.Text);
                                    slide_GS(x, y, temp, x2, y2);

                                }
                            }

                        }
                    }
                }
            }

            for (x = 1; x <= xmax; x++)
            {
                for (y = 1; y <= ymax; y++)
                {
                    elev[x, y] += tempcreep[x, y];

                    flow_dir[x, y, 0] = 0;
                    flow_dir[x, y, 1] = 0;
                    for (n = 0; n <= 8; n++)
                    {
                        max_flow[x, y, n] = 0;
                    }
                    old_water_depth[x, y] = water_depth[x, y];
                    if (water_depth[x, y] > 0) water_depth[x, y] = 0;
                    qcounter[x, y] = 0;

                    if (discharge[x, y] < 0) discharge[x, y] = 0;
                    lat_vol[x, y] = discharge[x, y];//
                    left_in[x, y] = 0;
                    left_out[x, y] = 0;
                    right_in[x, y] = 0;
                    right_out[x, y] = 0;
                    up_in[x, y] = 0;
                    up_out[x, y] = 0;
                    down_in[x, y] = 0;
                    down_out[x, y] = 0;
                    //Tau[x, y] = 0;
                    flowout[x, y] = 0;
                    flowin[x, y] = 0;
                    //discharge[x,y]*=0.99;
                    //max_left[x,y]=discharge[x,y];
                    //discharge[x,y]/=1.002;

                    //if(discharge[x,y]>0)Console.WriteLine(Convert.ToString(discharge[x,y]));

                    // this line also reduces part of the remaining Qw - a kind of evaporation
                    // else you can end up with trapped bodies of water..

                    // altered by MJ 15/03/05 - parameterized evaporation
                    if ((k_evap > 0.0) && (discharge[x, y] > 0.0))
                    {
                        discharge[x, y] -= time_factor * k_evap * (DX * DX);
                        if (discharge[x, y] < 0.0) discharge[x, y] = 0.0;
                    }

                }
            }

        }





        void no_lateral()
        {
            int x, y, inc,n;

            for (y = ymax; y >= 1; y--)
            {
                inc = 1;
                while (down_scan[y, inc] > 0)
                {
                    x = down_scan[y, inc];
                    inc++;

                    flow_dir[x, y, 0] = 0;
                    flow_dir[x, y, 1] = 0;
                    for (n = 0; n <= 8; n++)
                    {
                        max_flow[x, y, n] = 0;
                    }
                    old_water_depth[x, y] = water_depth[x, y];
                    if (water_depth[x, y] > 0) water_depth[x, y] = 0;
                    qcounter[x, y] = 0;
                    lat_vol[x, y] = discharge[x, y];
                    left_in[x, y] = 0;
                    left_out[x, y] = 0;
                    right_in[x, y] = 0;
                    right_out[x, y] = 0;
                    up_in[x, y] = 0;
                    up_out[x, y] = 0;
                    down_in[x, y] = 0;
                    down_out[x, y] = 0;
                    //Tau[x, y] = 0;

                    flowout[x, y] = 0;
                    flowin[x, y] = 0;
                    // this line also reduces part of the remaining Qw - a kind of evaporation
                    // else you can end up with trapped bodies of water..

                    // altered by MJ 15/03/05 - parameterized evaporation
                    if ((k_evap > 0.0) && (discharge[x, y] > 0.0))
                    {
                        discharge[x, y] -= time_factor * k_evap * (DX * DX);
                        if (discharge[x, y] < 0.0) discharge[x, y] = 0.0;
                    }

                }
            }
        }


		private void Form1_Load(object sender, System.EventArgs e)
		{

            zoomPanImageBox1.Height = this.Height - 225;
            zoomPanImageBox1.Width = this.Width - 20;
            //googleToggle();

			HttpWebRequest req;
			HttpWebResponse res;
			try
			{
				req = (HttpWebRequest) WebRequest.Create("http://www.coulthard.org.uk/");
				res = (HttpWebResponse) req.GetResponse();
			} 
			catch(Exception ex)
			{
				/// do nothing.
			}

			//JMW <20040929 -start>
			this.Text = basetext;
			//DoingGraphics = false;
			//JMW <20040929 - end>

		}


		void button1_Click(object sender, System.EventArgs e)
		{
            //close google earth animation kml and make kmz
            if (googleAnimationCheckbox.Checked == true)
            {
                StreamWriter kmlsr = File.AppendText(KML_FILE_NAME);
                kml = "\n</Folder>"
                      + "\n</kml>";
                kmlsr.WriteLine(kml);
                kmlsr.Close();
            }
			save_data(1,9999);
            if (menuItem25.Checked == true) save_data(1, 0); // save waterdepths
            if (menuItem13.Checked == true) save_data(2, 0); // save elevdiff
            if (menuItem12.Checked == true) save_data(3, 0); // save elevations
            if (menuItem14.Checked == true) save_data(4, 0); // save grainsize
            if (menuItem15.Checked == true) save_data(5, 0); // save tracer grainsizes
            if (menuItem16.Checked == true) save_data(6, 0); // save tracer surface
            if (menuItem17.Checked == true) save_data(7, 0); // save tracer 2
            if (menuItem18.Checked == true) save_data(8, 0); // save tracer 3
            if (menuItem19.Checked == true) save_data(9, 0); // save tracer 4
            if (menuItem20.Checked == true) save_data(10, 0); // save tracer 5
            if (menuItem21.Checked == true) save_data(11, 0); // save tracer 6 
            if (menuItem22.Checked == true) save_data(12, 0); // save tracer 7
            if (menuItem23.Checked == true) save_data(13, 0); // save tracer 8 
            if (menuItem24.Checked == true) save_data(14, 0); // save tracer 9
            if (menuItem29.Checked == true) save_data(15, 0); // save d50 top layer
            if (menuItem33.Checked == true) save_data(16, 0); // save velocity	<JOE 20050605>
            if (menuItem34.Checked == true) save_data(17, 0); // save soil_saturation	<JOE 20050605>

			try
			{
				if (checkBoxGenerateAVIFile.Checked)
					aw.Close();  //JMW 20041109
			}
			catch(Exception ex)
			{
				/// do nothing.
			}

			this.Close();			
		}


		private void button2_Click(object sender, System.EventArgs e)
		{
            int ok;
            ok = read_header();

            if (ok == 1)
            {
                initialise();
                zero_values();
                load_data();

                // nActualGridSize 
                // moved from initialse() to here MJ 29/03/05 
                int x, y;
                nActualGridCells = 0;
                for (x = 1; x <= xmax; x++)
                {
                    for (y = 1; y <= ymax; y++)
                    {
                        if (elev[x, y] > -999) nActualGridCells++;
                    }
                }

                tabControl1.Visible = false;
                checkBox1.Checked = false;
                zoomPanImageBox1.Visible = true;// MJ 14/01/05
                Panel1.Visible = true;						// MJ 14/01/05
                button2.Enabled = false;					// MJ 17/01/05
                start_button.Enabled = true;				// MJ 17/01/05  
                groupBox2.Visible = true;
                groupBox3.Visible = true;
            }
		}


		private void textBox2_TextChanged(object sender, System.EventArgs e)
		{
		
		}


		private void contextMenu1_Popup(object sender, System.EventArgs e)
		{
		
		}

        private void popComboBox1()
        {
            if (comboBox1.Items.Count == 1)
            {
                comboBox1.Text = "water depth";
                comboBox1.Text = "erosion/dep";
                comboBox1.Text = "Bed sheer stress";
                comboBox1.Text = "grainsize";
                comboBox1.Text = "tracer";
                comboBox1.Text = "susp conc";
                comboBox1.Text = "susp vol";
                comboBox1.Text = "flow velocity";
            }
        }
		private void menuItem3_Click(object sender, System.EventArgs e)
		{
			menuItem3.Checked=(!menuItem3.Checked);
            if (menuItem3.Checked == true)
            {
                comboBox1.Items.Add("water depth");
            }
            else
            {
                comboBox1.Items.Remove("water depth");
            }
            popComboBox1();
            updateClick = 1;
            this.Refresh();
            drawwater(mygraphics);

		}


		private void menuItem4_Click(object sender, System.EventArgs e)
		{
			menuItem4.Checked=(!menuItem4.Checked);
            if (menuItem4.Checked == true)
            {
                comboBox1.Items.Add("erosion/dep");
            }
            else
            {
                comboBox1.Items.Remove("erosion/dep");
            }
            popComboBox1();
            updateClick = 1;
            this.Refresh();
            drawwater(mygraphics);
		}


		private void menuItem5_Click(object sender, System.EventArgs e)
		{
			menuItem5.Checked=(!menuItem5.Checked);
            updateClick = 1;
            this.Refresh();
            drawwater(mygraphics);
		}


		private void menuItem6_Click(object sender, System.EventArgs e)
		{
			menuItem6.Checked=(!menuItem6.Checked);
            updateClick = 1;
            this.Refresh();
            drawwater(mygraphics);
		}


		private void menuItem7_Click(object sender, System.EventArgs e)
		{
			menuItem7.Checked=(!menuItem7.Checked);
            updateClick = 1;
            this.Refresh();
            drawwater(mygraphics);
		}


		private void menuItem8_Click(object sender, System.EventArgs e)
		{
			menuItem8.Checked=(!menuItem8.Checked);
            if (menuItem8.Checked == true)
            {
                comboBox1.Items.Add("Bed sheer stress");
            }
            else
            {
                comboBox1.Items.Remove("Bed sheer stress");
            }
            popComboBox1();
            updateClick = 1;
            this.Refresh();
            drawwater(mygraphics);
		}


		private void menuItem9_Click(object sender, System.EventArgs e)
		{
			menuItem9.Checked=(!menuItem9.Checked);
            if (menuItem9.Checked == true)
            {
                comboBox1.Items.Add("grainsize");
            }
            else
            {
                comboBox1.Items.Remove("grainsize");
            }
            popComboBox1();
            updateClick = 1;
            this.Refresh();
            drawwater(mygraphics);
		}


		private void menuItem10_Click(object sender, System.EventArgs e)
		{
			menuItem10.Checked=(!menuItem10.Checked);
            if (menuItem10.Checked == true)
            {
                comboBox1.Items.Add("tracer");
            }
            else
            {
                comboBox1.Items.Remove("tracer");
            }
            popComboBox1();
            updateClick = 1;
            this.Refresh();
            drawwater(mygraphics);
		}


		private void menuItem19_Click(object sender, System.EventArgs e)
		{
			menuItem19.Checked=(!menuItem19.Checked);
		}


		private void menuItem12_Click(object sender, System.EventArgs e)
		{
			menuItem12.Checked=(!menuItem12.Checked);
		}


		private void menuItem13_Click(object sender, System.EventArgs e)
		{
			menuItem13.Checked=(!menuItem13.Checked);
		}


		private void menuItem14_Click(object sender, System.EventArgs e)
		{
			menuItem14.Checked=(!menuItem14.Checked);
		}


		private void menuItem15_Click(object sender, System.EventArgs e)
		{
			menuItem15.Checked=(!menuItem15.Checked);
		}


		private void menuItem16_Click(object sender, System.EventArgs e)
		{
			menuItem16.Checked=(!menuItem16.Checked);
		}


		private void menuItem17_Click(object sender, System.EventArgs e)
		{
			menuItem17.Checked=(!menuItem17.Checked);
		}


		private void menuItem18_Click(object sender, System.EventArgs e)
		{
			menuItem18.Checked=(!menuItem18.Checked);
		}


		private void menuItem20_Click(object sender, System.EventArgs e)
		{
			menuItem20.Checked=(!menuItem20.Checked);
		}


		private void menuItem21_Click(object sender, System.EventArgs e)
		{
			menuItem21.Checked=(!menuItem21.Checked);
		}


		private void menuItem22_Click(object sender, System.EventArgs e)
		{
			menuItem22.Checked=(!menuItem22.Checked);
		}


		private void menuItem23_Click(object sender, System.EventArgs e)
		{
			menuItem23.Checked=(!menuItem23.Checked);
		}


		private void menuItem24_Click(object sender, System.EventArgs e)
		{
			menuItem24.Checked=(!menuItem24.Checked);
		}

		private void menuItem25_Click(object sender, System.EventArgs e)
		{
			menuItem25.Checked=(!menuItem25.Checked);
		}


		private void menuItem26_Click(object sender, System.EventArgs e)
		{
			menuItem26.Checked=(!menuItem26.Checked);
            updateClick = 1;
            this.Refresh();
            drawwater(mygraphics);
		}

		private void menuItem27_Click(object sender, System.EventArgs e)
		{
			menuItem27.Checked=(!menuItem27.Checked);
            if (menuItem27.Checked == true)
            {
                comboBox1.Items.Add("susp conc");
            }
            else
            {
                comboBox1.Items.Remove("susp conc");
            }
            popComboBox1();
            updateClick = 1;
            this.Refresh();
            drawwater(mygraphics);
		}

		private void menuItem28_Click(object sender, System.EventArgs e)
		{
			menuItem28.Checked=(!menuItem28.Checked);
            if (menuItem28.Checked == true)
            {
                comboBox1.Items.Add("susp vol");
            }
            else
            {
                comboBox1.Items.Remove("susp vol");
            }
            popComboBox1();
            updateClick = 1;
            this.Refresh();
            drawwater(mygraphics);
        }


		private void menuItem29_Click(object sender, System.EventArgs e)
		{
			menuItem29.Checked=(!menuItem29.Checked);	
		}

		private void menuItem30_Click(object sender, System.EventArgs e)
		{
			menuItem30.Checked=(!menuItem30.Checked);
            updateClick = 1;
            this.Refresh();
            drawwater(mygraphics);
		}

		private void menuItem31_Click(object sender, System.EventArgs e)
		{
			menuItem31.Checked=(!menuItem31.Checked);
            if (menuItem31.Checked == true)
            {
                comboBox1.Items.Add("flow velocity");
            }
            else
            {
                comboBox1.Items.Remove("flow velocity");
            }
            updateClick = 1;
            this.Refresh();
            drawwater(mygraphics);
		}

		private void menuItem32_Click(object sender, System.EventArgs e)
		{
			menuItem32.Checked=(!menuItem32.Checked);
            updateClick = 1;
            this.Refresh();
            drawwater(mygraphics);
		}

		private void menuItem33_Click(object sender, System.EventArgs e)
		{
			menuItem33.Checked=(!menuItem33.Checked);	
		}

		private void menuItem34_Click(object sender, System.EventArgs e)
		{
			menuItem34.Checked=(!menuItem34.Checked);	
		}

		private void button3_Click(object sender, System.EventArgs e)
		{
			grow_grass(1);
		}

		private void menuItemConfigFileOpen_Click(object sender, System.EventArgs e)
		{
			XmlTextReader xreader;
			String dum;

			OpenFileDialog openFileDialog1 = new OpenFileDialog();

			openFileDialog1.InitialDirectory = workdir ;
			openFileDialog1.Filter = "cfg files (*.xml)|*.xml|All files (*.*)|*.*" ;
			openFileDialog1.FilterIndex = 1 ;
			openFileDialog1.RestoreDirectory = false ;

			if(openFileDialog1.ShowDialog() == DialogResult.OK)
			{
				cfgname = openFileDialog1.FileName;

				xreader = new XmlTextReader(cfgname);

				//Read the file
				if (xreader != null) 				
				{
					xreader.ReadStartElement("Parms");
					xreader.ReadStartElement("General-Parms");
					try
					{
						overrideheaderBox.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("headeroverride"));
					}
					catch
					{};
					xtextbox.Text = xreader.ReadElementString("x-coordinate");
					ytextbox.Text = xreader.ReadElementString("y-coordinate");
					initscansbox.Text = xreader.ReadElementString("initscans");
					erodefactorbox.Text = xreader.ReadElementString("maxerodelimit");
					dxbox.Text = xreader.ReadElementString("cellsize");
					limitbox.Text = xreader.ReadElementString("memorylimit");
					minqbox.Text = xreader.ReadElementString("minq");
					creepratebox.Text = xreader.ReadElementString("creeprate");
					lateralratebox.Text = xreader.ReadElementString("lateralerosionrate");
					itermaxbox.Text = xreader.ReadElementString("maxiter");
					textBox1.Text = xreader.ReadElementString("runstarttime");
					cyclemaxbox.Text = xreader.ReadElementString("maxrunduration");
					slopebox.Text = xreader.ReadElementString("slopefailurethreshold");
					smoothbox.Text = xreader.ReadElementString("wssmoothingradius");
					mvaluebox.Text = xreader.ReadElementString("mvalue");

					grasstextbox.Text = xreader.ReadElementString("growgrasstime");
					textBox2.Text = xreader.ReadElementString("initialq");
					checkBox3.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("wssmoothing"));
					grassbox.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("grass-sediment"));

					try // MJ 24/01/05
					{
						textBox3.Text = xreader.ReadElementString("flowdistribution");
						mintimestepbox.Text = xreader.ReadElementString("mintimestep");
					}
					catch
					{};

					try // MJ 15/03/05
					{
						k_evapBox.Text = xreader.ReadElementString("evaporation");
					}
					catch
					{};

					try // MJ 10/05/05
					{
						vegTauCritBox.Text = xreader.ReadElementString("vegcritshear");
					}
					catch
					{};

					try 
					{
						bedslope_box.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("bedslope"));
					}
					catch
					{};
					try 
					{
						bool dum_bool = XmlConvert.ToBoolean(xreader.ReadElementString("wsslope"));
					}
					catch
					{};
                    try
                    {
                        veltaubox.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("veltaubox"));
                    }
                    catch
                    { };
                    try 
					{
						catchment_mode_box.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("catchment_mode"));
					}
					catch
					{};
					try 
					{
						reach_mode_box.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("reach_mode"));
					}
					catch
					{};
					try 
					{
						latbox1.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("lat1"));
					}
					catch
					{};
					try 
					{
						latbox2.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("lat2"));
					}
					catch
					{};
					try 
					{
						bool dum_bool = XmlConvert.ToBoolean(xreader.ReadElementString("lat3"));
					}
					catch
					{};
					try 
					{
						string dum_string = xreader.ReadElementString("cross_stream_grad");
					}
					catch
					{};
					xreader.ReadStartElement("SaveOptions");
					dum = xreader.ReadElementString("Option");
					menuItem12.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("Checked"));
					xreader.ReadEndElement();
					xreader.ReadStartElement("SaveOptions");
					dum = xreader.ReadElementString("Option");
					menuItem13.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("Checked"));
					xreader.ReadEndElement();
					xreader.ReadStartElement("SaveOptions");
					dum = xreader.ReadElementString("Option");
					menuItem14.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("Checked"));
					xreader.ReadEndElement();
					xreader.ReadStartElement("SaveOptions");
					dum = xreader.ReadElementString("Option");
					menuItem15.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("Checked"));
					xreader.ReadEndElement();				    
					xreader.ReadStartElement("SaveOptions");
					dum = xreader.ReadElementString("Option");
					menuItem16.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("Checked"));
					xreader.ReadEndElement();				    
					xreader.ReadStartElement("SaveOptions");
					dum = xreader.ReadElementString("Option");
					menuItem17.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("Checked"));
					xreader.ReadEndElement();				    
					xreader.ReadStartElement("SaveOptions");
					dum = xreader.ReadElementString("Option");
					menuItem18.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("Checked"));
					xreader.ReadEndElement();				    
					xreader.ReadStartElement("SaveOptions");
					dum = xreader.ReadElementString("Option");
					menuItem19.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("Checked"));
					xreader.ReadEndElement();				    
					xreader.ReadStartElement("SaveOptions");
					dum = xreader.ReadElementString("Option");
					menuItem20.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("Checked"));
					xreader.ReadEndElement();				    
					xreader.ReadStartElement("SaveOptions");
					dum = xreader.ReadElementString("Option");
					menuItem21.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("Checked"));
					xreader.ReadEndElement();				    
					xreader.ReadStartElement("SaveOptions");
					dum = xreader.ReadElementString("Option");
					menuItem22.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("Checked"));
					xreader.ReadEndElement();				    
					xreader.ReadStartElement("SaveOptions");
					dum = xreader.ReadElementString("Option");
					menuItem23.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("Checked"));
					xreader.ReadEndElement();				   
					xreader.ReadStartElement("SaveOptions");
					dum = xreader.ReadElementString("Option");
					menuItem24.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("Checked"));
					xreader.ReadEndElement();				    
					xreader.ReadStartElement("SaveOptions");
					dum = xreader.ReadElementString("Option");
					menuItem25.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("Checked"));
					xreader.ReadEndElement();				   
					try
					{
						xreader.ReadStartElement("SaveOptions");
						dum = xreader.ReadElementString("Option");
						menuItem29.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("Checked"));
					xreader.ReadEndElement();
						xreader.ReadStartElement("SaveOptions");
						dum = xreader.ReadElementString("Option");
						menuItem33.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("Checked"));
						xreader.ReadEndElement();				    
						xreader.ReadStartElement("SaveOptions");
						dum = xreader.ReadElementString("Option");
						menuItem34.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("Checked"));
						xreader.ReadEndElement();				    
					}
					catch
					{};
					xreader.ReadEndElement();
				
					xreader.ReadStartElement("Grain-Size");
					g1box.Text = xreader.ReadElementString("gs");
					gp1box.Text = xreader.ReadElementString("gp");
					try
					{
						suspGS1box.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("ss"));
						fallGS1box.Text = xreader.ReadElementString("fv");
					}
					catch
					{};
					xreader.ReadEndElement();

					xreader.ReadStartElement("Grain-Size");
					g2box.Text = xreader.ReadElementString("gs");
					gp2box.Text = xreader.ReadElementString("gp");
					try
					{
						suspGS2box.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("ss"));
						fallGS2box.Text = xreader.ReadElementString("fv");
					}
					catch
					{};
					xreader.ReadEndElement();

					xreader.ReadStartElement("Grain-Size");
					g3box.Text = xreader.ReadElementString("gs");
					gp3box.Text = xreader.ReadElementString("gp");
					try
					{
						suspGS3box.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("ss"));
						fallGS3box.Text = xreader.ReadElementString("fv");
					}
					catch
					{};
					xreader.ReadEndElement();

					xreader.ReadStartElement("Grain-Size");
					g4box.Text = xreader.ReadElementString("gs");
					gp4box.Text = xreader.ReadElementString("gp");
					try
					{
						suspGS4box.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("ss"));
						fallGS4box.Text = xreader.ReadElementString("fv");
					}
					catch
					{};
					xreader.ReadEndElement();

					xreader.ReadStartElement("Grain-Size");
					g5box.Text = xreader.ReadElementString("gs");
					gp5box.Text = xreader.ReadElementString("gp");
					try
					{
						suspGS5box.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("ss"));
						fallGS5box.Text = xreader.ReadElementString("fv");
					}
					catch
					{};
					xreader.ReadEndElement();

					xreader.ReadStartElement("Grain-Size");
					g6box.Text = xreader.ReadElementString("gs");
					gp6box.Text = xreader.ReadElementString("gp");
					try
					{
						suspGS6box.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("ss"));
						fallGS6box.Text = xreader.ReadElementString("fv");
					}
					catch
					{};
					xreader.ReadEndElement();

					xreader.ReadStartElement("Grain-Size");
					g7box.Text = xreader.ReadElementString("gs");
					gp7box.Text = xreader.ReadElementString("gp");
					try
					{
						suspGS7box.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("ss"));
						fallGS7box.Text = xreader.ReadElementString("fv");
					}
					catch
					{};
					xreader.ReadEndElement();

					xreader.ReadStartElement("Grain-Size");
					g8box.Text = xreader.ReadElementString("gs");
					gp8box.Text = xreader.ReadElementString("gp");
					try
					{
						suspGS8box.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("ss"));
						fallGS8box.Text = xreader.ReadElementString("fv");
					}
					catch
					{};
					xreader.ReadEndElement();

					try
					{
						xreader.ReadStartElement("Grain-Size");
						g9box.Text = xreader.ReadElementString("gs");
						gp9box.Text = xreader.ReadElementString("gp");
						try
						{
							suspGS9box.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("ss"));
							fallGS9box.Text = xreader.ReadElementString("fv");
						}
						catch
						{};
						xreader.ReadEndElement();
					}
					catch
					{};

					xreader.ReadStartElement("File-Parms");

					input_time_step_box.Text = xreader.ReadElementString("inputtimestep");
					saveintervalbox.Text = xreader.ReadElementString("saveinterval");
					outputfilesaveintervalbox.Text = xreader.ReadElementString("savetologfileinterval");
					tracerbox.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("tracerrun"));
					uniquefilecheck.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("uniquefilecheck"));

					xreader.ReadStartElement("Filenames");
					dum = xreader.ReadElementString("Desc");
					openfiletextbox.Text = xreader.ReadElementString("Name");
					xreader.ReadEndElement();
					xreader.ReadStartElement("Filenames");
					dum = xreader.ReadElementString("Desc");
					graindataloadbox.Text = xreader.ReadElementString("Name");
					xreader.ReadEndElement();
					xreader.ReadStartElement("Filenames");
					dum = xreader.ReadElementString("Desc");
					bedrockbox.Text = xreader.ReadElementString("Name");
					xreader.ReadEndElement();
					xreader.ReadStartElement("Filenames");
					dum = xreader.ReadElementString("Desc");
					raindataloadbox.Text = xreader.ReadElementString("Name");
					xreader.ReadEndElement();
					xreader.ReadStartElement("Filenames");
					dum = xreader.ReadElementString("Desc");
					tracerfile.Text = xreader.ReadElementString("Name");
					xreader.ReadEndElement();
					xreader.ReadStartElement("Filenames");
					dum = xreader.ReadElementString("Desc");
					tracerhydrofile.Text = xreader.ReadElementString("Name");
					xreader.ReadEndElement();
					xreader.ReadStartElement("Filenames");
					dum = xreader.ReadElementString("Desc");
					tracergrainbox.Text = xreader.ReadElementString("Name");
					xreader.ReadEndElement();
					try{

					xreader.ReadStartElement("Sources");
					inbox1.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("input"));  
					xbox1.Text = xreader.ReadElementString("X");
					ybox1.Text = xreader.ReadElementString("Y");
					infile1.Text = xreader.ReadElementString("Filename");
					xreader.ReadEndElement();
					xreader.ReadStartElement("Sources");
					inbox2.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("input"));  
					xbox2.Text = xreader.ReadElementString("X");
					ybox2.Text = xreader.ReadElementString("Y");
					infile2.Text = xreader.ReadElementString("Filename");
					xreader.ReadEndElement();
					xreader.ReadStartElement("Sources");
					inbox3.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("input"));  
					xbox3.Text = xreader.ReadElementString("X");
					ybox3.Text = xreader.ReadElementString("Y");
					infile3.Text = xreader.ReadElementString("Filename");
					xreader.ReadEndElement();
					xreader.ReadStartElement("Sources");
					inbox4.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("input"));  
					xbox4.Text = xreader.ReadElementString("X");
					ybox4.Text = xreader.ReadElementString("Y");
					infile4.Text = xreader.ReadElementString("Filename");
					xreader.ReadEndElement();
					xreader.ReadStartElement("Sources");
					inbox5.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("input"));  
					xbox5.Text = xreader.ReadElementString("X");
					ybox5.Text = xreader.ReadElementString("Y");
					infile5.Text = xreader.ReadElementString("Filename");
					xreader.ReadEndElement();
					xreader.ReadStartElement("Sources");
					inbox6.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("input"));  
					xbox6.Text = xreader.ReadElementString("X");
					ybox6.Text = xreader.ReadElementString("Y");
					infile6.Text = xreader.ReadElementString("Filename");
					xreader.ReadEndElement();
					xreader.ReadStartElement("Sources");
					inbox7.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("input"));  
					xbox7.Text = xreader.ReadElementString("X");
					ybox7.Text = xreader.ReadElementString("Y");
					infile7.Text = xreader.ReadElementString("Filename");
					xreader.ReadEndElement();
					xreader.ReadStartElement("Sources");
					inbox8.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("input"));  
					xbox8.Text = xreader.ReadElementString("X");
					ybox8.Text = xreader.ReadElementString("Y");
					infile8.Text = xreader.ReadElementString("Filename");
					xreader.ReadEndElement();
					}
					catch
					{};

					xreader.ReadEndElement();

					xreader.ReadStartElement("Description");
					DescBox.Text  = xreader.ReadElementString("S");
					xreader.ReadEndElement();

					//JMW 2004-11-11
					try
					{
						xreader.ReadStartElement("OutputFile-Parms");
						checkBoxGenerateAVIFile.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("generateavifile"));
						textBoxAVIFile.Text = xreader.ReadElementString("avifile");
						try
						{
							saveintervalbox.Text = xreader.ReadElementString("avifreq");
							checkBoxGenerateTimeSeries.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("generatetimeseriesfile"));
							TimeseriesOutBox.Text = xreader.ReadElementString("timeseriesfile");
							outputfilesaveintervalbox.Text = xreader.ReadElementString("timeseriesfreq");
							checkBoxGenerateIterations.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("generateiterationsfile"));
							IterationOutbox.Text = xreader.ReadElementString("iterationsfile");
						}
						catch
						{};
						xreader.ReadEndElement();
					}
					catch
					{};
					
					try
					{
						xreader.ReadStartElement("Display");
						Form1.ActiveForm.Top = XmlConvert.ToInt16(xreader.ReadElementString("top"));
						Form1.ActiveForm.Left = XmlConvert.ToInt16(xreader.ReadElementString("left"));
						Form1.ActiveForm.Width = XmlConvert.ToInt16(xreader.ReadElementString("width"));
						Form1.ActiveForm.Height = XmlConvert.ToInt16(xreader.ReadElementString("height"));

					xreader.ReadEndElement();
					}
					catch
					{};

					try
					{
						xreader.ReadStartElement("Lateral");
						bool dum_bool = XmlConvert.ToBoolean(xreader.ReadElementString("oldlat"));
						newlateral.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("newlat"));
						xreader.ReadEndElement();
					}
					catch
					{};
                    try
                    {
                        xreader.ReadStartElement("Add_Ons");
                        tracerOutcheckBox.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("tracer-out"));
                        tracerOutputtextBox.Text = xreader.ReadElementString("tracer-out-filename");
                        googleAnimationCheckbox.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("google_animation"));
                        googleAnimationTextBox.Text = xreader.ReadElementString("google_animation_file_name");
                        googleBeginDate.Text = xreader.ReadElementString("google_begin");
                        googAnimationSaveInterval.Text = xreader.ReadElementString("google_interval");
                        jmeaninputfilebox.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("jMean"));
                        avge_smoothbox.Text = xreader.ReadElementString("edge_smoothing");
                        string dum_string = xreader.ReadElementString("displacement");
                        propremaining.Text = xreader.ReadElementString("prop_remain");
                        max_time_step_Box.Text = xreader.ReadElementString("max_time_step");
                        mine_checkBox.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("contam_input"));
                        mineX_textBox.Text = xreader.ReadElementString("mineX");
                        mineY_textBox.Text = xreader.ReadElementString("mineY");
                        mine_input_textBox.Text = xreader.ReadElementString("contam_input_file");
                        soil_ratebox.Text = xreader.ReadElementString("soil_rate");
                        SiberiaBox.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("siberia"));
                        Beta1Box.Text = xreader.ReadElementString("beta1");
                        Beta3Box.Text = xreader.ReadElementString("beta3");
                        m1Box.Text = xreader.ReadElementString("m1");
                        m3Box.Text = xreader.ReadElementString("m3");
                        n1Box.Text = xreader.ReadElementString("n1");
                        Q2box.Text = xreader.ReadElementString("W_depth_erosion_threshold");
                        dum_string = xreader.ReadElementString("fexp");
                        div_inputs_box.Text = xreader.ReadElementString("div_inputs");
                        init_depth_box.Text = xreader.ReadElementString("initial_sand_depth");
                        slab_depth_box.Text = xreader.ReadElementString("maxslabdepth");
                        shadow_angle_box.Text = xreader.ReadElementString("angle");
                        upstream_check_box.Text = xreader.ReadElementString("checkup");
                        depo_prob_box.Text = xreader.ReadElementString("dep_probability");
                        offset_box.Text = xreader.ReadElementString("downstream_offset");
                        wilcockbox.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("wilcock"));
                        einsteinbox.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("einstein"));
                        DuneBox.Checked = XmlConvert.ToBoolean(xreader.ReadElementString("dune"));
                        xreader.ReadEndElement();
                        xreader.ReadEndElement();
                    }
                    catch
                    { };
                    
					xreader.Close();

					
					this.Text = basetext + " (" + Path.GetFileName(cfgname) + ")";
					button2.Enabled = true;
					start_button.Enabled = false;
					Panel1.Visible = false;
					tabControl1.Visible = true;
					
				}
			}		
		}


		// JMW - Config File Save & SaveAs Event Handler
		private void menuItemConfigFileSave_Click(object sender, System.EventArgs e)
		{
			XmlTextWriter xwriter;

			if ((sender == menuItemConfigFileSaveAs) || (cfgname == null))
			{
				
				SaveFileDialog saveFileDialog1 = new SaveFileDialog();

				saveFileDialog1.InitialDirectory = workdir ;
				saveFileDialog1.Filter = "cfg files (*.xml)|*.xml|All files (*.*)|*.*" ;
				saveFileDialog1.FilterIndex = 1 ;
				saveFileDialog1.RestoreDirectory = false ;

				if(saveFileDialog1.ShowDialog() == DialogResult.OK)
				{
					cfgname = saveFileDialog1.FileName;
				}

			}

			if (cfgname != null)
			{

				//Create a new XmlTextWriter.
				xwriter = new XmlTextWriter(cfgname,System.Text.Encoding.UTF8);
				//Write the beginning of the document including the 
				//document declaration. Standalone is true. 
				//Use indentation for readability.
				xwriter.Formatting = Formatting.Indented;
				xwriter.Indentation = 4;


				xwriter.WriteStartDocument(true);

				//Write the beginning of the "data" element. This is 
				//the opening tag to our data 
				xwriter.WriteStartElement("Parms");
				xwriter.WriteStartElement("General-Parms");
				xwriter.WriteElementString("headeroverride",XmlConvert.ToString(overrideheaderBox.Checked));
				xwriter.WriteElementString("x-coordinate",xtextbox.Text);				
				xwriter.WriteElementString("y-coordinate",ytextbox.Text);
				xwriter.WriteElementString("initscans",initscansbox.Text);
				xwriter.WriteElementString("maxerodelimit",erodefactorbox.Text);
				xwriter.WriteElementString("cellsize",dxbox.Text);
				xwriter.WriteElementString("memorylimit",limitbox.Text);
				xwriter.WriteElementString("minq",minqbox.Text);
				xwriter.WriteElementString("creeprate",creepratebox.Text);
				xwriter.WriteElementString("lateralerosionrate",lateralratebox.Text);
				xwriter.WriteElementString("maxiter",itermaxbox.Text);
				xwriter.WriteElementString("runstarttime",textBox1.Text);
				xwriter.WriteElementString("maxrunduration",cyclemaxbox.Text);
				xwriter.WriteElementString("slopefailurethreshold",slopebox.Text);
				xwriter.WriteElementString("wssmoothingradius",smoothbox.Text);
				xwriter.WriteElementString("mvalue",mvaluebox.Text);
				xwriter.WriteElementString("growgrasstime",grasstextbox.Text);
				xwriter.WriteElementString("initialq",textBox2.Text);
				xwriter.WriteElementString("wssmoothing",XmlConvert.ToString(checkBox3.Checked));
				xwriter.WriteElementString("grass-sediment",XmlConvert.ToString(grassbox.Checked));
				xwriter.WriteElementString("flowdistribution",textBox3.Text); // MJ 24/01/05
				xwriter.WriteElementString("mintimestep",mintimestepbox.Text); // MJ 24/01/05
				xwriter.WriteElementString("evaporation",k_evapBox.Text); // MJ 15/03/05
				xwriter.WriteElementString("vegcritshear",vegTauCritBox.Text); // MJ 10/05/05
				xwriter.WriteElementString("bedslope",XmlConvert.ToString(bedslope_box.Checked));
				xwriter.WriteElementString("wsslope",XmlConvert.ToString(false));
                xwriter.WriteElementString("veltaubox", XmlConvert.ToString(veltaubox.Checked));
				xwriter.WriteElementString("catchment_mode",XmlConvert.ToString(catchment_mode_box.Checked));
				xwriter.WriteElementString("reach_mode",XmlConvert.ToString(reach_mode_box.Checked));
				xwriter.WriteElementString("lat1",XmlConvert.ToString(latbox1.Checked));
				xwriter.WriteElementString("lat2",XmlConvert.ToString(latbox2.Checked));
				xwriter.WriteElementString("lat3",XmlConvert.ToString(false));
                xwriter.WriteElementString("cross_stream_grad", XmlConvert.ToString(0));



				xwriter.WriteStartElement("SaveOptions");
				xwriter.WriteElementString("Option","elevations");
				xwriter.WriteElementString("Checked",XmlConvert.ToString(menuItem12.Checked));
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("SaveOptions");
				xwriter.WriteElementString("Option","elevdiff");
				xwriter.WriteElementString("Checked",XmlConvert.ToString(menuItem13.Checked));
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("SaveOptions");
				xwriter.WriteElementString("Option","grainsize");
				xwriter.WriteElementString("Checked",XmlConvert.ToString(menuItem14.Checked));
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("SaveOptions");
				xwriter.WriteElementString("Option","total tracer g/s");
				xwriter.WriteElementString("Checked",XmlConvert.ToString(menuItem15.Checked));
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("SaveOptions");
				xwriter.WriteElementString("Option","tracer layer 1");
				xwriter.WriteElementString("Checked",XmlConvert.ToString(menuItem16.Checked));
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("SaveOptions");
				xwriter.WriteElementString("Option","tracer layer 2");
				xwriter.WriteElementString("Checked",XmlConvert.ToString(menuItem17.Checked));
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("SaveOptions");
				xwriter.WriteElementString("Option","tracer layer 3");
				xwriter.WriteElementString("Checked",XmlConvert.ToString(menuItem18.Checked));
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("SaveOptions");
				xwriter.WriteElementString("Option","tracer layer 4");
				xwriter.WriteElementString("Checked",XmlConvert.ToString(menuItem19.Checked));
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("SaveOptions");
				xwriter.WriteElementString("Option","tracer layer 5");
				xwriter.WriteElementString("Checked",XmlConvert.ToString(menuItem20.Checked));
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("SaveOptions");
				xwriter.WriteElementString("Option","tracer layer 6");
				xwriter.WriteElementString("Checked",XmlConvert.ToString(menuItem21.Checked));
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("SaveOptions");
				xwriter.WriteElementString("Option","tracer layer 7");
				xwriter.WriteElementString("Checked",XmlConvert.ToString(menuItem22.Checked));
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("SaveOptions");
				xwriter.WriteElementString("Option","tracer layer 8");
				xwriter.WriteElementString("Checked",XmlConvert.ToString(menuItem23.Checked));
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("SaveOptions");
				xwriter.WriteElementString("Option","tracer layer 9");
				xwriter.WriteElementString("Checked",XmlConvert.ToString(menuItem24.Checked));
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("SaveOptions");
				xwriter.WriteElementString("Option","water depth");
				xwriter.WriteElementString("Checked",XmlConvert.ToString(menuItem25.Checked));
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("SaveOptions");
				xwriter.WriteElementString("Option","d50");
				xwriter.WriteElementString("Checked",XmlConvert.ToString(menuItem29.Checked));
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("SaveOptions");
				xwriter.WriteElementString("Option","flow velocity");
				xwriter.WriteElementString("Checked",XmlConvert.ToString(menuItem33.Checked));
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("SaveOptions");
				xwriter.WriteElementString("Option","soil saturation");
				xwriter.WriteElementString("Checked",XmlConvert.ToString(menuItem34.Checked));
				xwriter.WriteEndElement();

				xwriter.WriteEndElement();

				xwriter.WriteStartElement("Grain-Size");
				xwriter.WriteElementString("gs",g1box.Text);
				xwriter.WriteElementString("gp",gp1box.Text);
				xwriter.WriteElementString("ss",XmlConvert.ToString(suspGS1box.Checked));					
				xwriter.WriteElementString("fv",fallGS1box.Text);					
				xwriter.WriteEndElement();

				xwriter.WriteStartElement("Grain-Size");
				xwriter.WriteElementString("gs",g2box.Text);
				xwriter.WriteElementString("gp",gp2box.Text);
				xwriter.WriteElementString("ss",XmlConvert.ToString(suspGS2box.Checked));					
				xwriter.WriteElementString("fv",fallGS2box.Text);					
				xwriter.WriteEndElement();
				
				xwriter.WriteStartElement("Grain-Size");
				xwriter.WriteElementString("gs",g3box.Text);				
				xwriter.WriteElementString("gp",gp3box.Text);
				xwriter.WriteElementString("ss",XmlConvert.ToString(suspGS3box.Checked));					
				xwriter.WriteElementString("fv",fallGS3box.Text);					
				xwriter.WriteEndElement();
				
				xwriter.WriteStartElement("Grain-Size");
				xwriter.WriteElementString("gs",g4box.Text);				
				xwriter.WriteElementString("gp",gp4box.Text);
				xwriter.WriteElementString("ss",XmlConvert.ToString(suspGS4box.Checked));					
				xwriter.WriteElementString("fv",fallGS4box.Text);					
				xwriter.WriteEndElement();
				
				xwriter.WriteStartElement("Grain-Size");
				xwriter.WriteElementString("gs",g5box.Text);				
				xwriter.WriteElementString("gp",gp5box.Text);
				xwriter.WriteElementString("ss",XmlConvert.ToString(suspGS5box.Checked));					
				xwriter.WriteElementString("fv",fallGS5box.Text);					
				xwriter.WriteEndElement();
	
				xwriter.WriteStartElement("Grain-Size");
				xwriter.WriteElementString("gs",g6box.Text);				
				xwriter.WriteElementString("gp",gp6box.Text);	
				xwriter.WriteElementString("ss",XmlConvert.ToString(suspGS6box.Checked));					
				xwriter.WriteElementString("fv",fallGS6box.Text);					
				xwriter.WriteEndElement();

				xwriter.WriteStartElement("Grain-Size");
				xwriter.WriteElementString("gs",g7box.Text);				
				xwriter.WriteElementString("gp",gp7box.Text);	
				xwriter.WriteElementString("ss",XmlConvert.ToString(suspGS7box.Checked));					
				xwriter.WriteElementString("fv",fallGS7box.Text);					
				xwriter.WriteEndElement();

				xwriter.WriteStartElement("Grain-Size");
				xwriter.WriteElementString("gs",g8box.Text);				
				xwriter.WriteElementString("gp",gp8box.Text);					
				xwriter.WriteElementString("ss",XmlConvert.ToString(suspGS8box.Checked));					
				xwriter.WriteElementString("fv",fallGS8box.Text);					
				xwriter.WriteEndElement();

				xwriter.WriteStartElement("Grain-Size");
				xwriter.WriteElementString("gs",g9box.Text);				
				xwriter.WriteElementString("gp",gp9box.Text);					
				xwriter.WriteElementString("ss",XmlConvert.ToString(suspGS9box.Checked));					
				xwriter.WriteElementString("fv",fallGS9box.Text);					
				xwriter.WriteEndElement();
                
				xwriter.WriteStartElement("File-Parms");

				xwriter.WriteElementString("inputtimestep",input_time_step_box.Text);
				xwriter.WriteElementString("saveinterval",saveintervalbox.Text);
				xwriter.WriteElementString("savetologfileinterval",outputfilesaveintervalbox.Text);
				xwriter.WriteElementString("tracerrun",XmlConvert.ToString(tracerbox.Checked));
				xwriter.WriteElementString("uniquefilecheck",XmlConvert.ToString(uniquefilecheck.Checked));


				xwriter.WriteStartElement("Filenames");
				xwriter.WriteElementString("Desc","DEM Data File");
				xwriter.WriteElementString("Name",openfiletextbox.Text);
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("Filenames");
				xwriter.WriteElementString("Desc","Grain Data File");
				xwriter.WriteElementString("Name",graindataloadbox.Text);
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("Filenames");
				xwriter.WriteElementString("Desc","Bedrock Data File");
				xwriter.WriteElementString("Name",bedrockbox.Text);
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("Filenames");
				xwriter.WriteElementString("Desc","Rain Data File");
				xwriter.WriteElementString("Name",raindataloadbox.Text);
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("Filenames");
				xwriter.WriteElementString("Desc","Tracer File");
				xwriter.WriteElementString("Name",tracerfile.Text);
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("Filenames");
				xwriter.WriteElementString("Desc","Tracer Sed Vol File");
				xwriter.WriteElementString("Name",tracerhydrofile.Text);
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("Filenames");
				xwriter.WriteElementString("Desc","Tracer Grain Size Data File");
				xwriter.WriteElementString("Name",tracergrainbox.Text);
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("Sources");
				xwriter.WriteElementString("input",XmlConvert.ToString(inbox1.Checked));  
				xwriter.WriteElementString("X",xbox1.Text);
				xwriter.WriteElementString("Y",ybox1.Text);
				xwriter.WriteElementString("Filename",infile1.Text);
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("Sources");
				xwriter.WriteElementString("input",XmlConvert.ToString(inbox2.Checked));  
				xwriter.WriteElementString("X",xbox2.Text);
				xwriter.WriteElementString("Y",ybox2.Text);
				xwriter.WriteElementString("Filename",infile2.Text);
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("Sources");
				xwriter.WriteElementString("input",XmlConvert.ToString(inbox3.Checked));  
				xwriter.WriteElementString("X",xbox3.Text);
				xwriter.WriteElementString("Y",ybox3.Text);
				xwriter.WriteElementString("Filename",infile3.Text);
				xwriter.WriteEndElement();
				xwriter.WriteStartElement("Sources");
				xwriter.WriteElementString("input",XmlConvert.ToString(inbox4.Checked));  
				xwriter.WriteElementString("X",xbox4.Text);
				xwriter.WriteElementString("Y",ybox4.Text);
				xwriter.WriteElementString("Filename",infile4.Text);
				xwriter.WriteEndElement();	
				xwriter.WriteStartElement("Sources");
				xwriter.WriteElementString("input",XmlConvert.ToString(inbox5.Checked));  
				xwriter.WriteElementString("X",xbox5.Text);
				xwriter.WriteElementString("Y",ybox5.Text);
				xwriter.WriteElementString("Filename",infile5.Text);
				xwriter.WriteEndElement();	
				xwriter.WriteStartElement("Sources");
				xwriter.WriteElementString("input",XmlConvert.ToString(inbox6.Checked));  
				xwriter.WriteElementString("X",xbox6.Text);
				xwriter.WriteElementString("Y",ybox6.Text);
				xwriter.WriteElementString("Filename",infile6.Text);
				xwriter.WriteEndElement();	
				xwriter.WriteStartElement("Sources");
				xwriter.WriteElementString("input",XmlConvert.ToString(inbox7.Checked));  
				xwriter.WriteElementString("X",xbox7.Text);
				xwriter.WriteElementString("Y",ybox7.Text);
				xwriter.WriteElementString("Filename",infile7.Text);
				xwriter.WriteEndElement();	
				xwriter.WriteStartElement("Sources");
				xwriter.WriteElementString("input",XmlConvert.ToString(inbox8.Checked));  
				xwriter.WriteElementString("X",xbox8.Text);
				xwriter.WriteElementString("Y",ybox8.Text);
				xwriter.WriteElementString("Filename",infile8.Text);
				xwriter.WriteEndElement();	
				xwriter.WriteEndElement();

				
				xwriter.WriteStartElement("Description");
				xwriter.WriteElementString("S",DescBox.Text);
				xwriter.WriteEndElement();

				//JMW 2004-11-11; updated MJ 24/01/05
				xwriter.WriteStartElement("OutputFile-Parms");
				xwriter.WriteElementString("generateavifile",XmlConvert.ToString(checkBoxGenerateAVIFile.Checked));
				xwriter.WriteElementString("avifile",textBoxAVIFile.Text);
				xwriter.WriteElementString("avifreq",saveintervalbox.Text);
				xwriter.WriteElementString("generatetimeseriesfile",XmlConvert.ToString(checkBoxGenerateTimeSeries.Checked));
				xwriter.WriteElementString("timeseriesfile",TimeseriesOutBox.Text);
				xwriter.WriteElementString("timeseriesfreq",outputfilesaveintervalbox.Text);
				xwriter.WriteElementString("generateiterationsfile",XmlConvert.ToString(checkBoxGenerateIterations.Checked));
				xwriter.WriteElementString("iterationsfile",IterationOutbox.Text);
				xwriter.WriteEndElement();


				xwriter.WriteStartElement("Display");
				xwriter.WriteElementString("top",string.Format(" {0}",Form1.ActiveForm.Top));
				xwriter.WriteElementString("left",string.Format(" {0}",Form1.ActiveForm.Left));
				xwriter.WriteElementString("width",string.Format(" {0}",Form1.ActiveForm.Width));
				xwriter.WriteElementString("height",string.Format(" {0}",Form1.ActiveForm.Height));
				xwriter.WriteEndElement();
				
				xwriter.WriteStartElement("Lateral");
				xwriter.WriteElementString("oldlat",XmlConvert.ToString(false));
				xwriter.WriteElementString("newlat",XmlConvert.ToString(newlateral.Checked));
                xwriter.WriteEndElement();

                xwriter.WriteStartElement("Add_Ons");
                xwriter.WriteElementString("tracer-out", XmlConvert.ToString(tracerOutcheckBox.Checked));
                xwriter.WriteElementString("tracer-out-filename", tracerOutputtextBox.Text);
                xwriter.WriteElementString("google_animation", XmlConvert.ToString(googleAnimationCheckbox.Checked));
                xwriter.WriteElementString("google_animation_file_name", googleAnimationTextBox.Text);
                xwriter.WriteElementString("google_begin", googleBeginDate.Text);
                xwriter.WriteElementString("google_interval", googAnimationSaveInterval.Text);
                xwriter.WriteElementString("jMean", XmlConvert.ToString(jmeaninputfilebox.Checked));
                xwriter.WriteElementString("edge_smoothing", avge_smoothbox.Text);
                xwriter.WriteElementString("displacement", XmlConvert.ToString(false));
                xwriter.WriteElementString("prop_remain", propremaining.Text);
                xwriter.WriteElementString("max_time_step", max_time_step_Box.Text);
                xwriter.WriteElementString("contam_input", XmlConvert.ToString(mine_checkBox.Checked));
                xwriter.WriteElementString("mineX", mineX_textBox.Text);
                xwriter.WriteElementString("mineY", mineY_textBox.Text);
                xwriter.WriteElementString("contam_input_file", mine_input_textBox.Text);
                xwriter.WriteElementString("soil_rate", soil_ratebox.Text);
                xwriter.WriteElementString("siberia", XmlConvert.ToString(SiberiaBox.Checked));
                xwriter.WriteElementString("beta1", Beta1Box.Text);
                xwriter.WriteElementString("beta3", Beta3Box.Text);
                xwriter.WriteElementString("m1", m1Box.Text);
                xwriter.WriteElementString("m3", m3Box.Text);
                xwriter.WriteElementString("n1", n1Box.Text);
                xwriter.WriteElementString("W_depth_erosion_threshold", Q2box.Text);
                xwriter.WriteElementString("fexp",XmlConvert.ToString(1));
                xwriter.WriteElementString("div_inputs",div_inputs_box.Text);
                xwriter.WriteElementString("initial_sand_depth", init_depth_box.Text);
                xwriter.WriteElementString("maxslabdepth", slab_depth_box.Text);
                xwriter.WriteElementString("angle", shadow_angle_box.Text);
                xwriter.WriteElementString("checkup", upstream_check_box.Text);
                xwriter.WriteElementString("dep_probability", depo_prob_box.Text);
                xwriter.WriteElementString("downstream_offset", offset_box.Text);
                xwriter.WriteElementString("wilcock", XmlConvert.ToString(wilcockbox.Checked));
                xwriter.WriteElementString("einstein", XmlConvert.ToString(einsteinbox.Checked));
                xwriter.WriteElementString("dune", XmlConvert.ToString(DuneBox.Checked));

                //xwriter.WriteElementString();

                xwriter.WriteEndElement();
				xwriter.WriteEndElement();


				//End the document
				xwriter.WriteEndDocument();

				//Flush the xml document to the underlying stream and
				//close the underlying stream. The data will not be
				//written out to the stream until either the Flush()
				//method is called or the Close() method is called.
				xwriter.Close();

				this.Text = basetext + " (" + Path.GetFileName(cfgname) + ")";
			}
		}
	

		private void suspCheckedChange(object sender, System.EventArgs e)
		{
			fallGS1box.Enabled = suspGS1box.Checked;
			fallGS2box.Enabled = suspGS2box.Checked;
			fallGS3box.Enabled = suspGS3box.Checked;
			fallGS4box.Enabled = suspGS4box.Checked;
			fallGS5box.Enabled = suspGS5box.Checked;
			fallGS6box.Enabled = suspGS6box.Checked;
			fallGS7box.Enabled = suspGS7box.Checked;
			fallGS8box.Enabled = suspGS8box.Checked;
			fallGS9box.Enabled = suspGS9box.Checked;
		}

		private void fracGSchanged(object sender, System.EventArgs e)
		{
			double sum;

			sum = 0.0;
			if (gp1box.Text != "") sum += double.Parse(gp1box.Text);
			if (gp2box.Text != "") sum += double.Parse(gp2box.Text);
			if (gp3box.Text != "") sum += double.Parse(gp3box.Text);
			if (gp4box.Text != "") sum += double.Parse(gp4box.Text);
			if (gp5box.Text != "") sum += double.Parse(gp5box.Text);
			if (gp6box.Text != "") sum += double.Parse(gp6box.Text);
			if (gp7box.Text != "") sum += double.Parse(gp7box.Text);
			if (gp8box.Text != "") sum += double.Parse(gp8box.Text);
			if (gp9box.Text != "") sum += double.Parse(gp9box.Text);

			if (Math.Abs(sum-1.0) < 0.000000001)
			{
				gpSumLabel.Text = "OK";
				gpSumLabel.ForeColor = Color.Black;
				gpSumLabel2.ForeColor = Color.Black;
			}
			else
			{
				gpSumLabel.Text = string.Format("{0:F8}",sum);
				gpSumLabel.ForeColor = Color.Red;
				gpSumLabel2.ForeColor = Color.Red;
			}
		}


		private void button4_Click_1(object sender, System.EventArgs e)
		{
            updateClick = 1;
			this.Refresh();
			drawwater(mygraphics);
		}

		
		private void overrideheaderBox_CheckedChanged(object sender, System.EventArgs e)
		{
			label1.Enabled = overrideheaderBox.Checked;
			label2.Enabled = overrideheaderBox.Checked;
			label11.Enabled = overrideheaderBox.Checked;
			xtextbox.Enabled = overrideheaderBox.Checked;
			ytextbox.Enabled = overrideheaderBox.Checked;
			dxbox.Enabled = overrideheaderBox.Checked;
		}




		// MJ 04/04/05
		void WriteSedFile(string posnote)
		{
			int x,y;
			double sumVsusp, sumV1susp, sumV2susp;
			double sumTsusp, sumT1susp, sumT2susp;
			double sumdV;
			sumdV = 0.0;
			sumVsusp = 0.0;
			sumV1susp = 0.0;
			sumV2susp = 0.0;
			sumTsusp = 0.0;
			sumT1susp = 0.0;
			sumT2susp = 0.0;
			for (y=1; y<= ymax; y++)
			{
				for (x=1; x<=xmax; x++)
				{
					if (elev[x,y] > -9998)
					{
						sumdV += (init_elevs[x,y]-elev[x,y]);
						sumVsusp += Vsusptot[x,y];
						sumTsusp += tempsusptot[x,y];
						for (int p=0; p<=(TRACERS-1); p++)
						{
							sumV1susp += Vsusp[x,y,1,p];
							sumV2susp += Vsusp[x,y,2,p];
							sumT1susp += tempsusp[x,y,1,p];
							sumT2susp += tempsusp[x,y,2,p];
						}
					}
				}
			}
			sumdV = sumdV * (DX*DX);

			string output = string.Format("{0:G}",counter);
			output = output + string.Format("  {0:F6}",cycle/1440);
			output = output + "  " + posnote;
			output = output + string.Format("  {0:F6}",sumdV);
			output = output + string.Format("  {0:F6}",sumVsusp);
			output = output + string.Format("  {0:F6}",sumV1susp);
			output = output + string.Format("  {0:F6}",sumV2susp);
			output = output + string.Format("  {0:F6}",sumTsusp);
			output = output + string.Format("  {0:F6}",sumT1susp);
			output = output + string.Format("  {0:F6}",sumT2susp);

			string EXCHANGE_FILE = "sedexchangeA.txt";
			StreamWriter sw = File.AppendText(EXCHANGE_FILE);
			sw.WriteLine(output);
			sw.Close();
		}

		private void checkBox1_CheckedChanged(object sender, System.EventArgs e)
		{
		
		}

		private void bedslope_box_CheckedChanged(object sender, System.EventArgs e)
		{
			if(bedslope_box.Checked==true){
                veltaubox.Checked=false;
            }
		}



		private void newlateral_CheckedChanged(object sender, System.EventArgs e)
		{
			
            if (newlateral.Checked == true) nolateral.Checked = false;
		}

		private void label54_Click(object sender, System.EventArgs e)
		{
		
		}

		private void button5_Click(object sender, System.EventArgs e)
		{
			Form1.ActiveForm.Show();
		}

		private void button5_Click_1(object sender, System.EventArgs e)
		{
            get_area();
			init_route(TRUE,init_discharge, baseflow);
			time_factor=0.0000000001;
		}

		private void statusBar1_PanelClick(object sender, System.Windows.Forms.StatusBarPanelClickEventArgs e)
		{
		
		}

        private void veltaubox_CheckedChanged(object sender, EventArgs e)
        {
            if (veltaubox.Checked == true)
            {
                
                bedslope_box.Checked = false;
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
           
        }

        private void nolateral_CheckedChanged(object sender, EventArgs e)
        {
            
            if (nolateral.Checked == true) newlateral.Checked = false;
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
           zoomPanImageBox1.Height = this.Height - 225;
           zoomPanImageBox1.Width = this.Width - 20;
        }

        private void menuItem36_Click(object sender, EventArgs e)
        {
            plotType = 1;//sediment plot
            DynamicData.dynamicPlot dischargePlot1 = new DynamicData.dynamicPlot(1);
            dischargePlot1.Show();
        }

        private void menuItem37_Click(object sender, EventArgs e)
        {
            plotType = 2;//discharge plot
            DynamicData.dynamicPlot dischargePlot2 = new DynamicData.dynamicPlot(2);
            dischargePlot2.Show();
        }

        private void zoomPanImageBox1_Load(object sender, EventArgs e)
        {

        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            contrastMultiplier = contrastFactor[trackBar1.Value];
            drawwater(mygraphics);
        }

        private void trackBar2_Scroll(object sender, EventArgs e)
        {
            magnifyValue = zoomFactor[this.trackBar2.Value];
            zoomPanImageBox1.setZoom();
        }

        private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            updateClick = 1;
            this.Refresh();
            drawwater(mygraphics);
        }

        private void n1Box_TextChanged(object sender, EventArgs e)
        {

        }

        private void graphicToGoogleEarthButton_Click(object sender, EventArgs e)
        {
            if (coordinateDone == 0)
            {
                //transfrom coordinates
                point testPoint = new point(xll, yll);
                testPoint.transformPoint();
                yurcorner = yll + (System.Convert.ToDouble(ymax) * System.Convert.ToDouble(DX));
                xurcorner = xll + (System.Convert.ToDouble(xmax) * System.Convert.ToDouble(DX));
                point testPoint2 = new point(xurcorner, yurcorner);
                testPoint2.transformPoint();
                urfinalLati = testPoint2.ycoord;
                urfinalLongi = testPoint2.xcoord;
                llfinalLati = testPoint.ycoord;
                llfinalLongi = testPoint.xcoord;
                coordinateDone = 1;
            }

            //Save image
            m_objDrawingSurface.MakeTransparent();
            m_objDrawingSurface.Save(@"mysavedimage" + imageCount + ".png", System.Drawing.Imaging.ImageFormat.Png);
            //create kml file for image
            string kml_file_name = "image" + imageCount + ".kml";
            StreamWriter kmlsr = File.CreateText(kml_file_name);
            string kml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
                                 <kml xmlns=""http://earth.google.com/kml/2.1"">
                                 <GroundOverlay>
                                 	<name>Untitled Image Overlay</name>";
            kml = kml + "\n<Icon>"
                   + "\n<href>mySavedImage" + imageCount + ".png</href>"
                   + "\n</Icon>"
                   + "\n<LatLonBox>";
            kml = kml + "\n<north>" + urfinalLati + "</north>"
                      + "\n<south>" + llfinalLati + "</south>"
                      + "\n<east>" + urfinalLongi + "</east>"
                      + "\n<west>" + llfinalLongi + "</west>\n";
            kml = kml + @"</LatLonBox>
                                 </GroundOverlay>
                                 </kml>
                                             ";
            kmlsr.Write(kml);
            kmlsr.Close();
            imageCount++;
        }

        private void einsteinbox_CheckedChanged(object sender, EventArgs e)
        {
            if (wilcockbox.Checked == true) wilcockbox.Checked = false;
        }

        private void wilcockbox_CheckedChanged(object sender, EventArgs e)
        {
            if (einsteinbox.Checked == true) einsteinbox.Checked = false;
        }

        private void HydrologyTab_Click(object sender, EventArgs e)
        {

        }

        private void button6_Click(object sender, EventArgs e)
        {
            int x, y;
            for (x = 1; x <= xmax; x++)
            {
                for (y = 1; y <= ymax; y++)
                {
                    if (x > 0 && x <= 200) elev[x, y] += 1;
                }
            }
        }

        private void checkBox1_CheckedChanged_1(object sender, EventArgs e)
        {
            if (checkBox1.Checked==false) tabControl1.Visible = false;
            if (checkBox1.Checked == true) tabControl1.Visible = true;
        }

        private void tabPage5_Click(object sender, EventArgs e)
        {

        }

        private void button6_Click_1(object sender, EventArgs e)
        {
            gameClock.Stop();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            gameClock.Start();
        }

        private void label88_Click(object sender, EventArgs e)
        {

        }

        private void textBox12_TextChanged(object sender, EventArgs e)
        {

        }

        private void label58_Click(object sender, EventArgs e)
        {

        }

    }
    class point
    {
        //lat long variables
        public double xcoord;
        public double ycoord;
        double transParallelX = 446.448;
        double transParallelY = -125.157;
        double transParallelZ = 542.060;
        double scaleChange = -20.4894 * 0.000001;
        double rotX = (0.1502 / 3600) * (Math.PI / 180);
        double rotY = (0.2470 / 3600) * (Math.PI / 180);
        double rotZ = (0.8421 / 3600) * (Math.PI / 180);
        double a = 6377563.396; //airy 1830 semi-major axis
        double b = 6356256.910; //airy 1830 semi-minor axis
        double a2 = 6378137.000;
        double b2 = 6356752.3142;
        double eSquared = 0;
        double eSquared2 = 0;
        double nO = -100000;//northing of true origin
        double eO = 400000;//easting of true origin
        double fO = 0.9996012717;//scale factor
        double latTrue = 49.0 * (Math.PI / 180.0);//latitude of true origin
        double longTrue = -2.0 * (Math.PI / 180.0);//longitude of true origin
        double psiHash, MBig, v, v2, v3, nLittle, rho, nSquare = 0;
        double vii, viii, ix, Tx2, xi, xii, xiia = 0;
        double helmertX, helmertY, helmertZ, cartX, cartY, cartZ;
        double Height2 = 0;
        double Height3 = 0;
        double finalLati, finalLongi, latiRad, longiRad = 0;
        double rootXYSqr = 0;
        double PHI1, PHI2, PHI = 0;

        public point(double theXcoord, double theYcoord)//constructor
        {
            this.xcoord = theXcoord;
            this.ycoord = theYcoord;
        }

        public void transformPoint()//british os to lat long
        {
            eSquared = (Math.Pow(a, 2) - Math.Pow(b, 2)) / Math.Pow(a, 2);
            Height2 = 0;
            Height3 = 0;
            //OSGB36 easting and northing to OSGB36 latitude and longitude (lower left corner of DTM)
            psiHash = ((this.ycoord - nO) / (a * fO)) + latTrue;
            nLittle = (a - b) / (a + b);
            MBig = b * fO * (((1 + nLittle + ((5.0 / 4.0) * Math.Pow(nLittle, 2)) + ((5.0 / 4.0) * Math.Pow(nLittle, 3))) * (psiHash -
                     latTrue))
               - (((3.0 * nLittle) + (3.0 * Math.Pow(nLittle, 2)) + ((21.0 / 8.0) * Math.Pow(nLittle, 3))) *
                     Math.Sin(psiHash - latTrue) * Math.Cos(psiHash + latTrue))
               + (((15.0 / 8.0 * Math.Pow(nLittle, 2)) + (15.0 / 8.0 * Math.Pow(nLittle, 3))) * Math.Sin(2.0 * (psiHash - latTrue)) * Math.Cos(2.0 * (psiHash + latTrue)))
               - ((35.0 / 24.0 * Math.Pow(nLittle, 3)) * Math.Sin(3.0 * (psiHash - latTrue)) * Math.Cos(3.0 * (psiHash + latTrue))));
            if (Math.Abs((this.ycoord - nO - MBig)) >= 0.01)
            {
                while (Math.Abs((this.ycoord - nO - MBig)) >= 0.01)
                {
                    psiHash = ((this.ycoord - nO - MBig) / (a * fO)) + psiHash;
                    MBig = b * fO * (((1 + nLittle + ((5.0 / 4.0) * Math.Pow(nLittle, 2)) + ((5.0 / 4.0) * Math.Pow(nLittle, 3))) * (psiHash -
                       latTrue))
                 - (((3.0 * nLittle) + (3.0 * Math.Pow(nLittle, 2)) + ((21.0 / 8.0) * Math.Pow(nLittle, 3))) *
                       Math.Sin(psiHash - latTrue) * Math.Cos(psiHash + latTrue))
                 + (((15.0 / 8.0 * Math.Pow(nLittle, 2)) + (15.0 / 8.0 * Math.Pow(nLittle, 3))) * Math.Sin(2.0 * (psiHash - latTrue)) * Math.Cos(2.0 * (psiHash + latTrue)))
                 - ((35.0 / 24.0 * Math.Pow(nLittle, 3)) * Math.Sin(3.0 * (psiHash - latTrue)) * Math.Cos(3.0 * (psiHash + latTrue))));
                }
            }
            v = a * fO * Math.Pow(1 - eSquared * Math.Pow(Math.Sin(psiHash), 2), -.5);
            rho = a * fO * (1 - eSquared) * Math.Pow(1.0 - eSquared * Math.Pow(Math.Sin(psiHash), 2), -1.5);
            nSquare = v / rho - 1.0;
            vii = (Math.Tan(psiHash)) / (2.0 * rho * v);
            viii = ((Math.Tan(psiHash)) / (24.0 * rho * Math.Pow(v, 3))) * (5 + 3.0 * Math.Pow(Math.Tan(psiHash), 2) + nSquare - 9.0 * (Math.Pow(Math.Tan(psiHash), 2) * nSquare));
            ix = (Math.Tan(psiHash) / ((720.0 * rho * Math.Pow(v, 5)))) * (61 + 90.0 * Math.Pow(Math.Tan(psiHash), 2) + 45.0 * Math.Pow(Math.Tan(psiHash), 4));
            Tx2 = (1.0 / Math.Cos(psiHash)) / v;
            xi = (1.0 / Math.Cos(psiHash)) / (6.0 * Math.Pow(v, 3)) * ((v / rho) + (2.0 * Math.Pow(Math.Tan(psiHash), 2)));
            xii = (1.0 / Math.Cos(psiHash)) / (120.0 * Math.Pow(v, 5)) * (5.0 + (28.0 * Math.Pow(Math.Tan(psiHash), 2)) + (24.0 * Math.Pow(Math.Tan(psiHash), 4)));
            xiia = ((1.0 / Math.Cos(psiHash)) / (5040.0 * Math.Pow(v, 7))) * (61.0 + (662.0 * Math.Pow(Math.Tan(psiHash), 2)) + (1320.0 * Math.Pow(Math.Tan(psiHash), 4)) + (720.0 * Math.Pow(Math.Tan(psiHash), 6)));
            latiRad = psiHash - (vii * Math.Pow((this.xcoord - eO), 2)) + (viii * Math.Pow((this.xcoord - eO), 4)) - (ix * Math.Pow((this.xcoord - eO), 6));
            longiRad = longTrue + (Tx2 * (this.xcoord - eO)) - (xi * (Math.Pow((this.xcoord - eO), 3))) + (xii * (Math.Pow((this.xcoord - eO), 5))) - (xiia * (Math.Pow((this.xcoord - eO), 7)));
            //Console.WriteLine(latiRad * (180 / Math.PI));
            //Console.WriteLine(longiRad * (180 / Math.PI));
            //OSGB36 Latitude Longitude Height to OSGB36 Cartesian XYZ
            v2 = a / (Math.Sqrt(1 - (eSquared * ((Math.Pow(Math.Sin(latiRad), 2))))));
            cartX = (v2 + Height2) * Math.Cos(latiRad) * Math.Cos(longiRad);
            cartY = (v2 + Height2) * (Math.Cos(latiRad) * Math.Sin(longiRad));
            cartZ = ((v2 * (1 - eSquared)) + Height2) * Math.Sin(latiRad);
            //Console.WriteLine();
            //Console.WriteLine(cartX);
            //Console.WriteLine(cartY);
            //Helmert Datum Transformation (OSGB36 to WGS84)
            helmertX = cartX + (cartX * scaleChange) - (cartY * rotZ) + (cartZ * rotY) + transParallelX;
            helmertY = (cartX * rotZ) + cartY + (cartY * scaleChange) - (cartZ * rotX) + transParallelY;
            helmertZ = (-1 * cartX * rotY) + (cartY * rotX) + cartZ + (cartZ * scaleChange) + transParallelZ;
            //Console.WriteLine();
            //Console.WriteLine(helmertX);
            //Console.WriteLine(helmertY);
            //WGS84 Cartesian XYZ to WGS84 Latitude, longitude and Ellipsoidal height								
            rootXYSqr = Math.Sqrt((Math.Pow(helmertX, 2)) + (Math.Pow(helmertY, 2)));
            eSquared2 = (Math.Pow(a2, 2) - Math.Pow(b2, 2)) / Math.Pow(a2, 2);
            PHI1 = Math.Atan(helmertZ / (rootXYSqr * (1 - eSquared2)));
            v3 = a2 / (Math.Sqrt(1.0 - (eSquared2 * ((Math.Pow(Math.Sin(PHI1), 2))))));
            PHI2 = Math.Atan((helmertZ + (eSquared2 * v3 * (Math.Sin(PHI1)))) / rootXYSqr);
            while (Math.Abs(PHI1 - PHI2) > 0.000000001)
            {
                PHI1 = PHI2;
                v3 = a2 / (Math.Sqrt(1 - (eSquared2 * ((Math.Pow(Math.Sin(PHI1), 2))))));
                PHI2 = Math.Atan((helmertZ + (eSquared2 * v3 * (Math.Sin(PHI1)))) / rootXYSqr);
            }
            PHI = PHI2;
            finalLati = PHI * (180.0 / Math.PI);
            finalLongi = (Math.Atan(helmertY / helmertX)) * (180.0 / Math.PI);
            this.xcoord = finalLongi;
            this.ycoord = finalLati;
        }
    }


}




