Пример #1
0
int QgsRasterFileWriter::pyramidsProgress( double dfComplete, const char *pszMessage, void* pData )
{
  Q_UNUSED( pszMessage );
  GDALTermProgress( dfComplete, 0, 0 );
  QProgressDialog* progressDialog = static_cast<QProgressDialog*>( pData );
  if ( pData && progressDialog->wasCanceled() )
  {
    return 0;
  }

  if ( pData )
  {
    progressDialog->setRange( 0, 100 );
    progressDialog->setValue( dfComplete * 100 );
  }
  return 1;
}
Пример #2
0
/**
 * Read in output from Isaac and populate a sqlite db with the read in values
 * as well as calculated values using erc.  Calculated values include:
 */
int main( int argc, char *argv[] )
{
    GDALAllRegister();
    const char *pszInputfile = NULL;
    const char *pszOutputDB = NULL;
    const char *pszTableName = NULL;
    const char *pszOutputfile = NULL;
    int bDrop = FALSE;
    int bProgress = TRUE;

    int i = 1;
    while( i < argc )
    {
        if( EQUAL( argv[i], "-d" ) )
        {
            bDrop = TRUE;
        }
        else if( EQUAL( argv[i], "-p" ) )
        {
            bProgress = TRUE;
        }
        else if( EQUAL( argv[i], "-db" ) )
        {
            pszOutputDB = argv[++i];
        }
        else if( EQUAL( argv[i], "-p" ) )
        {
            pszTableName = argv[++i];
        }
        else if( EQUAL( argv[i], "-f" ) )
        {
            pszOutputfile = argv[++i];
        }
        else if( EQUAL( argv[i], "-h" ) )
        {
            Usage();
        }
        else if( pszInputfile == NULL )
        {
            pszInputfile = argv[i];
        }
        else
        {
            Usage();
        }
        i++;
    }

    if( pszInputfile == NULL )
    {
        fprintf( stderr, "No input file provided\n");
        Usage();
    }
    if( pszOutputfile == NULL && 
        ( pszOutputDB == NULL || pszTableName == NULL ) )
    {
        fprintf( stderr, "Invalid output selected, use database and table or "
                         "output file\n" );
    }
    // Setup outputs
    int bDbOut = FALSE;
    int bTextOut = FALSE;
    if( pszOutputfile != NULL )
    {
        bTextOut = TRUE;
    }
    if( pszOutputDB != NULL && pszTableName != NULL )
    {
        bDbOut = TRUE;
    }

    sqlite3 *db;
    char *zErr;
    int rc;
    char sql[BUF_SIZE];

    if( bDbOut )
    {
        rc = sqlite3_open( pszOutputDB, &db );

        if ( rc )
        {
            fprintf( stderr, "Can't open database: %s\n", sqlite3_errmsg( db ) );
            sqlite3_close( db );
            exit( 1 );
        }

        if( bDrop )
        {
            sprintf( sql, "drop table %s", pszTableName );

            rc = sqlite3_exec( db, sql, NULL, NULL, &zErr );

            if ( rc != SQLITE_OK )
            {
                if ( zErr != NULL )
                {
                    fprintf( stderr, "SQL error: %s\n", zErr );
                    sqlite3_free( zErr );
                }
            }
        }

        sprintf( sql, "create table %s ( day integer, year integer, x float, "
                      "y float, cause int, time int, erc float, bi float, ros float, "
                      "fuel int)", pszTableName );

        rc = sqlite3_exec( db, sql, NULL, NULL, &zErr );

        if ( rc != SQLITE_OK )
        {
            if ( zErr != NULL )
            {
                fprintf( stderr, "SQL error: %s\n", zErr );
                sqlite3_free( zErr );
            }
            exit( 1 );
        }
    }
    FILE *fout;
    if( bTextOut )
    {
        fout = fopen( pszOutputfile, "w" );
    }
    if( fout == NULL )
    {
        fprintf( stderr, "Could not open %s for writing\n", pszOutputfile );
        exit( 1 );
    }

    FILE *fin;
    char buffer[BUF_SIZE];
    fin = fopen( pszInputfile, "r" );
    if( fin == NULL )
    {
        fprintf( stderr, "Could not open %s for reading\n", pszInputfile );
        exit( 1 );
    }
    int nRecords = 0;
    if( bProgress )
    {
        while( fgets( buffer, BUF_SIZE - 1, fin ) )
            nRecords++;
        fseek( fin, 0, SEEK_SET );
    }
    /*
     * Isaac's fields:
     * day year lat long cause time erc
     */
    /* Skip header */
    if( fgets( buffer, BUF_SIZE - 1, fin ) == NULL )
    {
        fprintf( stderr, "Could not read data from file" );
        exit( 1 );
    }

        //int iNFDRSVersion = 78,iClimateClass = 1,iJulianLookFreeze = 365,iJulianGreenUp = 1,iLat = (int) 45,iHerbAnnual=0,iWoodyDeciduous=0,iOneIsTen=0,iStartKBDI=800;
    //double fStart100 = 20.0,fStart1000=20.0,fAvgPrecip = 45.0;
    //double fMC1 = 3,fMC10 = 4,fMC100 = 5,fMC1000 = 10,fMCWood = 120,fMCHerb = 120;
    //int iRainEvent = 0, iKBDI = 800,iGreenWoody = 20,iGreenHerb = 20,iSeason = 2,iSOW = 0;

    // Initialize the NFDRS calculator
    //nfdrs.iInitialize(iNFDRSVersion,iClimateClass,iJulianLookFreeze,
    //                  iJulianGreenUp,iLat,iHerbAnnual,
    //                  iWoodyDeciduous,iOneIsTen,
    //                  fStart100,fStart1000, 
    //                  iStartKBDI,fAvgPrecip);
    //double fROS=0,fERC=0,fFL=0;
    //int iSC=0,iFIL=0,iBI=0,iWS=0,iSlopeCls=1;

    NFDRCalc nfdr;
    nfdr.iSetFuelModel( FUEL_MODEL_G, 0 );
    nfdr.SetVersion( 78 );

    double one_hour, ten_hour, hundred_hour, thousand_hour, woody, herb;
    /* What we actually get */
    double nfdr_erc;
    int nfdr_bi, nfdr_sc;;
    double dfDummy;
    int nDummy;

    GDALDatasetH hFuelDS;
    hFuelDS = GDALOpen( "/home/kyle/src/omfrr/trunk/data/"
                        "small_fuel40.tif", GA_ReadOnly );
    if( hFuelDS == NULL )
    {
        fprintf( stderr, "Cannot open fuels data for query.\n" );
        exit( 1 );
    }
    GDALDatasetH hSlopeDS;
    hSlopeDS = GDALOpen( "/home/kyle/src/omfrr/trunk/data/"
                         "small_slope.tif", GA_ReadOnly );
    if( hSlopeDS == NULL )
    {
        fprintf( stderr, "Cannot open slope data for query.\n" );
        exit( 1 );
    }
    GDALDatasetH hNarrMaskDS;
    hNarrMaskDS = GDALOpen( "/home/kyle/src/omfrr/trunk/data/"
                            "narr_mask_byte.tif", GA_ReadOnly );
    if( hNarrMaskDS == NULL )
    {
        fprintf( stderr, "Cannot open NARR mask for query.\n" );
        exit( 1 );
    }
    int nMaskXSize = GDALGetRasterXSize( hNarrMaskDS );
    int nMaskYSize = GDALGetRasterYSize( hNarrMaskDS );

    const char *pszAlbersWkt =
        "PROJCS[\"USA_Contiguous_Albers_Equal_Area_Conic_USGS_version\","
        "GEOGCS[\"GCS_North_American_1983\",DATUM[\"D_North_American_1983\","
        "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]],"
        "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],"
        "PROJECTION[\"Albers\"],PARAMETER[\"False_Easting\",0.0],"
        "PARAMETER[\"False_Northing\",0.0],"
        "PARAMETER[\"Central_Meridian\",-96.0],"
        "PARAMETER[\"Standard_Parallel_1\",29.5],"
        "PARAMETER[\"Standard_Parallel_2\",45.5],"
        "PARAMETER[\"Latitude_Of_Origin\",23.0],UNIT[\"Meter\",1.0]]";
    /* Assume same srs */
    //const char *pszAlbersWkt = NULL;

    char out_buf[2048];
    int day, year, cause, time;
    double x, y, erc;
    int fuel, mask, slope, slope_class;
    ifstream frisk_stream( "/home/kyle/src/omfrr/trunk/data/"
                           "narr_32km_frisk.flt", ios::binary );

    FRisk oFRisk;
    int skip = 0;
    int done = 0;
    int wind_speed;
    long offset;
    int nPixel;
    int nLine;
    if( bProgress )
    {
        GDALTermProgress( 0.0, NULL, NULL );
    }
    while( fgets( buffer, BUF_SIZE - 1, fin ) ) 
    {
        //frisk_stream.seekg( 0, ios::beg );
        done++;
        /* Note that it *appears* that isaac writes x,y and not lat,lon */
        sscanf( buffer, "%d %d %lf %lf %d %d %lf", &day, &year, &x, &y,
                &cause, &time, &erc );

        /* Calculate fire behavior indices based on fire risk data.
         * Load all into the sqlite db.  We need:
         * | BI | ROS | ERC | Flame Length | Fuel Model |
         * ROS and Flame length need to be calculated with rothermel.
         * BI, ERC and SC are calculated with nfdrs and fuel model G
         */

        /* Get the slope and find the class */
        slope = (int)PixelValue( hSlopeDS, 1, x, y, pszAlbersWkt );
        if( slope <= 25 )
            slope_class = 1;
        else if( slope <= 40 )
            slope_class = 2;
        else if( slope <= 55 )
            slope_class = 3;
        else if( slope <= 75 )
            slope_class = 4;
        else
            slope_class = 5;

        /* Check the mask, if we don't have data, skip it and emit a
         * warning
         */

        mask = (int)PixelValue( hNarrMaskDS, 1, x, y, pszAlbersWkt );
        if( !mask )
        {
            fprintf( stderr, "NARR data not available, skipping record\n" );
            skip++;
            continue;
        }
        /* NFDRS Stuff */

        PixelIndex(hNarrMaskDS, x, y, pszAlbersWkt, &nPixel, &nLine);
        if( nPixel >= nMaskXSize || nLine >= nMaskYSize )
        {
            CPLDebug( "fig_load", "Invalid pixel x:%d y:%d", nPixel, nLine );
            continue;
        }

        /* We should always have data for our query */
        assert( mask );
        assert( nPixel < nMaskXSize );
        assert( nLine < nMaskYSize );

        offset = nPixel + nLine * nMaskXSize;
        frisk_stream.seekg( offset * FRISK_SIZE, ios::beg );
        oFRisk.ReadBinary( frisk_stream );

        wind_speed = (int)oFRisk.GetRandomWindSpeed( day );
        one_hour = (double)oFRisk.GetOneHour( erc );
        ten_hour = (double)oFRisk.GetTenHour( erc );
        hundred_hour = (double)oFRisk.GetHundredHour( erc );
        thousand_hour = (double)oFRisk.GetThousandHour( erc );
        woody = (double)oFRisk.GetWoody( erc );
        herb = (double)oFRisk.GetHerb( erc );

        nfdr.iSetMoistures( one_hour, ten_hour, hundred_hour, thousand_hour,
                            woody, herb, nDummy, nDummy, nDummy, nDummy,
                            nDummy, nDummy );

        nfdr_erc = nfdr_bi = nfdr_sc = 0.0;
        nfdr.iCalcIndexes( wind_speed, slope_class, &dfDummy, &nfdr_sc, &nfdr_erc,
                           &dfDummy, &nDummy, &nfdr_bi );

        /* Look up fuel model for fb calculations, *not* nfdr */
        fuel = (int)PixelValue( hFuelDS, 1, x, y, pszAlbersWkt );

        if( bDbOut )
        {
            sprintf( sql, "insert into %s values(%d, %d, %lf, %lf, %d, %d,"
                          "%lf, %d, %lf, %d)",
                     pszTableName, day, year, x, y, cause, time, erc, nfdr_bi,
                     erc, fuel);

            rc = sqlite3_exec( db, sql, NULL, NULL, &zErr );

            if ( rc != SQLITE_OK )
            {
                if ( zErr != NULL )
                {
                    fprintf( stderr, "SQL error: %s\n", zErr );
                    sqlite3_free( zErr );
                    break;
                }
            }
        }
        if( bTextOut )
        {
            sprintf( out_buf, "%d %d %lf %lf %d %d %lf %d %lf %d\n",
                     day, year, x, y, cause, time, erc, nfdr_bi, erc, fuel);
            fputs( out_buf, fout );
        }

        if( bProgress )
        {
            double percent = (float)done / (float) nRecords;
            GDALTermProgress( percent, NULL, NULL );
        }
    }
    if( bProgress )
    {
        GDALTermProgress( 1.0, NULL, NULL );
    }

    if( skip )
    {
        fprintf( stderr, "Skipped %d records\n", skip );
    }

    fclose( fin );
    if( bDbOut )
    {
        sqlite3_close( db );
    }
    if( bTextOut )
    {
        fclose( fout );
    }

    return 0;
}
Пример #3
0
/* What we need:  specific condition, is walk in , tactic, distance elevation
 * minsteps, maxsteps, waterdrops, pump/roll, fwa id.
 */
int main( int argc, char *argv[] )
{
    GDALAllRegister();
    OGRRegisterAll();

    const char *pszInputfile = NULL;
    const char *pszOutputfile = NULL;
    const char *pszOutputFormat = "CSV";
    char **papszCreateOptions = NULL;
    const char *pszDataPath = NULL;
    const char *pszFpuCode = NULL;
    int nLimit = 0;
    int bProgress = TRUE;
    double dfMaxX, dfMinX, dfMaxY, dfMinY;
    int bLimit = FALSE;
    double dfBuffer = 0.0;

    int i = 1;
    while( i < argc )
    {
        if( EQUAL( argv[i], "-p" ) )
        {
            bProgress = TRUE;
        }
        else if( EQUAL( argv[i], "-d" ) )
        {
            pszDataPath = argv[++i];
        }
        else if( EQUAL( argv[i], "-of" ) )
        {
            pszOutputFormat = argv[++i];
        }        
        else if( EQUAL( argv[i], "-co" ) )
        {
            papszCreateOptions = CSLAddString( papszCreateOptions, argv[++i] );
        }
        else if( EQUAL( argv[i], "-sl" ) )
        {
            dfMaxX = atof(argv[++i]);
            dfMinX = atof(argv[++i]);
            dfMaxY = atof(argv[++i]);
            dfMinY = atof(argv[++i]);
            bLimit = TRUE;
        }
        else if( EQUAL( argv[i], "-fpu" ) )
        {
            pszFpuCode = argv[++i];
        }
        else if( EQUAL( argv[i], "-b" ) )
        {
            dfBuffer = atof( argv[++i] );
        }
        else if( EQUAL( argv[i], "-l" ) )
        {
            nLimit = atoi( argv[++i] );
        }        
        else if( EQUAL( argv[i], "-h" ) )
        {
            Usage();
        }
        else if( pszInputfile == NULL )
        {
            pszInputfile = argv[i];
        }
        else if( pszOutputfile == NULL )
        {
            pszOutputfile = argv[i];
        }
        else
        {
            Usage();
        }
        i++;
    }

    if( pszInputfile == NULL )
    {
        CPLError( CE_Failure, CPLE_OpenFailed, "No input file provided\n");
        Usage();
    }
    if( pszOutputfile == NULL )
    {
        CPLError( CE_Failure, CPLE_OpenFailed, "Invalid output selected, "
                "use database and table or output file\n" );
        Usage();
    }

    pszDataPath = CPLGetConfigOption( "OMFFR_DATA", NULL );

    OGRDataSourceH hInputDS = OGROpen( pszInputfile, FALSE, NULL );
    if( hInputDS == NULL )
    {
        CPLError( CE_Failure, CPLE_OpenFailed, "Cannot open input file\n" );
        Usage();
    }

    int year, num, day;
    const char *dow, *disc_time;
    int bi;
    double ros;
    int fuel;
    const char *spec_cond;
    int slope, walkin;
    const char *tactic;
    double dist;
    int elev;
    double ltow;
    int minsteps = 250;
    int maxsteps = 10000;
    const char *sunrise, *sunset;
    int waterdrops, pumproll;
    char *abyFwa;
    const char *fwaid;
    double lon, lat;

    OGRLayerH hInputLayer;
    hInputLayer = OGR_DS_GetLayerByName( hInputDS, CPLGetBasename( pszInputfile ) );
    OGRFeatureDefnH hInputFeatureDefn;

    OGRFeatureH hInputFeature;

    OGRGeometryH hGeometry;

    hInputFeatureDefn = OGR_L_GetLayerDefn( hInputLayer );

    const char *pszTmpFilename =CPLFormFilename( pszDataPath, "irs/FWA", ".dat" );
    std::vector<CFWA>fwas = LoadFwas( pszTmpFilename );
    
    int nFeatures = OGR_L_GetFeatureCount( hInputLayer, TRUE );
    FILE *fout = fopen( pszOutputfile, "w" );

    //CFWA *fwa;

    Random random;

    char pszDb[8192];
    sprintf( pszDb, "%s/omffr.sqlite", pszDataPath );

    IRSDataAccess *poDA = IRSDataAccess::Create( 0, pszDb );
    int rc;
    sqlite3 *db;
    rc = sqlite3_open_v2( pszDb, &db, SQLITE_OPEN_READONLY, NULL );
    rc = sqlite3_enable_load_extension( db, 1 );
    rc = sqlite3_load_extension( db, "/usr/local/lib/libspatialite.so", 0, NULL );
    sqlite3_stmt *stmt;
    rc = sqlite3_prepare_v2( db, "SELECT * from fwa join fwa_bndry USING(fwa_gis_id) " \
                                 "WHERE ST_Contains(fwa_bndry.geometry, MakePoint(?, ?, 4269))",
                                 -1, &stmt, NULL );

    if(rc)
    {
        CPLError( CE_Failure, CPLE_AppDefined, "Could not open DB");
    }

    GDALTermProgress( 0.0, NULL, NULL );
    OGR_L_ResetReading( hInputLayer );
    const char *pszFwaName;
    int nDone = 0;
    while( ( hInputFeature = OGR_L_GetNextFeature( hInputLayer ) ) != NULL )
    {
        /*
        fwaid = OGR_F_GetFieldAsString( hInputFeature,
                                        OGR_FD_GetFieldIndex( hInputFeatureDefn,
                                                              "fwa_name" ) );
        abyFwa = CPLStrdup( fwaid );
        LaunderFwaName( abyFwa );
        fwa = FindFwa( fwas, abyFwa );
        if( fwa == NULL )
        {
            CPLError( CE_Warning, CPLE_FileIO,
                    "Could not load fwa (%s)from file, missing\n", abyFwa );
            continue;
        }
        */
        /* Get fwa by point */
        hGeometry = OGR_F_GetGeometryRef( hInputFeature );
        /* Try to handle non-geometry types (csv) */
        if( hGeometry != NULL )
        {
            lat = OGR_G_GetY( hGeometry, 0 );
            lon = OGR_G_GetX( hGeometry, 0 );
        }
        else
        {
            lat = OGR_F_GetFieldAsDouble( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, 
                                                            "Y") );
            lon = OGR_F_GetFieldAsDouble( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, 
                                                            "X") );
        }

        std::string oFwaName = poDA->PointQuery( "fwa_bndry", "fwa_lndr_name",
                                                 lon, lat );
        rc = sqlite3_bind_double( stmt, 1, lon );
        rc = sqlite3_bind_double( stmt, 2, lat );
        //sqlite3_bind_text( stmt, 1, oFwaName.c_str(), -1, SQLITE_TRANSIENT);
        rc = sqlite3_step( stmt );
        if( rc != SQLITE_ROW && rc != SQLITE_DONE )
        {
            CPLError( CE_Warning, CPLE_FileIO,
                    "Could not load fwa (%s)from file, missing\n", oFwaName.c_str() );
            sqlite3_reset(stmt);
            continue;
        }

        int nFwaWalkIn, nFwaHead, nFwaTail, nFwaPara, nFwaAttackD;
        int nFwaWaterDrop, nFwaPumpRoll;
        nFwaWalkIn = sqlite3_column_int( stmt, 4 );
        nFwaHead = sqlite3_column_int( stmt, 6 );
        nFwaTail = sqlite3_column_int( stmt, 7 );
        nFwaPara = sqlite3_column_int( stmt, 8 );
        nFwaAttackD = sqlite3_column_int( stmt, 9 );
        nFwaWaterDrop = sqlite3_column_int( stmt, 10 );
        nFwaPumpRoll = sqlite3_column_int( stmt, 5 );

        year = OGR_F_GetFieldAsInteger( hInputFeature,
                                        OGR_FD_GetFieldIndex( hInputFeatureDefn,
                                                              "year" ) );
        num = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn,
                                                           "fire_num" ) );
        day = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn,
                                                           "day" ) );
        dow = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn,
                                                           "week_day" ) );
        disc_time = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn,
                                                                "disc_time" ) );
        bi = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn,
                                                          "bi" ) );
        ros = OGR_F_GetFieldAsDouble( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn,
                                                           "ros" ) );
        fuel = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn,
                                                            "fuel" ) );
        spec_cond = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn,
                                                                "spec_cond" ) );
        slope = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn,
                                                             "slope_perc" ) );
        //if( random.rand3() * 100 > fwa->GetWalkInPct() )
        if( random.rand3() * 100 > nFwaWalkIn )
            walkin = 0;
        else
            walkin = 1;
        //if( fwa->GetHead() == 100 )
        if( nFwaHead == 100 )
            tactic = "HEAD\0";
        //else if( fwa->GetTail() == 100 )
        else if( nFwaTail == 100 )
            tactic = "TAIL\0";
        //else if( fwa->GetParallel() == 100 )
        else if( nFwaTail == 100 )
            tactic = "PARALLEL\0";
        else
        {
            int r = (int)(random.rand3() * 100 );
            int total = 0;
            if( r < nFwaHead )
                tactic = "HEAD\0";
            else if( r < nFwaTail + nFwaTail )
                tactic = "TAIL\0";
            else
                tactic = "PARALLEL\0";
        }
        //dist = fwa->GetAttackDist();
        dist = nFwaAttackD;
        elev = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn,
                                                            "elev" ) );
        ltow = OGR_F_GetFieldAsDouble( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn,
                                                           "ratio" ) );
        sunrise = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn,
                                                             "sunrise" ) );
        sunset = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn,
                                                             "sunset" ) );
        //if( fwa->GetWaterDrops() )
        if( nFwaWaterDrop )
            waterdrops = TRUE;
        else
            waterdrops = FALSE;
        //if( fwa->GetPumpnRoll() )
        if( nFwaPumpRoll )
            pumproll = TRUE;
        else
            pumproll = FALSE;

        fprintf( fout, "%d %d %d %s %s "
                       "%d %lf %d %s %d "
                       "%d %s %lf %d %lf "
                       "%d %d %s %s %d "
                       "%d %s %lf %lf\n",
                 year, num, day, dow, disc_time,
                 bi, ros, fuel, spec_cond, slope, 
                 walkin, tactic, dist, elev, ltow, 
                 minsteps, maxsteps, sunrise, sunset, waterdrops, 
                 pumproll, /* abyFwa */ oFwaName.c_str(), lat, lon );

        sqlite3_reset(stmt);
        nDone++;
        GDALTermProgress( (float)nDone / (float)nFeatures, NULL, NULL );
    }
    GDALTermProgress( 1.0, NULL, NULL );
    fclose( fout );
    OGR_DS_Destroy( hInputDS );

    return 0;
}
Пример #4
0
int main( int argc, char ** argv )

{
    /* Check that we are running against at least GDAL 1.4 (probably older in fact !) */
    /* Note to developers : if we use newer API, please change the requirement */
    if (atoi(GDALVersionInfo("VERSION_NUM")) < 1400)
    {
        fprintf(stderr, "At least, GDAL >= 1.4.0 is required for this version of %s, "
                "which was compiled against GDAL %s\n", argv[0], GDAL_RELEASE_NAME);
        exit(1);
    }

/* -------------------------------------------------------------------- */
/*      Generic arg processing.                                         */
/* -------------------------------------------------------------------- */
    GDALAllRegister();
    GDALSetCacheMax( 100000000 );
    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
    if( argc < 1 )
        exit( -argc );
    
/* -------------------------------------------------------------------- */
/*      Parse arguments.                                                */
/* -------------------------------------------------------------------- */
    int i;
    const char *pszOutFile = NULL;
    const char *pszInFile = NULL;
    int nMaxNonBlack = 2;
    int nNearDist = 15;
    int bNearWhite = FALSE;
    int bSetAlpha = FALSE;
    int bSetMask = FALSE;
    const char* pszDriverName = "HFA";
    int bFormatExplicitelySet = FALSE;
    char** papszCreationOptions = NULL;
    int bQuiet = FALSE;

    Colors oColors;
    
    for( i = 1; i < argc; i++ )
    {
        if( EQUAL(argv[i], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( EQUAL(argv[i], "-o") && i < argc-1 )
            pszOutFile = argv[++i];
        else if( EQUAL(argv[i], "-of") && i < argc-1 )
        {
            pszDriverName = argv[++i];
            bFormatExplicitelySet = TRUE;
        }
        else if( EQUAL(argv[i], "-white") ) {
            bNearWhite = TRUE;
        }

        /***** -color c1,c2,c3...cn *****/
        
        else if( EQUAL(argv[i], "-color") && i < argc-1 ) {
            Color oColor;
            
            /***** tokenize the arg on , *****/
            
            char **papszTokens;
            papszTokens = CSLTokenizeString2( argv[++i], ",", 0 );

            /***** loop over the tokens *****/
            
            int iToken;
            for( iToken = 0; papszTokens && papszTokens[iToken]; iToken++ )
            {

                /***** ensure the token is an int and add it to the color *****/
                
                if ( IsInt( papszTokens[iToken] ) )
                    oColor.push_back( atoi( papszTokens[iToken] ) );
                else {
                    CPLError(CE_Failure, CPLE_AppDefined,
                             "Colors must be valid integers." );
                    CSLDestroy( papszTokens );
                    exit(1);
                }
            }
            
            CSLDestroy( papszTokens );

            /***** check if the number of bands is consistant *****/

            if ( oColors.size() > 0 &&
                 oColors.front().size() != oColor.size() )
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "ERROR: all -color args must have the same number of values.\n" );
                exit(1);
            }

            /***** add the color to the colors *****/
            
            oColors.push_back( oColor );
            
        }
        
        else if( EQUAL(argv[i], "-nb") && i < argc-1 )
            nMaxNonBlack = atoi(argv[++i]);
        else if( EQUAL(argv[i], "-near") && i < argc-1 )
            nNearDist = atoi(argv[++i]);
        else if( EQUAL(argv[i], "-setalpha") )
            bSetAlpha = TRUE;
        else if( EQUAL(argv[i], "-setmask") )
            bSetMask = TRUE;
        else if( EQUAL(argv[i], "-q") || EQUAL(argv[i], "-quiet") )
            bQuiet = TRUE;
        else if( EQUAL(argv[i], "-co") && i < argc-1 )
            papszCreationOptions = CSLAddString(papszCreationOptions, argv[++i]);
        else if( argv[i][0] == '-' )
            Usage();
        else if( pszInFile == NULL )
            pszInFile = argv[i];
        else
            Usage();
    }

    if( pszInFile == NULL )
        Usage();

    if( pszOutFile == NULL )
        pszOutFile = pszInFile;

/* -------------------------------------------------------------------- */
/*      Open input file.                                                */
/* -------------------------------------------------------------------- */
    GDALDatasetH hInDS, hOutDS = NULL;
    int nXSize, nYSize, nBands;

    if( pszOutFile == pszInFile )
        hInDS = hOutDS = GDALOpen( pszInFile, GA_Update );
    else
        hInDS = GDALOpen( pszInFile, GA_ReadOnly );

    if( hInDS == NULL )
        exit( 1 );

    nXSize = GDALGetRasterXSize( hInDS );
    nYSize = GDALGetRasterYSize( hInDS );
    nBands = GDALGetRasterCount( hInDS );
    int nDstBands = nBands;

    if( hOutDS != NULL && papszCreationOptions != NULL)
    {
        CPLError(CE_Warning, CPLE_AppDefined,
                  "Warning: creation options are ignored when writing to an existing file.");
    }

/* -------------------------------------------------------------------- */
/*      Do we need to create output file?                               */
/* -------------------------------------------------------------------- */
    if( hOutDS == NULL )
    {
        GDALDriverH hDriver = GDALGetDriverByName( pszDriverName );
        if (hDriver == NULL)
            exit(1);

        if (!bQuiet && !bFormatExplicitelySet)
            CheckExtensionConsistency(pszOutFile, pszDriverName);

        if (bSetAlpha)
        {
            /***** fixme there should be a way to preserve alpha band data not in the collar *****/
            if (nBands == 4)
                nBands --;
            else
                nDstBands ++;
        }

        if (bSetMask)
        {
            if (nBands == 4)
                nDstBands = nBands = 3;
        }

        hOutDS = GDALCreate( hDriver, pszOutFile, 
                             nXSize, nYSize, nDstBands, GDT_Byte, 
                             papszCreationOptions );
        if( hOutDS == NULL )
            exit( 1 );

        double adfGeoTransform[6];

        if( GDALGetGeoTransform( hInDS, adfGeoTransform ) == CE_None )
        {
            GDALSetGeoTransform( hOutDS, adfGeoTransform );
            GDALSetProjection( hOutDS, GDALGetProjectionRef( hInDS ) );
        }
    }
    else
    {
        if (bSetAlpha)
        {
            if (nBands != 4 &&
                (nBands < 2 ||
                 GDALGetRasterColorInterpretation(GDALGetRasterBand(hOutDS, nBands)) != GCI_AlphaBand))
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                        "Last band is not an alpha band.");
                exit(1);
            }

            nBands --;
        }

        if (bSetMask)
        {
            if (nBands == 4)
                nDstBands = nBands = 3;
        }
    }

    /***** set a color if there are no colors set? *****/

    if ( oColors.size() == 0) {
        Color oColor;

        /***** loop over the bands to get the right number of values *****/

        int iBand;
        for (iBand = 0; iBand < nBands ; iBand++) {

            /***** black or white? *****/

            if (bNearWhite) 
                oColor.push_back(255);
            else
                oColor.push_back(0);
        }

        /***** add the color to the colors *****/

        oColors.push_back(oColor);
            
    }

    /***** does the number of bands match the number of color values? *****/

    if ( (int)oColors.front().size() != nBands ) {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "-color args must have the same number of values as the non alpha input band count.\n" );
        exit(1); 
    }

    /***** check the input and output datasets are the same size *****/
    
    if (GDALGetRasterXSize(hOutDS) != nXSize ||
        GDALGetRasterYSize(hOutDS) != nYSize)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "The dimensions of the output dataset don't match "
                 "the dimensions of the input dataset.");
        exit(1);
    }


    int iBand;
    for( iBand = 0; iBand < nBands; iBand++ )
    {
        GDALRasterBandH hBand = GDALGetRasterBand(hInDS, iBand+1);
        if (GDALGetRasterDataType(hBand) != GDT_Byte)
        {
            CPLError(CE_Warning, CPLE_AppDefined,
                     "Band %d is not of type GDT_Byte. It can lead to unexpected results.", iBand+1);
        }
        if (GDALGetRasterColorTable(hBand) != NULL)
        {
            CPLError(CE_Warning, CPLE_AppDefined,
                     "Band %d has a color table, which is ignored by nearblack. "
                     "It can lead to unexpected results.", iBand+1);
        }
    }

    GDALRasterBandH hMaskBand = NULL;
    
    if (bSetMask) {

        /***** if there isn't already a mask band on the output file create one *****/
        
        if ( GMF_PER_DATASET != GDALGetMaskFlags( GDALGetRasterBand(hOutDS, 1) ) )
        {

            if ( CE_None != GDALCreateDatasetMaskBand(hOutDS, GMF_PER_DATASET) ) {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Failed to create mask band on output DS");
                bSetMask = FALSE;
            }
        }

        if (bSetMask) {
            hMaskBand = GDALGetMaskBand(GDALGetRasterBand(hOutDS, 1));
        }
    }

/* -------------------------------------------------------------------- */
/*      Allocate a line buffer.                                         */
/* -------------------------------------------------------------------- */
    GByte *pabyLine;
    GByte *pabyMask=NULL;
    
    int   *panLastLineCounts;

    pabyLine = (GByte *) CPLMalloc(nXSize * nDstBands);
    
    if (bSetMask)
        pabyMask = (GByte *) CPLMalloc(nXSize);
    
    panLastLineCounts = (int *) CPLCalloc(sizeof(int),nXSize);

/* -------------------------------------------------------------------- */
/*      Processing data one line at a time.                             */
/* -------------------------------------------------------------------- */
    int iLine;

    for( iLine = 0; iLine < nYSize; iLine++ )
    {
        CPLErr eErr;

        eErr = GDALDatasetRasterIO( hInDS, GF_Read, 0, iLine, nXSize, 1, 
                                    pabyLine, nXSize, 1, GDT_Byte, 
                                    nBands, NULL, nDstBands, nXSize * nDstBands, 1 );
        if( eErr != CE_None )
            break;
        
        if (bSetAlpha)
        {
            int iCol;
            for(iCol = 0; iCol < nXSize; iCol ++)
            {
                pabyLine[iCol * nDstBands + nDstBands - 1] = 255;
            }
        }
        
        if (bSetMask)
        {
            int iCol;
            for(iCol = 0; iCol < nXSize; iCol ++)
            {
                pabyMask[iCol] = 255;
            }
        }
        
        ProcessLine( pabyLine, pabyMask, 0, nXSize-1, nBands, nDstBands,
                     nNearDist, nMaxNonBlack, bNearWhite, &oColors,
                     panLastLineCounts,
                     TRUE, // bDoHorizontalCheck
                     TRUE, // bDoVerticalCheck
                     FALSE // bBottomUp
                    );
        ProcessLine( pabyLine, pabyMask, nXSize-1, 0, nBands, nDstBands,
                     nNearDist, nMaxNonBlack, bNearWhite, &oColors,
                     panLastLineCounts,
                     TRUE,  // bDoHorizontalCheck
                     FALSE, // bDoVerticalCheck
                     FALSE  // bBottomUp
                    );
        
        eErr = GDALDatasetRasterIO( hOutDS, GF_Write, 0, iLine, nXSize, 1, 
                                    pabyLine, nXSize, 1, GDT_Byte, 
                                    nDstBands, NULL, nDstBands, nXSize * nDstBands, 1 );

        if( eErr != CE_None )
            break;
    
        /***** write out the mask band line *****/

        if (bSetMask) {

            eErr = GDALRasterIO ( hMaskBand, GF_Write, 0, iLine, nXSize, 1,
                                  pabyMask, nXSize, 1, GDT_Byte,
                                  0, 0 );
                             
            if( eErr != CE_None ) {
                CPLError(CE_Warning, CPLE_AppDefined,
                         "ERROR writeing out line to mask band.");
               break;
            }
        }
        
        if (!bQuiet)
            GDALTermProgress( 0.5 * ((iLine+1) / (double) nYSize), NULL, NULL );
    }

/* -------------------------------------------------------------------- */
/*      Now process from the bottom back up                            .*/
/* -------------------------------------------------------------------- */
    memset( panLastLineCounts, 0, sizeof(int) * nXSize);
    
    for( iLine = nYSize-1; iLine >= 0; iLine-- )
    {
        CPLErr eErr;

        eErr = GDALDatasetRasterIO( hOutDS, GF_Read, 0, iLine, nXSize, 1, 
                                    pabyLine, nXSize, 1, GDT_Byte, 
                                    nDstBands, NULL, nDstBands, nXSize * nDstBands, 1 );
        if( eErr != CE_None )
            break;

        /***** read the mask band line back in *****/

        if (bSetMask) {

            eErr = GDALRasterIO ( hMaskBand, GF_Read, 0, iLine, nXSize, 1,
                                  pabyMask, nXSize, 1, GDT_Byte,
                                  0, 0 );
                             
                                
            if( eErr != CE_None )
                break;
        }

        
        ProcessLine( pabyLine, pabyMask, 0, nXSize-1, nBands, nDstBands,
                     nNearDist, nMaxNonBlack, bNearWhite, &oColors,
                     panLastLineCounts,
                     TRUE, // bDoHorizontalCheck
                     TRUE, // bDoVerticalCheck
                     TRUE  // bBottomUp
                   );
        ProcessLine( pabyLine, pabyMask, nXSize-1, 0, nBands, nDstBands,
                     nNearDist, nMaxNonBlack, bNearWhite, &oColors,
                     panLastLineCounts,
                     TRUE,  // bDoHorizontalCheck
                     FALSE, // bDoVerticalCheck
                     TRUE   // bBottomUp
                    );
        
        eErr = GDALDatasetRasterIO( hOutDS, GF_Write, 0, iLine, nXSize, 1, 
                                    pabyLine, nXSize, 1, GDT_Byte, 
                                    nDstBands, NULL, nDstBands, nXSize * nDstBands, 1 );
        if( eErr != CE_None )
            break;

        /***** write out the mask band line *****/

        if (bSetMask) {

            eErr = GDALRasterIO ( hMaskBand, GF_Write, 0, iLine, nXSize, 1,
                                  pabyMask, nXSize, 1, GDT_Byte,
                                  0, 0 );
                             
                                
            if( eErr != CE_None )
                break;
        }

        
        if (!bQuiet)
            GDALTermProgress( 0.5 + 0.5 * (nYSize-iLine) / (double) nYSize, 
                            NULL, NULL );
    }

    CPLFree(pabyLine);
    if (bSetMask)
        CPLFree(pabyMask);
    
    CPLFree( panLastLineCounts );

    GDALClose( hOutDS );
    if( hInDS != hOutDS )
        GDALClose( hInDS );
    GDALDumpOpenDatasets( stderr );
    CSLDestroy( argv );
    CSLDestroy( papszCreationOptions );
    GDALDestroyDriverManager();
    
    return 0;
}
Пример #5
0
int main( int argc, char ** argv )

{
    /* Check that we are running against at least GDAL 1.4 (probably older in fact !) */
    /* Note to developers : if we use newer API, please change the requirement */
    if (atoi(GDALVersionInfo("VERSION_NUM")) < 1400)
    {
        fprintf(stderr, "At least, GDAL >= 1.4.0 is required for this version of %s, "
                "which was compiled against GDAL %s\n", argv[0], GDAL_RELEASE_NAME);
        exit(1);
    }

/* -------------------------------------------------------------------- */
/*      Generic arg processing.                                         */
/* -------------------------------------------------------------------- */
    GDALAllRegister();
    GDALSetCacheMax( 100000000 );
    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
    if( argc < 1 )
        exit( -argc );
    
/* -------------------------------------------------------------------- */
/*      Parse arguments.                                                */
/* -------------------------------------------------------------------- */
    int i;
    const char *pszOutFile = NULL;
    const char *pszInFile = NULL;
    int nMaxNonBlack = 2;
    int nNearDist = 15;
    int bNearWhite = FALSE;
    
    for( i = 1; i < argc; i++ )
    {
        if( EQUAL(argv[i], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( EQUAL(argv[i], "-o") && i < argc-1 )
            pszOutFile = argv[++i];
        else if( EQUAL(argv[i], "-white") )
            bNearWhite = TRUE;
        else if( EQUAL(argv[i], "-nb") && i < argc-1 )
            nMaxNonBlack = atoi(argv[++i]);
        else if( EQUAL(argv[i], "-near") && i < argc-1 )
            nNearDist = atoi(argv[++i]);
        else if( argv[i][0] == '-' )
            Usage();
        else if( pszInFile == NULL )
            pszInFile = argv[i];
        else
            Usage();
    }

    if( pszInFile == NULL )
        Usage();

    if( pszOutFile == NULL )
        pszOutFile = pszInFile;

/* -------------------------------------------------------------------- */
/*      Open input file.                                                */
/* -------------------------------------------------------------------- */
    GDALDatasetH hInDS, hOutDS = NULL;
    int nXSize, nYSize, nBands;

    if( pszOutFile == pszInFile )
        hInDS = hOutDS = GDALOpen( pszInFile, GA_Update );
    else
        hInDS = GDALOpen( pszInFile, GA_ReadOnly );

    if( hInDS == NULL )
        exit( 1 );

    nXSize = GDALGetRasterXSize( hInDS );
    nYSize = GDALGetRasterYSize( hInDS );
    nBands = GDALGetRasterCount( hInDS );

/* -------------------------------------------------------------------- */
/*      Do we need to create output file?                               */
/* -------------------------------------------------------------------- */
    if( hOutDS == NULL )
    {
        GDALDriverH hDriver = GDALGetDriverByName( "HFA" );
        
        hOutDS = GDALCreate( hDriver, pszOutFile, 
                             nXSize, nYSize, nBands, GDT_Byte, 
                             NULL );
        if( hOutDS == NULL )
            exit( 1 );

        double adfGeoTransform[6];

        if( GDALGetGeoTransform( hInDS, adfGeoTransform ) == CE_None )
        {
            GDALSetGeoTransform( hOutDS, adfGeoTransform );
            GDALSetProjection( hOutDS, GDALGetProjectionRef( hInDS ) );
        }
    }

    int iBand;
    for( iBand = 0; iBand < nBands; iBand++ )
    {
        GDALRasterBandH hBand = GDALGetRasterBand(hInDS, iBand+1);
        if (GDALGetRasterDataType(hBand) != GDT_Byte)
        {
            CPLError(CE_Warning, CPLE_AppDefined,
                     "Band %d is not of type GDT_Byte. It can lead to unexpected results.", iBand+1);
        }
        if (GDALGetRasterColorTable(hBand) != NULL)
        {
            CPLError(CE_Warning, CPLE_AppDefined,
                     "Band %d has a color table, which is ignored by nearblack. "
                     "It can lead to unexpected results.", iBand+1);
        }
    }

/* -------------------------------------------------------------------- */
/*      Allocate a line buffer.                                         */
/* -------------------------------------------------------------------- */
    GByte *pabyLine;
    int   *panLastLineCounts;

    pabyLine = (GByte *) CPLMalloc(nXSize * nBands);

    panLastLineCounts = (int *) CPLCalloc(sizeof(int),nXSize);

/* -------------------------------------------------------------------- */
/*      Processing data one line at a time.                             */
/* -------------------------------------------------------------------- */
    int iLine;

    for( iLine = 0; iLine < nYSize; iLine++ )
    {
        CPLErr eErr;

        eErr = GDALDatasetRasterIO( hInDS, GF_Read, 0, iLine, nXSize, 1, 
                                    pabyLine, nXSize, 1, GDT_Byte, 
                                    nBands, NULL, nBands, nXSize * nBands, 1 );
        if( eErr != CE_None )
            break;
        
        ProcessLine( pabyLine, 0, nXSize-1, nBands, nNearDist, nMaxNonBlack,
                     bNearWhite, panLastLineCounts, TRUE, TRUE );
        ProcessLine( pabyLine, nXSize-1, 0, nBands, nNearDist, nMaxNonBlack,
                     bNearWhite, NULL, TRUE, FALSE );
        
        eErr = GDALDatasetRasterIO( hOutDS, GF_Write, 0, iLine, nXSize, 1, 
                                    pabyLine, nXSize, 1, GDT_Byte, 
                                    nBands, NULL, nBands, nXSize * nBands, 1 );
        if( eErr != CE_None )
            break;
        
        GDALTermProgress( 0.5 * ((iLine+1) / (double) nYSize), NULL, NULL );
    }

/* -------------------------------------------------------------------- */
/*      Now process from the bottom back up, doing only the vertical pass.*/
/* -------------------------------------------------------------------- */
    memset( panLastLineCounts, 0, sizeof(int) * nXSize);
    
    for( iLine = nYSize-1; iLine >= 0; iLine-- )
    {
        CPLErr eErr;

        eErr = GDALDatasetRasterIO( hOutDS, GF_Read, 0, iLine, nXSize, 1, 
                                    pabyLine, nXSize, 1, GDT_Byte, 
                                    nBands, NULL, nBands, nXSize * nBands, 1 );
        if( eErr != CE_None )
            break;
        
        ProcessLine( pabyLine, 0, nXSize-1, nBands, nNearDist, nMaxNonBlack,
                     bNearWhite, panLastLineCounts, FALSE, TRUE );
        
        eErr = GDALDatasetRasterIO( hOutDS, GF_Write, 0, iLine, nXSize, 1, 
                                    pabyLine, nXSize, 1, GDT_Byte, 
                                    nBands, NULL, nBands, nXSize * nBands, 1 );
        if( eErr != CE_None )
            break;
        
        GDALTermProgress( 0.5 + 0.5 * (nYSize-iLine) / (double) nYSize, 
                          NULL, NULL );
    }

    CPLFree(pabyLine);
    CPLFree( panLastLineCounts );

    GDALClose( hOutDS );
    if( hInDS != hOutDS )
        GDALClose( hInDS );
    GDALDumpOpenDatasets( stderr );
    GDALDestroyDriverManager();
    
    return 0;
}
Пример #6
0
int main(int argc, char *argv[])
{
    const char *pszInputfile = NULL;
    const char *pszOutputfile = NULL;
    const char *pszFormat = "GTiff";
    int bProgress = FALSE;
    int bMaskNoData = FALSE;
    GDALDatasetH hSrcDS;
    GDALDatasetH hMaskDS;
    GDALDriverH hDriver;
    double adfGeoTransform[6];
    const char *pszWkt;
    int nXSize, nYSize;
    int nMaskCount = 0;
    int nPixelsMasked = 0;
    double adfMaskValues[1024];
    int anMaskFound[1024];
    int bMaskProvided = FALSE;
    double dfNoData;
    int i, j, k;
    GDALRasterBandH hSrcBand, hMaskBand;
    double *padfScanline;
    unsigned char *pabyScanline;
    int nHasNoData;
    char** papszCreationOptions = NULL;

    i = 1;
    while( i < argc )
    {
        if( EQUAL( argv[i], "-p" ) )
        {
            bProgress = TRUE;
        }
        else if( EQUAL( argv[i], "-mask_nodata" ) )
        {
            bMaskNoData = TRUE;
            bMaskProvided = TRUE;
        }
        else if( EQUAL( argv[i], "-of" ) )
        {
            pszFormat = argv[++i];
        }
        else if( EQUAL( argv[i], "-co" ) )
        {
            papszCreationOptions = CSLAddString(papszCreationOptions,
                                                argv[++i]);
        }
        else if( EQUAL( argv[i], "-h" ) )
        {
            Usage();
        }
        else if( pszInputfile == NULL )
        {
            pszInputfile = argv[i];
        }
        else if( pszOutputfile == NULL )
        {
            pszOutputfile = argv[i];
        }
        else
        {
            adfMaskValues[nMaskCount++] = atof(argv[i]);
            bMaskProvided = TRUE;
        }
        //else
        //{
        //    Usage();
        //}
        i++;
    }

    if( pszInputfile == NULL )
    {
        fprintf( stderr, "No input file provided\n");
        Usage();
    }
    if( pszOutputfile == NULL )
    {
        fprintf( stderr, "No output file provided\n" );
        Usage();
    }
    GDALAllRegister();

    hSrcDS = GDALOpen(pszInputfile, GA_ReadOnly);
    if(hSrcDS == NULL)
    {
        CPLError(CE_Fatal, CPLE_OpenFailed, "Failed to open source dataset");
    }

    hDriver = GDALGetDriverByName(pszFormat);
    if(hDriver == NULL)
    {
        CPLError(CE_Fatal, CPLE_NotSupported, "Failed to load output driver");
    }

    nXSize = GDALGetRasterXSize(hSrcDS);
    nYSize = GDALGetRasterYSize(hSrcDS);
    hMaskDS = GDALCreate(hDriver, pszOutputfile, nXSize, nYSize, 1, GDT_Byte,
                         papszCreationOptions);
    pszWkt = GDALGetProjectionRef(hSrcDS);
    if(pszWkt != NULL)
    {
        GDALSetProjection(hMaskDS, pszWkt);
    }
    if(GDALGetGeoTransform(hSrcDS, adfGeoTransform) == CE_None)
    {
        GDALSetGeoTransform(hMaskDS, adfGeoTransform);
    }
    hSrcBand = GDALGetRasterBand(hSrcDS, 1);
    hMaskBand = GDALGetRasterBand(hMaskDS, 1);

    nHasNoData = FALSE;
    if(bMaskNoData)
    {
        dfNoData = GDALGetRasterNoDataValue(hSrcBand, &nHasNoData);
        if(nHasNoData)
        {
            adfMaskValues[nMaskCount++] = dfNoData;
        }
    }
    for(i = 0;i < nMaskCount;i++)
    {
        anMaskFound[i] = 0;
    }

    padfScanline = (double*)CPLMalloc(nXSize * sizeof(double));
    pabyScanline = (unsigned char*)CPLMalloc(nXSize * sizeof(unsigned char));

    if(bProgress)
    {
        GDALTermProgress(0.0, NULL, NULL);
    }

    for(i = 0;i < nYSize;i++)
    {
        GDALRasterIO(hSrcBand, GF_Read, 0, i, nXSize, 1, padfScanline, nXSize,
                     1, GDT_Float64, 0, 0);
        for(j = 0; j < nXSize;j++)
        {
            pabyScanline[j] = 255;
            for(k = 0; k < nMaskCount; k++)
            {
                if(CPLIsEqual(padfScanline[j], adfMaskValues[k]))
                {
                    pabyScanline[j] = 0;
                    anMaskFound[k]++;
                    nPixelsMasked++;
                    break;
                }
            }
        }
        GDALRasterIO(hMaskBand, GF_Write, 0, i, nXSize, 1, pabyScanline, 
                     nXSize, 1, GDT_Byte, 0, 0);
        if(bProgress)
        {
            GDALTermProgress((double)i / (double)nYSize, NULL, NULL);
        }
    }
    if(bProgress)
    {
        GDALTermProgress(1.0, NULL, NULL);
    }

    for(i = 0; i < nMaskCount;i++)
    {
        CPLDebug("addmask", "%d pixels were masked for value: %lf",
                 anMaskFound[i], adfMaskValues[i]);
    }
    CPLDebug("addmask", "%d pixels were masked total", nPixelsMasked);

    CPLFree(padfScanline);
    CPLFree(pabyScanline);

    GDALClose(hSrcDS);
    GDALClose(hMaskDS);
}