Esempio n. 1
0
        /// <summary>
        /// Hydrology function used to add to the subbasin shapefile average slope attribute
        /// </summary>
        /// <param name="subBasinGridPath"></param>
        /// <param name="subBasinShapePath"></param>
        /// <param name="slopeGridPath"></param>
        /// <param name="elevUnits"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public static bool ApplyWatershedSlopeAttribute(string subBasinGridPath, string subBasinShapePath, string slopeGridPath, ElevationUnits elevUnits, IProgressHandler callback)
        {
            int sindx;
            int row;

            if (callback != null)
            {
                callback.Progress("Status", 0, "Calculating WS Slope Parameters");
            }

            var shedShape = FeatureSet.Open(subBasinShapePath);
            var subBasinGrid = Raster.Open(subBasinGridPath);
            var slopeGrid = Raster.Open(slopeGridPath);

            var numberRows = slopeGrid.NumRows;
            var numberCols = slopeGrid.NumColumns;
            var nodataVal = slopeGrid.NoDataValue;
            var slopeProj = slopeGrid.Projection;

            var countSlope = new int[shedShape.NumRows()];
            var sumSlope = new double[shedShape.NumRows()];
            var avgSlope = new double[shedShape.NumRows()];

            var currPolyIDIdx = -1;
            var currLinkIDIdx = -1;
            for (sindx = 0; sindx < shedShape.DataTable.Columns.Count; sindx++)
            {
                if (shedShape.DataTable.Columns[sindx].ColumnName == "PolygonID" || shedShape.DataTable.Columns[sindx].ColumnName == "MWShapeID")
                {
                    currPolyIDIdx = sindx;
                }

                if (shedShape.DataTable.Columns[sindx].ColumnName == "LinkIDs")
                {
                    currLinkIDIdx = sindx;
                }

                // Paul Meems, 24-Aug-2011: Added:
                if (currPolyIDIdx != -1 && currLinkIDIdx != -1)
                {
                    // Found the values so stop searching:
                    break;
                }
            }

            string tmpLinkIDs;
            var linkIDVals = new List<int>();
            var linkIDMerged = new List<int>();

            if (currLinkIDIdx != -1 && currPolyIDIdx != -1)
            {
                for (sindx = 0; sindx < shedShape.NumRows(); sindx++)
                {
                    tmpLinkIDs = shedShape.get_CellValue(currLinkIDIdx, sindx).ToString();
                    var tmpLinks = tmpLinkIDs.Split(',');
                    foreach (var tmpLink in tmpLinks)
                    {
                        linkIDMerged.Add(sindx);
                        linkIDVals.Add(int.Parse(tmpLink.Trim()));
                    }
                }
            }
            else
            {
                for (sindx = 0; sindx < shedShape.NumRows(); sindx++)
                {
                    linkIDMerged.Add(sindx);
                    linkIDVals.Add(int.Parse(shedShape.get_CellValue(currPolyIDIdx, sindx).ToString()));
                }
            }

            var oldperc = 0;
            for (row = 0; row < numberRows; row++)
            {
                var newperc = Convert.ToInt32((Convert.ToDouble(row) / Convert.ToDouble(numberRows - 1)) * 100);
                if (newperc > oldperc)
                {
                    if (callback != null)
                    {
                        callback.Progress("Status", newperc, "Calculating WS Slope Parameters");
                    }

                    oldperc = newperc;
                }

                int col;
                for (col = 0; col < numberCols; col++)
                {
                    var currVal = double.Parse(slopeGrid.Rows[col][row].ToString());

                    if (currVal == nodataVal)
                    {
                        continue;
                    }

                    var currBasinID = int.Parse(subBasinGrid.Rows[col][row].ToString());

                    // Paul Meems, 24-Aug-2011: Changed:
                    // if (currBasinID != -1)
                    // TODO: Check if the result is still the same
                    if (currBasinID > -1)
                    {
                        // Paul Meems, 24-Aug-2011: Added extra check:
                        var tmp = linkIDVals.IndexOf(currBasinID);
                        if (tmp != -1)
                        {
                            var currID = linkIDMerged[tmp];

                            countSlope[currID] = countSlope[currID] + 1;
                            sumSlope[currID] = sumSlope[currID] + currVal;
                        }
                    }
                }
            }

            slopeGrid.Close();

            if (callback != null)
            {
                callback.Progress("Status", 0, "Calculating WS Slope Parameters");
            }

            var slopeFieldNum = AddField(shedShape, "AveSlope", typeof(double));

            oldperc = 0;
            for (sindx = 0; sindx < shedShape.NumRows(); sindx++)
            {
                // TODO: Why > 1 instead of > 0?
                if (shedShape.NumRows() > 1)
                {
                    var newperc = Convert.ToInt32((Convert.ToDouble(sindx) / Convert.ToDouble(shedShape.NumRows())) * 100);
                    if (newperc > oldperc)
                    {
                        if (callback != null)
                        {
                            callback.Progress("Status", newperc, "Calculating WS Slope Parameters");
                        }

                        oldperc = newperc;
                    }
                }

                if (countSlope[sindx] <= 0)
                {
                    continue;
                }

                //if (!string.IsNullOrEmpty(slopeProj))
                //{
                if (slopeProj.Unit.Name == "Meter")
                {
                    switch (elevUnits)
                    {
                        case ElevationUnits.meters:
                            avgSlope[sindx] = (sumSlope[sindx] / countSlope[sindx]) * 100;
                            break;
                        case ElevationUnits.centimeters:
                            avgSlope[sindx] = sumSlope[sindx] / countSlope[sindx];
                            break;
                        case ElevationUnits.feet:
                            avgSlope[sindx] = ((sumSlope[sindx] / countSlope[sindx]) / 3.280839895) * 100;
                            break;
                    }
                }
                else if (slopeProj.Unit.Name == "Foot")
                {
                    switch (elevUnits)
                    {
                        case ElevationUnits.meters:
                            avgSlope[sindx] = ((sumSlope[sindx] / countSlope[sindx]) * 3.280839895) * 100;
                            break;
                        case ElevationUnits.centimeters:
                            avgSlope[sindx] = ((sumSlope[sindx] / countSlope[sindx]) / 30.48) * 100;
                            break;
                        case ElevationUnits.feet:
                            avgSlope[sindx] = (sumSlope[sindx] / countSlope[sindx]) * 100;
                            break;
                    }
                }
                //}
                //else
                //{
                //    switch (elevUnits)
                //    {
                //        case ElevationUnits.meters:
                //            avgSlope[sindx] = (sumSlope[sindx] / countSlope[sindx]) * 100;
                //            break;
                //        case ElevationUnits.centimeters:
                //            avgSlope[sindx] = sumSlope[sindx] / countSlope[sindx];
                //            break;
                //        case ElevationUnits.feet:
                //            avgSlope[sindx] = ((sumSlope[sindx] / countSlope[sindx]) / 3.280839895) * 100;
                //            break;
                //    }
                //}

                shedShape.EditCellValue(slopeFieldNum, sindx, avgSlope[sindx]);
            }

            shedShape.Save();
            shedShape.Close();

            subBasinGrid.Close();

            if (callback != null)
            {
                callback.Progress(string.Empty, 0, string.Empty);
            }

            return true;
        }
Esempio n. 2
0
        /// <summary>
        /// Hydrology function used to add to the subbasin shapefile average slope attribute
        /// </summary>
        /// <param name="subBasinShapePath"></param>
        /// <param name="slopeGridPath"></param>
        /// <param name="elevUnits"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public static bool ApplyWatershedSlopeAttribute(string subBasinShapePath, string slopeGridPath, ElevationUnits elevUnits, IProgressHandler callback)
        {
            // CWG 23/1/2011 changed to GeoTiff for Taudem V5
            var tmpClipPath = Path.Combine(
                Path.GetDirectoryName(slopeGridPath), Path.GetFileNameWithoutExtension(slopeGridPath) + "_clip.tif");

            //DataManagement.DeleteGrid(tmpClipPath);

            if (callback != null)
            {
                callback.Progress("Status", 0, "Calculating WS Slope Parameters");
            }

            var shedShape = FeatureSet.Open(subBasinShapePath);

            var slopeGrid = Raster.Open(slopeGridPath);
            var slopeProj = slopeGrid.Projection;
            slopeGrid.Close();

            var countSlope = new int[shedShape.NumRows()];
            var sumSlope = new double[shedShape.NumRows()];
            var avgSlope = new double[shedShape.NumRows()];

            var oldperc = 0;
            for (var sindx = 0; sindx < shedShape.NumRows(); sindx++)
            {
                if (shedShape.NumRows() > 1)
                {
                    var newperc = Convert.ToInt32((Convert.ToDouble(sindx) / Convert.ToDouble(shedShape.NumRows() - 1)) * 100);
                    if (newperc > oldperc)
                    {
                        if (callback != null)
                        {
                            callback.Progress("Status", newperc, "Calculating WS Slope Parameters");
                        }

                        oldperc = newperc;
                    }
                }
                var tmpPoly = shedShape.get_Shape(sindx);

                if (ClipRaster.ClipRasterWithPolygon(slopeGridPath, tmpPoly, tmpClipPath) != null)
                {
                    continue;
                }

                var tmpClipGrid = Raster.Open(tmpClipPath);

                var numberRows = tmpClipGrid.NumRows;
                var numberCols = tmpClipGrid.NumColumns;
                var nodataVal = tmpClipGrid.NoDataValue;
                countSlope[sindx] = 0;
                sumSlope[sindx] = 0;
                avgSlope[sindx] = 0;
                int row;
                for (row = 0; row < numberRows; row += 2)
                {
                    int col;
                    for (col = 0; col < numberCols; col += 2)
                    {
                        var currVal = double.Parse(tmpClipGrid.Rows[col][row].ToString());
                        if (currVal == nodataVal)
                        {
                            continue;
                        }

                        countSlope[sindx] = countSlope[sindx] + 1;
                        sumSlope[sindx] = sumSlope[sindx] + currVal;
                    }
                }

                tmpClipGrid.Close();

                //DataManagement.DeleteGrid(tmpClipPath);
            }

            if (callback != null)
            {
                callback.Progress("Status", 0, "Calculating WS Slope Parameters");
            }

            var slopeFieldNum = AddField(shedShape, "AveSlope", typeof(double));

            oldperc = 0;
            for (var sindx = 0; sindx < shedShape.NumRows(); sindx++)
            {
                if (shedShape.NumRows() > 1)
                {
                    var newperc = Convert.ToInt32((Convert.ToDouble(sindx) / Convert.ToDouble(shedShape.NumRows())) * 100);
                    if (newperc > oldperc)
                    {
                        if (callback != null)
                        {
                            callback.Progress("Status", newperc, "Calculating WS Slope Parameters");
                        }

                        oldperc = newperc;
                    }
                }

                if (countSlope[sindx] <= 0)
                {
                    continue;
                }

                //if (!string.IsNullOrEmpty(slopeProj))
                //{
                if (slopeProj.Unit.Name == "Meter")
                {
                    switch (elevUnits)
                    {
                        case ElevationUnits.meters:
                            avgSlope[sindx] = (sumSlope[sindx] / countSlope[sindx]) * 100;
                            break;
                        case ElevationUnits.centimeters:
                            avgSlope[sindx] = sumSlope[sindx] / countSlope[sindx];
                            break;
                        case ElevationUnits.feet:
                            avgSlope[sindx] = ((sumSlope[sindx] / countSlope[sindx]) / 3.280839895) * 100;
                            break;
                    }
                }
                else if (slopeProj.Unit.Name == "Foot")
                {
                    switch (elevUnits)
                    {
                        case ElevationUnits.meters:
                            avgSlope[sindx] = ((sumSlope[sindx] / countSlope[sindx]) * 3.280839895) * 100;
                            break;
                        case ElevationUnits.centimeters:
                            avgSlope[sindx] = ((sumSlope[sindx] / countSlope[sindx]) / 30.48) * 100;
                            break;
                        case ElevationUnits.feet:
                            avgSlope[sindx] = (sumSlope[sindx] / countSlope[sindx]) * 100;
                            break;
                    }
                }
                //}
                //else
                //{
                //    switch (elevUnits)
                //    {
                //        case ElevationUnits.meters:
                //            avgSlope[sindx] = (sumSlope[sindx] / countSlope[sindx]) * 100;
                //            break;
                //        case ElevationUnits.centimeters:
                //            avgSlope[sindx] = sumSlope[sindx] / countSlope[sindx];
                //            break;
                //        case ElevationUnits.feet:
                //            avgSlope[sindx] = ((sumSlope[sindx] / countSlope[sindx]) / 3.280839895) * 100;
                //            break;
                //    }
                //}

                shedShape.EditCellValue(slopeFieldNum, sindx, avgSlope[sindx]);
            }

            shedShape.Save();
            shedShape.Close();

            if (callback != null)
            {
                callback.Progress(string.Empty, 0, string.Empty);
            }

            return true;
        }
Esempio n. 3
0
        //        /// <summary>
        //        /// A function to generation only the path length grids using taudem GridNet
        //        /// </summary>
        //        /// <param name="D8Path"></param>
        //        /// <param name="StrahlOrdResultPath"></param>
        //        /// <param name="LongestUpslopeResultPath"></param>
        //        /// <param name="TotalUpslopeResultPath"></param>
        //        /// <param name="numProcesses">Number of threads to be used by Taudem</param>
        //        /// <param name="showTaudemOutput">Show Taudem output if true</param>
        //        /// <param name="callback"></param>
        //        /// <returns></returns>
        //        public static int PathLength(string D8Path, string StrahlOrdResultPath, string LongestUpslopeResultPath, string TotalUpslopeResultPath, int numProcesses, bool showTaudemOutput, IProgressHandler callback)
        //        {
        //           Trace.WriteLine("PathLength: " + D8Path + "\n" +
        //                                     "strahlOrdResultPath: " + StrahlOrdResultPath + "\n" +
        //                                     "longestUpslopeResultPath: " + LongestUpslopeResultPath + "\n" +
        //                                     "totalUpslopeResultPath: " + TotalUpslopeResultPath + "\n" +
        //                                     "NumProcesses: " + numProcesses.ToString() + "\n" +
        //                                     "ShowTaudemOutput: " + showTaudemOutput.ToString() + "\n" +
        //                                     "callback)");
        //            int result = -1;
        //            string pars =
        //                "-p " + Quote(D8Path) +
        //                " -plen " + Quote(LongestUpslopeResultPath) +
        //                " -tlen " + Quote(TotalUpslopeResultPath) +
        //                " -gord " + Quote(StrahlOrdResultPath);
        //            result = RunTaudem("GridNet.exe", pars, numProcesses, showTaudemOutput);

        //            if (result != 0)
        //            {
        //                MessageBox.Show("TauDEM Error " + result, "TauDEM Error " + result, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.DialogResult.OK);

        //                return result;
        //            }

        //            CopyProjectionFromGrid(D8Path, StrahlOrdResultPath);
        //            CopyProjectionFromGrid(D8Path, LongestUpslopeResultPath);
        //            CopyProjectionFromGrid(D8Path, TotalUpslopeResultPath);
        //            if (callback != null) callback.Progress("Status", 0, String.Empty);
        //            return result;
        //        }

        //        #region "     Grid Net conversion"

        //        private static int GridNet(string pfile, string plenfile, string tlenfile, string gordfile, string afile, double[] x, double[] y, long nxy, int useMask, int useOutlets, int thresh, IProgressHandler callback)
        //        {
        //            int row, col;
        //            double dx, dy, nx, ny;
        //            int err = 0;
        //            int[] d1 = new int[9];
        //            int[] d2 = new int[9];
        //            double[] dist = new double[9];

        //            /* define directions */
        //            d1[1] = 0; d1[2] = -1; d1[3] = -1; d1[4] = -1; d1[5] = 0; d1[6] = 1; d1[7] = 1; d1[8] = 1;
        //            d2[1] = 1; d2[2] = 1; d2[3] = 0; d2[4] = -1; d2[5] = -1; d2[6] = -1; d2[7] = 0; d2[8] = 1;

        //            Raster sdir = new Raster();
        //            if (sdir.Open(pfile, RasterDataType.UnknownDataType, true, RasterFileType.UseExtension, null))
        //            {
        //                err = 0;
        //            }
        //            else
        //            {
        //                err = 1; //TD_FAILED_GRID_OPEN
        //            }
        //            if (err != 0) return err;
        //            dx = sdir.Header.dX;
        //            dy = sdir.Header.dY;
        //            nx = sdir.NumColumns;
        //            ny = sdir.NumRows;

        //            Raster laag = new Raster();
        //            if (useMask == 1)
        //            {
        //                /*   read mask  */
        //                if (laag.Open(afile, RasterDataType.UnknownDataType, true, RasterFileType.UseExtension, null))
        //                {
        //                    err = 0;
        //                }
        //                else
        //                {
        //                    err = 1; //TD_FAILED_GRID_OPEN
        //                }
        //                if (err != 0) return err;
        //            }
        //            else
        //            {
        //                RasterHeader laagHead = new RasterHeader();
        //                laagHead.CopyFrom(sdir.Header);
        //                laag.CreateNew(afile, laagHead, RasterDataType.LongDataType, 0, true, RasterFileType.UseExtension, null);
        //            }

        //            RasterHeader sordgHead = new RasterHeader();
        //            sordgHead.CopyFrom(sdir.Header);
        //            sordgHead.NodataValue = -1;
        //            Raster sordg = new Raster();
        //            sordg.CreateNew(gordfile, sordgHead, RasterDataType.ShortDataType, sordgHead.NodataValue, true, RasterFileType.UseExtension, null);

        //            RasterHeader fltpgHead = new RasterHeader();
        //            fltpgHead.CopyFrom(sdir.Header);
        //            fltpgHead.NodataValue = -1;
        //            Raster fltpg = new Raster();
        //            fltpg.CreateNew(tlenfile, fltpgHead, RasterDataType.FloatDataType, fltpgHead.NodataValue, true, RasterFileType.UseExtension, null);

        //            RasterHeader flengHead = new RasterHeader();
        //            flengHead.CopyFrom(sdir.Header);
        //            flengHead.NodataValue = -1;
        //            Raster fleng = new Raster();
        //            fleng.CreateNew(plenfile, flengHead, RasterDataType.FloatDataType, flengHead.NodataValue, true, RasterFileType.UseExtension, null);

        //            /*  Calculate Distances  */
        //            for (int i = 1; i <= 8; i++)
        //            {
        //                dist[i] = Math.Sqrt(d1[i] * d1[i] * dy * dy + d2[i] * d2[i] * dx * dx);
        //            }

        //            if (useOutlets == 1)  /*  Only compute area's for designated locations  */
        //            {
        //                for (int curXY = 0; curXY < nxy; curXY++)
        //                {
        //                    sdir.ProjToCell(x[curXY], y[curXY], out col, out row);
        //                    if (row < 0 || row > ny || col < 0 || col > nx)
        //                    {
        //                        row = 0; col = 0;
        //                    }
        //                    d2area(row, col, nx, ny, d1, d2, dist, thresh, sdir, laag, sordg, fltpg, fleng);
        //                }
        //            }
        //            else
        //            {
        //                for (int i = 0; i < ny; i++)
        //                    for (int j = 0; j < nx; j++)
        //                        d2area(i, j, nx, ny, d1, d2, dist, thresh, sdir, laag, sordg, fltpg, fleng);
        //            }

        //            if (fleng.Save(plenfile, RasterFileType.UseExtension, null))
        //            {
        //                err = 0;
        //            }
        //            else
        //            {
        //                err = 2; //TD_FAILED_GRID_SAVE
        //                return err;
        //            }

        //            if (fltpg.Save(tlenfile, RasterFileType.UseExtension, null))
        //            {
        //                err = 0;
        //            }
        //            else
        //            {
        //                err = 2; //TD_FAILED_GRID_SAVE
        //                return err;
        //            }

        //            if (sordg.Save(gordfile, RasterFileType.UseExtension, null))
        //            {
        //                err = 0;
        //            }
        //            else
        //            {
        //                err = 2; //TD_FAILED_GRID_SAVE
        //                return err;
        //            }

        //            sordg.Close();
        //            laag.Close();
        //            fltpg.Close();
        //            fleng.Close();

        //            return err;
        //        }

        //        private static void d2area(int i, int j, double nx, double ny, int[] d1, int[] d2, double[] dist, int thresh, Raster sdir, Raster laag, Raster sordg, Raster fltpg, Raster fleng)
        //        {
        //            int ni, nj;
        //            short a1, a2;
        //            double ld;

        //            if ((short)sordg.get_Value(j, i) <= 0)
        //            {
        //                if (i != 0 && i != ny - 1 && j != nx - 1 && (short)sdir.get_Value(j, i) != -32767)
        //                {
        //                    sordg.set_Value(j, i, 1);
        //                    fltpg.set_Value(j, i, 0);
        //                    fleng.set_Value(j, i, 0);
        //                    a1 = 0;
        //                    a2 = 0;

        //                    for (int k = 1; k <= 8; k++)
        //                    {
        //                        ni = i + d1[k];
        //                        nj = j + d2[k];

        //                        /* test if neighbor drains towards cell excluding boundaries */
        //                        if ((short)sdir.get_Value(nj, ni) >= 0)
        //                        {
        //                            if ((int)laag.get_Value(nj, ni) >= thresh && ((short)sdir.get_Value(nj, ni) - k == 4 || (short)sdir.get_Value(nj, ni) - k == -4))
        //                            {
        //                                d2area(ni, nj, nx, ny, d1, d2, dist, thresh, sdir, laag, sordg, fltpg, fleng);
        //                                if ((short)sordg.get_Value(nj, ni) >= a1)
        //                                {
        //                                    a2 = a1;
        //                                    a1 = (short)sordg.get_Value(nj, ni);
        //                                }
        //                                else if ((short)sordg.get_Value(nj, ni) > a2)
        //                                {
        //                                    a2 = (short)sordg.get_Value(nj, ni);
        //                                }

        //                                ld = (float)fleng.get_Value(nj, ni) + dist[(short)sdir.get_Value(nj, ni)];
        //                                fltpg.set_Value(j, i, (float)fltpg.get_Value(j, i) + (float)fltpg.get_Value(nj, ni) + dist[(short)sdir.get_Value(nj, ni)]);
        //                                if (ld > (float)fleng.get_Value(j, i))
        //                                {
        //                                    fleng.set_Value(j, i, ld);
        //                                }
        //                            }
        //                        }
        //                    }
        //                    if (a2 + 1 > a1)
        //                    {
        //                        sordg.set_Value(j, i, a2 + 1);
        //                    }
        //                    else
        //                    {
        //                        sordg.set_Value(j, i, a1);
        //                    }
        //                }
        //            }
        //        }

        //        #endregion //GridNet conversion

        //        #region "     Source Def conversion"

        //        private static int SourceDef(string areafile, string slopefile, string plenfile, string dirfile, string srcfile, string elvfile, string gordfile, string scafile, string fdrfile, int ipar, float[] p, int nxy, double[] x, double[] y, int contcheck, int dropan, int masksca, IProgressHandler callback)
        //        {
        //            int err = 0;

        //            //    float ndvs,ndvp,ndvd,emax,ndve,ndvo,wsum,val;

        //            //    float **selev ;

        //            //    /**********Grid Declarations*************/
        //            //    fgrid faagrid;
        //            //    fgrid fplengrid;
        //            //    sgrid sgordgrid;
        //            //    //=============================
        //            //    int row, col, i,j,iomax,jomax,bound,ik,jk,k,itresh;
        //            //    err = TD_NO_ERROR;
        //            //    int rcgood=1;
        //            //    ccheck=contcheck;

        //            //    /* define directions */
        //            //    d1[1]=0; d1[2]= -1; d1[3]= -1; d1[4]= -1; d1[5]=0; d1[6]=1; d1[7]=1; d1[8]=1;
        //            //    d2[1]=1; d2[2]=1; d2[3]=0; d2[4]= -1; d2[5]= -1; d2[6]= -1; d2[7]=0; d2[8]=1;

        //            //    /* read grid files */
        //            //    if(ipar == 1)
        //            //    {
        //            //        if(gridread(areafile,&faagrid,&filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //        {
        //            //            err=TD_FAILED_GRID_OPEN;
        //            //        }

        //            //        nx = faagrid.head.nx;
        //            //        ny = faagrid.head.ny;
        //            //        dx = faagrid.head.dx;
        //            //        dy = faagrid.head.dy;
        //            //        csize = dx;
        //            //        ndva = faagrid.nodata;
        //            //        for(i=0;i<4;i++) bndbox[i]=faagrid.head.bndbox[i];

        //            //        if(err != TD_NO_ERROR)goto ERROR1;
        //            //    }

        //            //    if(ipar == 2)
        //            //    {
        //            //        if ( gridread(scafile,&faagrid,&filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //            err=TD_FAILED_GRID_OPEN;

        //            //        nx =faagrid.head.nx;
        //            //        ny = faagrid.head.ny;
        //            //        dx = faagrid.head.dx;
        //            //        dy = faagrid.head.dy;
        //            //        csize = dx;
        //            //        ndva = faagrid.nodata;
        //            //        for(i=0;i<4;i++) bndbox[i]=faagrid.head.bndbox[i];

        //            //        if(err != TD_NO_ERROR)goto ERROR1;

        //            //        if ( gridread(slopefile,&fslopeg,&filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //            err=TD_FAILED_GRID_OPEN;

        //            //        ndvs = fslopeg.nodata;

        //            //        if(err != TD_NO_ERROR)goto ERROR1;
        //            //    }
        //            //    if(ipar == 3)
        //            //    {
        //            //        if ( gridread(scafile,&faagrid,&filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //            err=TD_FAILED_GRID_OPEN;

        //            //        nx = faagrid.head.nx;
        //            //        ny = faagrid.head.ny;
        //            //        dx = faagrid.head.dx;
        //            //        dy = faagrid.head.dy;
        //            //        csize = dx;
        //            //        ndva = faagrid.nodata;
        //            //        for(i=0;i<4;i++) bndbox[i]=faagrid.head.bndbox[i];

        //            //        if(err != TD_NO_ERROR)goto ERROR1;

        //            //        if ( gridread(plenfile,&fplengrid,&filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //            err=TD_FAILED_GRID_OPEN;

        //            //        ndvp = fplengrid.nodata;

        //            //        if(err != TD_NO_ERROR)goto ERROR1;
        //            //    }
        //            //    if(ipar == 4)
        //            //    {
        //            //        if( gridread(elvfile,&felevg,&filetype)==0)

        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //            err=TD_FAILED_GRID_OPEN;

        //            //        nx = felevg.head.nx;
        //            //        ny = felevg.head.ny;
        //            //        dx = felevg.head.dx;
        //            //        dy = felevg.head.dy;
        //            //        csize = dx;
        //            //        ndve = felevg.nodata;
        //            //        for(i=0;i<4;i++) bndbox[i]=felevg.head.bndbox[i];

        //            //        if(err != TD_NO_ERROR)goto ERROR1;
        //            //    }
        //            //    if(ipar == 5)
        //            //    {
        //            //        if ( gridread(gordfile,&sgordgrid,&filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //            err=TD_FAILED_GRID_OPEN;

        //            //        nx = sgordgrid.head.nx;
        //            //        ny = sgordgrid.head.ny;
        //            //        dx = sgordgrid.head.dx;
        //            //        dy = sgordgrid.head.dy;
        //            //        csize = dx;
        //            //        ndvo = sgordgrid.nodata;
        //            //        for(i=0;i<4;i++)bndbox[i]=sgordgrid.head.bndbox[i];

        //            //        if(err != TD_NO_ERROR)goto ERROR1;
        //            //    }
        //            //    if(ipar == 6)
        //            //    {
        //            //        if (gridread(fdrfile,&sgordgrid,&filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //            err=TD_FAILED_GRID_OPEN;

        //            //        nx = sgordgrid.head.nx;
        //            //        ny = sgordgrid.head.ny;
        //            //        dx = sgordgrid.head.dx;
        //            //        dy = sgordgrid.head.dy;
        //            //        csize = dx;
        //            //        ndvo = sgordgrid.nodata;
        //            //        for(i=0;i<4;i++)bndbox[i]=sgordgrid.head.bndbox[i];

        //            //        if(err != TD_NO_ERROR)goto ERROR1;
        //            //    }

        //            //    if((src = (short **)matalloc(nx,ny, RPSHRDTYPE)) == NULL)
        //            //    {
        //            //        err=TD_FAILED_MEMORY_ALLOC;
        //            //        //  printf("Could not allocate memory for src\n");
        //            //        goto ERROR1;
        //            //    }

        //            //    /*  Flag sources  */
        //            //    for(i=0; i < ny; i++)
        //            //        for(j=0; j< nx; j++)
        //            //        {
        //            //            src[j][i] = 0;
        //            //            if(ipar == 1)   /*  Area threshold   */
        //            //            {
        //            //                src[j][i] = (faagrid.d[j][i] >= p[0]) ? 1 : 0;
        //            //            }
        //            //            else if(ipar == 2)   /*  Slope and area combination   */
        //            //            {
        //            //                if( fslopeg.d[j][i] > 0.)
        //            //                {
        //            //                    val = (faagrid.d[j][i] * pow((double)fslopeg.d[j][i],(double)p[1])) ;
        //            //                    src[j][i] = (val >= p[0])	  ? 1: 0;
        //            //                }
        //            //            }else if(ipar == 3)  /*  Slope and Length combination   */
        //            //            {
        //            //                if(fplengrid.d[j][i] > 0.)
        //            //                {
        //            //                    src[j][i] = (faagrid.d[j][i] >= p[0]* pow((double)fplengrid.d[j][i],(double)p[1]))
        //            //                        ? 1: 0;
        //            //                }
        //            //            }
        //            //            else if(ipar == 5)  /*  Grid order threshold  */
        //            //                src[j][i] = (sgordgrid.d[j][i] >= p[0]) ? 1: 0;
        //            //            else if(ipar == 6)  /*  Given flow directions threshold  */
        //            //                src[j][i] = (sgordgrid.d[j][i] > 0) ? 1: 0;
        //            //        }
        //            //        if(ipar == 4)  /* Peuker and Douglas algorithm  */
        //            //        {
        //            //            /*  Initialize internal cells to 1 for Peuker and Douglas algorithm and smooth  */
        //            //            if((selev = (float **)matalloc(nx,ny, RPFLTDTYPE)) == NULL)
        //            //            {
        //            //                err=TD_FAILED_MEMORY_ALLOC;
        //            //                //  printf("Could not allocate memory for selev\n");
        //            //                goto ERROR1;
        //            //            }
        //            //            for(i=0; i <ny; i++)
        //            //                for(j=0; j<nx; j++)
        //            //                {
        //            //                    if (ndve > 0) //ARA 10/17/05 Fixed for possible positive nodata
        //            //              {
        //            //                  if(i == 0 || i == (ny-1) || j == 0 || j == (nx-1) || felevg.d[j][i] >= ndve)
        //            //                  {
        //            //                      selev[j][i]=felevg.d[j][i];
        //            //                  }
        //            //                  else
        //            //                  {
        //            //                      src[j][i] = 1;
        //            //                      selev[j][i]=p[1] * felevg.d[j][i];
        //            //                      wsum=p[1];
        //            //                      if(p[2] > 0.)
        //            //                          for(k=1; k<=7; k=k+2)
        //            //                          {
        //            //                              if(felevg.d[j+d2[k]][i+d1[k]] < ndve)
        //            //                              {
        //            //                                  selev[j][i] += felevg.d[j+d2[k]][i+d1[k]] *p[2];
        //            //                                  wsum += p[2];
        //            //                              }
        //            //                          }
        //            //                          if(p[3] > 0.)
        //            //                              for(k=2; k<=8; k=k+2)
        //            //                              {
        //            //                                  if(felevg.d[j+d2[k]][i+d1[k]] < ndve)
        //            //                                  {
        //            //                                      selev[j][i] += felevg.d[j+d2[k]][i+d1[k]] *p[3];
        //            //                                      wsum += p[3];
        //            //                                  }
        //            //                              }
        //            //                  }
        //            //              }
        //            //                    else
        //            //              {
        //            //                  if(i == 0 || i == (ny-1) || j == 0 || j == (nx-1) || felevg.d[j][i] <= ndve)
        //            //                  {
        //            //                      selev[j][i]=felevg.d[j][i];
        //            //                  }
        //            //                  else
        //            //                  {
        //            //                      src[j][i] = 1;
        //            //                      selev[j][i]=p[1] * felevg.d[j][i];
        //            //                      wsum=p[1];
        //            //                      if(p[2] > 0.)
        //            //                          for(k=1; k<=7; k=k+2)
        //            //                          {
        //            //                              if(felevg.d[j+d2[k]][i+d1[k]] > ndve)
        //            //                              {
        //            //                                  selev[j][i] += felevg.d[j+d2[k]][i+d1[k]] *p[2];
        //            //                                  wsum += p[2];
        //            //                              }
        //            //                          }
        //            //                          if(p[3] > 0.)
        //            //                              for(k=2; k<=8; k=k+2)
        //            //                              {
        //            //                                  if(felevg.d[j+d2[k]][i+d1[k]] > ndve)
        //            //                                  {
        //            //                                      selev[j][i] += felevg.d[j+d2[k]][i+d1[k]] *p[3];
        //            //                                      wsum += p[3];
        //            //                                  }
        //            //                              }
        //            //                  }
        //            //              }

        //            //                    if(i == 0 || i == (ny-1) || j == 0 || j == (nx-1) || felevg.d[j][i] <= ndve)
        //            //              {
        //            //                  selev[j][i]=felevg.d[j][i];
        //            //              }
        //            //                    else
        //            //              {
        //            //                  src[j][i] = 1;
        //            //                  selev[j][i]=p[1] * felevg.d[j][i];
        //            //                  wsum=p[1];
        //            //                  if(p[2] > 0.)
        //            //                      for(k=1; k<=7; k=k+2)
        //            //                      {
        //            //                          if(felevg.d[j+d2[k]][i+d1[k]] > ndve)
        //            //                          {
        //            //                              selev[j][i] += felevg.d[j+d2[k]][i+d1[k]] *p[2];
        //            //                              wsum += p[2];
        //            //                          }
        //            //                      }
        //            //                      if(p[3] > 0.)
        //            //                          for(k=2; k<=8; k=k+2)
        //            //                          {
        //            //                              if(felevg.d[j+d2[k]][i+d1[k]] > ndve)
        //            //                              {
        //            //                                  selev[j][i] += felevg.d[j+d2[k]][i+d1[k]] *p[3];
        //            //                                  wsum += p[3];
        //            //                              }
        //            //                          }
        //            //              }
        //            //                }

        //            //                for (int curcol = 0; curcol < nx; curcol++)
        //            //                    for (int currow = 0; currow < ny; currow++)

        //            //                        felevg.d[curcol][currow]=selev[curcol][currow];

        //            //                for(i=0; i <ny-1; i++)
        //            //                    for(j=0; j<nx-1; j++)
        //            //                    {
        //            //                        emax= felevg.d[j][i];
        //            //                        iomax=0;
        //            //                        jomax=0;
        //            //                        bound= 0;  /*  .false.  */
        //            //                        /*  --FIRST PASS FLAG MAX ELEVATION IN GROUP OF FOUR  */
        //            //                        for(ik=0; ik<2; ik++)
        //            //                            for(jk=1-ik; jk < 2; jk++)
        //            //                            {
        //            //                                if(felevg.d[j+jk][i+ik] > emax)
        //            //                                {
        //            //                                    emax=felevg.d[j+jk][i+ik];
        //            //                                    iomax=ik;
        //            //                                    jomax=jk;
        //            //                                }
        //            //                                if( felevg.d[j+jk][i+ik] <= ndve)
        //            //                                    bound= 1;  /*  .true.  */
        //            //                            }
        //            //                            /*  c---Unflag max pixel */
        //            //                            src[j+jomax][i+iomax] = 0;
        //            //                            /*  c---Unflag pixels where the group of 4 touches a boundary  */
        //            //                            if(bound == 1)
        //            //                            {
        //            //                                for(ik=0; ik < 2; ik++)
        //            //                                    for(jk=0; jk< 2; jk++)
        //            //                                    {
        //            //                                        src[j+jk][i+ik]=0;
        //            //                                    }
        //            //                            }
        //            //                            /* 		  i.e. unflag flats.  */
        //            //                            for(ik=0; ik < 2; ik++)
        //            //                                for(jk=0; jk< 2; jk++)
        //            //                                {
        //            //                                    if(felevg.d[j+jk][i+ik] == emax)src[j+jk][i+ik] = 0;
        //            //                                }
        //            //                    }
        //            //        }

        //            //        if(ipar == 2){
        //            //            free(fslopeg.d[0]); free(fslopeg.d);
        //            //            free(faagrid.d[0]); free(faagrid.d);
        //            //        }
        //            //        if(ipar == 3){
        //            //            free(fplengrid.d[0]); free(fplengrid.d);
        //            //            free(faagrid.d[0]); free(faagrid.d);
        //            //        }
        //            //        if(ipar == 4){
        //            //            free(felevg.d[0]); free(felevg.d);
        //            //        }
        //            //        if(ipar == 5 || ipar == 6){
        //            //            free(sgordgrid.d[0]); free(sgordgrid.d);
        //            //        }

        //            //        /*  Now get directions and compute area's  */

        //            //        if ( gridread(dirfile,&sdir,&filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //            err=TD_FAILED_GRID_OPEN;

        //            //        ndvd = sdir.nodata;

        //            //        if(err != TD_NO_ERROR)goto ERROR1;

        //            //        //allocate memory and headers for larr
        //            //        larr.head.dx=dx;
        //            //        larr.head.dy=dy;
        //            //        larr.head.nx=nx;
        //            //        larr.head.ny=ny;
        //            //        larr.nodata=-2;
        //            //        for(i=0;i<4;i++) larr.head.bndbox[i]=bndbox[i];

        //            //        larr.nodata = -2;
        //            //        allocategrid(&larr,larr.head,larr.nodata);

        //            //        nout=0;
        //            //        itresh=1;
        //            //        if(ipar == 4)itresh = p[0];
        //            //        err=TD_CHANNEL_NETWORK_MISMATCH;   //This flag will indicate no outlet found  12/15/02  DGT moved to outside the if block
        //            //        // so that code works for at least one outlet found
        //            //        if(nxy >0)
        //            //        {
        //            //            for(i=0; i<nxy; i++)
        //            //            {
        //            //                col= (int)floor((x[i]-bndbox[0])/csize);
        //            //                row= (int)floor((bndbox[3]-y[i])/csize);
        //            //                if(row >0 && row < ny-1 && col > 0 && col < nx-1
        //            //                    && sdir.d[col][row]>0)  // DGT* this condition added 12/15/02 to not do outlets outside the domain
        //            //                {
        //            //                    /* call drainage area subroutine for pixel to zero on  */
        //            //                    srcarea(row,col);

        //            //                    if(larr.d[col][row] >= itresh)err=TD_NO_ERROR;  // an outlet found so no error
        //            //                }
        //            //            }
        //            //            if(err==TD_CHANNEL_NETWORK_MISMATCH)goto ERROR9;  //  no outlet error
        //            //        }
        //            //        else
        //            //        {
        //            //            //  Do all pixels
        //            //            for(i=1; i < ny-1; i++)
        //            //                for(j=1; j<nx-1; j++)srcarea(i,j);
        //            //            rcgood=0;  // no outlet coordinates found
        //            //        }

        //            //        //  Now threshold the src file
        //            //        if(dropan == 0)
        //            //        {
        //            //            for(i=1; i < ny-1; i++)
        //            //                for(j=1; j<nx-1; j++)
        //            //                {
        //            //                    if(larr.d[j][i] >= itresh && sdir.d[j][i]>0) larr.d[j][i]=1;
        //            //                    //  8/13/04  DGT added condition on sdir.d
        //            //                    else larr.d[j][i]=0;
        //            //                }
        //            //        }
        //            //        if(dropan == 1 && ipar == 1)  // overwrite accumulated source area with actual area
        //            //        {
        //            //            for(i=1; i < ny-1; i++)
        //            //                for(j=1; j<nx-1; j++)
        //            //                {
        //            //                    if(larr.d[j][i] >= itresh && sdir.d[j][i]>0)larr.d[j][i]=faagrid.d[j][i];
        //            //                    //  8/13/04  DGT added condition on sdir.d
        //            //                    else larr.d[j][i]=0;
        //            //                }
        //            //        }
        //            //        //free memory for sdir
        //            //        free(sdir.d[0]);free(sdir.d);

        //            //        if(ipar <= 3){free(faagrid.d[0]);free(faagrid.d);}  // Moved from below so that could reopen with sca file for sure
        //            //        // Exclude area with specific catchment area no data
        //            //        if(masksca == 1)
        //            //        {
        //            //            if(gridread(scafile,&faagrid,&filetype)==0)
        //            //                err=TD_NO_ERROR;
        //            //            else
        //            //            {
        //            //                err=TD_FAILED_GRID_OPEN;
        //            //                return err;
        //            //                //	AfxMessageBox( LPCTSTR(strcat( "Failed to open sca file for masking: ", scafile) ));
        //            //            }
        //            //            if(err != TD_NO_ERROR)goto ERROR9;
        //            //            for(i=1; i < ny-1; i++)
        //            //                for(j=1; j<nx-1; j++)
        //            //                {
        //            //                    if(faagrid.d[j][i] < 0)larr.d[j][i]=0;
        //            //                }
        //            //        }

        //            //        if ( gridwrite(srcfile,larr,filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else{
        //            //            err=TD_FAILED_GRID_SAVE;
        //            //            //if (srcfile)
        //            //            //	AfxMessageBox( LPCTSTR(strcat( "Failed to save file: ", srcfile) ));
        //            //        }

        //            //        free(src[0]); free(src);
        //            //        free(larr.d[0]); free(larr.d);
        //            //        return(err);
        //            //ERROR9:
        //            //        free(src[0]); free(src);
        //            //        //Kiran added the following statement to clean up.
        //            //        free(larr.d[0]); free(larr.d);
        //            //        if(faagrid.d != NULL) free(faagrid.d[0]); free(faagrid.d);
        //            //        if(sdir.d[0] != NULL) free(sdir.d[0]); free(sdir.d);
        //            //        return(err);

        //            //ERROR1:
        //            //        free(src[0]); free(src);
        //            //        free(larr.d[0]); free(larr.d);
        //            //        return(err);

        //            return err;
        //        }

        //        #endregion 'Sourcedef conversion

        //        #region "     Netsetup conversion"
        //        private static int NetSetup(string fnprefix, string pfile, string srcfile, string ordfile, string ad8file, string elevfile, string treefile, string coordfile, double[] xnode, double[] ynode, int nxy, long usetrace, int[] idnodes, IProgressHandler callback)
        //        {
        //            int err = 0;
        //            int itresh, icr, icend;

        //            /* define directions */
        //            int[] d1 = new int[9];
        //            int[] d2 = new int[9];
        //            d1[1] = 0; d1[2] = -1; d1[3] = -1; d1[4] = -1; d1[5] = 0; d1[6] = 1; d1[7] = 1; d1[8] = 1;
        //            d2[1] = 1; d2[2] = 1; d2[3] = 0; d2[4] = -1; d2[5] = -1; d2[6] = -1; d2[7] = 0; d2[8] = 1;

        //            itresh = 1;  // Thresholding to 1 done in source

        //            /*read dirfile   */
        //            Raster dirg = new Raster();
        //            if (dirg.Open(pfile, RasterDataType.UnknownDataType, true, RasterFileType.UseExtension, null))
        //            {
        //                err = 0;
        //            }
        //            else
        //            {
        //                err = 1; //TD_FAILED_GRID_OPEN
        //                return err;
        //            }

        //            double dx = dirg.Header.dX;
        //            double dy = dirg.Header.dY;
        //            int ny = dirg.NumRows;
        //            int nx = dirg.NumColumns;
        //            double[] bndbox = new double[4];
        //            bndbox[0] = dirg.Header.XllCenter - dx / 2;
        //            bndbox[1] = dirg.Header.YllCenter - dy / 2;
        //            bndbox[2] = dirg.Header.XllCenter + dx * nx - dx / 2;
        //            bndbox[3] = dirg.Header.YllCenter + dy * ny - dy / 2;

        //            float[] tmpRow;
        //            short[,] dir = new short[ny, nx];
        //            for (int i = 0; i < ny; i++)
        //            {
        //                tmpRow = new float[nx];
        //                dirg.GetRow(i, tmpRow[0]);
        //                for (int j = 0; j < nx; j++)
        //                {
        //                    dir[i, j] = Convert.ToInt16(tmpRow[j]);
        //                }
        //            }

        //            /*read srcfile   */
        //            Raster area = new Raster();
        //            if (area.Open(srcfile, RasterDataType.UnknownDataType, true, RasterFileType.UseExtension, null))
        //            {
        //                err = 0;
        //            }
        //            else
        //            {
        //                err = 1; //TD_FAILED_GRID_OPEN
        //                dirg.Close();
        //                return err;
        //            }
        //            if (area.NumColumns != nx || area.NumRows != ny)
        //            {
        //                err = 27; //TD_GRID_SIZE_MISMATCH
        //                dirg.Close();
        //                area.Close();
        //                return 1;
        //            }

        //            int[,] aread = new int[ny, nx];
        //            for (int i = 0; i < ny; i++)
        //            {
        //                tmpRow = new float[nx];
        //                area.GetRow(i, tmpRow[0]);
        //                for (int j = 0; j < nx; j++)
        //                {
        //                    aread[i, j] = Convert.ToInt32(tmpRow[j]);
        //                }
        //            }

        //            /*  check for source values >= threshold else fortran crashes*/
        //            int n = 0;
        //            short dirgNoData = Convert.ToInt16(dirg.Header.NodataValue);
        //            for (int i = 0; i < ny; i++)
        //            {
        //                for (int j = 0; j < nx; j++)
        //                {
        //                    if (dir[i, j] == dirgNoData)
        //                    {
        //                        dir[i, j] = 0;  // set direction no data to 0. netex needs this
        //                    }
        //                    if (aread[i, j] >= itresh)
        //                    {
        //                        n = n + 1;
        //                    }
        //                }
        //            }

        //            if (n <= 0)
        //            {
        //                err = 8; //TD_CHANNEL_NETWORK_MISMATCH
        //            }
        //            else
        //            {
        //                int[] inodes;
        //                int[] jnodes;

        //                //  If there are outlets set up inodes, jnodes arrays
        //                if (nxy > 0)
        //                {
        //                    inodes = new int[nxy];
        //                    jnodes = new int[nxy];
        //                }
        //                else
        //                {
        //                    inodes = new int[1];
        //                    jnodes = new int[1];
        //                }

        //                for (int inode = 0; inode < nxy; inode++)
        //                {
        //                    jnodes[inode] = (int)Math.Floor((xnode[inode] - bndbox[0]) / dx);
        //                    inodes[inode] = (int)Math.Floor((bndbox[3] - ynode[inode]) / dy);
        //                    //   Trace to raster if necessary but only for nodes that are inside the domain
        //                    if (usetrace == 1 && inodes[inode] > 0 && inodes[inode] < ny - 1 && jnodes[inode] > 0 && jnodes[inode] < nx - 1)
        //                    {
        //                        if ((int)aread[jnodes[inode], inodes[inode]] < itresh)  // Not on grid
        //                        {
        //                            //   Next downslope
        //                            short dirn = dir[jnodes[inode], inodes[inode]];
        //                            int nexti = inodes[inode] + d1[dirn];
        //                            int nextj = jnodes[inode] + d2[dirn];
        //                            int loopcount = 0;
        //                            while (nexti > 0 && nexti < ny - 1 && nextj > 0 && nextj < nx - 1 && (int)area.get_Value(jnodes[inode], inodes[inode]) < itresh)
        //                            {
        //                                inodes[inode] = nexti;
        //                                jnodes[inode] = nextj;
        //                                dirn = dir[jnodes[inode], inodes[inode]];
        //                                if (dirn < 1 || dirn > 8) break;   // Here have gone out of grid so terminate trace downwards
        //                                nexti = nexti + d1[dirn];
        //                                nextj = nextj + d2[dirn];
        //                                loopcount = loopcount + 1;
        //                                if (loopcount > nx && loopcount > ny) break;   // Here possible infinite loop so terminate trace downwards
        //                            }
        //                        }
        //                    }
        //                }

        //                Netex(dir, aread, treefile, coordfile, ordfile, nx, ny, itresh, out icr, out icend, dx, dy, 0, dx, 0, err, inodes, jnodes, nxy, idnodes);

        //                //Write any changes that were made to the area
        //                for (int i = 0; i < ny; i++)
        //                {
        //                    tmpRow = new float[nx];
        //                    for (int j = 0; j < nx; j++)
        //                    {
        //                        tmpRow[j] = aread[i, j];
        //                    }
        //                    area.PutRow(i, tmpRow[0]);
        //                }

        //                area.Header.NodataValue = -1;
        //                if (area.Save(ordfile, RasterFileType.UseExtension, null))
        //                {
        //                    err = 0;
        //                }
        //                else
        //                {
        //                    err = 2; //TD_FAILED_GRID_SAVE;
        //                    dirg.Close();
        //                    area.Close();
        //                    return err;
        //                }
        //                area.Close();

        //                //Fix negative markers
        //                for (int i = 0; i < ny; i++)
        //                {
        //                    for (int j = 0; j < nx; j++)
        //                    {
        //                        if (dir[i, j] < 0 && dir[i, j] > -9)
        //                        {
        //                            dir[i, j] = (short)-dir[i, j];
        //                        }
        //                    }
        //                }

        //                area = new Raster();
        //                if (area.Open(ad8file, RasterDataType.UnknownDataType, true, RasterFileType.UseExtension, null))
        //                {
        //                    err = 0;
        //                }
        //                else
        //                {
        //                    err = 1; //TD_FAILED_GRID_OPEN
        //                    dirg.Close();
        //                    return err;
        //                }
        //                aread = new int[ny, nx];
        //                for (int i = 0; i < ny; i++)
        //                {
        //                    tmpRow = new float[nx];
        //                    area.GetRow(i, tmpRow[0]);
        //                    for (int j = 0; j < nx; j++)
        //                    {
        //                        aread[i, j] = Convert.ToInt32(tmpRow[j]);
        //                    }
        //                }

        //                /*****read elevfile   *****/
        //                Raster elevg = new Raster();
        //                if (elevg.Open(elevfile, RasterDataType.UnknownDataType, true, RasterFileType.UseExtension, null))
        //                {
        //                    err = 0;
        //                }
        //                else
        //                {
        //                    err = 1; //TD_FAILED_GRID_OPEN
        //                    dirg.Close();
        //                    area.Close();
        //                    return err;
        //                }
        //                if (elevg.NumColumns != nx || elevg.NumRows != ny)
        //                {
        //                    dirg.Close();
        //                    area.Close();
        //                    elevg.Close();
        //                    return 1;
        //                }

        //                float[,] elevd = new float[ny, nx];
        //                for (int i = 0; i < ny; i++)
        //                {
        //                    tmpRow = new float[nx];
        //                    elevg.GetRow(i, tmpRow[0]);
        //                    for (int j = 0; j < nx; j++)
        //                    {
        //                        elevd[i, j] = tmpRow[j];
        //                    }
        //                }

        //                NetProp(dir, aread, elevd, coordfile, icr, icend, dx, dy, nx, ny, bndbox, err);

        //                elevg.Close();
        //            }  //  end if associated with err from source
        //            dirg.Close();
        //            area.Close();

        //            return err;
        //        }

        //        private static int Netex(short[,] dir, int[,] area, string treefile, string coordfile, string ordfile, int nx, int ny, int itresh, out int icr, out int icend, double dx, double dy, double bndbox, double csize, int iftype, int err, int[] inodes, int[] jnodes, int nnodes, int[] idnodes)
        //        {
        //            int i, j;
        //            int inodeid;
        //            int nodeno;
        //            int ics;
        //            int[] iordup = new int[8];
        //            int[] ipoint = new int[8];
        //            int[] d1 = new int[9];
        //            int[] d2 = new int[9];
        //            d1[1] = 0; d1[2] = -1; d1[3] = -1; d1[4] = -1; d1[5] = 0; d1[6] = 1; d1[7] = 1; d1[8] = 1;
        //            d2[1] = 1; d2[2] = 1; d2[3] = 0; d2[4] = -1; d2[5] = -1; d2[6] = -1; d2[7] = 0; d2[8] = 1;
        //            icr = 0;
        //            icend = 0;
        //            err = 0;

        //            int[] ist, jst, iord, istart, jstart, iend, jend, mag;

        //            //READ INPUT
        //            int igy = ny;
        //            int igx = nx;

        //            //
        //            //     MEANING OF POINTERS IS -------------
        //            //                            I 4 I 3 I 2 I
        //            //      0 = POINTS TO SELF    -------------
        //            //          I.E. UNRESOLVED   I 5 I 0 I 1 I
        //            //     -1 = BOUNDARY PIXEL    -------------
        //            //                            I 6 I 7 I 8 I
        //            //                            -------------
        //            //

        //            //-----FIRST FIND ALL START PIXELS
        //            int n = 0;
        //            for (i = 1; i < ny - 1; i++)
        //            {
        //                for (j = 1; j < nx - 1; j++)
        //                {
        //                    if (strt(i, j, area, dir, nx, ny, igx, igy, itresh))
        //                    {
        //                        n = n + 1;
        //                    }
        //                }
        //            }

        //            int nmax = n;
        //            int mnl = 2 * n + 1 + nnodes;   // 11/17/04  DGT added nnodes to avoid memory overflow

        //            //     when added nodes increase the number of links
        //            int[] nextl = new int[mnl + 1];
        //            int[] prevl1 = new int[mnl + 1];
        //            int[] prevl2 = new int[mnl + 1];
        //            ist = new int[nmax + 1];
        //            jst = new int[nmax + 1];
        //            iord = new int[mnl + 1];
        //            istart = new int[mnl + 1];
        //            jstart = new int[mnl + 1];
        //            iend = new int[mnl + 1];
        //            jend = new int[mnl + 1];
        //            mag = new int[mnl + 1];

        //            n = 0;
        //            for (i = 1; i < ny - 1; i++)
        //            {
        //                for (j = 1; j < nx - 1; j++)
        //                {
        //                    if (strt(i, j, area, dir, nx, ny, igx, igy, itresh))
        //                    {
        //                        n = n + 1;
        //                        if (n <= nmax)
        //                        {
        //                            ist[n] = i;
        //                            jst[n] = j;
        //                        }
        //                    }
        //                }
        //            }

        //            if (n > nmax)
        //            {
        //                err = 2;//stop too big
        //                return err;
        //            }

        //            //---ZERO AREA ARRAY
        //            for (i = 1; i < ny - 1; i++)
        //            {
        //                for (j = 1; j < nx - 1; j++)
        //                {
        //                    area[i, j] = 0;
        //                }
        //            }

        //            //----TRACE STREAMS DOWNWARDS ADDING 1 TO MAGNITUDE OF EACH PIXEL (MAGNITUDE STORED IN AREA ARRAY)
        //            int inext;
        //            int jnext;
        //            for (int si = 1; si <= n; si++)
        //            {
        //                i = ist[si];
        //                j = jst[si];
        //                while (dir[i, j] > 0)
        //                {
        //                    area[i, j] = area[i, j] + 1;
        //                    inext = i + d1[dir[i, j]];
        //                    jnext = j + d2[dir[i, j]];
        //                    i = inext;
        //                    j = jnext;
        //                }
        //            }

        //            //----IDENTIFY LINKS BY DIFFERENT MAGNITUDES
        //            bool runEndPath;
        //            int ilink = 1;
        //            int mnext, intemp, jntemp, msum, iconv, itemp;
        //            for (int si = 1; si <= n; si++)
        //            {
        //                istart[ilink] = ist[si];
        //                jstart[ilink] = jst[si];

        //                //---INITIALISE POINTERS
        //                prevl1[ilink] = 0;
        //                prevl2[ilink] = 0;
        //                i = ist[si];
        //                j = jst[si];
        //                mag[ilink] = area[i, j];
        //                iord[ilink] = 1;

        //                inext = i + d1[Math.Abs(dir[i, j])];
        //                jnext = j + d2[Math.Abs(dir[i, j])];
        //                runEndPath = true;
        //                while (dir[inext, jnext] != 0)
        //                {
        //                    mnext = area[inext, jnext];
        //                    i = inext;
        //                    j = jnext;
        //                    iend[ilink] = i;
        //                    jend[ilink] = j;

        //                    //mods allow insertion of nodes   DGT 7/17/02
        //                    if (isnode(mnext, mag[ilink], i, j, inodes, jnodes, nnodes))
        //                    {
        //                        //heck here that this is not the end of a path because then it will be a node anyway
        //                        intemp = i + d1[Math.Abs(dir[i, j])];
        //                        jntemp = j + d2[Math.Abs(dir[i, j])];
        //                        if (dir[intemp, jntemp] != 0)
        //                        {
        //                            ilink = ilink + 1;
        //                            istart[ilink] = i;
        //                            jstart[ilink] = j;
        //                            prevl1[ilink] = ilink - 1;
        //                            prevl2[ilink] = 0;
        //                            nextl[ilink - 1] = ilink;
        //                            mag[ilink] = mag[ilink - 1];
        //                            iord[ilink] = iord[ilink - 1];
        //                            iend[ilink] = i;
        //                            jend[ilink] = j;
        //                        }
        //                    }
        //                    //end mods to allow insertion of nodes  DGT
        //                    if (mnext != mag[ilink])
        //                    {
        //                        //----CONTINUE HERE FOR NEW LINK
        //                        //----CHECK IF JUNCTION ALREADY REACHED (FLAGGED BY NEGATIVE DIRECTION)
        //                        if (dir[i, j] < 0)
        //                        {
        //                            //----CHECK IF ALL LINKS CONVERGING HERE HAVE BEEN DONE BY SUMMING MAGNITUDE
        //                            msum = 0;
        //                            iconv = 0;
        //                            for (int il = 1; il <= ilink; il++)
        //                            {
        //                                if (iend[il] == i && jend[il] == j)
        //                                {
        //                                    iconv = iconv + 1;
        //                                    ipoint[iconv] = il;
        //                                    iordup[iconv] = iord[il];
        //                                    msum = msum + mag[il];
        //                                }
        //                            }

        //                            if (msum == mnext) //All links have been processed
        //                            {
        //                                //---SORT IORDUP,IPOINT INTO DECENDING STREAM ORDER
        //                                for (int ic = 1; ic <= iconv - 1; ic++)
        //                                {
        //                                    for (int iic = ic + 1; iic <= iconv; iic++)
        //                                    {
        //                                        if (iordup[iic] > iordup[ic]) //switch these
        //                                        {
        //                                            itemp = iordup[iic];
        //                                            iordup[iic] = iordup[ic];
        //                                            iordup[ic] = itemp;
        //                                            itemp = ipoint[iic];
        //                                            ipoint[iic] = ipoint[ic];
        //                                            ipoint[ic] = itemp;
        //                                        }
        //                                    }
        //                                }
        //                                for (int ic = 1; ic <= iconv - 1; ic++)
        //                                {
        //                                    ilink = ilink + 1;
        //                                    istart[ilink] = i;
        //                                    jstart[ilink] = j;
        //                                    prevl1[ilink] = ipoint[ic];
        //                                    prevl2[ilink] = ipoint[ic + 1];
        //                                    nextl[ipoint[ic]] = ilink;
        //                                    nextl[ipoint[ic + 1]] = ilink;
        //                                    mag[ilink] = mag[prevl1[ilink]] + mag[prevl2[ilink]];
        //                                    iord[ilink] = Math.Max(iordup[1], iordup[2] + 1);
        //                                    ipoint[ic + 1] = ilink;
        //                                    iend[ilink] = i;
        //                                    jend[ilink] = j;
        //                                }
        //                            }
        //                            else
        //                            {
        //                                ilink = ilink + 1;
        //                                runEndPath = false;
        //                                break;
        //                            }
        //                        }
        //                        else
        //                        {
        //                            dir[i, j] = (short)(-dir[i, j]);
        //                            ilink = ilink + 1;
        //                            runEndPath = false;
        //                            break;
        //                        }
        //                    } //end if mnext != mag(ilink)

        //                    inext = i + d1[Math.Abs(dir[i, j])];
        //                    jnext = j + d2[Math.Abs(dir[i, j])];
        //                } // end while dir != 0

        //                if (runEndPath)
        //                {
        //                    iend[ilink] = i;
        //                    jend[ilink] = j;
        //                    nextl[ilink] = -1;
        //                    if (si < n)
        //                    {
        //                        ilink = ilink + 1;
        //                    }
        //                }
        //            } //end for (int si=1; si <= n; si++)

        //            StreamWriter coord = new System.IO.StreamWriter(coordfile);
        //            StreamWriter tree = new System.IO.StreamWriter(treefile);

        //            //     reinitialize area array - for output it will contain order
        //            for (i = 0; i < ny; i++)
        //            {
        //                for (j = 0; j < nx; j++)
        //                {
        //                    area[i, j] = 0;
        //                }
        //            }

        //            int icord = 0;

        //            //---  WRITE ROOT LINK FIRST
        //            i = istart[ilink];
        //            j = jstart[ilink];
        //            ics = icord;

        //            if (i != 0 && j != 0)
        //            {
        //                coord.Write("{0,10:G} {1,10:G}\n", i + 1, j + 1);
        //                area[i, j] = Math.Max(iord[ilink], area[i, j]);
        //            }
        //            icend = icord;
        //            icord = icord + 1;
        //            while (i != iend[ilink] || j != jend[ilink] && i != 0 && j != 0)
        //            {
        //                inext = i + d1[Math.Abs(dir[i, j])];
        //                jnext = j + d2[Math.Abs(dir[i, j])];
        //                i = inext;
        //                j = jnext;

        //                if (i != 0 && j != 0)
        //                {
        //                    coord.Write("{0,10:G} {1,10:G}\n", i + 1, j + 1);
        //                    area[i, j] = Math.Max(iord[ilink], area[i, j]);
        //                    icend = icord;
        //                    icord = icord + 1;
        //                }
        //            }

        //            inodeid = 0; //This is the first one so it will be the most downstream
        //            if (isnode2(iend[ilink], jend[ilink], inodes, jnodes, nnodes, out nodeno))
        //            {
        //                if (idnodes[nodeno] >= 0)
        //                {
        //                    inodeid = idnodes[nodeno];
        //                    idnodes[nodeno] = -1; //This logic to pick only the first one if there are multiple at a junction
        //                }
        //            }
        //            tree.Write("{0,10:G} {1,10:G} {2,10:G} {3,10:G} {4,10:G} {5,10:G} {6,10:G} {7,10:G}\n", 0, ics, icend, -1, prevl1[ilink], prevl2[ilink], iord[ilink], inodeid);

        //            icr = icord;

        //            //---  WRITE REMAINDER OF LINKS
        //            for (int il = 1; il <= ilink - 1; il++)
        //            {
        //                i = istart[il];
        //                j = jstart[il];
        //                ics = icord;

        //                if (i != 0 && j != 0)
        //                {
        //                    coord.Write("{0,10:G} {1,10:G}\n", i + 1, j + 1);
        //                    area[i, j] = Math.Max(iord[il], area[i, j]);
        //                }
        //                icend = icord;
        //                icord = icord + 1;
        //                while (i != iend[il] || j != jend[il] && i != 0 && j != 0)
        //                {
        //                    inext = i + d1[Math.Abs(dir[i, j])];
        //                    jnext = j + d2[Math.Abs(dir[i, j])];
        //                    i = inext;
        //                    j = jnext;

        //                    if (i != 0 && j != 0)
        //                    {
        //                        coord.Write("{0,10:G} {1,10:G}\n", i + 1, j + 1);
        //                        area[i, j] = Math.Max(iord[il], area[i, j]);
        //                        icend = icord;
        //                        icord = icord + 1;
        //                    }
        //                }

        //                if (nextl[il] == ilink)
        //                {
        //                    nextl[il] = 0;
        //                }
        //                inodeid = -1;

        //                if (nextl[il] < 0)
        //                {
        //                    inodeid = 0;
        //                }

        //                if (isnode2(iend[il], jend[il], inodes, jnodes, nnodes, out nodeno))
        //                {
        //                    if (idnodes[nodeno] >= 0)
        //                    {
        //                        inodeid = idnodes[nodeno];
        //                        idnodes[nodeno] = -1; //This logic to pick only the first one if there are multiple at a junction
        //                    }
        //                }

        //                tree.Write("{0,10:G} {1,10:G} {2,10:G} {3,10:G} {4,10:G} {5,10:G} {6,10:G} {7,10:G}\n", il, ics, icend, nextl[il], prevl1[il], prevl2[il], iord[il], inodeid);
        //            }

        //            coord.Close();
        //            tree.Close();

        //            return err;
        //        }

        //        private static bool strt(int i, int j, int[,] area, short[,] dir, int nx, int ny, int igx, int igy, int itresh)
        //        {
        //            bool result = true;
        //            int[] d1 = new int[9];
        //            int[] d2 = new int[9];
        //            d1[1] = 0; d1[2] = -1; d1[3] = -1; d1[4] = -1; d1[5] = 0; d1[6] = 1; d1[7] = 1; d1[8] = 1;
        //            d2[1] = 1; d2[2] = 1; d2[3] = 0; d2[4] = -1; d2[5] = -1; d2[6] = -1; d2[7] = 0; d2[8] = 1;

        //            if (area[i, j] < itresh || dir[i, j] < 0)
        //            {
        //                result = false;
        //                if (area[i, j] <= 0)
        //                {
        //                    dir[i, j] = 0; //ZERO DIRECTIONS OUTSIDE AREA
        //                }
        //            }
        //            else //CHECK UPSTREAM PIXELS
        //            {
        //                int ni, nj, ind, jnd;
        //                for (int k = 1; k <= 8; k++)
        //                {
        //                    ni = i + d1[k]; //neighbor pixel
        //                    nj = j + d2[k];
        //                    if (dir[ni, nj] > 0)
        //                    {
        //                        ind = ni + d1[dir[ni, nj]]; //pixel downstream from neighbor
        //                        jnd = nj + d2[dir[ni, nj]];
        //                        if (ind == i && jnd == j) //Neighbor drains into i,j
        //                        {
        //                            if (area[ni, nj] >= itresh)
        //                            {
        //                                result = false;
        //                            }
        //                        }
        //                    }
        //                }
        //                //Do not allow sources that drain off the raster set i.e. a link of 0 length
        //                ni = i + d1[dir[i, j]];
        //                nj = j + d2[dir[i, j]];
        //                if (area[ni, nj] < itresh)
        //                {
        //                    result = false;
        //                }
        //            }

        //            return result;
        //        }

        //        private static bool isnode(int mnext, int mag, int i, int j, int[] inodes, int[] jnodes, int nnodes)
        //        {
        //            bool result = false;
        //            for (int k = 0; k < nnodes; k++)
        //            {
        //                if ((inodes[k]) == i && (jnodes[k]) == j)
        //                {
        //                    result = true;
        //                    if (mnext != mag) //false alarm it is a junction
        //                    {
        //                        result = false;
        //                    }
        //                    return result;
        //                }
        //            }
        //            return result;
        //        }

        //        private static bool isnode2(int i, int j, int[] inodes, int[] jnodes, int nnodes, out int nodeno)
        //        {
        //            nodeno = -1;
        //            for (int k = 0; k < nnodes; k++)
        //            {
        //                if ((inodes[k]) == i && (jnodes[k]) == j)
        //                {
        //                    //+1 is because arrays came from C
        //                    nodeno = k;  // for return to use in indexing
        //                    return true;
        //                }
        //            }
        //            return false;
        //        }

        //        private static int NetProp(short[,] dir, int[,] area, float[,] elev, string coordfile, int icr, int icmax, double dx, double dy, int nx, int ny, double[] bndbox, int err)
        //        {
        //            int[] d1 = new int[9];
        //            int[] d2 = new int[9];
        //            d1[1] = 0; d1[2] = -1; d1[3] = -1; d1[4] = -1; d1[5] = 0; d1[6] = 1; d1[7] = 1; d1[8] = 1;
        //            d2[1] = 1; d2[2] = 1; d2[3] = 0; d2[4] = -1; d2[5] = -1; d2[6] = -1; d2[7] = 0; d2[8] = 1;

        //            int mc = icmax + 1;
        //            double[] rarea = new double[mc];
        //            double[] length = new double[mc];
        //            double[] elv = new double[mc];
        //            int[] ia = new int[mc];
        //            int[] ja = new int[mc];

        //            StreamReader coordr = new StreamReader(coordfile);

        //            string bufferLine;
        //            int n;
        //            for (n = 0; n <= mc; n++)
        //            {
        //                try
        //                {
        //                    bufferLine = coordr.ReadLine();
        //                    if (bufferLine != String.Empty)
        //                    {
        //                        ia[n] = Convert.ToInt32(bufferLine.Substring(0, 10).Trim()) - 1;
        //                        ja[n] = Convert.ToInt32(bufferLine.Substring(11, 10).Trim()) - 1;
        //                    }
        //                    else
        //                    {
        //                        break;
        //                    }
        //                }
        //                catch
        //                {
        //                    break;
        //                }
        //            }
        //            coordr.Close();

        //            n = n - 1;
        //            for (int ic = 0; ic <= n; ic++)
        //            {
        //                rarea[ic] = area[ia[ic], ja[ic]] * dx * dy;
        //                elv[ic] = elev[ia[ic], ja[ic]];
        //            }

        //            int iroot = ia[icr];
        //            int jroot = ja[icr];

        //            //----TRACE STREAMS DOWNWARDS
        //            int i, j, inext, jnext;
        //            double DXx, DYy;
        //            for (int ic = 0; ic <= n; ic++)
        //            {
        //                length[ic] = 0;
        //                i = ia[ic];
        //                j = ja[ic];
        //                inext = i + d1[dir[i, j]];
        //                jnext = j + d2[dir[i, j]];

        //                while (dir[inext, jnext] != 0) //not yet end of path
        //                {
        //                    DXx = dx * (double)(j - jnext);
        //                    DYy = dy * (double)(i - inext);
        //                    length[ic] = length[ic] + Math.Sqrt(DXx * DXx + DYy * DYy);
        //                    i = inext;
        //                    j = jnext;
        //                    inext = i + d1[dir[i, j]];
        //                    jnext = j + d2[dir[i, j]];
        //                }
        //            }

        //            //--WRITE OUTPUT
        //            StreamWriter coordw = new StreamWriter(coordfile);
        //            double x, y;
        //            for (int ic = 0; ic <= n; ic++)
        //            {
        //                x = (ja[ic]) * dx + bndbox[0] + dx * 0.5;
        //                y = dy * (ny - ia[ic] - 1) + bndbox[1] + dy * 0.5;
        //                coordw.Write("{0,15:F4} {1,15:F4} {2,15:F4} {3,15:F4} {4,15:F4}\n", x, y, length[ic], elv[ic], rarea[ic]);
        //            }
        //            coordw.Close();

        //            return 0;
        //        }
        //        #endregion

        //        #endregion

        //        #region "Delin Streams Shapefile And Subbasins Grid"
        //        // CWG 27/1/2011 In TauDEM V5 this functionality is included in DelinStreamGrids

        //        //		/// <summary>
        //        //		/// A function which makes calls to TauDEM to delineate streams shapefile and subbasin grid
        //        //		/// </summary>
        //        //		/// <param name="d8Path"></param>
        //        //		/// <param name="TreeDatPath"></param>
        //        //		/// <param name="CoordDatPath"></param>
        //        //		/// <param name="streamShapeResultPath"></param>
        //        //		/// <param name="watershedGridResultPath"></param>
        //        //		/// <param name="callback"></param>
        //        //		/// <returns></returns>
        //        //		public static int DelinStreamsAndSubBasins(string d8Path, string TreeDatPath, string CoordDatPath, string streamShapeResultPath, string watershedGridResultPath, IProgressHandler callback)
        //        //		{
        //        //			int result = -1;
        //        //			int ordert = 1;
        //        //			int subbno = 0;
        //        //
        //        //			TKTAUDEMLib.TauDEM TaudemLib = new TKTAUDEMLib.TauDEM();
        //        //			if (callback != null) TaudemLib.Callback = callback;
        //        //
        //        //			if (callback != null) callback.Progress("Status", 0, "Stream Shapefile and Watershed Grid");
        //        //			DataManagement.DeleteGrid(watershedGridResultPath);
        //        //			DataManagement.DeleteShapefile(streamShapeResultPath);
        //        //
        //        //			try
        //        //			{
        //        //				//result = TaudemLib.Subbasinsetup(d8Path, watershedGridResultPath, TreeDatPath, CoordDatPath, streamShapeResultPath, ordert, subbno);
        //        //				result = CreateSubbasinGridAndNetworkShape(d8Path, TreeDatPath, CoordDatPath, ordert, subbno, watershedGridResultPath, streamShapeResultPath, callback);
        //        //			}
        //        //			catch
        //        //			{
        //        //			}
        //        //
        //        //			if (result != 0)
        //        //			{
        //        //				MessageBox.Show(TaudemLib.getErrorMsg(result), "TauDEM Error " + result, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.DialogResult.OK);
        //        //			}
        //        //
        //        //			CopyProjectionFromGrid(d8Path, watershedGridResultPath);
        //        //			CopyProjectionFromGrid(d8Path, streamShapeResultPath);
        //        //			if (callback != null) callback.Progress("Status", 0, String.Empty);
        //        //			return result;
        //        //		}
        //        //
        //        //		/// <summary>
        //        //		/// An overload of the DelinStreamsAndSubBasins function which will generate a GeoprocDialog for the DelinStreamsAndSubBasins function
        //        //		/// </summary>
        //        //		/// <param name="callback"></param>
        //        //		/// <returns></returns>
        //        //		public static int DelinStreamsAndSubBasins(IProgressHandler callback)
        //        //		{
        //        //			return doDelinStreamsAndSubBasinsDiag(callback);
        //        //		}
        //        //
        //        //		/// <summary>
        //        //		/// An overload of the DelinStreamsAndSubBasins function which will generate a GeoprocDialog for the DelinStreamsAndSubBasins function
        //        //		/// </summary>
        //        //		/// <returns></returns>
        //        //		public static int DelinStreamsAndSubBasins()
        //        //		{
        //        //			return doDelinStreamsAndSubBasinsDiag(null);
        //        //		}
        //        //
        //        //		private static int doDelinStreamsAndSubBasinsDiag(IProgressHandler callback)
        //        //		{
        //        //			GeoProcDialog delinstreamshedDiag = new GeoProcDialog();
        //        //			FileElement d8Elem = delinstreamshedDiag.Add_FileElement(GeoProcDialog.ElementTypes.OpenGridFile);
        //        //			FileElement treeDatElem = delinstreamshedDiag.Add_FileElement(GeoProcDialog.ElementTypes.OpenFile);
        //        //			FileElement coordDatElem = delinstreamshedDiag.Add_FileElement(GeoProcDialog.ElementTypes.OpenFile);
        //        //			FileElement streamShapeResElem = delinstreamshedDiag.Add_FileElement(GeoProcDialog.ElementTypes.SaveShapefile);
        //        //			FileElement shedGridResElem = delinstreamshedDiag.Add_FileElement(GeoProcDialog.ElementTypes.SaveGridFile);
        //        //
        //        //			delinstreamshedDiag.Text = "TauDEM Stream Network Shapefile and Sub-basin Grid";
        //        //			delinstreamshedDiag.HelpTitle = "TauDEM Stream Network Shapefile and Sub-basin Grid";
        //        //			delinstreamshedDiag.HelpText = "This function will generate a stream network shapefile and sub-basin grid from the given inputs.";
        //        //			delinstreamshedDiag.Height = 350;
        //        //			delinstreamshedDiag.HelpPanelVisible = false;
        //        //
        //        //			d8Elem.Caption = "D8 Flow Direction Grid Path";
        //        //			d8Elem.HelpButtonVisible = false;
        //        //
        //        //			treeDatElem.Caption = "Network Tree Data File Path";
        //        //			treeDatElem.Filter = "Data Files (*.dat)|*.dat";
        //        //			treeDatElem.HelpButtonVisible = false;
        //        //
        //        //			coordDatElem.Caption = "Network Coordinates Data File Path";
        //        //			coordDatElem.Filter = "Data Files (*.dat)|*.dat";
        //        //			coordDatElem.HelpButtonVisible = false;
        //        //
        //        //			streamShapeResElem.Caption = "Stream Network Shapefile Result Path";
        //        //			streamShapeResElem.HelpButtonVisible = false;
        //        //
        //        //			shedGridResElem.Caption = "Sub-basins Grid Result Path";
        //        //			shedGridResElem.HelpButtonVisible = false;
        //        //
        //        //
        //        //			if (delinstreamshedDiag.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //        //			{
        //        //				return Hydrology.DelinStreamsAndSubBasins(d8Elem.Filename, treeDatElem.Filename, coordDatElem.Filename, streamShapeResElem.Filename, shedGridResElem.Filename, callback);
        //        //			}
        //        //			return -2;
        //        //		}

        //        #region "    Subbasinsetup conversion"

        //        private static int CreateSubbasinGridAndNetworkShape(string D8GridPath, string TreeDatPath, string CoordDatPath, int ordert, int subbno, string ResultBasinGridPath, string ResultNetShapePath, IProgressHandler callback)
        //        {
        //            int newperc = 0;
        //            int oldperc = 0;
        //            if (callback != null) callback.Progress("Status", 0, "Stream Shapefile and Watershed Grid");
        //            int err = 0;
        //            bool success;

        //            int numTreeNodes = -1;
        //            long[] dsNodeID;
        //            int[,] FlowNet;
        //            if (ReadTreeFile(TreeDatPath, out FlowNet, out dsNodeID, numTreeNodes) == 1)
        //            {
        //                return 1;
        //            }

        //            int numCoords = 0;
        //            float[,] CoordList;
        //            if (ReadCoordFile(CoordDatPath, out CoordList, numCoords) == 1)
        //            {
        //                return 1;
        //            }

        //            int numBasins = 0;
        //            int currReach = 2 * (numTreeNodes + 1) - 1; //Initialize current reach number
        //            int maxReaches = 5 * (numTreeNodes + 1) - 2; //The maximum number of reaches possible in binary tree
        //            int[,] ReachConnections = new int[maxReaches + 1, 3];
        //            float[,] ReachProperties = new float[maxReaches + 1, 5];
        //            int[] Magnitude = new int[numTreeNodes + 2];

        //            Raster d8Grid = new Raster();
        //            success = d8Grid.Open(D8GridPath, RasterDataType.UnknownDataType, true, RasterFileType.UseExtension, null);
        //            if (success)
        //            {
        //                err = 0;
        //            }
        //            else
        //            {
        //                err = 1;
        //            }

        //            int numCols = d8Grid.NumColumns;
        //            int numRows = d8Grid.NumRows;
        //            RasterHeader BasinGridHead = new RasterHeader();
        //            BasinGridHead.CopyFrom(d8Grid.Header);
        //            BasinGridHead.NodataValue = -1;

        //            Raster BasinGrid = new Raster();
        //            BasinGrid.CreateNew(ResultBasinGridPath, BasinGridHead, RasterDataType.ShortDataType, BasinGridHead.NodataValue, true, RasterFileType.UseExtension, null);
        //            //TODO: May need this to be a temp path instead of result grid

        //            Shapefile NetSF = new Shapefile();
        //            NetSF.CreateNew(ResultNetShapePath, MapWinGIS.ShpfileType.SHP_POLYLINE);
        //            NetSF.StartEditingShapes(true, null);
        //            InitializeNetFields(NetSF);

        //            Queue<int> Links = new Queue<int>();

        //            for (int i = 0; i <= numTreeNodes; i++)
        //            {
        //                if (numTreeNodes > 0)
        //                {
        //                    newperc = Convert.ToInt32((Convert.ToDouble(i) / Convert.ToDouble(numTreeNodes)) * 100);
        //                    if (newperc > oldperc)
        //                    {
        //                        if (callback != null) callback.Progress("Status", newperc, "Stream Shapefile and Watershed Grid");
        //                        oldperc = newperc;
        //                    }
        //                }

        //                if (FlowNet[i, 3] == -1) //This is a root link
        //                {
        //                    if (ordert >= 0)
        //                    {
        //                        PopulateNetworkProperties(numBasins, i, FlowNet, CoordList, currReach, ordert, subbno, Magnitude, dsNodeID, numRows, numCols, ReachConnections, ReachProperties, d8Grid, BasinGrid, NetSF, callback);
        //                    }
        //                    else
        //                    {
        //                        subbno = subbno + 1;
        //                        PopulateNetworkProperties(numBasins, i, FlowNet, CoordList, currReach, ordert, subbno, Magnitude, dsNodeID, numRows, numCols, ReachConnections, ReachProperties, d8Grid, BasinGrid, NetSF, callback);
        //                    }
        //                }

        //                if (FlowNet[i, 4] == 0 && FlowNet[i, 5] == 0) //This is a branch
        //                {
        //                    Links.Enqueue(i);
        //                }
        //            }

        //            if (Links.Count > 0)
        //            {
        //                numBasins = 0;
        //                if (ordert >= 0)
        //                {
        //                    MarkBasinsAndNetworkStack(Links, numBasins, FlowNet, CoordList, currReach, ordert, subbno, Magnitude, dsNodeID, numRows, numCols, ReachConnections, ReachProperties, d8Grid, BasinGrid, NetSF, callback);
        //                }
        //                else
        //                {
        //                    subbno = subbno + 1;
        //                    MarkBasinsAndNetworkStack(Links, numBasins, FlowNet, CoordList, currReach, ordert, subbno, Magnitude, dsNodeID, numRows, numCols, ReachConnections, ReachProperties, d8Grid, BasinGrid, NetSF, callback);
        //                }
        //            }

        //            NetSF.Save();
        //            NetSF.Close();

        //            success = BasinGrid.Save(ResultBasinGridPath, RasterFileType.UseExtension, null);
        //            if (success)
        //            {
        //                err = 0;
        //            }
        //            else
        //            {
        //                err = 2;
        //            }
        //            BasinGrid.Close();
        //            if (callback != null) callback.Progress("Status", 0, "Stream Shapefile and Watershed Grid");

        //            return err;
        //        }

        //        private static int ReadTreeFile(string TreeDatPath, out int[,] FlowNet, out long[] dsNodeID, int numTreeNodes)
        //        {
        //            System.IO.StreamReader tree = null;
        //            try
        //            {
        //                tree = new System.IO.StreamReader(TreeDatPath);
        //                string line;
        //                while (!tree.EndOfStream)
        //                {
        //                    line = tree.ReadLine();
        //                    numTreeNodes = numTreeNodes + 1;
        //                }
        //                tree.Close();
        //                FlowNet = new int[numTreeNodes + 1, 7];
        //                dsNodeID = new long[numTreeNodes + 1];
        //                tree = new System.IO.StreamReader(TreeDatPath);
        //                for (int i = 0; i <= numTreeNodes; i++)
        //                {
        //                    line = tree.ReadLine();
        //                    int counter = -1;
        //                    string[] split = line.Split(' ');
        //                    for (int j = 0; j <= split.Length - 1; j++)
        //                    {
        //                        if (split[j] != String.Empty)
        //                        {
        //                            counter = counter + 1;
        //                            if (counter < 7)
        //                            {
        //                                FlowNet[i, counter] = Int32.Parse(split[j]);
        //                            }
        //                            else if (counter == 7)
        //                            {
        //                                dsNodeID[i] = Int32.Parse(split[j]);
        //                                break;
        //                            }
        //                        }
        //                    }
        //                }
        //                tree.Close();
        //            }
        //            catch
        //            {
        //                FlowNet = new int[0, 0];
        //                dsNodeID = new long[0];
        //                return 1;
        //            }
        //            finally
        //            {
        //                if (tree != null)
        //                {
        //                    tree.Close();
        //                }
        //            }
        //            return 0;
        //        }

        //        private static int ReadCoordFile(string CoordDatPath, out float[,] CoordList, int numCoords)
        //        {
        //            System.IO.StreamReader coordSR = null;
        //            try
        //            {
        //                string line;
        //                coordSR = new System.IO.StreamReader(CoordDatPath);
        //                while (!coordSR.EndOfStream)
        //                {
        //                    line = coordSR.ReadLine();
        //                    numCoords = numCoords + 1;
        //                }
        //                coordSR.Close();
        //                CoordList = new float[numCoords + 1, 5];
        //                numCoords = numCoords - 1;
        //                coordSR = new System.IO.StreamReader(CoordDatPath);
        //                for (int i = 0; i <= numCoords; i++)
        //                {
        //                    line = coordSR.ReadLine();
        //                    int counter = -1;
        //                    string[] split = line.Split(' ');
        //                    for (int j = 0; j <= split.Length - 1; j++)
        //                    {
        //                        if (split[j] != String.Empty)
        //                        {
        //                            counter = counter + 1;
        //                            if (counter < 4)
        //                            {
        //                                CoordList[i, counter] = float.Parse(split[j]);
        //                            }
        //                            else if (counter == 4)
        //                            {
        //                                CoordList[i, counter] = float.Parse(split[j]);
        //                                break;
        //                            }
        //                        }
        //                    }
        //                }
        //                coordSR.Close();
        //            }
        //            catch
        //            {
        //                CoordList = new float[0, 0];
        //                return 1;
        //            }
        //            finally
        //            {
        //                if (coordSR != null)
        //                {
        //                    coordSR.Close();
        //                }
        //            }
        //            return 0;
        //        }

        //        private static int PopulateNetworkProperties(int numBasins, int StartLink, int[,] FlowNet, float[,] CoordList, int currReach, int ordert, int subbno, int[] Magnitude, long[] dsNodeID, int numRows, int numCols, int[,] ReachConnections, float[,] ReachProperties, Raster d8Grid, Raster BasinGrid, Shapefile NetSF, IProgressHandler callback)
        //        {
        //            int currLink;
        //            int currDSLink;
        //            int currDSFrom;
        //            int row;
        //            int UpstreamLink1;
        //            int UpstreamLink2;
        //            int col;
        //            int thisreach;
        //            int BasinID;
        //            int flag = 0;
        //            int LinkEnd;
        //            int LinkBegin;
        //            int LinkEndArea = 0;
        //            //  variables for CoordList positions
        //            float x;
        //            float y;

        //            Stack<int> links = new Stack<int>();
        //            links.Push(-1);
        //            links.Push(-1);
        //            links.Push(StartLink);

        //            while (links.Count != 0)
        //            {
        //                if (callback != null) callback.Progress("Status", 0, "Stream Shapefile and Watershed Grid");
        //                flag = 0;
        //                LinkEndArea = 0;

        //                currLink = links.Pop();
        //                currDSFrom = links.Pop();
        //                currDSLink = links.Pop();

        //                LinkEnd = FlowNet[currLink, 3 - 1];//*  This is CoordList of end of link */
        //                LinkBegin = FlowNet[currLink, 2 - 1];//*  This is CoordList of beg of link */
        //                Magnitude[currLink] = 0;// Initiaize magnitude recursion

        //                if (LinkBegin < LinkEnd)
        //                {
        //                    //has physical length
        //                    numBasins = numBasins + 1;
        //                    if (ordert < 0)
        //                    {
        //                        numBasins = subbno;
        //                    }

        //                    if (FlowNet[currLink, 4 - 1] != -1) //For anything other than a downstream end area is defined one grid cell back
        //                    {
        //                        LinkEndArea = LinkEnd - 1;
        //                    }
        //                    else
        //                    {
        //                        LinkEndArea = LinkEnd;
        //                    }

        //                    x = CoordList[LinkEndArea, 1 - 1];
        //                    y = CoordList[LinkEndArea, 2 - 1];
        //                    BasinGrid.ProjToCell(x, y, out col, out row);
        //                    if (row < 0 | row > numRows | col < 0 | col > numCols)
        //                    {
        //                        if (currDSLink != -1 && currDSFrom != -1)
        //                        {
        //                            ReachConnections[currDSLink, currDSFrom] = -1;
        //                        }
        //                    }
        //                }
        //                else
        //                {
        //                    x = CoordList[LinkEndArea, 1 - 1];
        //                    y = CoordList[LinkEndArea, 2 - 1];
        //                    BasinGrid.ProjToCell(x, y, out col, out row);
        //                    if (row < 0 | row > numRows | col < 0 | col > numCols)
        //                    {
        //                        if (currDSLink != -1 && currDSFrom != -1)
        //                        {
        //                            ReachConnections[currDSLink, currDSFrom] = -2;
        //                        }
        //                    }
        //                    LinkEndArea = LinkEnd;
        //                    flag = 1;
        //                }

        //                if (callback != null) callback.Progress("Status", 50, "Stream Shapefile and Watershed Grid");

        //                //Search for upstream basins
        //                UpstreamLink1 = FlowNet[currLink, 5 - 1]; //pointers to upstream links
        //                UpstreamLink2 = FlowNet[currLink, 6 - 1];

        //                if (UpstreamLink1 > 0 | UpstreamLink2 > 0)
        //                {
        //                    if (flag == 1)
        //                    {
        //                        //dummy 0 length reach
        //                        currReach = currReach + 1;
        //                        thisreach = currReach;
        //                        if (ordert <= 0)
        //                        {
        //                            BasinID = subbno;
        //                        }
        //                        else
        //                        {
        //                            BasinID = 0;
        //                        }

        //                        ReachConnections[thisreach, 1 - 1] = thisreach;
        //                        if (UpstreamLink1 > 0)
        //                        {
        //                            links.Push(thisreach);
        //                            links.Push(2 - 1);
        //                            links.Push(UpstreamLink1);
        //                            Magnitude[currLink] = Magnitude[currLink] + Magnitude[UpstreamLink1];
        //                        }
        //                        else
        //                        {
        //                            ReachConnections[thisreach, 2 - 1] = 0;
        //                        }
        //                        // CWG 20/7/2010 missing code for second link added
        //                        if (UpstreamLink2 > 0)
        //                        {
        //                            links.Push(thisreach);
        //                            links.Push(3 - 1);
        //                            links.Push(UpstreamLink2);
        //                            Magnitude[currLink] = Magnitude[currLink] + Magnitude[UpstreamLink2];
        //                        }
        //                        else
        //                        {
        //                            ReachConnections[thisreach, 3 - 1] = 0;
        //                        }
        //                        //AddReachShape3(NetSF, FlowNet, CoordList, currLink, BasinID, Magnitude[currLink], dsNodeID[currLink]);

        //                        //'Assign properties to dummy reach
        //                        ReachProperties[thisreach, 1 - 1] = 0.01f; //slope
        //                        ReachProperties[thisreach, 2 - 1] = CoordList[LinkEndArea, 5 - 1]; //ontributing area
        //                        ReachProperties[thisreach, 3 - 1] = 0; //Length
        //                        ReachProperties[thisreach, 4 - 1] = CoordList[LinkEndArea, 0]; //end x CoordList
        //                        ReachProperties[thisreach, 5 - 1] = CoordList[LinkEndArea, 1]; //end x CoordList
        //                    }
        //                    else
        //                    {
        //                        //Lower half reach
        //                        currReach = currReach + 1;
        //                        thisreach = currReach;
        //                        ReachConnections[thisreach, 1 - 1] = thisreach;
        //                        ReachConnections[thisreach, 2 - 1] = numBasins;
        //                        ReachConnections[thisreach, 3 - 1] = currReach + 1;
        //                        ReachProperties[thisreach, 3 - 1] = (CoordList[LinkBegin, 3 - 1] - CoordList[LinkEnd, 3 - 1]) / 2;
        //                        ReachProperties[thisreach, 2 - 1] = CoordList[LinkEndArea, 5 - 1];
        //                        ReachProperties[thisreach, 1 - 1] = (CoordList[LinkBegin, 4 - 1] - CoordList[LinkEnd, 4 - 1]);
        //                        ReachProperties[thisreach, 4 - 1] = CoordList[LinkEndArea, 0]; //end x CoordList
        //                        ReachProperties[thisreach, 5 - 1] = CoordList[LinkEndArea, 1]; //end y coordinate
        //                        if (ordert <= 0)
        //                        {
        //                            BasinID = subbno;
        //                        }
        //                        else
        //                        {
        //                            BasinID = numBasins;
        //                        }

        //                        //Upper half reach
        //                        currReach = currReach + 1;
        //                        ReachConnections[thisreach + 1, 1 - 1] = currReach;
        //                        if (UpstreamLink1 > 0)
        //                        {
        //                            links.Push(thisreach + 1);
        //                            links.Push(2 - 1);
        //                            links.Push(UpstreamLink1);
        //                            Magnitude[currLink] = Magnitude[currLink] + Magnitude[UpstreamLink1];
        //                        }
        //                        else
        //                        {
        //                            ReachConnections[thisreach + 1, 2 - 1] = 0;
        //                        }
        //                        if (UpstreamLink2 > 0)
        //                        {
        //                            links.Push(thisreach + 1);
        //                            links.Push(3 - 1);
        //                            links.Push(UpstreamLink2);
        //                            Magnitude[currLink] = Magnitude[currLink] + Magnitude[UpstreamLink2];
        //                        }
        //                        else
        //                        {
        //                            ReachConnections[thisreach + 1, 3 - 1] = 0;
        //                        }
        //                        //AddReachShape3(NetSF, FlowNet, CoordList, currLink, BasinID, Magnitude[currLink], dsNodeID[currLink]);
        //                        ReachProperties[thisreach + 1, 3 - 1] = ReachProperties[thisreach, 3 - 1];
        //                        ReachProperties[thisreach + 1, 2 - 1] = ReachProperties[thisreach, 2 - 1];
        //                        ReachProperties[thisreach + 1, 1 - 1] = ReachProperties[thisreach, 1 - 1];
        //                        ReachProperties[thisreach + 1, 4 - 1] = CoordList[(LinkEndArea + LinkBegin) / 2, 0]; //approx midpoint
        //                        ReachProperties[thisreach + 1, 5 - 1] = CoordList[(LinkEndArea + LinkBegin) / 2, 1];
        //                    }
        //                }
        //                else
        //                {
        //                    //This is an external basin
        //                    currReach = currReach + 1;
        //                    thisreach = currReach;
        //                    ReachConnections[thisreach, 1 - 1] = currReach;
        //                    ReachConnections[thisreach, 2 - 1] = numBasins;
        //                    ReachConnections[thisreach, 3 - 1] = 0;
        //                    ReachProperties[thisreach, 3 - 1] = (CoordList[LinkBegin, 3 - 1] - CoordList[LinkEnd, 3 - 1]) / 2;
        //                    ReachProperties[thisreach, 2 - 1] = CoordList[LinkEndArea, 5 - 1];
        //                    if (ReachProperties[thisreach, 3 - 1] <= 0)
        //                    {
        //                        ReachProperties[thisreach, 1 - 1] = 0.01f;
        //                    }
        //                    else
        //                    {
        //                        ReachProperties[thisreach, 1 - 1] = (CoordList[LinkBegin, 4 - 1] - CoordList[LinkEnd, 4 - 1]) / (2 * ReachProperties[thisreach, 3 - 1]);
        //                    }
        //                    ReachProperties[thisreach, 4 - 1] = CoordList[LinkEndArea, 0]; //end x coordinate
        //                    ReachProperties[thisreach, 5 - 1] = CoordList[LinkEndArea, 1]; //end y coordinate

        //                    if (ordert <= 0)
        //                    {
        //                        BasinID = subbno;
        //                    }
        //                    else
        //                    {
        //                        BasinID = numBasins;
        //                    }
        //                    Magnitude[currLink] = 1;  //magnitude of external basin
        //                    //AddReachShape3(NetSF, FlowNet, CoordList, currLink, BasinID, Magnitude[currLink], dsNodeID[currLink]);
        //                }
        //                if (currDSLink != -1 && currDSFrom != -1)
        //                {
        //                    ReachConnections[currDSLink, currDSFrom] = thisreach;
        //                }

        //                if (callback != null) callback.Progress("Status", 100, "Stream Shapefile and Watershed Grid");
        //            }
        //            return 0;
        //        }

        //        private static int MarkBasinsAndNetworkStack(Queue<int> Links, int numBasins, int[,] FlowNet, float[,] CoordList, int currReach, int ordert, int subbno, int[] Magnitude, long[] dsNodeID, int numRows, int numCols, int[,] ReachConnections, float[,] ReachProperties, Raster d8Grid, Raster BasinGrid, Shapefile NetSF, IProgressHandler callback)
        //        {
        //            int newperc = 0;
        //            int oldperc = 0;
        //            bool alreadyMarked = false;
        //            int currLink, row, col, DownstreamLink, LinkEnd, LinkBegin, LinkEndArea = 0;
        //            //  variables for CoordList positions
        //            float x, y;

        //            List<int> marked = new List<int>();
        //            List<MapWinGIS.Point> markedPoint = new List<MapWinGIS.Point>();

        //            int totLinks;
        //            while (Links.Count != 0)
        //            {
        //                totLinks = Links.Count;
        //                if (totLinks > 0)
        //                {
        //                    newperc = Convert.ToInt32((Convert.ToDouble(Links.Count) / Convert.ToDouble(totLinks)) * 100);
        //                    if (newperc > oldperc)
        //                    {
        //                        if (callback != null) callback.Progress("Status", newperc, "Stream Shapefile and Watershed Grid");
        //                        oldperc = newperc;
        //                    }
        //                }

        //                LinkEndArea = 0;

        //                currLink = Links.Dequeue();

        //                if ((FlowNet[currLink, 4] == 0 || (FlowNet[currLink, 4] != 0 && marked.Contains(FlowNet[currLink, 4]))) && (FlowNet[currLink, 5] == 0 || (FlowNet[currLink, 5] != 0 && marked.Contains(FlowNet[currLink, 5]))))
        //                {
        //                    LinkEnd = FlowNet[currLink, 3 - 1];//*  This is CoordList of end of link */
        //                    LinkBegin = FlowNet[currLink, 2 - 1];//*  This is CoordList of beg of link */
        //                    if (LinkBegin < LinkEnd)
        //                    {
        //                        //has physical length
        //                        numBasins = numBasins + 1;
        //                        if (ordert < 0)
        //                        {
        //                            numBasins = subbno;
        //                        }

        //                        if (FlowNet[currLink, 4 - 1] != -1) //For anything other than a downstream end area is defined one grid cell back
        //                        {
        //                            LinkEndArea = LinkEnd - 1;
        //                        }
        //                        else
        //                        {
        //                            LinkEndArea = LinkEnd;
        //                        }

        //                        x = CoordList[LinkEndArea, 1 - 1];
        //                        y = CoordList[LinkEndArea, 2 - 1];
        //                        BasinGrid.ProjToCell(x, y, out col, out row);
        //                        alreadyMarked = false;
        //                        for (int i = 0; i < markedPoint.Count; i++)
        //                        {
        //                            if ((double)col == markedPoint[i].x && (double)row == markedPoint[i].y)
        //                            {
        //                                alreadyMarked = true;
        //                                break;
        //                            }
        //                        }
        //                        if (!alreadyMarked)
        //                        {
        //                            marked.Add(currLink);
        //                            MapWinGIS.Point pt = new MapWinGIS.Point();
        //                            pt.x = (double)col;
        //                            pt.y = (double)row;
        //                            markedPoint.Add(pt);
        //                            MarkBasinAreaStack(d8Grid, row, col, numBasins, numCols, numRows, BasinGrid, callback); //Label the region that drains to this pixel
        //                            AddReachShape(NetSF, FlowNet, CoordList, currLink, numBasins, Magnitude[currLink], dsNodeID[currLink]);
        //                        }
        //                    }
        //                    else
        //                    {
        //                        LinkEndArea = LinkEnd;
        //                        marked.Add(currLink); // CWG 20/7/2010 added to prevent loop
        //                        // CWG 20/7/2010 include zero length links in network shapefile
        //                        AddReachShape(NetSF, FlowNet, CoordList, currLink, 0, Magnitude[currLink], dsNodeID[currLink]);
        //                    }

        //                    DownstreamLink = FlowNet[currLink, 4 - 1];
        //                    if (DownstreamLink >= 0 && !Links.Contains(DownstreamLink) && !marked.Contains(DownstreamLink))
        //                    {
        //                        Links.Enqueue(DownstreamLink);
        //                    }
        //                }
        //                else
        //                {
        //                    Links.Enqueue(currLink);
        //                }
        //            }

        //            return 0;
        //        }

        //        private static void MarkBasinAreaStack(Raster d8Grid, int StartRow, int StartCol, int BasinID, int numCols, int numRows, Raster BasinGrid, IProgressHandler callback)
        //        {
        //            int row;
        //            int col;
        //            int newRow;
        //            int newCol;
        //            int[] rowMod = new int[9];
        //            int[] colMod = new int[9];
        //            rowMod[1] = 0; rowMod[2] = -1; rowMod[3] = -1; rowMod[4] = -1; rowMod[5] = 0; rowMod[6] = 1; rowMod[7] = 1; rowMod[8] = 1;
        //            colMod[1] = 1; colMod[2] = 1; colMod[3] = 0; colMod[4] = -1; colMod[5] = -1; colMod[6] = -1; colMod[7] = 0; colMod[8] = 1;

        //            Stack<int> cells = new Stack<int>();
        //            cells.Push(StartCol);
        //            cells.Push(StartRow);

        //            int totCells = 0, newperc = 0, oldperc = 0;
        //            while (cells.Count != 0)
        //            {
        //                if (totCells > 0)
        //                {
        //                    newperc = Convert.ToInt32((Convert.ToDouble(cells.Count) / Convert.ToDouble(totCells)) * 100);
        //                    if (newperc > oldperc)
        //                    {
        //                        if (callback != null) callback.Progress("Status", newperc, "Stream Shapefile and Watershed Grid");
        //                        oldperc = newperc;
        //                    }
        //                }

        //                row = cells.Pop();
        //                col = cells.Pop();

        //                if ((short)BasinGrid.get_Value(col, row) == -1)
        //                {
        //                    if (row != 0 & row != numRows - 1 & col != 0 & col != numCols - 1 & (short)d8Grid.get_Value(col, row) != -1)
        //                    {
        //                        //Not on boundary
        //                        BasinGrid.set_Value(col, row, BasinID);
        //                        for (int k = 1; k <= 8; k++)
        //                        {
        //                            newRow = row + rowMod[k];
        //                            newCol = col + colMod[k];

        //                            //test if neighbor drains towards cell excluding boundaries
        //                            if ((short)d8Grid.get_Value(newCol, newRow) >= 0 & (((short)d8Grid.get_Value(newCol, newRow) - k) == 4 | ((short)d8Grid.get_Value(newCol, newRow) - k) == -4))
        //                            {
        //                                cells.Push(newCol);
        //                                cells.Push(newRow);
        //                            }
        //                        }
        //                    }
        //                }
        //            }
        //        }

        //        private static void InitializeNetFields(Shapefile netSF)
        //        {
        //            int zero = 0;
        //            MapWinGIS.Field field = new MapWinGIS.Field();
        //            field.Name = "DOUT_MID";
        //            field.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field.Width = 16;
        //            field.Precision = 1;
        //            netSF.EditInsertField(field, zero, null);

        //            MapWinGIS.Field field2 = new MapWinGIS.Field();
        //            field2.Name = "DOUT_START";
        //            field2.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field2.Width = 16;
        //            field2.Precision = 1;
        //            netSF.EditInsertField(field2, zero, null);

        //            MapWinGIS.Field field3 = new MapWinGIS.Field();
        //            field3.Name = "DOUT_END";
        //            field3.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field3.Width = 16;
        //            field3.Precision = 1;
        //            netSF.EditInsertField(field3, zero, null);

        //            MapWinGIS.Field field4 = new MapWinGIS.Field();
        //            field4.Name = "WSNO";
        //            field4.Type = MapWinGIS.FieldType.INTEGER_FIELD;
        //            field4.Width = 6;
        //            field4.Precision = 0;
        //            netSF.EditInsertField(field4, zero, null);

        //            MapWinGIS.Field field5 = new MapWinGIS.Field();
        //            field5.Name = "US_Cont_Area";
        //            field5.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field5.Width = 16;
        //            field5.Precision = 1;
        //            netSF.EditInsertField(field5, zero, null);

        //            MapWinGIS.Field field6 = new MapWinGIS.Field();
        //            field6.Name = "Straight_Length";
        //            field6.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field6.Width = 16;
        //            field6.Precision = 0;
        //            netSF.EditInsertField(field6, zero, null);

        //            MapWinGIS.Field field7 = new MapWinGIS.Field();
        //            field7.Name = "Slope";
        //            field7.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field7.Width = 16;
        //            field7.Precision = 12;
        //            netSF.EditInsertField(field7, zero, null);

        //            MapWinGIS.Field field8 = new MapWinGIS.Field();
        //            field8.Name = "Drop";
        //            field8.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field8.Width = 16;
        //            field8.Precision = 2;
        //            netSF.EditInsertField(field8, zero, null);

        //            MapWinGIS.Field field9 = new MapWinGIS.Field();
        //            field9.Name = "DS_Cont_Area";
        //            field9.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field9.Width = 16;
        //            field9.Precision = 1;
        //            netSF.EditInsertField(field9, zero, null);

        //            MapWinGIS.Field field10 = new MapWinGIS.Field();
        //            field10.Name = "Magnitude";
        //            field10.Type = MapWinGIS.FieldType.INTEGER_FIELD;
        //            field10.Width = 6;
        //            field10.Precision = 0;
        //            netSF.EditInsertField(field10, zero, null);

        //            MapWinGIS.Field field11 = new MapWinGIS.Field();
        //            field11.Name = "Length";
        //            field11.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field11.Width = 16;
        //            field11.Precision = 1;
        //            netSF.EditInsertField(field11, zero, null);

        //            MapWinGIS.Field field12 = new MapWinGIS.Field();
        //            field12.Name = "Order";
        //            field12.Type = MapWinGIS.FieldType.INTEGER_FIELD;
        //            field12.Width = 6;
        //            field12.Precision = 0;
        //            netSF.EditInsertField(field12, zero, null);

        //            MapWinGIS.Field field13 = new MapWinGIS.Field();
        //            field13.Name = "dsNodeID";
        //            field13.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field13.Width = 12;
        //            field13.Precision = 1;
        //            netSF.EditInsertField(field13, zero, null);

        //            MapWinGIS.Field field14 = new MapWinGIS.Field();
        //            field14.Name = "USLINKNO2";
        //            field14.Type = MapWinGIS.FieldType.INTEGER_FIELD;
        //            field14.Width = 6;
        //            field14.Precision = 0;
        //            netSF.EditInsertField(field14, zero, null);

        //            MapWinGIS.Field field15 = new MapWinGIS.Field();
        //            field15.Name = "USLINKNO1";
        //            field15.Type = MapWinGIS.FieldType.INTEGER_FIELD;
        //            field15.Width = 6;
        //            field15.Precision = 0;
        //            netSF.EditInsertField(field15, zero, null);

        //            MapWinGIS.Field field16 = new MapWinGIS.Field();
        //            field16.Name = "DSLINKNO";
        //            field16.Type = MapWinGIS.FieldType.INTEGER_FIELD;
        //            field16.Width = 6;
        //            field16.Precision = 0;
        //            netSF.EditInsertField(field16, zero, null);

        //            MapWinGIS.Field field17 = new MapWinGIS.Field();
        //            field17.Name = "LINKNO";
        //            field17.Type = MapWinGIS.FieldType.INTEGER_FIELD;
        //            field17.Width = 6;
        //            field17.Precision = 0;
        //            netSF.EditInsertField(field17, zero, null);
        //        }

        //        private static int AddReachShape(Shapefile NetSF, int[,] FlowNet, float[,] CoordList, int currLink, int BasinID, int Magnitude, long dsNodeID)
        //        {
        //            double x = 0;
        //            double y = 0;
        //            double length;
        //            double glength;
        //            double x1;
        //            double y1;
        //            double xlast;
        //            double ylast;
        //            double usarea;
        //            double dsarea;
        //            double dslast;
        //            double dl;
        //            double drop;
        //            double slope;
        //            int istart;
        //            int iend;
        //            int zero;

        //            istart = FlowNet[currLink, 1];  //start index for reach
        //            iend = FlowNet[currLink, 2]; //end index for reach
        //            x1 = CoordList[istart, 0]; //start x CoordList for reach
        //            y1 = CoordList[istart, 1]; //start y CoordList for reach
        //            length = 0;
        //            xlast = x1;
        //            ylast = y1;
        //            usarea = CoordList[istart, 4];
        //            dslast = usarea;
        //            dsarea = usarea;

        //            IFeature shp = new IFeature();
        //            shp.Create(MapWinGIS.ShpfileType.SHP_POLYLINE);
        //            for (int j = 0; j <= (iend - istart); j++)
        //            {
        //                x = CoordList[j + istart, 0];
        //                y = CoordList[j + istart, 1];
        //                dl = Math.Sqrt((x - xlast) * (x - xlast) + (y - ylast) * (y - ylast));
        //                if (dl > 0)
        //                {
        //                    length = length + dl;
        //                    xlast = x;
        //                    ylast = y;
        //                    dsarea = dslast; //keeps track of last ds area
        //                    dslast = CoordList[j + istart, 4];
        //                }
        //                MapWinGIS.Point p = new MapWinGIS.Point();
        //                p.x = x;
        //                p.y = y;
        //                zero = 0;
        //                shp.InsertPoint(p, zero);
        //            }
        //            if (iend == istart)
        //            {
        //                MapWinGIS.Point p = new MapWinGIS.Point();
        //                p.x = x;
        //                p.y = y;
        //                int numpts = shp.numPoints;
        //                shp.InsertPoint(p, numpts);
        //            }
        //            drop = CoordList[istart, 3] - CoordList[iend, 3];
        //            slope = 0;
        //            float dsdist = CoordList[iend, 2];
        //            float usdist = CoordList[istart, 2];
        //            float middist = (dsdist + usdist) * 0.5f;
        //            if (length > 0)
        //            {
        //                slope = drop / length;
        //            }
        //            glength = Math.Sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1));
        //            zero = 0;
        //            NetSF.EditInsertShape(shp, zero);
        //            NetSF.EditCellValue(0, 0, currLink);
        //            NetSF.EditCellValue(1, 0, FlowNet[currLink, 3]);
        //            NetSF.EditCellValue(2, 0, FlowNet[currLink, 4]);
        //            NetSF.EditCellValue(3, 0, FlowNet[currLink, 5]);
        //            NetSF.EditCellValue(4, 0, dsNodeID);
        //            NetSF.EditCellValue(5, 0, FlowNet[currLink, 6]);
        //            NetSF.EditCellValue(6, 0, length);
        //            NetSF.EditCellValue(7, 0, Magnitude);
        //            NetSF.EditCellValue(8, 0, dsarea);
        //            NetSF.EditCellValue(9, 0, drop);
        //            NetSF.EditCellValue(10, 0, slope);
        //            NetSF.EditCellValue(11, 0, glength);
        //            NetSF.EditCellValue(12, 0, usarea);
        //            NetSF.EditCellValue(13, 0, BasinID);
        //            NetSF.EditCellValue(14, 0, dsdist);
        //            NetSF.EditCellValue(15, 0, usdist);
        //            NetSF.EditCellValue(16, 0, middist);

        //            return 0;
        //        }

        //        #endregion //converted Subbasinsetup

        //        #endregion

        //        #region "Create Network Outlets"
        //        /// <summary>
        //        /// A function to generate a network outlets shapefile from the tree.dat and coords.dat files.
        //        /// </summary>
        //        /// <param name="TreeDatPath">The path to the tree.dat file</param>
        //        /// <param name="CoordDatPath">The path to the coords.dat file</param>
        //        /// <param name="OutletsShapeResultPath">The output path for the network outlets shapefile</param>
        //        /// <param name="callback">A callback for progress messages</param>
        //        /// <returns></returns>
        //        public static bool CreateNetworkOutlets(string TreeDatPath, string CoordDatPath, string OutletsShapeResultPath, IProgressHandler callback)
        //        {
        //            int newperc = 0;
        //            int oldperc = 0;
        //            int numShps = 0, LinkEnd, LinkBegin, LinkEndArea = 0;
        //            float x, y;

        //            if (callback != null) callback.Progress("Status", 0, "Create Network Outlets");
        //            DataManagement.DeleteShapefile(OutletsShapeResultPath);

        //            Shapefile sf = new Shapefile();
        //            sf.CreateNew(OutletsShapeResultPath, MapWinGIS.ShpfileType.SHP_POINT);
        //            sf.StartEditingShapes(true, null);

        //            int zero = 0;
        //            MapWinGIS.Field field = new MapWinGIS.Field();
        //            field.Name = "MWShapeID";
        //            field.Type = MapWinGIS.FieldType.INTEGER_FIELD;
        //            sf.EditInsertField(field, zero, null);

        //            int numTreeNodes = 0;
        //            long[] dsNodeID;
        //            int[,] FlowNet;
        //            if (ReadTreeFile(TreeDatPath, out FlowNet, out dsNodeID, numTreeNodes) == 1)
        //            {
        //                MessageBox.Show("An error occured in creating the network outlets while reading the tree.dat file.", "Creating Network Outlets Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.DialogResult.OK);
        //                return false;
        //            }

        //            int numCoords = 0;
        //            float[,] CoordList;
        //            if (ReadCoordFile(CoordDatPath, out CoordList, numCoords) == 1)
        //            {
        //                MessageBox.Show("An error occured in creating the network outlets while reading the coords.dat file.", "Creating Network Outlets Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.DialogResult.OK);
        //                return false;
        //            }

        //            for (int i = 0; i <= numTreeNodes; i++)
        //            {
        //                if (numTreeNodes > 0)
        //                {
        //                    newperc = Convert.ToInt32((Convert.ToDouble(i) / Convert.ToDouble(numTreeNodes)) * 100);
        //                    if (newperc > oldperc)
        //                    {
        //                        if (callback != null) callback.Progress("Status", newperc, "Create Network Outlets");
        //                        oldperc = newperc;
        //                    }
        //                }

        //                LinkEnd = FlowNet[i, 3 - 1];//*  This is CoordList of end of link */
        //                LinkBegin = FlowNet[i, 2 - 1];//*  This is CoordList of beg of link */
        //                if (LinkBegin < LinkEnd)
        //                {
        //                    //has physical length
        //                    if (FlowNet[i, 4 - 1] != -1) //For anything other than a downstream end area is defined one grid cell back
        //                    {
        //                        LinkEndArea = LinkEnd - 1;
        //                    }
        //                    else
        //                    {
        //                        LinkEndArea = LinkEnd;
        //                    }

        //                    x = CoordList[LinkEndArea, 1 - 1];
        //                    y = CoordList[LinkEndArea, 2 - 1];

        //                    MapWinGIS.Point pt = new MapWinGIS.Point();
        //                    pt.x = x;
        //                    pt.y = y;
        //                    IFeature shp = new IFeature();
        //                    shp.Create(MapWinGIS.ShpfileType.SHP_POINT);
        //                    shp.InsertPoint(pt, numShps);
        //                    numShps = sf.NumRows();
        //                    sf.EditInsertShape(shp, numShps);
        //                    sf.EditCellValue(0, numShps, numShps);
        //                }
        //            }
        //            sf.Save();
        //            sf.Close();
        //            if (callback != null) callback.Progress("Status", 0, String.Empty);
        //            return true;
        //        }

        //        #endregion

        //        #region "Subbasins to Shapes"
        ///// <summary>
        ///// A function which uses the mapwingis utils to convert the subbasin grid to a polygon shapefile
        ///// </summary>
        ///// <param name="d8Path"></param>
        ///// <param name="watershedGridPath"></param>
        ///// <param name="watershedShapeResultPath"></param>
        ///// <param name="callback">A MapWinGIS.IProgressHandler used to return error messages etc.</param>
        ///// <returns>0 on success, -1 otherwise </returns>
        //public static int SubbasinsToShape(string d8Path, string watershedGridPath, string watershedShapeResultPath, IProgressHandler callback)
        //{
        //    var result = -1;
        //    var gridD8 = new Grid();
        //    var gridWatershed = new Grid();

        //    var u = new MapWinGIS.Utils();

        //    if (callback != null)
        //    {
        //        callback.Progress("Status", 0, "Watershed Grid to Shapefile");
        //    }

        //    //DataManagement.DeleteShapefile(watershedShapeResultPath);
        //    gridD8.Open(d8Path, GridDataType.UnknownDataType, true, GridFileType.UseExtension, callback);
        //    gridWatershed.Open(watershedGridPath, GridDataType.UnknownDataType, true, GridFileType.UseExtension, callback);
        //    var sf = u.GridToShapefile(gridWatershed, gridD8, callback);
        //    if (sf.SaveAs(watershedShapeResultPath, callback))
        //    {
        //        result = 0;
        //    }

        //    sf.Projection = gridD8.Projection.ToString();
        //    gridD8.Close();

        //    gridWatershed.Close();
        //    sf.Close();

        //    if (callback != null)
        //    {
        //        callback.Progress("Status", 0, string.Empty);
        //    }

        //    return result;
        //}

        //        /// <summary>
        //        /// An overload of the SubbasinsToShape function which will generate a GeoprocDialog for the SubbasinsToShape function
        //        /// </summary>
        //        /// <param name="callback"></param>
        //        /// <returns></returns>
        //        public static int SubbasinsToShape(IProgressHandler callback)
        //        {
        //            return doSubbasinsToShapeDiag(callback);
        //        }

        //        /// <summary>
        //        /// An overload of the SubbasinsToShape function which will generate a GeoprocDialog for the SubbasinsToShape function
        //        /// </summary>
        //        /// <returns></returns>
        //        public static int SubbasinsToShape()
        //        {
        //            return doSubbasinsToShapeDiag(null);
        //        }

        //        private static int doSubbasinsToShapeDiag(IProgressHandler callback)
        //        {
        //            GeoProcDialog subtoshapeDiag = new GeoProcDialog();
        //            FileElement d8Elem = subtoshapeDiag.Add_FileElement(GeoProcDialog.ElementTypes.OpenGridFile);
        //            FileElement shedGridElem = subtoshapeDiag.Add_FileElement(GeoProcDialog.ElementTypes.OpenGridFile);
        //            FileElement shedShapeResElem = subtoshapeDiag.Add_FileElement(GeoProcDialog.ElementTypes.SaveShapefile);

        //            subtoshapeDiag.Text = "Sub-basins to Shapefile Conversion";
        //            subtoshapeDiag.HelpTitle = "Sub-basins to Shapefile Conversion";
        //            subtoshapeDiag.HelpText = "This function will generate a polygon shapefile of sub-basins from a sub-basin grid and D8 grid.";
        //            subtoshapeDiag.Height = 250;
        //            subtoshapeDiag.HelpPanelVisible = false;

        //            d8Elem.Caption = "D8 Flow Direction Grid Path";
        //            d8Elem.HelpButtonVisible = false;

        //            shedGridElem.Caption = "Sub-basins Grid Result Path";
        //            shedGridElem.HelpButtonVisible = false;

        //            shedShapeResElem.Caption = "Sub-basins Shapefile Result Path";
        //            shedShapeResElem.HelpButtonVisible = false;

        //            if (subtoshapeDiag.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //            {
        //                return Hydrology.SubbasinsToShape(d8Elem.Filename, shedGridElem.Filename, shedShapeResElem.Filename, callback);
        //            }
        //            return -2;
        //        }

        //        #endregion

        //        #region Move outlets to streams
        //        /// <summary>
        //        /// Move outlets down slope in d8Path to streams in StreamGridPath
        //        /// </summary>
        //        /// <param name="D8Path">D8 slope grid</param>
        //        /// <param name="StreamGridPath">grid of streams</param>
        //        /// <param name="OutletsPath">Point shape file of outlets and inlets</param>
        //        /// <param name="MovedOutletsPath">Result point shape file of moved outlets and inlets</param>
        //        /// <param name="Thresh">threshold</param>
        //        /// <param name="numProcesses">Limit on number of threads</param>
        //        /// <param name="showTaudemOutput">taudem output is shown if this is true</param>
        //        /// <param name="callback"></param>
        //        /// <returns>0 if success</returns>
        //        public static int MoveOutletsToStreams(string D8Path, string StreamGridPath, string OutletsPath, string MovedOutletsPath, int Thresh, int numProcesses, bool showTaudemOutput, IProgressHandler callback)
        //        {
        //           Trace.WriteLine("MoveOutletsToStreams(d8Path: " + D8Path + ",\n" +
        //                                     "       StreamGridPath: " + StreamGridPath + ",\n" +
        //                                     "       outletsPath: " + OutletsPath + ",\n" +
        //                                     "       MovedOutletsPath: " + MovedOutletsPath + ",\n" +
        //                                     "       threshold: " + Thresh + ",\n" +
        //                                     "       NumProcesses: " + numProcesses.ToString() + "\n" +
        //                                     "       ShowTaudemOutput: " + showTaudemOutput.ToString() + "\n" +
        //                                     "       callback)");
        //            int result = -1;
        //            DataManagement.DeleteShapefile(MovedOutletsPath);

        //            if (callback != null) callback.Progress("Status", 0, "Move Outlets to Streams");

        //            string pars =
        //                "-p " + D8Path +
        //                " -src " + StreamGridPath +
        //                " -o " + OutletsPath +
        //                " -om " + MovedOutletsPath +
        //                " -md " + Thresh.ToString();
        //            result = RunTaudem("MoveOutletsToStreams.exe", pars, numProcesses, showTaudemOutput);
        //            if (result != 0)
        //            {
        //                MessageBox.Show("TauDEM Error " + result, "TauDEM Error " + result, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.DialogResult.OK);
        //                return result;
        //            }

        //            DataManagement.TryCopy(System.IO.Path.ChangeExtension(OutletsPath, ".prj"),
        //                                   System.IO.Path.ChangeExtension(MovedOutletsPath, ".prj"));
        //            if (callback != null) callback.Progress("Status", 0, String.Empty);
        //           Trace.WriteLine("Finished Move Outlets to Streams");
        //            return result;
        //        }
        //        #endregion

        //        #region "Apply Stream Attributes"

        /// <summary>
        ///   Hydrology function used to add to the stream shapefile attributes
        /// </summary>
        /// <param name = "streamNetworkShapePath"></param>
        /// <param name = "demPath"></param>
        /// <param name = "subBasinShapePath"></param>
        /// <param name = "elevUnits"></param>
        /// <param name = "callback"></param>
        /// <returns></returns>
        public static bool ApplyStreamAttributes(
            string streamNetworkShapePath,
            string demPath,
            string subBasinShapePath,
            ElevationUnits elevUnits,
            IProgressHandler callback)
        {
            int sindx;
            int oldperc = 0;
            const int IDField = 0;
            const int DsField = 1;
            const int Us1Field = 2;
            const int Us2Field = 3;
            const int DsAreaField = 8;
            const int SlopeField = 10;
            const int UsAreaField = 12;

            if (callback != null)
            {
                callback.Progress("Status", 0, "Calculating Stream Parameters");
            }

            if (!File.Exists(streamNetworkShapePath))
            {
                MessageBox.Show(string.Format(@"The file {0} does not exists! ", streamNetworkShapePath));
                return false;
            }

            IFeatureSet streamShape = FeatureSet.Open(streamNetworkShapePath);
            if (streamShape == null)
            {
                throw new ApplicationException(String.Format("Error in opening {0}", streamNetworkShapePath));
            }
            int streamShapeNumShapes = streamShape.NumRows();

            // Add some fields:
            int lowFieldNum = AddField(streamShape, "ElevLow", typeof(double));
            int highFieldNum = AddField(streamShape, "Elevhigh", typeof(double));
            int mwidthFieldNum = AddField(streamShape, "MeanWidth", typeof(double));
            int mdepthFieldNum = AddField(streamShape, "MeanDepth", typeof(double));
            int dsareaAcreFieldNum = AddField(streamShape, "DSAreaAcre", typeof(double));
            int dsareaSqMiFieldNum = AddField(streamShape, "USAreaAcre", typeof(double));
            int usareaAcreFieldNum = AddField(streamShape, "DSAreaSqMi", typeof(double));
            int usareaSqMiFieldNum = AddField(streamShape, "USAreaSqMi", typeof(double));

            DotSpatial.Projections.ProjectionInfo projStr = streamShape.Projection;
            IRaster demGrid = Raster.Open(demPath);
            IFeatureSet shedShape = FeatureSet.Open(subBasinShapePath);
            int shedShapeNumShapes = shedShape.NumRows();

            for (sindx = 0; sindx < streamShapeNumShapes; sindx++)
            {
                if (callback != null && streamShapeNumShapes > 1)
                {
                    int newperc = Convert.ToInt32((Convert.ToDouble(sindx) / Convert.ToDouble(shedShapeNumShapes)) * 100);
                    if (newperc > oldperc)
                    {
                        callback.Progress("Status", newperc, "Calculating Stream Parameters");
                        oldperc = newperc;
                    }
                }

                int OriginalStreamID = Convert.ToInt32(streamShape.get_CellValue(IDField, sindx));

                double elevlow;
                double elevhigh;
                GetStreamElevationPoints(sindx, streamShape, demGrid, out elevlow, out elevhigh);

                switch (elevUnits)
                {
                    case ElevationUnits.centimeters:
                        elevlow /= 100;
                        elevhigh /= 100;
                        break;
                    case ElevationUnits.feet:
                        elevlow /= 3.280839895;
                        elevhigh /= 3.280839895;
                        break;
                }

                streamShape.EditCellValue(lowFieldNum, sindx, elevlow);
                streamShape.EditCellValue(highFieldNum, sindx, elevhigh);

                // Assume the first field in the watershed shape file is an ID field that corresponds to the IDs in streamShape IDField
                // GridToShapeManhattan creates this field for watershed shapes
                const int WShedIDField = 0;
                for (int shdindx = 0; shdindx < shedShapeNumShapes; shdindx++)
                {
                    if (Convert.ToInt32(shedShape.get_CellValue(WShedIDField, shdindx)) == OriginalStreamID)
                    {
                        var currShp = shedShape.get_Shape(shdindx);
                        double currArea = Utils.AreaOfPart(currShp, 0);
                        double meanWidth = 1.29 * Math.Pow(currArea / 1000000, 0.6);
                        double meanDepth = 0.13 * Math.Pow(currArea / 1000000, 0.4);
                        streamShape.EditCellValue(mwidthFieldNum, sindx, meanWidth);
                        streamShape.EditCellValue(mdepthFieldNum, sindx, meanDepth);
                        break;
                    }
                }

                // Change shape ID (and down/upstream IDs) from zero-based to one-based
                streamShape.EditCellValue(IDField, sindx, OriginalStreamID+1);

                int tmpID = Convert.ToInt32(streamShape.get_CellValue(DsField, sindx));
                if (tmpID > -1)
                {
                    tmpID++;
                }
                streamShape.EditCellValue(DsField, sindx, tmpID);

                tmpID = Convert.ToInt32(streamShape.get_CellValue(Us1Field, sindx));
                if (tmpID > 0)
                {
                    tmpID++;
                }
                else
                {
                    tmpID = -1;
                }
                streamShape.EditCellValue(Us1Field, sindx, tmpID);

                tmpID = Convert.ToInt32(streamShape.get_CellValue(Us2Field, sindx));
                if (tmpID > 0)
                {
                    tmpID++;
                }
                else
                {
                    tmpID = -1;
                }
                streamShape.EditCellValue(Us2Field, sindx, tmpID);

                double tmpSlope = Convert.ToDouble(streamShape.get_CellValue(SlopeField, sindx));
                double tmpDsArea = Convert.ToDouble(streamShape.get_CellValue(DsAreaField, sindx));
                double tmpUsArea = Convert.ToDouble(streamShape.get_CellValue(UsAreaField, sindx));

                if (projStr != null)
                {
                    if (projStr.Unit.Name == "Meter")
                    {
                        double dsAreaAcre = tmpDsArea * 0.000247105;
                        double dsAreaSqMi = dsAreaAcre * 0.0015625;
                        double usAreaAcre = tmpUsArea * 0.000247105;
                        double usAreaSqMi = usAreaAcre * 0.0015625;
                        streamShape.EditCellValue(dsareaAcreFieldNum, sindx, dsAreaAcre);
                        streamShape.EditCellValue(dsareaSqMiFieldNum, sindx, dsAreaSqMi);
                        streamShape.EditCellValue(usareaAcreFieldNum, sindx, usAreaAcre);
                        streamShape.EditCellValue(usareaSqMiFieldNum, sindx, usAreaSqMi);
                        switch (elevUnits)
                        {
                            case ElevationUnits.meters:
                                tmpSlope = tmpSlope * 100;
                                break;
                            case ElevationUnits.centimeters:
                                break;
                            case ElevationUnits.feet:
                                tmpSlope = (tmpSlope / 3.280839895) * 100;
                                break;
                        }

                        streamShape.EditCellValue(SlopeField, sindx, tmpSlope);
                    }
                    else if (projStr.Unit.Name == "Foot")
                    {
                        double dsAreaAcre = tmpDsArea * 2.2957E-05;
                        double dsAreaSqMi = dsAreaAcre * 0.0015625;
                        double usAreaAcre = tmpUsArea * 2.2957E-05;
                        double usAreaSqMi = usAreaAcre * 0.0015625;
                        streamShape.EditCellValue(dsareaAcreFieldNum, sindx, dsAreaAcre);
                        streamShape.EditCellValue(dsareaSqMiFieldNum, sindx, dsAreaSqMi);
                        streamShape.EditCellValue(usareaAcreFieldNum, sindx, usAreaAcre);
                        streamShape.EditCellValue(usareaSqMiFieldNum, sindx, usAreaSqMi);
                        switch (elevUnits)
                        {
                            case ElevationUnits.meters:
                                tmpSlope = (tmpSlope * 3.280839895) * 100;
                                break;
                            case ElevationUnits.centimeters:
                                tmpSlope = (tmpSlope / 30.48) * 100;
                                break;
                            case ElevationUnits.feet:
                                tmpSlope = tmpSlope * 100;
                                break;
                        }

                        streamShape.EditCellValue(SlopeField, sindx, tmpSlope);
                    }
                }
                else
                {
                    double dSAreaAcre = tmpDsArea * 0.000247105;
                    double dsAreaSqMi = dSAreaAcre * 0.0015625;
                    double uSAreaAcre = tmpUsArea * 0.000247105;
                    double uSAreaSqMi = uSAreaAcre * 0.0015625;
                    streamShape.EditCellValue(dsareaAcreFieldNum, sindx, dSAreaAcre);
                    streamShape.EditCellValue(dsareaSqMiFieldNum, sindx, dsAreaSqMi);
                    streamShape.EditCellValue(usareaAcreFieldNum, sindx, uSAreaAcre);
                    streamShape.EditCellValue(usareaSqMiFieldNum, sindx, uSAreaSqMi);
                    switch (elevUnits)
                    {
                        case ElevationUnits.meters:
                            tmpSlope = tmpSlope * 100;
                            break;
                        case ElevationUnits.centimeters:
                            break;
                        case ElevationUnits.feet:
                            tmpSlope = (tmpSlope / 3.280839895) * 100;
                            break;
                    }

                    streamShape.EditCellValue(SlopeField, sindx, tmpSlope);
                }
            }

            shedShape.Close();
            demGrid.Close();

            streamShape.Save();
            streamShape.Close();

            if (callback != null)
            {
                callback.Progress("Status", 0, String.Empty);
            }

            return true;
        }
Esempio n. 4
0
        //        #endregion

        //        #region "Apply Joined Basin Attributes"
        /// <summary>
        /// A function to apply attributes to a joined basin shapefile
        /// </summary>
        /// <param name="JoinBasinShapePath"></param>
        /// <param name="elevUnits"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public static bool ApplyJoinBasinAreaAttributes(string JoinBasinShapePath, ElevationUnits elevUnits, IProgressHandler callback)
        {
            if (callback != null) callback.Progress("Status", 0, "Calculating Merge Shed Area Attributes");
            double currarea;
            double aream;
            double areasqmi;
            double areaacre;

            int oldperc = 0;
            int newperc = 0;
            var mergeshed = FeatureSet.Open(JoinBasinShapePath);

            int areamfieldnum = mergeshed.DataTable.Columns.Count;
            mergeshed.DataTable.Columns.Add("Area_M", typeof(double));

            int areaacfieldnum = mergeshed.DataTable.Columns.Count;
            mergeshed.DataTable.Columns.Add("Area_Acre", typeof(double));

            int areasqmifieldnum = mergeshed.DataTable.Columns.Count;
            mergeshed.DataTable.Columns.Add("Area_SqMi", typeof(double));

            var projection = mergeshed.Projection;
            for (int i = 0; i <= mergeshed.NumRows() - 1; i++)
            {
                if (mergeshed.NumRows() > 1)
                {
                    newperc = Convert.ToInt32((Convert.ToDouble(i) / Convert.ToDouble(mergeshed.NumRows())) * 100);
                    if ((newperc > oldperc))
                    {
                        if (callback != null) callback.Progress("Status", newperc, "Calculating Merge Shed Area Attributes");
                        oldperc = newperc;
                    }
                }

                IFeature currShape = mergeshed.get_Shape(i);
                currarea = Utils.AreaOfPart(currShape, 0);
                aream = 0;
                if (projection != null)
                {
                    if ((projection.Unit.Name == "Meter"))
                    {
                        aream = currarea;
                    }
                    else if ((projection.Unit.Name == "Foot"))
                    {
                        aream = currarea * 0.09290304;
                    }
                }
                else
                {
                    aream = currarea;
                }
                areaacre = aream * 0.000247105;
                areasqmi = areaacre * 0.0015625;
                mergeshed.EditCellValue(areamfieldnum, i, aream);
                mergeshed.EditCellValue(areaacfieldnum, i, areaacre);
                mergeshed.EditCellValue(areasqmifieldnum, i, areasqmi);
            }
            mergeshed.Save();
            mergeshed.Close();

            if (callback != null) callback.Progress(String.Empty, 0, String.Empty);
            return true;
        }
Esempio n. 5
0
        //        /// <summary>
        //        /// A function to generation only the path length grids using taudem GridNet
        //        /// </summary>
        //        /// <param name="D8Path"></param>
        //        /// <param name="StrahlOrdResultPath"></param>
        //        /// <param name="LongestUpslopeResultPath"></param>
        //        /// <param name="TotalUpslopeResultPath"></param>
        //        /// <param name="numProcesses">Number of threads to be used by Taudem</param>
        //        /// <param name="showTaudemOutput">Show Taudem output if true</param>
        //        /// <param name="callback"></param>
        //        /// <returns></returns>
        //        public static int PathLength(string D8Path, string StrahlOrdResultPath, string LongestUpslopeResultPath, string TotalUpslopeResultPath, int numProcesses, bool showTaudemOutput, IProgressHandler callback)
        //        {
        //           Trace.WriteLine("PathLength: " + D8Path + "\n" +
        //                                     "strahlOrdResultPath: " + StrahlOrdResultPath + "\n" +
        //                                     "longestUpslopeResultPath: " + LongestUpslopeResultPath + "\n" +
        //                                     "totalUpslopeResultPath: " + TotalUpslopeResultPath + "\n" +
        //                                     "NumProcesses: " + numProcesses.ToString() + "\n" +
        //                                     "ShowTaudemOutput: " + showTaudemOutput.ToString() + "\n" +
        //                                     "callback)");
        //            int result = -1;
        //            string pars =
        //                "-p " + Quote(D8Path) +
        //                " -plen " + Quote(LongestUpslopeResultPath) +
        //                " -tlen " + Quote(TotalUpslopeResultPath) +
        //                " -gord " + Quote(StrahlOrdResultPath);
        //            result = RunTaudem("GridNet.exe", pars, numProcesses, showTaudemOutput);

        //            if (result != 0)
        //            {
        //                MessageBox.Show("TauDEM Error " + result, "TauDEM Error " + result, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.DialogResult.OK);

        //                return result;
        //            }

        //            CopyProjectionFromGrid(D8Path, StrahlOrdResultPath);
        //            CopyProjectionFromGrid(D8Path, LongestUpslopeResultPath);
        //            CopyProjectionFromGrid(D8Path, TotalUpslopeResultPath);
        //            if (callback != null) callback.Progress("Status", 0, String.Empty);
        //            return result;
        //        }

        //        #region "     Grid Net conversion"

        //        private static int GridNet(string pfile, string plenfile, string tlenfile, string gordfile, string afile, double[] x, double[] y, long nxy, int useMask, int useOutlets, int thresh, IProgressHandler callback)
        //        {
        //            int row, col;
        //            double dx, dy, nx, ny;
        //            int err = 0;
        //            int[] d1 = new int[9];
        //            int[] d2 = new int[9];
        //            double[] dist = new double[9];

        //            /* define directions */
        //            d1[1] = 0; d1[2] = -1; d1[3] = -1; d1[4] = -1; d1[5] = 0; d1[6] = 1; d1[7] = 1; d1[8] = 1;
        //            d2[1] = 1; d2[2] = 1; d2[3] = 0; d2[4] = -1; d2[5] = -1; d2[6] = -1; d2[7] = 0; d2[8] = 1;

        //            Raster sdir = new Raster();
        //            if (sdir.Open(pfile, RasterDataType.UnknownDataType, true, RasterFileType.UseExtension, null))
        //            {
        //                err = 0;
        //            }
        //            else
        //            {
        //                err = 1; //TD_FAILED_GRID_OPEN
        //            }
        //            if (err != 0) return err;
        //            dx = sdir.Header.dX;
        //            dy = sdir.Header.dY;
        //            nx = sdir.NumColumns;
        //            ny = sdir.NumRows;

        //            Raster laag = new Raster();
        //            if (useMask == 1)
        //            {
        //                /*   read mask  */
        //                if (laag.Open(afile, RasterDataType.UnknownDataType, true, RasterFileType.UseExtension, null))
        //                {
        //                    err = 0;
        //                }
        //                else
        //                {
        //                    err = 1; //TD_FAILED_GRID_OPEN
        //                }
        //                if (err != 0) return err;
        //            }
        //            else
        //            {
        //                RasterHeader laagHead = new RasterHeader();
        //                laagHead.CopyFrom(sdir.Header);
        //                laag.CreateNew(afile, laagHead, RasterDataType.LongDataType, 0, true, RasterFileType.UseExtension, null);
        //            }

        //            RasterHeader sordgHead = new RasterHeader();
        //            sordgHead.CopyFrom(sdir.Header);
        //            sordgHead.NodataValue = -1;
        //            Raster sordg = new Raster();
        //            sordg.CreateNew(gordfile, sordgHead, RasterDataType.ShortDataType, sordgHead.NodataValue, true, RasterFileType.UseExtension, null);

        //            RasterHeader fltpgHead = new RasterHeader();
        //            fltpgHead.CopyFrom(sdir.Header);
        //            fltpgHead.NodataValue = -1;
        //            Raster fltpg = new Raster();
        //            fltpg.CreateNew(tlenfile, fltpgHead, RasterDataType.FloatDataType, fltpgHead.NodataValue, true, RasterFileType.UseExtension, null);

        //            RasterHeader flengHead = new RasterHeader();
        //            flengHead.CopyFrom(sdir.Header);
        //            flengHead.NodataValue = -1;
        //            Raster fleng = new Raster();
        //            fleng.CreateNew(plenfile, flengHead, RasterDataType.FloatDataType, flengHead.NodataValue, true, RasterFileType.UseExtension, null);

        //            /*  Calculate Distances  */
        //            for (int i = 1; i <= 8; i++)
        //            {
        //                dist[i] = Math.Sqrt(d1[i] * d1[i] * dy * dy + d2[i] * d2[i] * dx * dx);
        //            }

        //            if (useOutlets == 1)  /*  Only compute area's for designated locations  */
        //            {
        //                for (int curXY = 0; curXY < nxy; curXY++)
        //                {
        //                    sdir.ProjToCell(x[curXY], y[curXY], out col, out row);
        //                    if (row < 0 || row > ny || col < 0 || col > nx)
        //                    {
        //                        row = 0; col = 0;
        //                    }
        //                    d2area(row, col, nx, ny, d1, d2, dist, thresh, sdir, laag, sordg, fltpg, fleng);
        //                }
        //            }
        //            else
        //            {
        //                for (int i = 0; i < ny; i++)
        //                    for (int j = 0; j < nx; j++)
        //                        d2area(i, j, nx, ny, d1, d2, dist, thresh, sdir, laag, sordg, fltpg, fleng);
        //            }

        //            if (fleng.Save(plenfile, RasterFileType.UseExtension, null))
        //            {
        //                err = 0;
        //            }
        //            else
        //            {
        //                err = 2; //TD_FAILED_GRID_SAVE
        //                return err;
        //            }

        //            if (fltpg.Save(tlenfile, RasterFileType.UseExtension, null))
        //            {
        //                err = 0;
        //            }
        //            else
        //            {
        //                err = 2; //TD_FAILED_GRID_SAVE
        //                return err;
        //            }

        //            if (sordg.Save(gordfile, RasterFileType.UseExtension, null))
        //            {
        //                err = 0;
        //            }
        //            else
        //            {
        //                err = 2; //TD_FAILED_GRID_SAVE
        //                return err;
        //            }

        //            sordg.Close();
        //            laag.Close();
        //            fltpg.Close();
        //            fleng.Close();

        //            return err;
        //        }

        //        private static void d2area(int i, int j, double nx, double ny, int[] d1, int[] d2, double[] dist, int thresh, Raster sdir, Raster laag, Raster sordg, Raster fltpg, Raster fleng)
        //        {
        //            int ni, nj;
        //            short a1, a2;
        //            double ld;

        //            if ((short)sordg.get_Value(j, i) <= 0)
        //            {
        //                if (i != 0 && i != ny - 1 && j != nx - 1 && (short)sdir.get_Value(j, i) != -32767)
        //                {
        //                    sordg.set_Value(j, i, 1);
        //                    fltpg.set_Value(j, i, 0);
        //                    fleng.set_Value(j, i, 0);
        //                    a1 = 0;
        //                    a2 = 0;

        //                    for (int k = 1; k <= 8; k++)
        //                    {
        //                        ni = i + d1[k];
        //                        nj = j + d2[k];

        //                        /* test if neighbor drains towards cell excluding boundaries */
        //                        if ((short)sdir.get_Value(nj, ni) >= 0)
        //                        {
        //                            if ((int)laag.get_Value(nj, ni) >= thresh && ((short)sdir.get_Value(nj, ni) - k == 4 || (short)sdir.get_Value(nj, ni) - k == -4))
        //                            {
        //                                d2area(ni, nj, nx, ny, d1, d2, dist, thresh, sdir, laag, sordg, fltpg, fleng);
        //                                if ((short)sordg.get_Value(nj, ni) >= a1)
        //                                {
        //                                    a2 = a1;
        //                                    a1 = (short)sordg.get_Value(nj, ni);
        //                                }
        //                                else if ((short)sordg.get_Value(nj, ni) > a2)
        //                                {
        //                                    a2 = (short)sordg.get_Value(nj, ni);
        //                                }

        //                                ld = (float)fleng.get_Value(nj, ni) + dist[(short)sdir.get_Value(nj, ni)];
        //                                fltpg.set_Value(j, i, (float)fltpg.get_Value(j, i) + (float)fltpg.get_Value(nj, ni) + dist[(short)sdir.get_Value(nj, ni)]);
        //                                if (ld > (float)fleng.get_Value(j, i))
        //                                {
        //                                    fleng.set_Value(j, i, ld);
        //                                }
        //                            }
        //                        }
        //                    }
        //                    if (a2 + 1 > a1)
        //                    {
        //                        sordg.set_Value(j, i, a2 + 1);
        //                    }
        //                    else
        //                    {
        //                        sordg.set_Value(j, i, a1);
        //                    }
        //                }
        //            }
        //        }

        //        #endregion //GridNet conversion

        //        #region "     Source Def conversion"

        //        private static int SourceDef(string areafile, string slopefile, string plenfile, string dirfile, string srcfile, string elvfile, string gordfile, string scafile, string fdrfile, int ipar, float[] p, int nxy, double[] x, double[] y, int contcheck, int dropan, int masksca, IProgressHandler callback)
        //        {
        //            int err = 0;

        //            //    float ndvs,ndvp,ndvd,emax,ndve,ndvo,wsum,val;

        //            //    float **selev ;

        //            //    /**********Grid Declarations*************/
        //            //    fgrid faagrid;
        //            //    fgrid fplengrid;
        //            //    sgrid sgordgrid;
        //            //    //=============================
        //            //    int row, col, i,j,iomax,jomax,bound,ik,jk,k,itresh;
        //            //    err = TD_NO_ERROR;
        //            //    int rcgood=1;
        //            //    ccheck=contcheck;

        //            //    /* define directions */
        //            //    d1[1]=0; d1[2]= -1; d1[3]= -1; d1[4]= -1; d1[5]=0; d1[6]=1; d1[7]=1; d1[8]=1;
        //            //    d2[1]=1; d2[2]=1; d2[3]=0; d2[4]= -1; d2[5]= -1; d2[6]= -1; d2[7]=0; d2[8]=1;

        //            //    /* read grid files */
        //            //    if(ipar == 1)
        //            //    {
        //            //        if(gridread(areafile,&faagrid,&filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //        {
        //            //            err=TD_FAILED_GRID_OPEN;
        //            //        }

        //            //        nx = faagrid.head.nx;
        //            //        ny = faagrid.head.ny;
        //            //        dx = faagrid.head.dx;
        //            //        dy = faagrid.head.dy;
        //            //        csize = dx;
        //            //        ndva = faagrid.nodata;
        //            //        for(i=0;i<4;i++) bndbox[i]=faagrid.head.bndbox[i];

        //            //        if(err != TD_NO_ERROR)goto ERROR1;
        //            //    }

        //            //    if(ipar == 2)
        //            //    {
        //            //        if ( gridread(scafile,&faagrid,&filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //            err=TD_FAILED_GRID_OPEN;

        //            //        nx =faagrid.head.nx;
        //            //        ny = faagrid.head.ny;
        //            //        dx = faagrid.head.dx;
        //            //        dy = faagrid.head.dy;
        //            //        csize = dx;
        //            //        ndva = faagrid.nodata;
        //            //        for(i=0;i<4;i++) bndbox[i]=faagrid.head.bndbox[i];

        //            //        if(err != TD_NO_ERROR)goto ERROR1;

        //            //        if ( gridread(slopefile,&fslopeg,&filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //            err=TD_FAILED_GRID_OPEN;

        //            //        ndvs = fslopeg.nodata;

        //            //        if(err != TD_NO_ERROR)goto ERROR1;
        //            //    }
        //            //    if(ipar == 3)
        //            //    {
        //            //        if ( gridread(scafile,&faagrid,&filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //            err=TD_FAILED_GRID_OPEN;

        //            //        nx = faagrid.head.nx;
        //            //        ny = faagrid.head.ny;
        //            //        dx = faagrid.head.dx;
        //            //        dy = faagrid.head.dy;
        //            //        csize = dx;
        //            //        ndva = faagrid.nodata;
        //            //        for(i=0;i<4;i++) bndbox[i]=faagrid.head.bndbox[i];

        //            //        if(err != TD_NO_ERROR)goto ERROR1;

        //            //        if ( gridread(plenfile,&fplengrid,&filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //            err=TD_FAILED_GRID_OPEN;

        //            //        ndvp = fplengrid.nodata;

        //            //        if(err != TD_NO_ERROR)goto ERROR1;
        //            //    }
        //            //    if(ipar == 4)
        //            //    {
        //            //        if( gridread(elvfile,&felevg,&filetype)==0)

        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //            err=TD_FAILED_GRID_OPEN;

        //            //        nx = felevg.head.nx;
        //            //        ny = felevg.head.ny;
        //            //        dx = felevg.head.dx;
        //            //        dy = felevg.head.dy;
        //            //        csize = dx;
        //            //        ndve = felevg.nodata;
        //            //        for(i=0;i<4;i++) bndbox[i]=felevg.head.bndbox[i];

        //            //        if(err != TD_NO_ERROR)goto ERROR1;
        //            //    }
        //            //    if(ipar == 5)
        //            //    {
        //            //        if ( gridread(gordfile,&sgordgrid,&filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //            err=TD_FAILED_GRID_OPEN;

        //            //        nx = sgordgrid.head.nx;
        //            //        ny = sgordgrid.head.ny;
        //            //        dx = sgordgrid.head.dx;
        //            //        dy = sgordgrid.head.dy;
        //            //        csize = dx;
        //            //        ndvo = sgordgrid.nodata;
        //            //        for(i=0;i<4;i++)bndbox[i]=sgordgrid.head.bndbox[i];

        //            //        if(err != TD_NO_ERROR)goto ERROR1;
        //            //    }
        //            //    if(ipar == 6)
        //            //    {
        //            //        if (gridread(fdrfile,&sgordgrid,&filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //            err=TD_FAILED_GRID_OPEN;

        //            //        nx = sgordgrid.head.nx;
        //            //        ny = sgordgrid.head.ny;
        //            //        dx = sgordgrid.head.dx;
        //            //        dy = sgordgrid.head.dy;
        //            //        csize = dx;
        //            //        ndvo = sgordgrid.nodata;
        //            //        for(i=0;i<4;i++)bndbox[i]=sgordgrid.head.bndbox[i];

        //            //        if(err != TD_NO_ERROR)goto ERROR1;
        //            //    }

        //            //    if((src = (short **)matalloc(nx,ny, RPSHRDTYPE)) == NULL)
        //            //    {
        //            //        err=TD_FAILED_MEMORY_ALLOC;
        //            //        //  printf("Could not allocate memory for src\n");
        //            //        goto ERROR1;
        //            //    }

        //            //    /*  Flag sources  */
        //            //    for(i=0; i < ny; i++)
        //            //        for(j=0; j< nx; j++)
        //            //        {
        //            //            src[j][i] = 0;
        //            //            if(ipar == 1)   /*  Area threshold   */
        //            //            {
        //            //                src[j][i] = (faagrid.d[j][i] >= p[0]) ? 1 : 0;
        //            //            }
        //            //            else if(ipar == 2)   /*  Slope and area combination   */
        //            //            {
        //            //                if( fslopeg.d[j][i] > 0.)
        //            //                {
        //            //                    val = (faagrid.d[j][i] * pow((double)fslopeg.d[j][i],(double)p[1])) ;
        //            //                    src[j][i] = (val >= p[0])	  ? 1: 0;
        //            //                }
        //            //            }else if(ipar == 3)  /*  Slope and Length combination   */
        //            //            {
        //            //                if(fplengrid.d[j][i] > 0.)
        //            //                {
        //            //                    src[j][i] = (faagrid.d[j][i] >= p[0]* pow((double)fplengrid.d[j][i],(double)p[1]))
        //            //                        ? 1: 0;
        //            //                }
        //            //            }
        //            //            else if(ipar == 5)  /*  Grid order threshold  */
        //            //                src[j][i] = (sgordgrid.d[j][i] >= p[0]) ? 1: 0;
        //            //            else if(ipar == 6)  /*  Given flow directions threshold  */
        //            //                src[j][i] = (sgordgrid.d[j][i] > 0) ? 1: 0;
        //            //        }
        //            //        if(ipar == 4)  /* Peuker and Douglas algorithm  */
        //            //        {
        //            //            /*  Initialize internal cells to 1 for Peuker and Douglas algorithm and smooth  */
        //            //            if((selev = (float **)matalloc(nx,ny, RPFLTDTYPE)) == NULL)
        //            //            {
        //            //                err=TD_FAILED_MEMORY_ALLOC;
        //            //                //  printf("Could not allocate memory for selev\n");
        //            //                goto ERROR1;
        //            //            }
        //            //            for(i=0; i <ny; i++)
        //            //                for(j=0; j<nx; j++)
        //            //                {
        //            //                    if (ndve > 0) //ARA 10/17/05 Fixed for possible positive nodata
        //            //              {
        //            //                  if(i == 0 || i == (ny-1) || j == 0 || j == (nx-1) || felevg.d[j][i] >= ndve)
        //            //                  {
        //            //                      selev[j][i]=felevg.d[j][i];
        //            //                  }
        //            //                  else
        //            //                  {
        //            //                      src[j][i] = 1;
        //            //                      selev[j][i]=p[1] * felevg.d[j][i];
        //            //                      wsum=p[1];
        //            //                      if(p[2] > 0.)
        //            //                          for(k=1; k<=7; k=k+2)
        //            //                          {
        //            //                              if(felevg.d[j+d2[k]][i+d1[k]] < ndve)
        //            //                              {
        //            //                                  selev[j][i] += felevg.d[j+d2[k]][i+d1[k]] *p[2];
        //            //                                  wsum += p[2];
        //            //                              }
        //            //                          }
        //            //                          if(p[3] > 0.)
        //            //                              for(k=2; k<=8; k=k+2)
        //            //                              {
        //            //                                  if(felevg.d[j+d2[k]][i+d1[k]] < ndve)
        //            //                                  {
        //            //                                      selev[j][i] += felevg.d[j+d2[k]][i+d1[k]] *p[3];
        //            //                                      wsum += p[3];
        //            //                                  }
        //            //                              }
        //            //                  }
        //            //              }
        //            //                    else
        //            //              {
        //            //                  if(i == 0 || i == (ny-1) || j == 0 || j == (nx-1) || felevg.d[j][i] <= ndve)
        //            //                  {
        //            //                      selev[j][i]=felevg.d[j][i];
        //            //                  }
        //            //                  else
        //            //                  {
        //            //                      src[j][i] = 1;
        //            //                      selev[j][i]=p[1] * felevg.d[j][i];
        //            //                      wsum=p[1];
        //            //                      if(p[2] > 0.)
        //            //                          for(k=1; k<=7; k=k+2)
        //            //                          {
        //            //                              if(felevg.d[j+d2[k]][i+d1[k]] > ndve)
        //            //                              {
        //            //                                  selev[j][i] += felevg.d[j+d2[k]][i+d1[k]] *p[2];
        //            //                                  wsum += p[2];
        //            //                              }
        //            //                          }
        //            //                          if(p[3] > 0.)
        //            //                              for(k=2; k<=8; k=k+2)
        //            //                              {
        //            //                                  if(felevg.d[j+d2[k]][i+d1[k]] > ndve)
        //            //                                  {
        //            //                                      selev[j][i] += felevg.d[j+d2[k]][i+d1[k]] *p[3];
        //            //                                      wsum += p[3];
        //            //                                  }
        //            //                              }
        //            //                  }
        //            //              }

        //            //                    if(i == 0 || i == (ny-1) || j == 0 || j == (nx-1) || felevg.d[j][i] <= ndve)
        //            //              {
        //            //                  selev[j][i]=felevg.d[j][i];
        //            //              }
        //            //                    else
        //            //              {
        //            //                  src[j][i] = 1;
        //            //                  selev[j][i]=p[1] * felevg.d[j][i];
        //            //                  wsum=p[1];
        //            //                  if(p[2] > 0.)
        //            //                      for(k=1; k<=7; k=k+2)
        //            //                      {
        //            //                          if(felevg.d[j+d2[k]][i+d1[k]] > ndve)
        //            //                          {
        //            //                              selev[j][i] += felevg.d[j+d2[k]][i+d1[k]] *p[2];
        //            //                              wsum += p[2];
        //            //                          }
        //            //                      }
        //            //                      if(p[3] > 0.)
        //            //                          for(k=2; k<=8; k=k+2)
        //            //                          {
        //            //                              if(felevg.d[j+d2[k]][i+d1[k]] > ndve)
        //            //                              {
        //            //                                  selev[j][i] += felevg.d[j+d2[k]][i+d1[k]] *p[3];
        //            //                                  wsum += p[3];
        //            //                              }
        //            //                          }
        //            //              }
        //            //                }

        //            //                for (int curcol = 0; curcol < nx; curcol++)
        //            //                    for (int currow = 0; currow < ny; currow++)

        //            //                        felevg.d[curcol][currow]=selev[curcol][currow];

        //            //                for(i=0; i <ny-1; i++)
        //            //                    for(j=0; j<nx-1; j++)
        //            //                    {
        //            //                        emax= felevg.d[j][i];
        //            //                        iomax=0;
        //            //                        jomax=0;
        //            //                        bound= 0;  /*  .false.  */
        //            //                        /*  --FIRST PASS FLAG MAX ELEVATION IN GROUP OF FOUR  */
        //            //                        for(ik=0; ik<2; ik++)
        //            //                            for(jk=1-ik; jk < 2; jk++)
        //            //                            {
        //            //                                if(felevg.d[j+jk][i+ik] > emax)
        //            //                                {
        //            //                                    emax=felevg.d[j+jk][i+ik];
        //            //                                    iomax=ik;
        //            //                                    jomax=jk;
        //            //                                }
        //            //                                if( felevg.d[j+jk][i+ik] <= ndve)
        //            //                                    bound= 1;  /*  .true.  */
        //            //                            }
        //            //                            /*  c---Unflag max pixel */
        //            //                            src[j+jomax][i+iomax] = 0;
        //            //                            /*  c---Unflag pixels where the group of 4 touches a boundary  */
        //            //                            if(bound == 1)
        //            //                            {
        //            //                                for(ik=0; ik < 2; ik++)
        //            //                                    for(jk=0; jk< 2; jk++)
        //            //                                    {
        //            //                                        src[j+jk][i+ik]=0;
        //            //                                    }
        //            //                            }
        //            //                            /* 		  i.e. unflag flats.  */
        //            //                            for(ik=0; ik < 2; ik++)
        //            //                                for(jk=0; jk< 2; jk++)
        //            //                                {
        //            //                                    if(felevg.d[j+jk][i+ik] == emax)src[j+jk][i+ik] = 0;
        //            //                                }
        //            //                    }
        //            //        }

        //            //        if(ipar == 2){
        //            //            free(fslopeg.d[0]); free(fslopeg.d);
        //            //            free(faagrid.d[0]); free(faagrid.d);
        //            //        }
        //            //        if(ipar == 3){
        //            //            free(fplengrid.d[0]); free(fplengrid.d);
        //            //            free(faagrid.d[0]); free(faagrid.d);
        //            //        }
        //            //        if(ipar == 4){
        //            //            free(felevg.d[0]); free(felevg.d);
        //            //        }
        //            //        if(ipar == 5 || ipar == 6){
        //            //            free(sgordgrid.d[0]); free(sgordgrid.d);
        //            //        }

        //            //        /*  Now get directions and compute area's  */

        //            //        if ( gridread(dirfile,&sdir,&filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else
        //            //            err=TD_FAILED_GRID_OPEN;

        //            //        ndvd = sdir.nodata;

        //            //        if(err != TD_NO_ERROR)goto ERROR1;

        //            //        //allocate memory and headers for larr
        //            //        larr.head.dx=dx;
        //            //        larr.head.dy=dy;
        //            //        larr.head.nx=nx;
        //            //        larr.head.ny=ny;
        //            //        larr.nodata=-2;
        //            //        for(i=0;i<4;i++) larr.head.bndbox[i]=bndbox[i];

        //            //        larr.nodata = -2;
        //            //        allocategrid(&larr,larr.head,larr.nodata);

        //            //        nout=0;
        //            //        itresh=1;
        //            //        if(ipar == 4)itresh = p[0];
        //            //        err=TD_CHANNEL_NETWORK_MISMATCH;   //This flag will indicate no outlet found  12/15/02  DGT moved to outside the if block
        //            //        // so that code works for at least one outlet found
        //            //        if(nxy >0)
        //            //        {
        //            //            for(i=0; i<nxy; i++)
        //            //            {
        //            //                col= (int)floor((x[i]-bndbox[0])/csize);
        //            //                row= (int)floor((bndbox[3]-y[i])/csize);
        //            //                if(row >0 && row < ny-1 && col > 0 && col < nx-1
        //            //                    && sdir.d[col][row]>0)  // DGT* this condition added 12/15/02 to not do outlets outside the domain
        //            //                {
        //            //                    /* call drainage area subroutine for pixel to zero on  */
        //            //                    srcarea(row,col);

        //            //                    if(larr.d[col][row] >= itresh)err=TD_NO_ERROR;  // an outlet found so no error
        //            //                }
        //            //            }
        //            //            if(err==TD_CHANNEL_NETWORK_MISMATCH)goto ERROR9;  //  no outlet error
        //            //        }
        //            //        else
        //            //        {
        //            //            //  Do all pixels
        //            //            for(i=1; i < ny-1; i++)
        //            //                for(j=1; j<nx-1; j++)srcarea(i,j);
        //            //            rcgood=0;  // no outlet coordinates found
        //            //        }

        //            //        //  Now threshold the src file
        //            //        if(dropan == 0)
        //            //        {
        //            //            for(i=1; i < ny-1; i++)
        //            //                for(j=1; j<nx-1; j++)
        //            //                {
        //            //                    if(larr.d[j][i] >= itresh && sdir.d[j][i]>0) larr.d[j][i]=1;
        //            //                    //  8/13/04  DGT added condition on sdir.d
        //            //                    else larr.d[j][i]=0;
        //            //                }
        //            //        }
        //            //        if(dropan == 1 && ipar == 1)  // overwrite accumulated source area with actual area
        //            //        {
        //            //            for(i=1; i < ny-1; i++)
        //            //                for(j=1; j<nx-1; j++)
        //            //                {
        //            //                    if(larr.d[j][i] >= itresh && sdir.d[j][i]>0)larr.d[j][i]=faagrid.d[j][i];
        //            //                    //  8/13/04  DGT added condition on sdir.d
        //            //                    else larr.d[j][i]=0;
        //            //                }
        //            //        }
        //            //        //free memory for sdir
        //            //        free(sdir.d[0]);free(sdir.d);

        //            //        if(ipar <= 3){free(faagrid.d[0]);free(faagrid.d);}  // Moved from below so that could reopen with sca file for sure
        //            //        // Exclude area with specific catchment area no data
        //            //        if(masksca == 1)
        //            //        {
        //            //            if(gridread(scafile,&faagrid,&filetype)==0)
        //            //                err=TD_NO_ERROR;
        //            //            else
        //            //            {
        //            //                err=TD_FAILED_GRID_OPEN;
        //            //                return err;
        //            //                //	AfxMessageBox( LPCTSTR(strcat( "Failed to open sca file for masking: ", scafile) ));
        //            //            }
        //            //            if(err != TD_NO_ERROR)goto ERROR9;
        //            //            for(i=1; i < ny-1; i++)
        //            //                for(j=1; j<nx-1; j++)
        //            //                {
        //            //                    if(faagrid.d[j][i] < 0)larr.d[j][i]=0;
        //            //                }
        //            //        }

        //            //        if ( gridwrite(srcfile,larr,filetype)==0)
        //            //            err=TD_NO_ERROR;
        //            //        else{
        //            //            err=TD_FAILED_GRID_SAVE;
        //            //            //if (srcfile)
        //            //            //	AfxMessageBox( LPCTSTR(strcat( "Failed to save file: ", srcfile) ));
        //            //        }

        //            //        free(src[0]); free(src);
        //            //        free(larr.d[0]); free(larr.d);
        //            //        return(err);
        //            //ERROR9:
        //            //        free(src[0]); free(src);
        //            //        //Kiran added the following statement to clean up.
        //            //        free(larr.d[0]); free(larr.d);
        //            //        if(faagrid.d != NULL) free(faagrid.d[0]); free(faagrid.d);
        //            //        if(sdir.d[0] != NULL) free(sdir.d[0]); free(sdir.d);
        //            //        return(err);

        //            //ERROR1:
        //            //        free(src[0]); free(src);
        //            //        free(larr.d[0]); free(larr.d);
        //            //        return(err);

        //            return err;
        //        }

        //        #endregion 'Sourcedef conversion

        //        #region "     Netsetup conversion"
        //        private static int NetSetup(string fnprefix, string pfile, string srcfile, string ordfile, string ad8file, string elevfile, string treefile, string coordfile, double[] xnode, double[] ynode, int nxy, long usetrace, int[] idnodes, IProgressHandler callback)
        //        {
        //            int err = 0;
        //            int itresh, icr, icend;

        //            /* define directions */
        //            int[] d1 = new int[9];
        //            int[] d2 = new int[9];
        //            d1[1] = 0; d1[2] = -1; d1[3] = -1; d1[4] = -1; d1[5] = 0; d1[6] = 1; d1[7] = 1; d1[8] = 1;
        //            d2[1] = 1; d2[2] = 1; d2[3] = 0; d2[4] = -1; d2[5] = -1; d2[6] = -1; d2[7] = 0; d2[8] = 1;

        //            itresh = 1;  // Thresholding to 1 done in source

        //            /*read dirfile   */
        //            Raster dirg = new Raster();
        //            if (dirg.Open(pfile, RasterDataType.UnknownDataType, true, RasterFileType.UseExtension, null))
        //            {
        //                err = 0;
        //            }
        //            else
        //            {
        //                err = 1; //TD_FAILED_GRID_OPEN
        //                return err;
        //            }

        //            double dx = dirg.Header.dX;
        //            double dy = dirg.Header.dY;
        //            int ny = dirg.NumRows;
        //            int nx = dirg.NumColumns;
        //            double[] bndbox = new double[4];
        //            bndbox[0] = dirg.Header.XllCenter - dx / 2;
        //            bndbox[1] = dirg.Header.YllCenter - dy / 2;
        //            bndbox[2] = dirg.Header.XllCenter + dx * nx - dx / 2;
        //            bndbox[3] = dirg.Header.YllCenter + dy * ny - dy / 2;

        //            float[] tmpRow;
        //            short[,] dir = new short[ny, nx];
        //            for (int i = 0; i < ny; i++)
        //            {
        //                tmpRow = new float[nx];
        //                dirg.GetRow(i, tmpRow[0]);
        //                for (int j = 0; j < nx; j++)
        //                {
        //                    dir[i, j] = Convert.ToInt16(tmpRow[j]);
        //                }
        //            }

        //            /*read srcfile   */
        //            Raster area = new Raster();
        //            if (area.Open(srcfile, RasterDataType.UnknownDataType, true, RasterFileType.UseExtension, null))
        //            {
        //                err = 0;
        //            }
        //            else
        //            {
        //                err = 1; //TD_FAILED_GRID_OPEN
        //                dirg.Close();
        //                return err;
        //            }
        //            if (area.NumColumns != nx || area.NumRows != ny)
        //            {
        //                err = 27; //TD_GRID_SIZE_MISMATCH
        //                dirg.Close();
        //                area.Close();
        //                return 1;
        //            }

        //            int[,] aread = new int[ny, nx];
        //            for (int i = 0; i < ny; i++)
        //            {
        //                tmpRow = new float[nx];
        //                area.GetRow(i, tmpRow[0]);
        //                for (int j = 0; j < nx; j++)
        //                {
        //                    aread[i, j] = Convert.ToInt32(tmpRow[j]);
        //                }
        //            }

        //            /*  check for source values >= threshold else fortran crashes*/
        //            int n = 0;
        //            short dirgNoData = Convert.ToInt16(dirg.Header.NodataValue);
        //            for (int i = 0; i < ny; i++)
        //            {
        //                for (int j = 0; j < nx; j++)
        //                {
        //                    if (dir[i, j] == dirgNoData)
        //                    {
        //                        dir[i, j] = 0;  // set direction no data to 0. netex needs this
        //                    }
        //                    if (aread[i, j] >= itresh)
        //                    {
        //                        n = n + 1;
        //                    }
        //                }
        //            }

        //            if (n <= 0)
        //            {
        //                err = 8; //TD_CHANNEL_NETWORK_MISMATCH
        //            }
        //            else
        //            {
        //                int[] inodes;
        //                int[] jnodes;

        //                //  If there are outlets set up inodes, jnodes arrays
        //                if (nxy > 0)
        //                {
        //                    inodes = new int[nxy];
        //                    jnodes = new int[nxy];
        //                }
        //                else
        //                {
        //                    inodes = new int[1];
        //                    jnodes = new int[1];
        //                }

        //                for (int inode = 0; inode < nxy; inode++)
        //                {
        //                    jnodes[inode] = (int)Math.Floor((xnode[inode] - bndbox[0]) / dx);
        //                    inodes[inode] = (int)Math.Floor((bndbox[3] - ynode[inode]) / dy);
        //                    //   Trace to raster if necessary but only for nodes that are inside the domain
        //                    if (usetrace == 1 && inodes[inode] > 0 && inodes[inode] < ny - 1 && jnodes[inode] > 0 && jnodes[inode] < nx - 1)
        //                    {
        //                        if ((int)aread[jnodes[inode], inodes[inode]] < itresh)  // Not on grid
        //                        {
        //                            //   Next downslope
        //                            short dirn = dir[jnodes[inode], inodes[inode]];
        //                            int nexti = inodes[inode] + d1[dirn];
        //                            int nextj = jnodes[inode] + d2[dirn];
        //                            int loopcount = 0;
        //                            while (nexti > 0 && nexti < ny - 1 && nextj > 0 && nextj < nx - 1 && (int)area.get_Value(jnodes[inode], inodes[inode]) < itresh)
        //                            {
        //                                inodes[inode] = nexti;
        //                                jnodes[inode] = nextj;
        //                                dirn = dir[jnodes[inode], inodes[inode]];
        //                                if (dirn < 1 || dirn > 8) break;   // Here have gone out of grid so terminate trace downwards
        //                                nexti = nexti + d1[dirn];
        //                                nextj = nextj + d2[dirn];
        //                                loopcount = loopcount + 1;
        //                                if (loopcount > nx && loopcount > ny) break;   // Here possible infinite loop so terminate trace downwards
        //                            }
        //                        }
        //                    }
        //                }

        //                Netex(dir, aread, treefile, coordfile, ordfile, nx, ny, itresh, out icr, out icend, dx, dy, 0, dx, 0, err, inodes, jnodes, nxy, idnodes);

        //                //Write any changes that were made to the area
        //                for (int i = 0; i < ny; i++)
        //                {
        //                    tmpRow = new float[nx];
        //                    for (int j = 0; j < nx; j++)
        //                    {
        //                        tmpRow[j] = aread[i, j];
        //                    }
        //                    area.PutRow(i, tmpRow[0]);
        //                }

        //                area.Header.NodataValue = -1;
        //                if (area.Save(ordfile, RasterFileType.UseExtension, null))
        //                {
        //                    err = 0;
        //                }
        //                else
        //                {
        //                    err = 2; //TD_FAILED_GRID_SAVE;
        //                    dirg.Close();
        //                    area.Close();
        //                    return err;
        //                }
        //                area.Close();

        //                //Fix negative markers
        //                for (int i = 0; i < ny; i++)
        //                {
        //                    for (int j = 0; j < nx; j++)
        //                    {
        //                        if (dir[i, j] < 0 && dir[i, j] > -9)
        //                        {
        //                            dir[i, j] = (short)-dir[i, j];
        //                        }
        //                    }
        //                }

        //                area = new Raster();
        //                if (area.Open(ad8file, RasterDataType.UnknownDataType, true, RasterFileType.UseExtension, null))
        //                {
        //                    err = 0;
        //                }
        //                else
        //                {
        //                    err = 1; //TD_FAILED_GRID_OPEN
        //                    dirg.Close();
        //                    return err;
        //                }
        //                aread = new int[ny, nx];
        //                for (int i = 0; i < ny; i++)
        //                {
        //                    tmpRow = new float[nx];
        //                    area.GetRow(i, tmpRow[0]);
        //                    for (int j = 0; j < nx; j++)
        //                    {
        //                        aread[i, j] = Convert.ToInt32(tmpRow[j]);
        //                    }
        //                }

        //                /*****read elevfile   *****/
        //                Raster elevg = new Raster();
        //                if (elevg.Open(elevfile, RasterDataType.UnknownDataType, true, RasterFileType.UseExtension, null))
        //                {
        //                    err = 0;
        //                }
        //                else
        //                {
        //                    err = 1; //TD_FAILED_GRID_OPEN
        //                    dirg.Close();
        //                    area.Close();
        //                    return err;
        //                }
        //                if (elevg.NumColumns != nx || elevg.NumRows != ny)
        //                {
        //                    dirg.Close();
        //                    area.Close();
        //                    elevg.Close();
        //                    return 1;
        //                }

        //                float[,] elevd = new float[ny, nx];
        //                for (int i = 0; i < ny; i++)
        //                {
        //                    tmpRow = new float[nx];
        //                    elevg.GetRow(i, tmpRow[0]);
        //                    for (int j = 0; j < nx; j++)
        //                    {
        //                        elevd[i, j] = tmpRow[j];
        //                    }
        //                }

        //                NetProp(dir, aread, elevd, coordfile, icr, icend, dx, dy, nx, ny, bndbox, err);

        //                elevg.Close();
        //            }  //  end if associated with err from source
        //            dirg.Close();
        //            area.Close();

        //            return err;
        //        }

        //        private static int Netex(short[,] dir, int[,] area, string treefile, string coordfile, string ordfile, int nx, int ny, int itresh, out int icr, out int icend, double dx, double dy, double bndbox, double csize, int iftype, int err, int[] inodes, int[] jnodes, int nnodes, int[] idnodes)
        //        {
        //            int i, j;
        //            int inodeid;
        //            int nodeno;
        //            int ics;
        //            int[] iordup = new int[8];
        //            int[] ipoint = new int[8];
        //            int[] d1 = new int[9];
        //            int[] d2 = new int[9];
        //            d1[1] = 0; d1[2] = -1; d1[3] = -1; d1[4] = -1; d1[5] = 0; d1[6] = 1; d1[7] = 1; d1[8] = 1;
        //            d2[1] = 1; d2[2] = 1; d2[3] = 0; d2[4] = -1; d2[5] = -1; d2[6] = -1; d2[7] = 0; d2[8] = 1;
        //            icr = 0;
        //            icend = 0;
        //            err = 0;

        //            int[] ist, jst, iord, istart, jstart, iend, jend, mag;

        //            //READ INPUT
        //            int igy = ny;
        //            int igx = nx;

        //            //
        //            //     MEANING OF POINTERS IS -------------
        //            //                            I 4 I 3 I 2 I
        //            //      0 = POINTS TO SELF    -------------
        //            //          I.E. UNRESOLVED   I 5 I 0 I 1 I
        //            //     -1 = BOUNDARY PIXEL    -------------
        //            //                            I 6 I 7 I 8 I
        //            //                            -------------
        //            //

        //            //-----FIRST FIND ALL START PIXELS
        //            int n = 0;
        //            for (i = 1; i < ny - 1; i++)
        //            {
        //                for (j = 1; j < nx - 1; j++)
        //                {
        //                    if (strt(i, j, area, dir, nx, ny, igx, igy, itresh))
        //                    {
        //                        n = n + 1;
        //                    }
        //                }
        //            }

        //            int nmax = n;
        //            int mnl = 2 * n + 1 + nnodes;   // 11/17/04  DGT added nnodes to avoid memory overflow

        //            //     when added nodes increase the number of links
        //            int[] nextl = new int[mnl + 1];
        //            int[] prevl1 = new int[mnl + 1];
        //            int[] prevl2 = new int[mnl + 1];
        //            ist = new int[nmax + 1];
        //            jst = new int[nmax + 1];
        //            iord = new int[mnl + 1];
        //            istart = new int[mnl + 1];
        //            jstart = new int[mnl + 1];
        //            iend = new int[mnl + 1];
        //            jend = new int[mnl + 1];
        //            mag = new int[mnl + 1];

        //            n = 0;
        //            for (i = 1; i < ny - 1; i++)
        //            {
        //                for (j = 1; j < nx - 1; j++)
        //                {
        //                    if (strt(i, j, area, dir, nx, ny, igx, igy, itresh))
        //                    {
        //                        n = n + 1;
        //                        if (n <= nmax)
        //                        {
        //                            ist[n] = i;
        //                            jst[n] = j;
        //                        }
        //                    }
        //                }
        //            }

        //            if (n > nmax)
        //            {
        //                err = 2;//stop too big
        //                return err;
        //            }

        //            //---ZERO AREA ARRAY
        //            for (i = 1; i < ny - 1; i++)
        //            {
        //                for (j = 1; j < nx - 1; j++)
        //                {
        //                    area[i, j] = 0;
        //                }
        //            }

        //            //----TRACE STREAMS DOWNWARDS ADDING 1 TO MAGNITUDE OF EACH PIXEL (MAGNITUDE STORED IN AREA ARRAY)
        //            int inext;
        //            int jnext;
        //            for (int si = 1; si <= n; si++)
        //            {
        //                i = ist[si];
        //                j = jst[si];
        //                while (dir[i, j] > 0)
        //                {
        //                    area[i, j] = area[i, j] + 1;
        //                    inext = i + d1[dir[i, j]];
        //                    jnext = j + d2[dir[i, j]];
        //                    i = inext;
        //                    j = jnext;
        //                }
        //            }

        //            //----IDENTIFY LINKS BY DIFFERENT MAGNITUDES
        //            bool runEndPath;
        //            int ilink = 1;
        //            int mnext, intemp, jntemp, msum, iconv, itemp;
        //            for (int si = 1; si <= n; si++)
        //            {
        //                istart[ilink] = ist[si];
        //                jstart[ilink] = jst[si];

        //                //---INITIALISE POINTERS
        //                prevl1[ilink] = 0;
        //                prevl2[ilink] = 0;
        //                i = ist[si];
        //                j = jst[si];
        //                mag[ilink] = area[i, j];
        //                iord[ilink] = 1;

        //                inext = i + d1[Math.Abs(dir[i, j])];
        //                jnext = j + d2[Math.Abs(dir[i, j])];
        //                runEndPath = true;
        //                while (dir[inext, jnext] != 0)
        //                {
        //                    mnext = area[inext, jnext];
        //                    i = inext;
        //                    j = jnext;
        //                    iend[ilink] = i;
        //                    jend[ilink] = j;

        //                    //mods allow insertion of nodes   DGT 7/17/02
        //                    if (isnode(mnext, mag[ilink], i, j, inodes, jnodes, nnodes))
        //                    {
        //                        //heck here that this is not the end of a path because then it will be a node anyway
        //                        intemp = i + d1[Math.Abs(dir[i, j])];
        //                        jntemp = j + d2[Math.Abs(dir[i, j])];
        //                        if (dir[intemp, jntemp] != 0)
        //                        {
        //                            ilink = ilink + 1;
        //                            istart[ilink] = i;
        //                            jstart[ilink] = j;
        //                            prevl1[ilink] = ilink - 1;
        //                            prevl2[ilink] = 0;
        //                            nextl[ilink - 1] = ilink;
        //                            mag[ilink] = mag[ilink - 1];
        //                            iord[ilink] = iord[ilink - 1];
        //                            iend[ilink] = i;
        //                            jend[ilink] = j;
        //                        }
        //                    }
        //                    //end mods to allow insertion of nodes  DGT
        //                    if (mnext != mag[ilink])
        //                    {
        //                        //----CONTINUE HERE FOR NEW LINK
        //                        //----CHECK IF JUNCTION ALREADY REACHED (FLAGGED BY NEGATIVE DIRECTION)
        //                        if (dir[i, j] < 0)
        //                        {
        //                            //----CHECK IF ALL LINKS CONVERGING HERE HAVE BEEN DONE BY SUMMING MAGNITUDE
        //                            msum = 0;
        //                            iconv = 0;
        //                            for (int il = 1; il <= ilink; il++)
        //                            {
        //                                if (iend[il] == i && jend[il] == j)
        //                                {
        //                                    iconv = iconv + 1;
        //                                    ipoint[iconv] = il;
        //                                    iordup[iconv] = iord[il];
        //                                    msum = msum + mag[il];
        //                                }
        //                            }

        //                            if (msum == mnext) //All links have been processed
        //                            {
        //                                //---SORT IORDUP,IPOINT INTO DECENDING STREAM ORDER
        //                                for (int ic = 1; ic <= iconv - 1; ic++)
        //                                {
        //                                    for (int iic = ic + 1; iic <= iconv; iic++)
        //                                    {
        //                                        if (iordup[iic] > iordup[ic]) //switch these
        //                                        {
        //                                            itemp = iordup[iic];
        //                                            iordup[iic] = iordup[ic];
        //                                            iordup[ic] = itemp;
        //                                            itemp = ipoint[iic];
        //                                            ipoint[iic] = ipoint[ic];
        //                                            ipoint[ic] = itemp;
        //                                        }
        //                                    }
        //                                }
        //                                for (int ic = 1; ic <= iconv - 1; ic++)
        //                                {
        //                                    ilink = ilink + 1;
        //                                    istart[ilink] = i;
        //                                    jstart[ilink] = j;
        //                                    prevl1[ilink] = ipoint[ic];
        //                                    prevl2[ilink] = ipoint[ic + 1];
        //                                    nextl[ipoint[ic]] = ilink;
        //                                    nextl[ipoint[ic + 1]] = ilink;
        //                                    mag[ilink] = mag[prevl1[ilink]] + mag[prevl2[ilink]];
        //                                    iord[ilink] = Math.Max(iordup[1], iordup[2] + 1);
        //                                    ipoint[ic + 1] = ilink;
        //                                    iend[ilink] = i;
        //                                    jend[ilink] = j;
        //                                }
        //                            }
        //                            else
        //                            {
        //                                ilink = ilink + 1;
        //                                runEndPath = false;
        //                                break;
        //                            }
        //                        }
        //                        else
        //                        {
        //                            dir[i, j] = (short)(-dir[i, j]);
        //                            ilink = ilink + 1;
        //                            runEndPath = false;
        //                            break;
        //                        }
        //                    } //end if mnext != mag(ilink)

        //                    inext = i + d1[Math.Abs(dir[i, j])];
        //                    jnext = j + d2[Math.Abs(dir[i, j])];
        //                } // end while dir != 0

        //                if (runEndPath)
        //                {
        //                    iend[ilink] = i;
        //                    jend[ilink] = j;
        //                    nextl[ilink] = -1;
        //                    if (si < n)
        //                    {
        //                        ilink = ilink + 1;
        //                    }
        //                }
        //            } //end for (int si=1; si <= n; si++)

        //            StreamWriter coord = new System.IO.StreamWriter(coordfile);
        //            StreamWriter tree = new System.IO.StreamWriter(treefile);

        //            //     reinitialize area array - for output it will contain order
        //            for (i = 0; i < ny; i++)
        //            {
        //                for (j = 0; j < nx; j++)
        //                {
        //                    area[i, j] = 0;
        //                }
        //            }

        //            int icord = 0;

        //            //---  WRITE ROOT LINK FIRST
        //            i = istart[ilink];
        //            j = jstart[ilink];
        //            ics = icord;

        //            if (i != 0 && j != 0)
        //            {
        //                coord.Write("{0,10:G} {1,10:G}\n", i + 1, j + 1);
        //                area[i, j] = Math.Max(iord[ilink], area[i, j]);
        //            }
        //            icend = icord;
        //            icord = icord + 1;
        //            while (i != iend[ilink] || j != jend[ilink] && i != 0 && j != 0)
        //            {
        //                inext = i + d1[Math.Abs(dir[i, j])];
        //                jnext = j + d2[Math.Abs(dir[i, j])];
        //                i = inext;
        //                j = jnext;

        //                if (i != 0 && j != 0)
        //                {
        //                    coord.Write("{0,10:G} {1,10:G}\n", i + 1, j + 1);
        //                    area[i, j] = Math.Max(iord[ilink], area[i, j]);
        //                    icend = icord;
        //                    icord = icord + 1;
        //                }
        //            }

        //            inodeid = 0; //This is the first one so it will be the most downstream
        //            if (isnode2(iend[ilink], jend[ilink], inodes, jnodes, nnodes, out nodeno))
        //            {
        //                if (idnodes[nodeno] >= 0)
        //                {
        //                    inodeid = idnodes[nodeno];
        //                    idnodes[nodeno] = -1; //This logic to pick only the first one if there are multiple at a junction
        //                }
        //            }
        //            tree.Write("{0,10:G} {1,10:G} {2,10:G} {3,10:G} {4,10:G} {5,10:G} {6,10:G} {7,10:G}\n", 0, ics, icend, -1, prevl1[ilink], prevl2[ilink], iord[ilink], inodeid);

        //            icr = icord;

        //            //---  WRITE REMAINDER OF LINKS
        //            for (int il = 1; il <= ilink - 1; il++)
        //            {
        //                i = istart[il];
        //                j = jstart[il];
        //                ics = icord;

        //                if (i != 0 && j != 0)
        //                {
        //                    coord.Write("{0,10:G} {1,10:G}\n", i + 1, j + 1);
        //                    area[i, j] = Math.Max(iord[il], area[i, j]);
        //                }
        //                icend = icord;
        //                icord = icord + 1;
        //                while (i != iend[il] || j != jend[il] && i != 0 && j != 0)
        //                {
        //                    inext = i + d1[Math.Abs(dir[i, j])];
        //                    jnext = j + d2[Math.Abs(dir[i, j])];
        //                    i = inext;
        //                    j = jnext;

        //                    if (i != 0 && j != 0)
        //                    {
        //                        coord.Write("{0,10:G} {1,10:G}\n", i + 1, j + 1);
        //                        area[i, j] = Math.Max(iord[il], area[i, j]);
        //                        icend = icord;
        //                        icord = icord + 1;
        //                    }
        //                }

        //                if (nextl[il] == ilink)
        //                {
        //                    nextl[il] = 0;
        //                }
        //                inodeid = -1;

        //                if (nextl[il] < 0)
        //                {
        //                    inodeid = 0;
        //                }

        //                if (isnode2(iend[il], jend[il], inodes, jnodes, nnodes, out nodeno))
        //                {
        //                    if (idnodes[nodeno] >= 0)
        //                    {
        //                        inodeid = idnodes[nodeno];
        //                        idnodes[nodeno] = -1; //This logic to pick only the first one if there are multiple at a junction
        //                    }
        //                }

        //                tree.Write("{0,10:G} {1,10:G} {2,10:G} {3,10:G} {4,10:G} {5,10:G} {6,10:G} {7,10:G}\n", il, ics, icend, nextl[il], prevl1[il], prevl2[il], iord[il], inodeid);
        //            }

        //            coord.Close();
        //            tree.Close();

        //            return err;
        //        }

        //        private static bool strt(int i, int j, int[,] area, short[,] dir, int nx, int ny, int igx, int igy, int itresh)
        //        {
        //            bool result = true;
        //            int[] d1 = new int[9];
        //            int[] d2 = new int[9];
        //            d1[1] = 0; d1[2] = -1; d1[3] = -1; d1[4] = -1; d1[5] = 0; d1[6] = 1; d1[7] = 1; d1[8] = 1;
        //            d2[1] = 1; d2[2] = 1; d2[3] = 0; d2[4] = -1; d2[5] = -1; d2[6] = -1; d2[7] = 0; d2[8] = 1;

        //            if (area[i, j] < itresh || dir[i, j] < 0)
        //            {
        //                result = false;
        //                if (area[i, j] <= 0)
        //                {
        //                    dir[i, j] = 0; //ZERO DIRECTIONS OUTSIDE AREA
        //                }
        //            }
        //            else //CHECK UPSTREAM PIXELS
        //            {
        //                int ni, nj, ind, jnd;
        //                for (int k = 1; k <= 8; k++)
        //                {
        //                    ni = i + d1[k]; //neighbor pixel
        //                    nj = j + d2[k];
        //                    if (dir[ni, nj] > 0)
        //                    {
        //                        ind = ni + d1[dir[ni, nj]]; //pixel downstream from neighbor
        //                        jnd = nj + d2[dir[ni, nj]];
        //                        if (ind == i && jnd == j) //Neighbor drains into i,j
        //                        {
        //                            if (area[ni, nj] >= itresh)
        //                            {
        //                                result = false;
        //                            }
        //                        }
        //                    }
        //                }
        //                //Do not allow sources that drain off the raster set i.e. a link of 0 length
        //                ni = i + d1[dir[i, j]];
        //                nj = j + d2[dir[i, j]];
        //                if (area[ni, nj] < itresh)
        //                {
        //                    result = false;
        //                }
        //            }

        //            return result;
        //        }

        //        private static bool isnode(int mnext, int mag, int i, int j, int[] inodes, int[] jnodes, int nnodes)
        //        {
        //            bool result = false;
        //            for (int k = 0; k < nnodes; k++)
        //            {
        //                if ((inodes[k]) == i && (jnodes[k]) == j)
        //                {
        //                    result = true;
        //                    if (mnext != mag) //false alarm it is a junction
        //                    {
        //                        result = false;
        //                    }
        //                    return result;
        //                }
        //            }
        //            return result;
        //        }

        //        private static bool isnode2(int i, int j, int[] inodes, int[] jnodes, int nnodes, out int nodeno)
        //        {
        //            nodeno = -1;
        //            for (int k = 0; k < nnodes; k++)
        //            {
        //                if ((inodes[k]) == i && (jnodes[k]) == j)
        //                {
        //                    //+1 is because arrays came from C
        //                    nodeno = k;  // for return to use in indexing
        //                    return true;
        //                }
        //            }
        //            return false;
        //        }

        //        private static int NetProp(short[,] dir, int[,] area, float[,] elev, string coordfile, int icr, int icmax, double dx, double dy, int nx, int ny, double[] bndbox, int err)
        //        {
        //            int[] d1 = new int[9];
        //            int[] d2 = new int[9];
        //            d1[1] = 0; d1[2] = -1; d1[3] = -1; d1[4] = -1; d1[5] = 0; d1[6] = 1; d1[7] = 1; d1[8] = 1;
        //            d2[1] = 1; d2[2] = 1; d2[3] = 0; d2[4] = -1; d2[5] = -1; d2[6] = -1; d2[7] = 0; d2[8] = 1;

        //            int mc = icmax + 1;
        //            double[] rarea = new double[mc];
        //            double[] length = new double[mc];
        //            double[] elv = new double[mc];
        //            int[] ia = new int[mc];
        //            int[] ja = new int[mc];

        //            StreamReader coordr = new StreamReader(coordfile);

        //            string bufferLine;
        //            int n;
        //            for (n = 0; n <= mc; n++)
        //            {
        //                try
        //                {
        //                    bufferLine = coordr.ReadLine();
        //                    if (bufferLine != String.Empty)
        //                    {
        //                        ia[n] = Convert.ToInt32(bufferLine.Substring(0, 10).Trim()) - 1;
        //                        ja[n] = Convert.ToInt32(bufferLine.Substring(11, 10).Trim()) - 1;
        //                    }
        //                    else
        //                    {
        //                        break;
        //                    }
        //                }
        //                catch
        //                {
        //                    break;
        //                }
        //            }
        //            coordr.Close();

        //            n = n - 1;
        //            for (int ic = 0; ic <= n; ic++)
        //            {
        //                rarea[ic] = area[ia[ic], ja[ic]] * dx * dy;
        //                elv[ic] = elev[ia[ic], ja[ic]];
        //            }

        //            int iroot = ia[icr];
        //            int jroot = ja[icr];

        //            //----TRACE STREAMS DOWNWARDS
        //            int i, j, inext, jnext;
        //            double DXx, DYy;
        //            for (int ic = 0; ic <= n; ic++)
        //            {
        //                length[ic] = 0;
        //                i = ia[ic];
        //                j = ja[ic];
        //                inext = i + d1[dir[i, j]];
        //                jnext = j + d2[dir[i, j]];

        //                while (dir[inext, jnext] != 0) //not yet end of path
        //                {
        //                    DXx = dx * (double)(j - jnext);
        //                    DYy = dy * (double)(i - inext);
        //                    length[ic] = length[ic] + Math.Sqrt(DXx * DXx + DYy * DYy);
        //                    i = inext;
        //                    j = jnext;
        //                    inext = i + d1[dir[i, j]];
        //                    jnext = j + d2[dir[i, j]];
        //                }
        //            }

        //            //--WRITE OUTPUT
        //            StreamWriter coordw = new StreamWriter(coordfile);
        //            double x, y;
        //            for (int ic = 0; ic <= n; ic++)
        //            {
        //                x = (ja[ic]) * dx + bndbox[0] + dx * 0.5;
        //                y = dy * (ny - ia[ic] - 1) + bndbox[1] + dy * 0.5;
        //                coordw.Write("{0,15:F4} {1,15:F4} {2,15:F4} {3,15:F4} {4,15:F4}\n", x, y, length[ic], elv[ic], rarea[ic]);
        //            }
        //            coordw.Close();

        //            return 0;
        //        }
        //        #endregion

        //        #endregion

        //        #region "Delin Streams Shapefile And Subbasins Grid"
        //        // CWG 27/1/2011 In TauDEM V5 this functionality is included in DelinStreamGrids

        //        //		/// <summary>
        //        //		/// A function which makes calls to TauDEM to delineate streams shapefile and subbasin grid
        //        //		/// </summary>
        //        //		/// <param name="d8Path"></param>
        //        //		/// <param name="TreeDatPath"></param>
        //        //		/// <param name="CoordDatPath"></param>
        //        //		/// <param name="streamShapeResultPath"></param>
        //        //		/// <param name="watershedGridResultPath"></param>
        //        //		/// <param name="callback"></param>
        //        //		/// <returns></returns>
        //        //		public static int DelinStreamsAndSubBasins(string d8Path, string TreeDatPath, string CoordDatPath, string streamShapeResultPath, string watershedGridResultPath, IProgressHandler callback)
        //        //		{
        //        //			int result = -1;
        //        //			int ordert = 1;
        //        //			int subbno = 0;
        //        //
        //        //			TKTAUDEMLib.TauDEM TaudemLib = new TKTAUDEMLib.TauDEM();
        //        //			if (callback != null) TaudemLib.Callback = callback;
        //        //
        //        //			if (callback != null) callback.Progress("Status", 0, "Stream Shapefile and Watershed Grid");
        //        //			DataManagement.DeleteGrid(watershedGridResultPath);
        //        //			DataManagement.DeleteShapefile(streamShapeResultPath);
        //        //
        //        //			try
        //        //			{
        //        //				//result = TaudemLib.Subbasinsetup(d8Path, watershedGridResultPath, TreeDatPath, CoordDatPath, streamShapeResultPath, ordert, subbno);
        //        //				result = CreateSubbasinGridAndNetworkShape(d8Path, TreeDatPath, CoordDatPath, ordert, subbno, watershedGridResultPath, streamShapeResultPath, callback);
        //        //			}
        //        //			catch
        //        //			{
        //        //			}
        //        //
        //        //			if (result != 0)
        //        //			{
        //        //				MessageBox.Show(TaudemLib.getErrorMsg(result), "TauDEM Error " + result, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.DialogResult.OK);
        //        //			}
        //        //
        //        //			CopyProjectionFromGrid(d8Path, watershedGridResultPath);
        //        //			CopyProjectionFromGrid(d8Path, streamShapeResultPath);
        //        //			if (callback != null) callback.Progress("Status", 0, String.Empty);
        //        //			return result;
        //        //		}
        //        //
        //        //		/// <summary>
        //        //		/// An overload of the DelinStreamsAndSubBasins function which will generate a GeoprocDialog for the DelinStreamsAndSubBasins function
        //        //		/// </summary>
        //        //		/// <param name="callback"></param>
        //        //		/// <returns></returns>
        //        //		public static int DelinStreamsAndSubBasins(IProgressHandler callback)
        //        //		{
        //        //			return doDelinStreamsAndSubBasinsDiag(callback);
        //        //		}
        //        //
        //        //		/// <summary>
        //        //		/// An overload of the DelinStreamsAndSubBasins function which will generate a GeoprocDialog for the DelinStreamsAndSubBasins function
        //        //		/// </summary>
        //        //		/// <returns></returns>
        //        //		public static int DelinStreamsAndSubBasins()
        //        //		{
        //        //			return doDelinStreamsAndSubBasinsDiag(null);
        //        //		}
        //        //
        //        //		private static int doDelinStreamsAndSubBasinsDiag(IProgressHandler callback)
        //        //		{
        //        //			GeoProcDialog delinstreamshedDiag = new GeoProcDialog();
        //        //			FileElement d8Elem = delinstreamshedDiag.Add_FileElement(GeoProcDialog.ElementTypes.OpenGridFile);
        //        //			FileElement treeDatElem = delinstreamshedDiag.Add_FileElement(GeoProcDialog.ElementTypes.OpenFile);
        //        //			FileElement coordDatElem = delinstreamshedDiag.Add_FileElement(GeoProcDialog.ElementTypes.OpenFile);
        //        //			FileElement streamShapeResElem = delinstreamshedDiag.Add_FileElement(GeoProcDialog.ElementTypes.SaveShapefile);
        //        //			FileElement shedGridResElem = delinstreamshedDiag.Add_FileElement(GeoProcDialog.ElementTypes.SaveGridFile);
        //        //
        //        //			delinstreamshedDiag.Text = "TauDEM Stream Network Shapefile and Sub-basin Grid";
        //        //			delinstreamshedDiag.HelpTitle = "TauDEM Stream Network Shapefile and Sub-basin Grid";
        //        //			delinstreamshedDiag.HelpText = "This function will generate a stream network shapefile and sub-basin grid from the given inputs.";
        //        //			delinstreamshedDiag.Height = 350;
        //        //			delinstreamshedDiag.HelpPanelVisible = false;
        //        //
        //        //			d8Elem.Caption = "D8 Flow Direction Grid Path";
        //        //			d8Elem.HelpButtonVisible = false;
        //        //
        //        //			treeDatElem.Caption = "Network Tree Data File Path";
        //        //			treeDatElem.Filter = "Data Files (*.dat)|*.dat";
        //        //			treeDatElem.HelpButtonVisible = false;
        //        //
        //        //			coordDatElem.Caption = "Network Coordinates Data File Path";
        //        //			coordDatElem.Filter = "Data Files (*.dat)|*.dat";
        //        //			coordDatElem.HelpButtonVisible = false;
        //        //
        //        //			streamShapeResElem.Caption = "Stream Network Shapefile Result Path";
        //        //			streamShapeResElem.HelpButtonVisible = false;
        //        //
        //        //			shedGridResElem.Caption = "Sub-basins Grid Result Path";
        //        //			shedGridResElem.HelpButtonVisible = false;
        //        //
        //        //
        //        //			if (delinstreamshedDiag.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //        //			{
        //        //				return Hydrology.DelinStreamsAndSubBasins(d8Elem.Filename, treeDatElem.Filename, coordDatElem.Filename, streamShapeResElem.Filename, shedGridResElem.Filename, callback);
        //        //			}
        //        //			return -2;
        //        //		}

        //        #region "    Subbasinsetup conversion"

        //        private static int CreateSubbasinGridAndNetworkShape(string D8GridPath, string TreeDatPath, string CoordDatPath, int ordert, int subbno, string ResultBasinGridPath, string ResultNetShapePath, IProgressHandler callback)
        //        {
        //            int newperc = 0;
        //            int oldperc = 0;
        //            if (callback != null) callback.Progress("Status", 0, "Stream Shapefile and Watershed Grid");
        //            int err = 0;
        //            bool success;

        //            int numTreeNodes = -1;
        //            long[] dsNodeID;
        //            int[,] FlowNet;
        //            if (ReadTreeFile(TreeDatPath, out FlowNet, out dsNodeID, numTreeNodes) == 1)
        //            {
        //                return 1;
        //            }

        //            int numCoords = 0;
        //            float[,] CoordList;
        //            if (ReadCoordFile(CoordDatPath, out CoordList, numCoords) == 1)
        //            {
        //                return 1;
        //            }

        //            int numBasins = 0;
        //            int currReach = 2 * (numTreeNodes + 1) - 1; //Initialize current reach number
        //            int maxReaches = 5 * (numTreeNodes + 1) - 2; //The maximum number of reaches possible in binary tree
        //            int[,] ReachConnections = new int[maxReaches + 1, 3];
        //            float[,] ReachProperties = new float[maxReaches + 1, 5];
        //            int[] Magnitude = new int[numTreeNodes + 2];

        //            Raster d8Grid = new Raster();
        //            success = d8Grid.Open(D8GridPath, RasterDataType.UnknownDataType, true, RasterFileType.UseExtension, null);
        //            if (success)
        //            {
        //                err = 0;
        //            }
        //            else
        //            {
        //                err = 1;
        //            }

        //            int numCols = d8Grid.NumColumns;
        //            int numRows = d8Grid.NumRows;
        //            RasterHeader BasinGridHead = new RasterHeader();
        //            BasinGridHead.CopyFrom(d8Grid.Header);
        //            BasinGridHead.NodataValue = -1;

        //            Raster BasinGrid = new Raster();
        //            BasinGrid.CreateNew(ResultBasinGridPath, BasinGridHead, RasterDataType.ShortDataType, BasinGridHead.NodataValue, true, RasterFileType.UseExtension, null);
        //            //TODO: May need this to be a temp path instead of result grid

        //            Shapefile NetSF = new Shapefile();
        //            NetSF.CreateNew(ResultNetShapePath, MapWinGIS.ShpfileType.SHP_POLYLINE);
        //            NetSF.StartEditingShapes(true, null);
        //            InitializeNetFields(NetSF);

        //            Queue<int> Links = new Queue<int>();

        //            for (int i = 0; i <= numTreeNodes; i++)
        //            {
        //                if (numTreeNodes > 0)
        //                {
        //                    newperc = Convert.ToInt32((Convert.ToDouble(i) / Convert.ToDouble(numTreeNodes)) * 100);
        //                    if (newperc > oldperc)
        //                    {
        //                        if (callback != null) callback.Progress("Status", newperc, "Stream Shapefile and Watershed Grid");
        //                        oldperc = newperc;
        //                    }
        //                }

        //                if (FlowNet[i, 3] == -1) //This is a root link
        //                {
        //                    if (ordert >= 0)
        //                    {
        //                        PopulateNetworkProperties(numBasins, i, FlowNet, CoordList, currReach, ordert, subbno, Magnitude, dsNodeID, numRows, numCols, ReachConnections, ReachProperties, d8Grid, BasinGrid, NetSF, callback);
        //                    }
        //                    else
        //                    {
        //                        subbno = subbno + 1;
        //                        PopulateNetworkProperties(numBasins, i, FlowNet, CoordList, currReach, ordert, subbno, Magnitude, dsNodeID, numRows, numCols, ReachConnections, ReachProperties, d8Grid, BasinGrid, NetSF, callback);
        //                    }
        //                }

        //                if (FlowNet[i, 4] == 0 && FlowNet[i, 5] == 0) //This is a branch
        //                {
        //                    Links.Enqueue(i);
        //                }
        //            }

        //            if (Links.Count > 0)
        //            {
        //                numBasins = 0;
        //                if (ordert >= 0)
        //                {
        //                    MarkBasinsAndNetworkStack(Links, numBasins, FlowNet, CoordList, currReach, ordert, subbno, Magnitude, dsNodeID, numRows, numCols, ReachConnections, ReachProperties, d8Grid, BasinGrid, NetSF, callback);
        //                }
        //                else
        //                {
        //                    subbno = subbno + 1;
        //                    MarkBasinsAndNetworkStack(Links, numBasins, FlowNet, CoordList, currReach, ordert, subbno, Magnitude, dsNodeID, numRows, numCols, ReachConnections, ReachProperties, d8Grid, BasinGrid, NetSF, callback);
        //                }
        //            }

        //            NetSF.Save();
        //            NetSF.Close();

        //            success = BasinGrid.Save(ResultBasinGridPath, RasterFileType.UseExtension, null);
        //            if (success)
        //            {
        //                err = 0;
        //            }
        //            else
        //            {
        //                err = 2;
        //            }
        //            BasinGrid.Close();
        //            if (callback != null) callback.Progress("Status", 0, "Stream Shapefile and Watershed Grid");

        //            return err;
        //        }

        //        private static int ReadTreeFile(string TreeDatPath, out int[,] FlowNet, out long[] dsNodeID, int numTreeNodes)
        //        {
        //            System.IO.StreamReader tree = null;
        //            try
        //            {
        //                tree = new System.IO.StreamReader(TreeDatPath);
        //                string line;
        //                while (!tree.EndOfStream)
        //                {
        //                    line = tree.ReadLine();
        //                    numTreeNodes = numTreeNodes + 1;
        //                }
        //                tree.Close();
        //                FlowNet = new int[numTreeNodes + 1, 7];
        //                dsNodeID = new long[numTreeNodes + 1];
        //                tree = new System.IO.StreamReader(TreeDatPath);
        //                for (int i = 0; i <= numTreeNodes; i++)
        //                {
        //                    line = tree.ReadLine();
        //                    int counter = -1;
        //                    string[] split = line.Split(' ');
        //                    for (int j = 0; j <= split.Length - 1; j++)
        //                    {
        //                        if (split[j] != String.Empty)
        //                        {
        //                            counter = counter + 1;
        //                            if (counter < 7)
        //                            {
        //                                FlowNet[i, counter] = Int32.Parse(split[j]);
        //                            }
        //                            else if (counter == 7)
        //                            {
        //                                dsNodeID[i] = Int32.Parse(split[j]);
        //                                break;
        //                            }
        //                        }
        //                    }
        //                }
        //                tree.Close();
        //            }
        //            catch
        //            {
        //                FlowNet = new int[0, 0];
        //                dsNodeID = new long[0];
        //                return 1;
        //            }
        //            finally
        //            {
        //                if (tree != null)
        //                {
        //                    tree.Close();
        //                }
        //            }
        //            return 0;
        //        }

        //        private static int ReadCoordFile(string CoordDatPath, out float[,] CoordList, int numCoords)
        //        {
        //            System.IO.StreamReader coordSR = null;
        //            try
        //            {
        //                string line;
        //                coordSR = new System.IO.StreamReader(CoordDatPath);
        //                while (!coordSR.EndOfStream)
        //                {
        //                    line = coordSR.ReadLine();
        //                    numCoords = numCoords + 1;
        //                }
        //                coordSR.Close();
        //                CoordList = new float[numCoords + 1, 5];
        //                numCoords = numCoords - 1;
        //                coordSR = new System.IO.StreamReader(CoordDatPath);
        //                for (int i = 0; i <= numCoords; i++)
        //                {
        //                    line = coordSR.ReadLine();
        //                    int counter = -1;
        //                    string[] split = line.Split(' ');
        //                    for (int j = 0; j <= split.Length - 1; j++)
        //                    {
        //                        if (split[j] != String.Empty)
        //                        {
        //                            counter = counter + 1;
        //                            if (counter < 4)
        //                            {
        //                                CoordList[i, counter] = float.Parse(split[j]);
        //                            }
        //                            else if (counter == 4)
        //                            {
        //                                CoordList[i, counter] = float.Parse(split[j]);
        //                                break;
        //                            }
        //                        }
        //                    }
        //                }
        //                coordSR.Close();
        //            }
        //            catch
        //            {
        //                CoordList = new float[0, 0];
        //                return 1;
        //            }
        //            finally
        //            {
        //                if (coordSR != null)
        //                {
        //                    coordSR.Close();
        //                }
        //            }
        //            return 0;
        //        }

        //        private static int PopulateNetworkProperties(int numBasins, int StartLink, int[,] FlowNet, float[,] CoordList, int currReach, int ordert, int subbno, int[] Magnitude, long[] dsNodeID, int numRows, int numCols, int[,] ReachConnections, float[,] ReachProperties, Raster d8Grid, Raster BasinGrid, Shapefile NetSF, IProgressHandler callback)
        //        {
        //            int currLink;
        //            int currDSLink;
        //            int currDSFrom;
        //            int row;
        //            int UpstreamLink1;
        //            int UpstreamLink2;
        //            int col;
        //            int thisreach;
        //            int BasinID;
        //            int flag = 0;
        //            int LinkEnd;
        //            int LinkBegin;
        //            int LinkEndArea = 0;
        //            //  variables for CoordList positions
        //            float x;
        //            float y;

        //            Stack<int> links = new Stack<int>();
        //            links.Push(-1);
        //            links.Push(-1);
        //            links.Push(StartLink);

        //            while (links.Count != 0)
        //            {
        //                if (callback != null) callback.Progress("Status", 0, "Stream Shapefile and Watershed Grid");
        //                flag = 0;
        //                LinkEndArea = 0;

        //                currLink = links.Pop();
        //                currDSFrom = links.Pop();
        //                currDSLink = links.Pop();

        //                LinkEnd = FlowNet[currLink, 3 - 1];//*  This is CoordList of end of link */
        //                LinkBegin = FlowNet[currLink, 2 - 1];//*  This is CoordList of beg of link */
        //                Magnitude[currLink] = 0;// Initiaize magnitude recursion

        //                if (LinkBegin < LinkEnd)
        //                {
        //                    //has physical length
        //                    numBasins = numBasins + 1;
        //                    if (ordert < 0)
        //                    {
        //                        numBasins = subbno;
        //                    }

        //                    if (FlowNet[currLink, 4 - 1] != -1) //For anything other than a downstream end area is defined one grid cell back
        //                    {
        //                        LinkEndArea = LinkEnd - 1;
        //                    }
        //                    else
        //                    {
        //                        LinkEndArea = LinkEnd;
        //                    }

        //                    x = CoordList[LinkEndArea, 1 - 1];
        //                    y = CoordList[LinkEndArea, 2 - 1];
        //                    BasinGrid.ProjToCell(x, y, out col, out row);
        //                    if (row < 0 | row > numRows | col < 0 | col > numCols)
        //                    {
        //                        if (currDSLink != -1 && currDSFrom != -1)
        //                        {
        //                            ReachConnections[currDSLink, currDSFrom] = -1;
        //                        }
        //                    }
        //                }
        //                else
        //                {
        //                    x = CoordList[LinkEndArea, 1 - 1];
        //                    y = CoordList[LinkEndArea, 2 - 1];
        //                    BasinGrid.ProjToCell(x, y, out col, out row);
        //                    if (row < 0 | row > numRows | col < 0 | col > numCols)
        //                    {
        //                        if (currDSLink != -1 && currDSFrom != -1)
        //                        {
        //                            ReachConnections[currDSLink, currDSFrom] = -2;
        //                        }
        //                    }
        //                    LinkEndArea = LinkEnd;
        //                    flag = 1;
        //                }

        //                if (callback != null) callback.Progress("Status", 50, "Stream Shapefile and Watershed Grid");

        //                //Search for upstream basins
        //                UpstreamLink1 = FlowNet[currLink, 5 - 1]; //pointers to upstream links
        //                UpstreamLink2 = FlowNet[currLink, 6 - 1];

        //                if (UpstreamLink1 > 0 | UpstreamLink2 > 0)
        //                {
        //                    if (flag == 1)
        //                    {
        //                        //dummy 0 length reach
        //                        currReach = currReach + 1;
        //                        thisreach = currReach;
        //                        if (ordert <= 0)
        //                        {
        //                            BasinID = subbno;
        //                        }
        //                        else
        //                        {
        //                            BasinID = 0;
        //                        }

        //                        ReachConnections[thisreach, 1 - 1] = thisreach;
        //                        if (UpstreamLink1 > 0)
        //                        {
        //                            links.Push(thisreach);
        //                            links.Push(2 - 1);
        //                            links.Push(UpstreamLink1);
        //                            Magnitude[currLink] = Magnitude[currLink] + Magnitude[UpstreamLink1];
        //                        }
        //                        else
        //                        {
        //                            ReachConnections[thisreach, 2 - 1] = 0;
        //                        }
        //                        // CWG 20/7/2010 missing code for second link added
        //                        if (UpstreamLink2 > 0)
        //                        {
        //                            links.Push(thisreach);
        //                            links.Push(3 - 1);
        //                            links.Push(UpstreamLink2);
        //                            Magnitude[currLink] = Magnitude[currLink] + Magnitude[UpstreamLink2];
        //                        }
        //                        else
        //                        {
        //                            ReachConnections[thisreach, 3 - 1] = 0;
        //                        }
        //                        //AddReachShape3(NetSF, FlowNet, CoordList, currLink, BasinID, Magnitude[currLink], dsNodeID[currLink]);

        //                        //'Assign properties to dummy reach
        //                        ReachProperties[thisreach, 1 - 1] = 0.01f; //slope
        //                        ReachProperties[thisreach, 2 - 1] = CoordList[LinkEndArea, 5 - 1]; //ontributing area
        //                        ReachProperties[thisreach, 3 - 1] = 0; //Length
        //                        ReachProperties[thisreach, 4 - 1] = CoordList[LinkEndArea, 0]; //end x CoordList
        //                        ReachProperties[thisreach, 5 - 1] = CoordList[LinkEndArea, 1]; //end x CoordList
        //                    }
        //                    else
        //                    {
        //                        //Lower half reach
        //                        currReach = currReach + 1;
        //                        thisreach = currReach;
        //                        ReachConnections[thisreach, 1 - 1] = thisreach;
        //                        ReachConnections[thisreach, 2 - 1] = numBasins;
        //                        ReachConnections[thisreach, 3 - 1] = currReach + 1;
        //                        ReachProperties[thisreach, 3 - 1] = (CoordList[LinkBegin, 3 - 1] - CoordList[LinkEnd, 3 - 1]) / 2;
        //                        ReachProperties[thisreach, 2 - 1] = CoordList[LinkEndArea, 5 - 1];
        //                        ReachProperties[thisreach, 1 - 1] = (CoordList[LinkBegin, 4 - 1] - CoordList[LinkEnd, 4 - 1]);
        //                        ReachProperties[thisreach, 4 - 1] = CoordList[LinkEndArea, 0]; //end x CoordList
        //                        ReachProperties[thisreach, 5 - 1] = CoordList[LinkEndArea, 1]; //end y coordinate
        //                        if (ordert <= 0)
        //                        {
        //                            BasinID = subbno;
        //                        }
        //                        else
        //                        {
        //                            BasinID = numBasins;
        //                        }

        //                        //Upper half reach
        //                        currReach = currReach + 1;
        //                        ReachConnections[thisreach + 1, 1 - 1] = currReach;
        //                        if (UpstreamLink1 > 0)
        //                        {
        //                            links.Push(thisreach + 1);
        //                            links.Push(2 - 1);
        //                            links.Push(UpstreamLink1);
        //                            Magnitude[currLink] = Magnitude[currLink] + Magnitude[UpstreamLink1];
        //                        }
        //                        else
        //                        {
        //                            ReachConnections[thisreach + 1, 2 - 1] = 0;
        //                        }
        //                        if (UpstreamLink2 > 0)
        //                        {
        //                            links.Push(thisreach + 1);
        //                            links.Push(3 - 1);
        //                            links.Push(UpstreamLink2);
        //                            Magnitude[currLink] = Magnitude[currLink] + Magnitude[UpstreamLink2];
        //                        }
        //                        else
        //                        {
        //                            ReachConnections[thisreach + 1, 3 - 1] = 0;
        //                        }
        //                        //AddReachShape3(NetSF, FlowNet, CoordList, currLink, BasinID, Magnitude[currLink], dsNodeID[currLink]);
        //                        ReachProperties[thisreach + 1, 3 - 1] = ReachProperties[thisreach, 3 - 1];
        //                        ReachProperties[thisreach + 1, 2 - 1] = ReachProperties[thisreach, 2 - 1];
        //                        ReachProperties[thisreach + 1, 1 - 1] = ReachProperties[thisreach, 1 - 1];
        //                        ReachProperties[thisreach + 1, 4 - 1] = CoordList[(LinkEndArea + LinkBegin) / 2, 0]; //approx midpoint
        //                        ReachProperties[thisreach + 1, 5 - 1] = CoordList[(LinkEndArea + LinkBegin) / 2, 1];
        //                    }
        //                }
        //                else
        //                {
        //                    //This is an external basin
        //                    currReach = currReach + 1;
        //                    thisreach = currReach;
        //                    ReachConnections[thisreach, 1 - 1] = currReach;
        //                    ReachConnections[thisreach, 2 - 1] = numBasins;
        //                    ReachConnections[thisreach, 3 - 1] = 0;
        //                    ReachProperties[thisreach, 3 - 1] = (CoordList[LinkBegin, 3 - 1] - CoordList[LinkEnd, 3 - 1]) / 2;
        //                    ReachProperties[thisreach, 2 - 1] = CoordList[LinkEndArea, 5 - 1];
        //                    if (ReachProperties[thisreach, 3 - 1] <= 0)
        //                    {
        //                        ReachProperties[thisreach, 1 - 1] = 0.01f;
        //                    }
        //                    else
        //                    {
        //                        ReachProperties[thisreach, 1 - 1] = (CoordList[LinkBegin, 4 - 1] - CoordList[LinkEnd, 4 - 1]) / (2 * ReachProperties[thisreach, 3 - 1]);
        //                    }
        //                    ReachProperties[thisreach, 4 - 1] = CoordList[LinkEndArea, 0]; //end x coordinate
        //                    ReachProperties[thisreach, 5 - 1] = CoordList[LinkEndArea, 1]; //end y coordinate

        //                    if (ordert <= 0)
        //                    {
        //                        BasinID = subbno;
        //                    }
        //                    else
        //                    {
        //                        BasinID = numBasins;
        //                    }
        //                    Magnitude[currLink] = 1;  //magnitude of external basin
        //                    //AddReachShape3(NetSF, FlowNet, CoordList, currLink, BasinID, Magnitude[currLink], dsNodeID[currLink]);
        //                }
        //                if (currDSLink != -1 && currDSFrom != -1)
        //                {
        //                    ReachConnections[currDSLink, currDSFrom] = thisreach;
        //                }

        //                if (callback != null) callback.Progress("Status", 100, "Stream Shapefile and Watershed Grid");
        //            }
        //            return 0;
        //        }

        //        private static int MarkBasinsAndNetworkStack(Queue<int> Links, int numBasins, int[,] FlowNet, float[,] CoordList, int currReach, int ordert, int subbno, int[] Magnitude, long[] dsNodeID, int numRows, int numCols, int[,] ReachConnections, float[,] ReachProperties, Raster d8Grid, Raster BasinGrid, Shapefile NetSF, IProgressHandler callback)
        //        {
        //            int newperc = 0;
        //            int oldperc = 0;
        //            bool alreadyMarked = false;
        //            int currLink, row, col, DownstreamLink, LinkEnd, LinkBegin, LinkEndArea = 0;
        //            //  variables for CoordList positions
        //            float x, y;

        //            List<int> marked = new List<int>();
        //            List<MapWinGIS.Point> markedPoint = new List<MapWinGIS.Point>();

        //            int totLinks;
        //            while (Links.Count != 0)
        //            {
        //                totLinks = Links.Count;
        //                if (totLinks > 0)
        //                {
        //                    newperc = Convert.ToInt32((Convert.ToDouble(Links.Count) / Convert.ToDouble(totLinks)) * 100);
        //                    if (newperc > oldperc)
        //                    {
        //                        if (callback != null) callback.Progress("Status", newperc, "Stream Shapefile and Watershed Grid");
        //                        oldperc = newperc;
        //                    }
        //                }

        //                LinkEndArea = 0;

        //                currLink = Links.Dequeue();

        //                if ((FlowNet[currLink, 4] == 0 || (FlowNet[currLink, 4] != 0 && marked.Contains(FlowNet[currLink, 4]))) && (FlowNet[currLink, 5] == 0 || (FlowNet[currLink, 5] != 0 && marked.Contains(FlowNet[currLink, 5]))))
        //                {
        //                    LinkEnd = FlowNet[currLink, 3 - 1];//*  This is CoordList of end of link */
        //                    LinkBegin = FlowNet[currLink, 2 - 1];//*  This is CoordList of beg of link */
        //                    if (LinkBegin < LinkEnd)
        //                    {
        //                        //has physical length
        //                        numBasins = numBasins + 1;
        //                        if (ordert < 0)
        //                        {
        //                            numBasins = subbno;
        //                        }

        //                        if (FlowNet[currLink, 4 - 1] != -1) //For anything other than a downstream end area is defined one grid cell back
        //                        {
        //                            LinkEndArea = LinkEnd - 1;
        //                        }
        //                        else
        //                        {
        //                            LinkEndArea = LinkEnd;
        //                        }

        //                        x = CoordList[LinkEndArea, 1 - 1];
        //                        y = CoordList[LinkEndArea, 2 - 1];
        //                        BasinGrid.ProjToCell(x, y, out col, out row);
        //                        alreadyMarked = false;
        //                        for (int i = 0; i < markedPoint.Count; i++)
        //                        {
        //                            if ((double)col == markedPoint[i].x && (double)row == markedPoint[i].y)
        //                            {
        //                                alreadyMarked = true;
        //                                break;
        //                            }
        //                        }
        //                        if (!alreadyMarked)
        //                        {
        //                            marked.Add(currLink);
        //                            MapWinGIS.Point pt = new MapWinGIS.Point();
        //                            pt.x = (double)col;
        //                            pt.y = (double)row;
        //                            markedPoint.Add(pt);
        //                            MarkBasinAreaStack(d8Grid, row, col, numBasins, numCols, numRows, BasinGrid, callback); //Label the region that drains to this pixel
        //                            AddReachShape(NetSF, FlowNet, CoordList, currLink, numBasins, Magnitude[currLink], dsNodeID[currLink]);
        //                        }
        //                    }
        //                    else
        //                    {
        //                        LinkEndArea = LinkEnd;
        //                        marked.Add(currLink); // CWG 20/7/2010 added to prevent loop
        //                        // CWG 20/7/2010 include zero length links in network shapefile
        //                        AddReachShape(NetSF, FlowNet, CoordList, currLink, 0, Magnitude[currLink], dsNodeID[currLink]);
        //                    }

        //                    DownstreamLink = FlowNet[currLink, 4 - 1];
        //                    if (DownstreamLink >= 0 && !Links.Contains(DownstreamLink) && !marked.Contains(DownstreamLink))
        //                    {
        //                        Links.Enqueue(DownstreamLink);
        //                    }
        //                }
        //                else
        //                {
        //                    Links.Enqueue(currLink);
        //                }
        //            }

        //            return 0;
        //        }

        //        private static void MarkBasinAreaStack(Raster d8Grid, int StartRow, int StartCol, int BasinID, int numCols, int numRows, Raster BasinGrid, IProgressHandler callback)
        //        {
        //            int row;
        //            int col;
        //            int newRow;
        //            int newCol;
        //            int[] rowMod = new int[9];
        //            int[] colMod = new int[9];
        //            rowMod[1] = 0; rowMod[2] = -1; rowMod[3] = -1; rowMod[4] = -1; rowMod[5] = 0; rowMod[6] = 1; rowMod[7] = 1; rowMod[8] = 1;
        //            colMod[1] = 1; colMod[2] = 1; colMod[3] = 0; colMod[4] = -1; colMod[5] = -1; colMod[6] = -1; colMod[7] = 0; colMod[8] = 1;

        //            Stack<int> cells = new Stack<int>();
        //            cells.Push(StartCol);
        //            cells.Push(StartRow);

        //            int totCells = 0, newperc = 0, oldperc = 0;
        //            while (cells.Count != 0)
        //            {
        //                if (totCells > 0)
        //                {
        //                    newperc = Convert.ToInt32((Convert.ToDouble(cells.Count) / Convert.ToDouble(totCells)) * 100);
        //                    if (newperc > oldperc)
        //                    {
        //                        if (callback != null) callback.Progress("Status", newperc, "Stream Shapefile and Watershed Grid");
        //                        oldperc = newperc;
        //                    }
        //                }

        //                row = cells.Pop();
        //                col = cells.Pop();

        //                if ((short)BasinGrid.get_Value(col, row) == -1)
        //                {
        //                    if (row != 0 & row != numRows - 1 & col != 0 & col != numCols - 1 & (short)d8Grid.get_Value(col, row) != -1)
        //                    {
        //                        //Not on boundary
        //                        BasinGrid.set_Value(col, row, BasinID);
        //                        for (int k = 1; k <= 8; k++)
        //                        {
        //                            newRow = row + rowMod[k];
        //                            newCol = col + colMod[k];

        //                            //test if neighbor drains towards cell excluding boundaries
        //                            if ((short)d8Grid.get_Value(newCol, newRow) >= 0 & (((short)d8Grid.get_Value(newCol, newRow) - k) == 4 | ((short)d8Grid.get_Value(newCol, newRow) - k) == -4))
        //                            {
        //                                cells.Push(newCol);
        //                                cells.Push(newRow);
        //                            }
        //                        }
        //                    }
        //                }
        //            }
        //        }

        //        private static void InitializeNetFields(Shapefile netSF)
        //        {
        //            int zero = 0;
        //            MapWinGIS.Field field = new MapWinGIS.Field();
        //            field.Name = "DOUT_MID";
        //            field.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field.Width = 16;
        //            field.Precision = 1;
        //            netSF.EditInsertField(field, zero, null);

        //            MapWinGIS.Field field2 = new MapWinGIS.Field();
        //            field2.Name = "DOUT_START";
        //            field2.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field2.Width = 16;
        //            field2.Precision = 1;
        //            netSF.EditInsertField(field2, zero, null);

        //            MapWinGIS.Field field3 = new MapWinGIS.Field();
        //            field3.Name = "DOUT_END";
        //            field3.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field3.Width = 16;
        //            field3.Precision = 1;
        //            netSF.EditInsertField(field3, zero, null);

        //            MapWinGIS.Field field4 = new MapWinGIS.Field();
        //            field4.Name = "WSNO";
        //            field4.Type = MapWinGIS.FieldType.INTEGER_FIELD;
        //            field4.Width = 6;
        //            field4.Precision = 0;
        //            netSF.EditInsertField(field4, zero, null);

        //            MapWinGIS.Field field5 = new MapWinGIS.Field();
        //            field5.Name = "US_Cont_Area";
        //            field5.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field5.Width = 16;
        //            field5.Precision = 1;
        //            netSF.EditInsertField(field5, zero, null);

        //            MapWinGIS.Field field6 = new MapWinGIS.Field();
        //            field6.Name = "Straight_Length";
        //            field6.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field6.Width = 16;
        //            field6.Precision = 0;
        //            netSF.EditInsertField(field6, zero, null);

        //            MapWinGIS.Field field7 = new MapWinGIS.Field();
        //            field7.Name = "Slope";
        //            field7.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field7.Width = 16;
        //            field7.Precision = 12;
        //            netSF.EditInsertField(field7, zero, null);

        //            MapWinGIS.Field field8 = new MapWinGIS.Field();
        //            field8.Name = "Drop";
        //            field8.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field8.Width = 16;
        //            field8.Precision = 2;
        //            netSF.EditInsertField(field8, zero, null);

        //            MapWinGIS.Field field9 = new MapWinGIS.Field();
        //            field9.Name = "DS_Cont_Area";
        //            field9.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field9.Width = 16;
        //            field9.Precision = 1;
        //            netSF.EditInsertField(field9, zero, null);

        //            MapWinGIS.Field field10 = new MapWinGIS.Field();
        //            field10.Name = "Magnitude";
        //            field10.Type = MapWinGIS.FieldType.INTEGER_FIELD;
        //            field10.Width = 6;
        //            field10.Precision = 0;
        //            netSF.EditInsertField(field10, zero, null);

        //            MapWinGIS.Field field11 = new MapWinGIS.Field();
        //            field11.Name = "Length";
        //            field11.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field11.Width = 16;
        //            field11.Precision = 1;
        //            netSF.EditInsertField(field11, zero, null);

        //            MapWinGIS.Field field12 = new MapWinGIS.Field();
        //            field12.Name = "Order";
        //            field12.Type = MapWinGIS.FieldType.INTEGER_FIELD;
        //            field12.Width = 6;
        //            field12.Precision = 0;
        //            netSF.EditInsertField(field12, zero, null);

        //            MapWinGIS.Field field13 = new MapWinGIS.Field();
        //            field13.Name = "dsNodeID";
        //            field13.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
        //            field13.Width = 12;
        //            field13.Precision = 1;
        //            netSF.EditInsertField(field13, zero, null);

        //            MapWinGIS.Field field14 = new MapWinGIS.Field();
        //            field14.Name = "USLINKNO2";
        //            field14.Type = MapWinGIS.FieldType.INTEGER_FIELD;
        //            field14.Width = 6;
        //            field14.Precision = 0;
        //            netSF.EditInsertField(field14, zero, null);

        //            MapWinGIS.Field field15 = new MapWinGIS.Field();
        //            field15.Name = "USLINKNO1";
        //            field15.Type = MapWinGIS.FieldType.INTEGER_FIELD;
        //            field15.Width = 6;
        //            field15.Precision = 0;
        //            netSF.EditInsertField(field15, zero, null);

        //            MapWinGIS.Field field16 = new MapWinGIS.Field();
        //            field16.Name = "DSLINKNO";
        //            field16.Type = MapWinGIS.FieldType.INTEGER_FIELD;
        //            field16.Width = 6;
        //            field16.Precision = 0;
        //            netSF.EditInsertField(field16, zero, null);

        //            MapWinGIS.Field field17 = new MapWinGIS.Field();
        //            field17.Name = "LINKNO";
        //            field17.Type = MapWinGIS.FieldType.INTEGER_FIELD;
        //            field17.Width = 6;
        //            field17.Precision = 0;
        //            netSF.EditInsertField(field17, zero, null);
        //        }

        //        private static int AddReachShape(Shapefile NetSF, int[,] FlowNet, float[,] CoordList, int currLink, int BasinID, int Magnitude, long dsNodeID)
        //        {
        //            double x = 0;
        //            double y = 0;
        //            double length;
        //            double glength;
        //            double x1;
        //            double y1;
        //            double xlast;
        //            double ylast;
        //            double usarea;
        //            double dsarea;
        //            double dslast;
        //            double dl;
        //            double drop;
        //            double slope;
        //            int istart;
        //            int iend;
        //            int zero;

        //            istart = FlowNet[currLink, 1];  //start index for reach
        //            iend = FlowNet[currLink, 2]; //end index for reach
        //            x1 = CoordList[istart, 0]; //start x CoordList for reach
        //            y1 = CoordList[istart, 1]; //start y CoordList for reach
        //            length = 0;
        //            xlast = x1;
        //            ylast = y1;
        //            usarea = CoordList[istart, 4];
        //            dslast = usarea;
        //            dsarea = usarea;

        //            IFeature shp = new IFeature();
        //            shp.Create(MapWinGIS.ShpfileType.SHP_POLYLINE);
        //            for (int j = 0; j <= (iend - istart); j++)
        //            {
        //                x = CoordList[j + istart, 0];
        //                y = CoordList[j + istart, 1];
        //                dl = Math.Sqrt((x - xlast) * (x - xlast) + (y - ylast) * (y - ylast));
        //                if (dl > 0)
        //                {
        //                    length = length + dl;
        //                    xlast = x;
        //                    ylast = y;
        //                    dsarea = dslast; //keeps track of last ds area
        //                    dslast = CoordList[j + istart, 4];
        //                }
        //                MapWinGIS.Point p = new MapWinGIS.Point();
        //                p.x = x;
        //                p.y = y;
        //                zero = 0;
        //                shp.InsertPoint(p, zero);
        //            }
        //            if (iend == istart)
        //            {
        //                MapWinGIS.Point p = new MapWinGIS.Point();
        //                p.x = x;
        //                p.y = y;
        //                int numpts = shp.numPoints;
        //                shp.InsertPoint(p, numpts);
        //            }
        //            drop = CoordList[istart, 3] - CoordList[iend, 3];
        //            slope = 0;
        //            float dsdist = CoordList[iend, 2];
        //            float usdist = CoordList[istart, 2];
        //            float middist = (dsdist + usdist) * 0.5f;
        //            if (length > 0)
        //            {
        //                slope = drop / length;
        //            }
        //            glength = Math.Sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1));
        //            zero = 0;
        //            NetSF.EditInsertShape(shp, zero);
        //            NetSF.EditCellValue(0, 0, currLink);
        //            NetSF.EditCellValue(1, 0, FlowNet[currLink, 3]);
        //            NetSF.EditCellValue(2, 0, FlowNet[currLink, 4]);
        //            NetSF.EditCellValue(3, 0, FlowNet[currLink, 5]);
        //            NetSF.EditCellValue(4, 0, dsNodeID);
        //            NetSF.EditCellValue(5, 0, FlowNet[currLink, 6]);
        //            NetSF.EditCellValue(6, 0, length);
        //            NetSF.EditCellValue(7, 0, Magnitude);
        //            NetSF.EditCellValue(8, 0, dsarea);
        //            NetSF.EditCellValue(9, 0, drop);
        //            NetSF.EditCellValue(10, 0, slope);
        //            NetSF.EditCellValue(11, 0, glength);
        //            NetSF.EditCellValue(12, 0, usarea);
        //            NetSF.EditCellValue(13, 0, BasinID);
        //            NetSF.EditCellValue(14, 0, dsdist);
        //            NetSF.EditCellValue(15, 0, usdist);
        //            NetSF.EditCellValue(16, 0, middist);

        //            return 0;
        //        }

        //        #endregion //converted Subbasinsetup

        //        #endregion

        //        #region "Create Network Outlets"
        //        /// <summary>
        //        /// A function to generate a network outlets shapefile from the tree.dat and coords.dat files.
        //        /// </summary>
        //        /// <param name="TreeDatPath">The path to the tree.dat file</param>
        //        /// <param name="CoordDatPath">The path to the coords.dat file</param>
        //        /// <param name="OutletsShapeResultPath">The output path for the network outlets shapefile</param>
        //        /// <param name="callback">A callback for progress messages</param>
        //        /// <returns></returns>
        //        public static bool CreateNetworkOutlets(string TreeDatPath, string CoordDatPath, string OutletsShapeResultPath, IProgressHandler callback)
        //        {
        //            int newperc = 0;
        //            int oldperc = 0;
        //            int numShps = 0, LinkEnd, LinkBegin, LinkEndArea = 0;
        //            float x, y;

        //            if (callback != null) callback.Progress("Status", 0, "Create Network Outlets");
        //            DataManagement.DeleteShapefile(OutletsShapeResultPath);

        //            Shapefile sf = new Shapefile();
        //            sf.CreateNew(OutletsShapeResultPath, MapWinGIS.ShpfileType.SHP_POINT);
        //            sf.StartEditingShapes(true, null);

        //            int zero = 0;
        //            MapWinGIS.Field field = new MapWinGIS.Field();
        //            field.Name = "MWShapeID";
        //            field.Type = MapWinGIS.FieldType.INTEGER_FIELD;
        //            sf.EditInsertField(field, zero, null);

        //            int numTreeNodes = 0;
        //            long[] dsNodeID;
        //            int[,] FlowNet;
        //            if (ReadTreeFile(TreeDatPath, out FlowNet, out dsNodeID, numTreeNodes) == 1)
        //            {
        //                MessageBox.Show("An error occured in creating the network outlets while reading the tree.dat file.", "Creating Network Outlets Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.DialogResult.OK);
        //                return false;
        //            }

        //            int numCoords = 0;
        //            float[,] CoordList;
        //            if (ReadCoordFile(CoordDatPath, out CoordList, numCoords) == 1)
        //            {
        //                MessageBox.Show("An error occured in creating the network outlets while reading the coords.dat file.", "Creating Network Outlets Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.DialogResult.OK);
        //                return false;
        //            }

        //            for (int i = 0; i <= numTreeNodes; i++)
        //            {
        //                if (numTreeNodes > 0)
        //                {
        //                    newperc = Convert.ToInt32((Convert.ToDouble(i) / Convert.ToDouble(numTreeNodes)) * 100);
        //                    if (newperc > oldperc)
        //                    {
        //                        if (callback != null) callback.Progress("Status", newperc, "Create Network Outlets");
        //                        oldperc = newperc;
        //                    }
        //                }

        //                LinkEnd = FlowNet[i, 3 - 1];//*  This is CoordList of end of link */
        //                LinkBegin = FlowNet[i, 2 - 1];//*  This is CoordList of beg of link */
        //                if (LinkBegin < LinkEnd)
        //                {
        //                    //has physical length
        //                    if (FlowNet[i, 4 - 1] != -1) //For anything other than a downstream end area is defined one grid cell back
        //                    {
        //                        LinkEndArea = LinkEnd - 1;
        //                    }
        //                    else
        //                    {
        //                        LinkEndArea = LinkEnd;
        //                    }

        //                    x = CoordList[LinkEndArea, 1 - 1];
        //                    y = CoordList[LinkEndArea, 2 - 1];

        //                    MapWinGIS.Point pt = new MapWinGIS.Point();
        //                    pt.x = x;
        //                    pt.y = y;
        //                    IFeature shp = new IFeature();
        //                    shp.Create(MapWinGIS.ShpfileType.SHP_POINT);
        //                    shp.InsertPoint(pt, numShps);
        //                    numShps = sf.NumRows();
        //                    sf.EditInsertShape(shp, numShps);
        //                    sf.EditCellValue(0, numShps, numShps);
        //                }
        //            }
        //            sf.Save();
        //            sf.Close();
        //            if (callback != null) callback.Progress("Status", 0, String.Empty);
        //            return true;
        //        }

        //        #endregion

        //        #region "Subbasins to Shapes"
        ///// <summary>
        ///// A function which uses the mapwingis utils to convert the subbasin grid to a polygon shapefile
        ///// </summary>
        ///// <param name="d8Path"></param>
        ///// <param name="watershedGridPath"></param>
        ///// <param name="watershedShapeResultPath"></param>
        ///// <param name="callback">A MapWinGIS.IProgressHandler used to return error messages etc.</param>
        ///// <returns>0 on success, -1 otherwise </returns>
        //public static int SubbasinsToShape(string d8Path, string watershedGridPath, string watershedShapeResultPath, IProgressHandler callback)
        //{
        //    var result = -1;
        //    var gridD8 = new Grid();
        //    var gridWatershed = new Grid();

        //    var u = new MapWinGIS.Utils();

        //    if (callback != null)
        //    {
        //        callback.Progress("Status", 0, "Watershed Grid to Shapefile");
        //    }

        //    //DataManagement.DeleteShapefile(watershedShapeResultPath);
        //    gridD8.Open(d8Path, GridDataType.UnknownDataType, true, GridFileType.UseExtension, callback);
        //    gridWatershed.Open(watershedGridPath, GridDataType.UnknownDataType, true, GridFileType.UseExtension, callback);
        //    var sf = u.GridToShapefile(gridWatershed, gridD8, callback);
        //    if (sf.SaveAs(watershedShapeResultPath, callback))
        //    {
        //        result = 0;
        //    }

        //    sf.Projection = gridD8.Projection.ToString();
        //    gridD8.Close();

        //    gridWatershed.Close();
        //    sf.Close();

        //    if (callback != null)
        //    {
        //        callback.Progress("Status", 0, string.Empty);
        //    }

        //    return result;
        //}

        //        /// <summary>
        //        /// An overload of the SubbasinsToShape function which will generate a GeoprocDialog for the SubbasinsToShape function
        //        /// </summary>
        //        /// <param name="callback"></param>
        //        /// <returns></returns>
        //        public static int SubbasinsToShape(IProgressHandler callback)
        //        {
        //            return doSubbasinsToShapeDiag(callback);
        //        }

        //        /// <summary>
        //        /// An overload of the SubbasinsToShape function which will generate a GeoprocDialog for the SubbasinsToShape function
        //        /// </summary>
        //        /// <returns></returns>
        //        public static int SubbasinsToShape()
        //        {
        //            return doSubbasinsToShapeDiag(null);
        //        }

        //        private static int doSubbasinsToShapeDiag(IProgressHandler callback)
        //        {
        //            GeoProcDialog subtoshapeDiag = new GeoProcDialog();
        //            FileElement d8Elem = subtoshapeDiag.Add_FileElement(GeoProcDialog.ElementTypes.OpenGridFile);
        //            FileElement shedGridElem = subtoshapeDiag.Add_FileElement(GeoProcDialog.ElementTypes.OpenGridFile);
        //            FileElement shedShapeResElem = subtoshapeDiag.Add_FileElement(GeoProcDialog.ElementTypes.SaveShapefile);

        //            subtoshapeDiag.Text = "Sub-basins to Shapefile Conversion";
        //            subtoshapeDiag.HelpTitle = "Sub-basins to Shapefile Conversion";
        //            subtoshapeDiag.HelpText = "This function will generate a polygon shapefile of sub-basins from a sub-basin grid and D8 grid.";
        //            subtoshapeDiag.Height = 250;
        //            subtoshapeDiag.HelpPanelVisible = false;

        //            d8Elem.Caption = "D8 Flow Direction Grid Path";
        //            d8Elem.HelpButtonVisible = false;

        //            shedGridElem.Caption = "Sub-basins Grid Result Path";
        //            shedGridElem.HelpButtonVisible = false;

        //            shedShapeResElem.Caption = "Sub-basins Shapefile Result Path";
        //            shedShapeResElem.HelpButtonVisible = false;

        //            if (subtoshapeDiag.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //            {
        //                return Hydrology.SubbasinsToShape(d8Elem.Filename, shedGridElem.Filename, shedShapeResElem.Filename, callback);
        //            }
        //            return -2;
        //        }

        //        #endregion

        //        #region Move outlets to streams
        //        /// <summary>
        //        /// Move outlets down slope in d8Path to streams in StreamGridPath
        //        /// </summary>
        //        /// <param name="D8Path">D8 slope grid</param>
        //        /// <param name="StreamGridPath">grid of streams</param>
        //        /// <param name="OutletsPath">Point shape file of outlets and inlets</param>
        //        /// <param name="MovedOutletsPath">Result point shape file of moved outlets and inlets</param>
        //        /// <param name="Thresh">threshold</param>
        //        /// <param name="numProcesses">Limit on number of threads</param>
        //        /// <param name="showTaudemOutput">taudem output is shown if this is true</param>
        //        /// <param name="callback"></param>
        //        /// <returns>0 if success</returns>
        //        public static int MoveOutletsToStreams(string D8Path, string StreamGridPath, string OutletsPath, string MovedOutletsPath, int Thresh, int numProcesses, bool showTaudemOutput, IProgressHandler callback)
        //        {
        //           Trace.WriteLine("MoveOutletsToStreams(d8Path: " + D8Path + ",\n" +
        //                                     "       StreamGridPath: " + StreamGridPath + ",\n" +
        //                                     "       outletsPath: " + OutletsPath + ",\n" +
        //                                     "       MovedOutletsPath: " + MovedOutletsPath + ",\n" +
        //                                     "       threshold: " + Thresh + ",\n" +
        //                                     "       NumProcesses: " + numProcesses.ToString() + "\n" +
        //                                     "       ShowTaudemOutput: " + showTaudemOutput.ToString() + "\n" +
        //                                     "       callback)");
        //            int result = -1;
        //            DataManagement.DeleteShapefile(MovedOutletsPath);

        //            if (callback != null) callback.Progress("Status", 0, "Move Outlets to Streams");

        //            string pars =
        //                "-p " + D8Path +
        //                " -src " + StreamGridPath +
        //                " -o " + OutletsPath +
        //                " -om " + MovedOutletsPath +
        //                " -md " + Thresh.ToString();
        //            result = RunTaudem("MoveOutletsToStreams.exe", pars, numProcesses, showTaudemOutput);
        //            if (result != 0)
        //            {
        //                MessageBox.Show("TauDEM Error " + result, "TauDEM Error " + result, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.DialogResult.OK);
        //                return result;
        //            }

        //            DataManagement.TryCopy(System.IO.Path.ChangeExtension(OutletsPath, ".prj"),
        //                                   System.IO.Path.ChangeExtension(MovedOutletsPath, ".prj"));
        //            if (callback != null) callback.Progress("Status", 0, String.Empty);
        //           Trace.WriteLine("Finished Move Outlets to Streams");
        //            return result;
        //        }
        //        #endregion

        //        #region "Apply Stream Attributes"

        /// <summary>
        ///   Hydrology function used to add to the stream shapefile attributes
        /// </summary>
        /// <param name = "streamNetworkShapePath"></param>
        /// <param name = "demPath"></param>
        /// <param name = "subBasinShapePath"></param>
        /// <param name = "elevUnits"></param>
        /// <param name = "callback"></param>
        /// <returns></returns>
        public static bool ApplyStreamAttributes(
            string streamNetworkShapePath,
            string demPath,
            string subBasinShapePath,
            ElevationUnits elevUnits,
            IProgressHandler callback)
        {
            int sindx;
            var oldperc = 0;
            const int IDField = 0;
            const int DsField = 1;
            const int Us1Field = 2;
            const int Us2Field = 3;
            const int DsAreaField = 8;
            const int SlopeField = 10;
            const int UsAreaField = 12;
            //const int WShedIDField = 13;

            if (callback != null)
            {
                callback.Progress("Status", 0, "Calculating Stream Parameters");
            }

            if (!File.Exists(streamNetworkShapePath))
            {
                MessageBox.Show(string.Format(@"The file {0} does not exists! ", streamNetworkShapePath));
                return false;
            }

            var streamShape = FeatureSet.Open(streamNetworkShapePath);
            if (streamShape == null)
            {
                throw new ApplicationException(
                    String.Format("Error in opening {0}", streamNetworkShapePath)
                    );
            }

            // Add some fields:
            var lowFieldNum = AddField(streamShape, "ElevLow", typeof(double));
            var highFieldNum = AddField(streamShape, "Elevhigh", typeof(double));
            var mwidthFieldNum = AddField(streamShape, "MeanWidth", typeof(double));
            var mdepthFieldNum = AddField(streamShape, "MeanDepth", typeof(double));
            var dsareaAcreFieldNum = AddField(streamShape, "DSAreaAcre", typeof(double));
            var dsareaSqMiFieldNum = AddField(streamShape, "USAreaAcre", typeof(double));
            var usareaAcreFieldNum = AddField(streamShape, "DSAreaSqMi", typeof(double));
            var usareaSqMiFieldNum = AddField(streamShape, "USAreaSqMi", typeof(double));

            var projStr = streamShape.Projection;
            var demGrid = Raster.Open(demPath);
            var shedShape = FeatureSet.Open(subBasinShapePath);
            var shedShapeNumShapes = shedShape.NumRows();

            for (sindx = 0; sindx < streamShape.NumRows(); sindx++)
            {
                if (streamShape.NumRows() > 1)
                {
                    var newperc = Convert.ToInt32((Convert.ToDouble(sindx) / Convert.ToDouble(shedShapeNumShapes)) * 100);
                    if (newperc > oldperc)
                    {
                        if (callback != null)
                        {
                            callback.Progress("Status", newperc, "Calculating Stream Parameters");
                        }

                        oldperc = newperc;
                    }
                }

                double elevlow;
                double elevhigh;
                GetStreamElevationPoints(sindx, streamShape, demGrid, out elevlow, out elevhigh);

                switch (elevUnits)
                {
                    case ElevationUnits.centimeters:
                        elevlow = elevlow / 100;
                        elevhigh = elevhigh / 100;
                        break;
                    case ElevationUnits.feet:
                        elevlow = elevlow / 3.280839895;
                        elevhigh = elevhigh / 3.280839895;
                        break;
                }

                streamShape.EditCellValue(lowFieldNum, sindx, elevlow);
                streamShape.EditCellValue(highFieldNum, sindx, elevhigh);
                // This code seems to rely on some attribute WShedIDField that would be added by the old Util.GetShapeFileFromGrid or similar method

                //for (int shdindx = 0; shdindx < shedShapeNumShapes; shdindx++)
                //{
                //if ((int)shedShape.get_CellValue(IDField, shdindx)
                //    != (int)streamShape.get_CellValue(WShedIDField, sindx))
                //{
                //    continue;
                //}

                //    var currShp = shedShape.get_Shape(shdindx);
                //    var currArea = Utils.AreaOfPart(currShp, 0);
                //    var meanWidth = 1.29 * Math.Pow(currArea / 1000000, 0.6);
                //    var meanDepth = 0.13 * Math.Pow(currArea / 1000000, 0.4);
                //    streamShape.EditCellValue(mwidthFieldNum, sindx, meanWidth);
                //    streamShape.EditCellValue(mdepthFieldNum, sindx, meanDepth);
                //    break;
                //}

                var tmpID = (short)streamShape.get_CellValue(IDField, sindx);
                tmpID++;
                streamShape.EditCellValue(IDField, sindx, tmpID);
                tmpID = (short)streamShape.get_CellValue(DsField, sindx);
                if (tmpID > -1)
                {
                    tmpID++;
                }

                streamShape.EditCellValue(DsField, sindx, tmpID);
                tmpID = (short)streamShape.get_CellValue(Us1Field, sindx);
                if (tmpID > 0)
                {
                    tmpID++;
                }
                else
                {
                    tmpID = -1;
                }

                streamShape.EditCellValue(Us1Field, sindx, tmpID);
                tmpID = (short)streamShape.get_CellValue(Us2Field, sindx);
                if (tmpID > 0)
                {
                    tmpID++;
                }
                else
                {
                    tmpID = -1;
                }

                streamShape.EditCellValue(Us2Field, sindx, tmpID);
                var tmpSlope = (double)streamShape.get_CellValue(SlopeField, sindx);
                var tmpDsArea = (double)streamShape.get_CellValue(DsAreaField, sindx);
                var tmpUsArea = (double)streamShape.get_CellValue(UsAreaField, sindx);

                if (projStr != null)
                {
                    if (projStr.Unit.Name == "Meter")
                    {
                        var dsAreaAcre = tmpDsArea * 0.000247105;
                        var dsAreaSqMi = dsAreaAcre * 0.0015625;
                        var usAreaAcre = tmpUsArea * 0.000247105;
                        var usAreaSqMi = usAreaAcre * 0.0015625;
                        streamShape.EditCellValue(dsareaAcreFieldNum, sindx, dsAreaAcre);
                        streamShape.EditCellValue(dsareaSqMiFieldNum, sindx, dsAreaSqMi);
                        streamShape.EditCellValue(usareaAcreFieldNum, sindx, usAreaAcre);
                        streamShape.EditCellValue(usareaSqMiFieldNum, sindx, usAreaSqMi);
                        switch (elevUnits)
                        {
                            case ElevationUnits.meters:
                                tmpSlope = tmpSlope * 100;
                                break;
                            case ElevationUnits.centimeters:
                                break;
                            case ElevationUnits.feet:
                                tmpSlope = (tmpSlope / 3.280839895) * 100;
                                break;
                        }

                        streamShape.EditCellValue(SlopeField, sindx, tmpSlope);
                    }
                    else if (projStr.Unit.Name == "Foot")
                    {
                        var dsAreaAcre = tmpDsArea * 2.2957E-05;
                        var dsAreaSqMi = dsAreaAcre * 0.0015625;
                        var usAreaAcre = tmpUsArea * 2.2957E-05;
                        var usAreaSqMi = usAreaAcre * 0.0015625;
                        streamShape.EditCellValue(dsareaAcreFieldNum, sindx, dsAreaAcre);
                        streamShape.EditCellValue(dsareaSqMiFieldNum, sindx, dsAreaSqMi);
                        streamShape.EditCellValue(usareaAcreFieldNum, sindx, usAreaAcre);
                        streamShape.EditCellValue(usareaSqMiFieldNum, sindx, usAreaSqMi);
                        switch (elevUnits)
                        {
                            case ElevationUnits.meters:
                                tmpSlope = (tmpSlope * 3.280839895) * 100;
                                break;
                            case ElevationUnits.centimeters:
                                tmpSlope = (tmpSlope / 30.48) * 100;
                                break;
                            case ElevationUnits.feet:
                                tmpSlope = tmpSlope * 100;
                                break;
                        }

                        streamShape.EditCellValue(SlopeField, sindx, tmpSlope);
                    }
                }
                else
                {
                    var dSAreaAcre = tmpDsArea * 0.000247105;
                    var dsAreaSqMi = dSAreaAcre * 0.0015625;
                    var uSAreaAcre = tmpUsArea * 0.000247105;
                    var uSAreaSqMi = uSAreaAcre * 0.0015625;
                    streamShape.EditCellValue(dsareaAcreFieldNum, sindx, dSAreaAcre);
                    streamShape.EditCellValue(dsareaSqMiFieldNum, sindx, dsAreaSqMi);
                    streamShape.EditCellValue(usareaAcreFieldNum, sindx, uSAreaAcre);
                    streamShape.EditCellValue(usareaSqMiFieldNum, sindx, uSAreaSqMi);
                    switch (elevUnits)
                    {
                        case ElevationUnits.meters:
                            tmpSlope = tmpSlope * 100;
                            break;
                        case ElevationUnits.centimeters:
                            break;
                        case ElevationUnits.feet:
                            tmpSlope = (tmpSlope / 3.280839895) * 100;
                            break;
                    }

                    streamShape.EditCellValue(SlopeField, sindx, tmpSlope);
                }
            }

            shedShape.Close();
            demGrid.Close();

            streamShape.Save();
            streamShape.Close();

            if (callback != null)
            {
                callback.Progress("Status", 0, String.Empty);
            }

            return true;
        }