/// <summary>
        /// Creates a MapWinGIS.Shape object from the point data specified by the user.
        /// </summary>
        /// <returns>Returns a MapWinGIS.Shape object.</returns>
        public MapWinGIS.Shape ToMWShape(MapWinGIS.ShpfileType type)
        {
            if (m_Points.Count == 0)
            {
                return(null);
            }

            MapWinGIS.Shape shp = new MapWinGIS.ShapeClass();
            MapWinGIS.Point pnt;

            int partNum    = 0;
            int pointIndex = 0;

            bool bres;

            bres = shp.Create(type);
            bres = shp.InsertPart(0, ref partNum);

            for (int i = 0; i < m_Points.Count; i++)
            {
                pnt        = new MapWinGIS.PointClass();
                pnt.x      = ((PointD)m_Points[i]).x;
                pnt.y      = ((PointD)m_Points[i]).y;
                pointIndex = i;
                bres       = shp.InsertPoint(pnt, ref pointIndex);
                pnt        = null;
            }

            return(shp);
        }
示例#2
0
        /// <summary>
        /// Will check to see if two points are identical.
        /// </summary>
        /// <param name="point1">The first point to consider.</param>
        /// <param name="point2">The second point to consider.</param>
        /// <param name="sfType">The type of shapefile the points belong to.</param>
        /// <param name="mergedShp">The result shape</param>
        /// <returns>True if the points were merged successfully, false otherwise.</returns>
        private static bool MergePoints(ref MapWinGIS.Point point1, ref MapWinGIS.Point point2, MapWinGIS.ShpfileType sfType, out MapWinGIS.Shape mergedShp)
        {
            MapWinUtility.Logger.Dbg("MergePoints(point1: " + Macro.ParamName(point1) + "\n," +
                                     "            point2: " + Macro.ParamName(point2) + "\n," +
                                     "            sfType: " + sfType.ToString() + "\n," +
                                     "            mergedShp: out)");

            MapWinGIS.Shape mShp = new MapWinGIS.ShapeClass();
            if (point1.x == point2.x && point1.y == point2.y && point1.Z == point2.Z)
            {
                mShp.Create(sfType);
                int ptIndex = 0;
                mShp.InsertPoint(point1, ref ptIndex);
            }
            mergedShp = mShp;
            if (mergedShp.numPoints > 0)
            {
                MapWinUtility.Logger.Dbg("Finished MergePoints");
                return(true);
            }
            else
            {
                gErrorMsg = "The points are not identical so they cannot be merged.";
                Debug.WriteLine(gErrorMsg);
                Error.SetErrorMsg(gErrorMsg);
                mergedShp = mShp;
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }
        }
示例#3
0
        /// <summary>
        /// Creates one multi-part polygon out of two input polygons.
        /// </summary>
        /// <param name="poly1">The first polygon to be combined.</param>
        /// <param name="poly2">The second polygon to be combined.</param>
        /// <param name="resultShp">The resulting multi-part polygon.</param>
        /// <returns>True if combining was successful, false otherwise.</returns>
        private static bool CombinePolygons(ref MapWinGIS.Shape poly1, ref MapWinGIS.Shape poly2, out MapWinGIS.Shape resultShp)
        {
            int p1NumParts = poly1.NumParts;

            if (p1NumParts == 0)
            {
                p1NumParts = 1;
            }
            int p2NumParts = poly2.NumParts;

            if (p2NumParts == 0)
            {
                p2NumParts = 1;
            }

            MapWinGIS.Shape multiShp = new MapWinGIS.ShapeClass();
            multiShp.Create(poly1.ShapeType);
            int partIndex  = 0;
            int pointIndex = 0;
            int numPoints  = poly1.numPoints;
            int begPart    = 0;
            int endPart    = numPoints;

            //deal with the first shape and all of its parts
            //			Globals.Vertex[][] p1VertArray = new Globals.Vertex[p1NumParts][];
            //			Globals.ConvertPolyToVertexArray(ref poly1, out p1VertArray);
            //bool firstIsClockwise = Globals.IsClockwise(ref p1VertArray[0]);

            for (int i = 0; i <= p1NumParts - 1; i++)
            {
                partIndex  = i;
                pointIndex = multiShp.numPoints;
                multiShp.InsertPart(pointIndex, ref partIndex);

                begPart = poly1.get_Part(i);
                if (i < p1NumParts - 1)
                {
                    endPart = poly1.get_Part(i + 1);
                }
                else
                {
                    endPart = poly1.numPoints;
                }
                //				if(firstIsClockwise)
                //				{
                //add part
                for (int j = begPart; j <= endPart - 1; j++)
                {
                    pointIndex = multiShp.numPoints;
                    multiShp.InsertPoint(poly1.get_Point(j), ref pointIndex);
                }
                //				}
                //				else
                //				{
                //					//add part in reverse order
                //					for(int j = endPart-1; j >= begPart; j--)
                //					{
                //						pointIndex = multiShp.numPoints;
                //						multiShp.InsertPoint(poly1.get_Point(j), ref pointIndex);
                //					}
                //				}
            }            //end of adding poly1 and all of its parts to the result shape

            //deal with the second shape and all of its parts
            //			Globals.Vertex[][] p2VertArray = new Globals.Vertex[p2NumParts][];
            //			Globals.ConvertPolyToVertexArray(ref poly2, out p2VertArray);
            //			bool secondIsClockwise = Globals.IsClockwise(ref p2VertArray[0]);
            partIndex++;
            numPoints = poly2.numPoints;
            begPart   = 0;
            endPart   = numPoints;

            for (int i = 0; i <= p2NumParts - 1; i++)
            {
                partIndex += i;
                pointIndex = multiShp.numPoints;
                multiShp.InsertPart(pointIndex, ref partIndex);

                begPart = poly2.get_Part(i);
                if (i < p2NumParts - 1)
                {
                    endPart = poly2.get_Part(i + 1);
                }
                else
                {
                    endPart = poly2.numPoints;
                }

                //				if(secondIsClockwise)
                //				{
                for (int j = begPart; j <= endPart - 1; j++)
                {
                    pointIndex = multiShp.numPoints;
                    multiShp.InsertPoint(poly2.get_Point(j), ref pointIndex);
                }
                //				}
                //				else
                //				{
                //					for(int j = endPart-1; j >= begPart; j--)
                //					{
                //						pointIndex = multiShp.numPoints;
                //						multiShp.InsertPoint(poly2.get_Point(j), ref pointIndex);
                //					}
                //				}
            }            //end of inserting parts from the second shape

            resultShp = multiShp;
            if (resultShp.numPoints > 0)
            {
                return(true);
            }
            else
            {
                gErrorMsg = "Error occured while trying to combine parts. No points in result shape.";
                Debug.WriteLine(gErrorMsg);
                Error.SetErrorMsg(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }
        }
示例#4
0
        /// <summary>
        /// Removes portions of the lineSF that fall within the erase polygon
        /// </summary>
        /// <param name="lineSF">The shapefile of lines to be erased.</param>
        /// <param name="erasePoly">The polygon to be used for erasing portion of the line shapefile.</param>
        /// <param name="resultSF">The resulting line shapefile with portions removed.</param>
        /// <param name="CopyAttributes">Indicates whether to copy attributes</param>
        /// <returns>False if an error was encountered, true otherwise.</returns>
        public static bool EraseLineSFWithPoly(ref MapWinGIS.Shapefile lineSF, ref MapWinGIS.Shape erasePoly, ref MapWinGIS.Shapefile resultSF, bool CopyAttributes)
        {
            MapWinUtility.Logger.Dbg("EraseLineSFWithPoly(lineSF: " + Macro.ParamName(lineSF) + ",\n" +
                                     "                    erasePoly: " + Macro.ParamName(erasePoly) + ",\n" +
                                     "                    resultSF: " + Macro.ParamName(resultSF) + ",\n" +
                                     "                    CopyAttributes: " + CopyAttributes.ToString() + ")");
            if (lineSF == null || erasePoly == null || resultSF == null)
            {
                gErrorMsg = "One of the input parameters is null.";
                Error.SetErrorMsg(gErrorMsg);
                Debug.WriteLine(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }

            if (CopyAttributes)
            {
                string          tmpName;
                MapWinGIS.Field tmpField, currField;
                for (int f = 0; f <= lineSF.NumFields - 1; f++)
                {
                    tmpField      = new MapWinGIS.Field();
                    currField     = lineSF.get_Field(f);
                    tmpName       = currField.Name;
                    tmpField.Name = tmpName;

                    tmpField.Width     = currField.Width;
                    tmpField.Type      = currField.Type;
                    tmpField.Precision = currField.Precision;
                    tmpField.Key       = currField.Key;
                    resultSF.EditInsertField(tmpField, ref f, null);
                }
            }

            int shpIndex = 0;
            int numLines = lineSF.NumShapes;

            for (int i = 0; i <= numLines - 1; i++)
            {
                MapWinGIS.Shape currLine = new MapWinGIS.ShapeClass();
                currLine.Create(lineSF.ShapefileType);
                currLine = lineSF.get_Shape(i);

                MapWinGIS.Shape lineEnvelope = new MapWinGIS.ShapeClass();
                lineEnvelope.Create(MapWinGIS.ShpfileType.SHP_POLYGON);
                //create lineExtents' points out of the line extent points
                MapWinGIS.Point lTop, rTop, rBottom, lBottom;
                lTop      = new MapWinGIS.PointClass();
                lTop.x    = currLine.Extents.xMin;
                lTop.y    = currLine.Extents.yMax;
                rTop      = new MapWinGIS.PointClass();
                rTop.x    = currLine.Extents.xMax;
                rTop.y    = currLine.Extents.yMax;
                rBottom   = new MapWinGIS.PointClass();
                rBottom.x = currLine.Extents.xMax;
                rBottom.y = currLine.Extents.yMin;
                lBottom   = new MapWinGIS.PointClass();
                lBottom.x = currLine.Extents.xMin;
                lBottom.y = currLine.Extents.yMin;
                //now add the extent points to the new polygon shape: lineEnvelope
                int ptIndex = 0;
                lineEnvelope.InsertPoint(lTop, ref ptIndex);
                ptIndex++;
                lineEnvelope.InsertPoint(rTop, ref ptIndex);
                ptIndex++;
                lineEnvelope.InsertPoint(rBottom, ref ptIndex);
                ptIndex++;
                lineEnvelope.InsertPoint(lBottom, ref ptIndex);
                ptIndex++;
                lineEnvelope.InsertPoint(lTop, ref ptIndex);
                //remove COM points from memory
                while (Marshal.ReleaseComObject(lTop) != 0)
                {
                    ;
                }
                while (Marshal.ReleaseComObject(rTop) != 0)
                {
                    ;
                }
                while (Marshal.ReleaseComObject(rBottom) != 0)
                {
                    ;
                }
                while (Marshal.ReleaseComObject(lBottom) != 0)
                {
                    ;
                }

                //Check if line extents and polygon extents overlap
                if (Globals.CheckBounds(ref lineEnvelope, ref erasePoly))
                {
                    //make the envelope polygon slightly larger
                    MapWinGIS.Shape lgEnvelope = new MapWinGIS.ShapeClass();
                    lgEnvelope.Create(MapWinGIS.ShpfileType.SHP_POLYGON);
                    SpatialOperations.BufferPolygon(ref lineEnvelope, 0.5, Enumerations.Buffer_HoleTreatment.Ignore, Enumerations.Buffer_CapStyle.Pointed, out lgEnvelope);
                    //take the difference of the envelope polygon with the erase polygon.
                    MapWinGIS.Shape diff = new MapWinGIS.ShapeClass();
                    diff.Create(MapWinGIS.ShpfileType.SHP_POLYGON);
                    diff = SpatialOperations.Difference(lgEnvelope, erasePoly);
                    if (diff.numPoints > 0)
                    {
                        //the difference shape represents the line envelope
                        //minus the area of the erase polygon.
                        MapWinGIS.Shapefile inputLine = new MapWinGIS.ShapefileClass();
                        string tempPath = System.IO.Path.GetTempPath() + "tempInputLine.shp";
                        //CDM 8/4/2006 inputLine.CreateNew(tempPath, lineSF.ShapefileType);
                        Globals.PrepareResultSF(ref tempPath, ref inputLine, lineSF.ShapefileType);
                        shpIndex = 0;
                        inputLine.EditInsertShape(currLine, ref shpIndex);

                        int numParts = diff.NumParts;
                        if (numParts == 0)
                        {
                            numParts = 1;
                        }

                        if (numParts > 1)
                        {
                            //separate and test each part individually
                            MapWinGIS.Shape[] diffParts = new MapWinGIS.Shape[numParts];
                            Globals.SeparateParts(ref diff, out diffParts);
                            for (int j = 0; j <= numParts - 1; j++)
                            {
                                //don't check inside of holes
                                if (Globals.IsClockwise(ref diffParts[j]))
                                {
                                    MapWinGIS.Shapefile tempLineResult = new MapWinGIS.ShapefileClass();
                                    string tempLineFile = System.IO.Path.GetTempPath() + "tempLines.shp";
                                    DataManagement.DeleteShapefile(ref tempLineFile);
                                    //CDM 8/4/2006 tempLineResult.CreateNew(tempLineFile, lineSF.ShapefileType);
                                    Globals.PrepareResultSF(ref tempLineFile, ref tempLineResult, lineSF.ShapefileType);
                                    tempLineResult.StartEditingShapes(true, null);

                                    SpatialOperations.ClipShapesWithPolygon(ref inputLine, ref diffParts[j], out tempLineResult, false);

                                    int numResults = tempLineResult.NumShapes;
                                    if (numResults > 0)
                                    {
                                        //add results to the final result file.
                                        for (int k = 0; k <= numResults - 1; k++)
                                        {
                                            shpIndex = resultSF.NumShapes;
                                            resultSF.EditInsertShape(tempLineResult.get_Shape(k), ref shpIndex);
                                            if (CopyAttributes)
                                            {
                                                for (int f = 0; f <= lineSF.NumFields - 1; f++)
                                                {
                                                    bool tmpbool = resultSF.EditCellValue(f, shpIndex, lineSF.get_CellValue(f, i));
                                                }
                                            }
                                        }
                                    }                    //clipping successful
                                }                        //done checking islands
                            }                            //done looping through parts of the difference shape
                        }
                        else
                        {
                            MapWinGIS.Shapefile tempLineResult = new MapWinGIS.ShapefileClass();
                            string tempLineFile = System.IO.Path.GetTempPath() + "tempLines.shp";
                            DataManagement.DeleteShapefile(ref tempLineFile);
                            //CDM 8/4/2006 tempLineResult.CreateNew(tempLineFile, lineSF.ShapefileType);
                            Globals.PrepareResultSF(ref tempLineFile, ref tempLineResult, lineSF.ShapefileType);

                            tempLineResult.StartEditingShapes(true, null);

                            SpatialOperations.ClipShapesWithPolygon(ref inputLine, ref diff, out tempLineResult, false);

                            int numResults = tempLineResult.NumShapes;
                            if (numResults > 0)
                            {
                                //add results to the final result file.
                                for (int k = 0; k <= numResults - 1; k++)
                                {
                                    shpIndex = resultSF.NumShapes;
                                    resultSF.EditInsertShape(tempLineResult.get_Shape(k), ref shpIndex);
                                    if (CopyAttributes)
                                    {
                                        for (int f = 0; f <= lineSF.NumFields - 1; f++)
                                        {
                                            bool tmpbool = resultSF.EditCellValue(f, shpIndex, lineSF.get_CellValue(f, i));
                                        }
                                    }
                                }
                            }    //clipping successful
                        }
                    }            //difference operation successful
                }                //bounds overlapped
                else
                {
                    shpIndex = resultSF.NumShapes;
                    resultSF.EditInsertShape(currLine, ref shpIndex);
                    if (CopyAttributes)
                    {
                        for (int f = 0; f <= lineSF.NumFields - 1; f++)
                        {
                            bool tmpbool = resultSF.EditCellValue(f, shpIndex, lineSF.get_CellValue(f, i));
                        }
                    }
                }
            }            //end of looping through lines in the input shapefile
            MapWinUtility.Logger.Dbg("Finished EraseLineSFWithPoly");
            return(true);
        }
        /// <summary>
        /// Creates a new grid containing data from the input grid that
        /// falls within the polygon boundary.
        /// </summary>
        /// <param name="inputGF">Full path to the input grid file.</param>
        /// <param name="poly">The 2D polygon used for clipping the input grid.</param>
        /// <param name="resultGF">Full path to where the resulting grid will be saved.</param>
        /// <param name="clipToExtents">True if clipping to polygon extents rather than actual polygon shape.</param>
        /// <returns>True if clipping was successful, false if an error occurs.</returns>
        public static bool ClipGridWithPolygon(ref string inputGF, ref MapWinGIS.Shape poly, ref string resultGF, bool clipToExtents)
        {
            MapWinUtility.Logger.Dbg("ClipGridWithPolygon(inputGF: " + inputGF + ",\n" +
                                     "                    poly: " + Macro.ParamName(poly) + ",\n" +
                                     "                    resultGF: " + resultGF + ",\n" +
                                     "                    clipToExtents: " + clipToExtents.ToString());
            Error.ClearErrorLog();
            //			System.Diagnostics.PerformanceCounter ramCounter;
            //			ramCounter = new PerformanceCounter("Memory", "Available Bytes");
            //			float availableRAM = ramCounter.NextValue();
            bool inRAM = true;

            //open grid to get info and traverse through points
            MapWinGIS.Grid grid = new MapWinGIS.GridClass();

            //check memory availability
            //			availableRAM = ramCounter.NextValue();//amount of RAM in bytes
            //			Debug.WriteLine("available RAM: " + availableRAM.ToString() + " bytes");

            //			System.IO.FileInfo fileInfo = new FileInfo(inputGF);
            //			long fileSize = fileInfo.Length; //size of file in bytes
            //			Debug.WriteLine("file size: " + fileSize.ToString() + " bytes");
            //			if(fileSize*2 < availableRAM)
            //			{//go ahead and load grid into memory
            //				inRAM = true;
            //			}
            //			else
            //			{
            //				inRAM = false;
            //			}
            if (grid.Open(inputGF, MapWinGIS.GridDataType.UnknownDataType, inRAM, MapWinGIS.GridFileType.UseExtension, null) == false)
            {
                gErrorMsg = "Error occurred while trying to open grid: " + grid.get_ErrorMsg(grid.LastErrorCode);
                Error.SetErrorMsg(gErrorMsg);
                Debug.WriteLine(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }

            int    numCols    = grid.Header.NumberCols;
            int    numRows    = grid.Header.NumberRows;
            double cellWidth  = grid.Header.dX;
            double cellHeight = grid.Header.dY;
            double xllCenter  = grid.Header.XllCenter;
            double yllCenter  = grid.Header.YllCenter;
            //now calculate the UNCOMPRESSED grid file size:
            long inputGFSize = numCols * numRows * 8;

            //find the grid extents
            double minX, maxX, minY, maxY;

            minX = xllCenter - (cellWidth / 2);
            maxX = xllCenter + (cellWidth * (numCols - 1)) + (cellWidth / 2);
            minY = yllCenter - (cellHeight / 2);
            maxY = yllCenter + (cellHeight * (numRows - 1)) + (cellHeight / 2);

            //see if grid and poly extents cross:
            double polyMinX = poly.Extents.xMin;
            double polyMaxX = poly.Extents.xMax;
            double polyMinY = poly.Extents.yMin;
            double polyMaxY = poly.Extents.yMax;

            bool boundsIntersect = Globals.CheckBounds(minX, maxX, minY, maxY, polyMinX, polyMaxX, polyMinY, polyMaxY);

            if (boundsIntersect == false)
            {
                grid.Close();
                gErrorMsg = "Polygon and Grid boundaries do not overlap.";
                Error.SetErrorMsg(gErrorMsg);
                Debug.WriteLine(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }

            double newXll, newYll, firstXPt, firstYPt;
            int    newNumCols, newNumRows, firstCol, firstRow;

            //check if polygon extents are completely inside of grid extents
            if ((polyMinX >= minX && polyMinX <= maxX) && (polyMaxX >= minX && polyMaxX <= maxX) &&
                (polyMinY >= minY && polyMinY <= maxY) && (polyMaxY >= minY && polyMaxY <= maxY))
            {
                Debug.WriteLine("Poly extents are inside of grid extents.");
                minX = polyMinX;
                minY = polyMinY;
                maxX = polyMaxX;
                maxY = polyMaxY;

                //Find the new number of cols, rows, Xll and Yll values.
                int lastCol, lastRow;
                Globals.ProjToCell(minX, maxY, out firstCol, out firstRow, xllCenter, yllCenter, cellWidth, cellHeight, numRows);
                Globals.ProjToCell(maxX, minY, out lastCol, out lastRow, xllCenter, yllCenter, cellWidth, cellHeight, numRows);
                newNumCols = (lastCol - firstCol) + 1;
                newNumRows = (lastRow - firstRow) + 1;
                Debug.WriteLine("New numRows = " + newNumRows + " New numCols = " + newNumCols);
                Globals.CellToProj(firstCol, lastRow, out newXll, out newYll, xllCenter, yllCenter, cellWidth, cellHeight, numRows);
                Globals.CellToProj(firstCol, firstRow, out firstXPt, out firstYPt, xllCenter, yllCenter, cellWidth, cellHeight, numRows);
            }

            //check if grid extents are completely inside of polygon extents
            //note: there is really no purpose in this, as the new grid is the same
            //as the orgiginal grid....but we'll do it anyway.
            else if ((minX >= polyMinX && minX <= polyMaxX) && (maxX >= polyMinX && maxX <= polyMaxX) &&
                     (minY >= polyMinY && minY <= polyMaxY) && (maxY >= polyMinY && maxY <= polyMaxY))
            {
                Debug.WriteLine("Grid extents are inside of polygon extents.");
                //keep min and max values the same....no need to change them.
                newNumCols = numCols;
                newNumRows = numRows;
                newXll     = xllCenter;
                newYll     = yllCenter;
                firstCol   = 0;
                firstRow   = 0;
                Globals.CellToProj(0, 0, out firstXPt, out firstYPt, xllCenter, yllCenter, cellWidth, cellHeight, numRows);
            }
            else             //part of polygon lies outside of the grid, find intersecting boundary shape
            {
                Debug.WriteLine("Grid extents and polygon extents overlap.");
                //create a new shape out of the grid extents
                MapWinGIS.Shape gridEnvelope = new MapWinGIS.ShapeClass();
                gridEnvelope.Create(MapWinGIS.ShpfileType.SHP_POLYGON);
                MapWinGIS.Point pt = new MapWinGIS.PointClass();
                pt.x = minX;
                pt.y = maxY;
                int ptIndex = 0;
                gridEnvelope.InsertPoint(pt, ref ptIndex);
                pt      = new MapWinGIS.PointClass();
                pt.x    = maxX;
                pt.y    = maxY;
                ptIndex = 1;
                gridEnvelope.InsertPoint(pt, ref ptIndex);
                pt      = new MapWinGIS.PointClass();
                pt.x    = maxX;
                pt.y    = minY;
                ptIndex = 2;
                gridEnvelope.InsertPoint(pt, ref ptIndex);
                pt      = new MapWinGIS.PointClass();
                pt.x    = minX;
                pt.y    = minY;
                ptIndex = 3;
                gridEnvelope.InsertPoint(pt, ref ptIndex);
                pt      = new MapWinGIS.PointClass();
                pt.x    = minX;
                pt.y    = maxY;
                ptIndex = 4;
                gridEnvelope.InsertPoint(pt, ref ptIndex);

                //create the final bounding envelope which is
                //the intersection of the polygon and grid envelope:
                MapWinGIS.Shape envelope = new MapWinGIS.ShapeClass();
                envelope.Create(MapWinGIS.ShpfileType.SHP_POLYGON);
                envelope = SpatialOperations.Intersection(gridEnvelope, poly);
                if (envelope.numPoints == 0)
                {
                    gErrorMsg = "Problem creating the bounding envelope. Aborting ClipGrid().";
                    Error.SetErrorMsg(gErrorMsg);
                    Debug.WriteLine(gErrorMsg);
                    MapWinUtility.Logger.Dbg(gErrorMsg);
                    return(false);
                }

                //calculate how many rows and columns will exist within the new grid
                //that is: how many rows/cols fit within the bounding envelope.
                minX = envelope.Extents.xMin;
                minY = envelope.Extents.yMin;
                maxX = envelope.Extents.xMax;
                maxY = envelope.Extents.yMax;

                newNumCols = (int)(((maxX - minX) / cellWidth) + 0.5);
                newNumRows = (int)(((maxY - minY) / cellHeight) + 0.5);
                newXll     = minX + (cellWidth / 2);
                newYll     = minY + (cellHeight / 2);
                firstXPt   = newXll;
                firstYPt   = newYll + (cellHeight * (newNumRows - 1));
                Globals.ProjToCell(firstXPt, firstYPt, out firstCol, out firstRow, xllCenter, yllCenter, cellWidth, cellHeight, numRows);

                //done using COM objects, release them
                while (Marshal.ReleaseComObject(pt) != 0)
                {
                    ;
                }
                pt = null;
                while (Marshal.ReleaseComObject(gridEnvelope) != 0)
                {
                    ;
                }
                gridEnvelope = null;
                while (Marshal.ReleaseComObject(envelope) != 0)
                {
                    ;
                }
                envelope = null;
            }

            // Chris M 12/13/2006 for BugZilla 377
            // Below code:
            // The grid header cannot be copied right across like that! The first line creates
            // a new grid header; the second line deletes the newly created grid header and
            // copies a reference to the original grid's header. Both grids then are using
            // the same header; and when the last lines set the XllCenter and YllCenter,
            // BOTH grids are updated with that information! A classic example of pointers gone wrong.
            //MapWinGIS.GridHeader resultHeader = new MapWinGIS.GridHeaderClass();
            //resultHeader = grid.Header;
            //resultHeader.NodataValue = grid.Header.NodataValue;
            //resultHeader.NumberCols = newNumCols;
            //resultHeader.NumberRows = newNumRows;
            //resultHeader.XllCenter = newXll;
            //resultHeader.YllCenter = newYll;
            // The right way to do it:
            MapWinGIS.GridHeader resultHeader = new MapWinGIS.GridHeaderClass();
            resultHeader.CopyFrom(grid.Header);
            // Not really needed due to CopyFrom: resultHeader.NodataValue = grid.Header.NodataValue;
            resultHeader.NumberCols = newNumCols;
            resultHeader.NumberRows = newNumRows;
            resultHeader.XllCenter  = newXll;
            resultHeader.YllCenter  = newYll;
            // Not really needed due to CopyFrom: resultHeader.dX = grid.Header.dX;
            // Not really needed due to CopyFrom: resultHeader.dY = grid.Header.dY;
            // Not really needed due to CopyFrom: resultHeader.Projection = grid.Header.Projection;

            //create the new grid object
            MapWinGIS.Grid resultGrid = new MapWinGIS.GridClass();
            DataManagement.DeleteGrid(ref resultGF);

            //check memory availability
            //			availableRAM = ramCounter.NextValue();//amount of RAM in bytes
            //			Debug.WriteLine("available RAM: " + availableRAM.ToString() + " bytes");

            long resultGFSize = newNumCols * newNumRows * 8;             //projected size of grid in bytes

            //			if(resultGFSize * 2 < availableRAM)
            //			{//go ahead and load grid into memory
            //				inRAM = true;
            //			}
            //			else
            //			{
            //				inRAM = false;
            //			}

            if (resultGrid.CreateNew(resultGF, resultHeader, grid.DataType, grid.Header.NodataValue, inRAM, MapWinGIS.GridFileType.UseExtension, null) == false)
            {
                gErrorMsg = "Problem creating the result grid: " + resultGrid.get_ErrorMsg(resultGrid.LastErrorCode);
                Debug.WriteLine(gErrorMsg);
                Error.SetErrorMsg(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }
            //close the grids, we need to use the wrapper class now due to memory issues
            resultGrid.Save(resultGF, MapWinGIS.GridFileType.UseExtension, null);
            resultGrid.Close();
            while (Marshal.ReleaseComObject(resultGrid) != 0)
            {
                ;
            }
            resultGrid = null;
            grid.Close();
            while (Marshal.ReleaseComObject(grid) != 0)
            {
                ;
            }
            grid = null;

            //fill the result grid with values from the original grid
            try
            {
                Debug.WriteLine("newNumRows = " + newNumRows + " newNumCols = " + newNumCols);

                int rowClearCount = Globals.DetermineRowClearCount(newNumRows, newNumCols);

                Debug.WriteLine("Clearing COM resources every " + rowClearCount + " rows.");

                if (FillGrid(ref inputGF, ref resultGF, ref poly, newNumRows, newNumCols, rowClearCount, firstCol, firstRow, firstXPt, firstYPt, clipToExtents) == false)
                {
                    MapWinUtility.Logger.Dbg("Error running FillGrid\n");
                    return(false);
                }
            }            //end of try block
            catch (Exception e)
            {
                gErrorMsg = e.Message + e.ToString();
                Debug.WriteLine(gErrorMsg);
                Error.SetErrorMsg(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }


            //NOTE: The need for trimGrid has been removed from this function.
            //It will always return the smallest possible grid because we
            //build it based on the intersection boundary.

            DataManagement.CopyGridLegend(inputGF, resultGF);
            MapWinUtility.Logger.Dbg("Finished ClipGridWithPolygon");
            return(true);
        }