#include "grid.h" #include // min - return the min of two ints // int min(int x, int y){ return (xname = path; int scan = fscanf(inputf,"%*s%d%*s%d%*s%lf%*s%lf%*s%d%*s%d", &g->ncols,&g->nrows,&g->x, &g->y,&g->cellsize,&g->nodata); if(scan==0){ printf("flow: trouble reading input file!\n"); exit(1); } // Dynamically allocate array for data if((g->data = (short**) malloc((g->nrows)*sizeof(short*)))==NULL){ printf("flow: insufficient memory"); exit(1); } assert(g->data); for(i=0;inrows;i++){ if((g->data[i] = (short*) malloc((g->ncols)*sizeof(short)))==NULL){ printf("flow: insufficient memory"); exit(1); } assert(g->data[i]); } // Put data into the array and calculate max & min g->min = 9999999; g->max = 0; for(i=0;inrows;i++){ for(j=0;jncols;j++){ if(fscanf(inputf,"%d",&value)!=EOF){ if(value < g->min && value != g->nodata) g->min = value; if(value > g->max) g->max = value; g->data[i][j]=value; } else{ printf("flow: data file is corrupt"); exit(1); } } } // Set resolution as a function of gridsize resolution = min(g->ncols,g->nrows)/8; // Close file fclose(inputf); // Return grid return g; } // writeGrid - write grid structure to file path // void writeGrid(GRID *g,char *path){ FILE *outputf; int i,j; // Validate output file if ((outputf = fopen(path, "w"))== NULL){ printf("mult: can't write to %s\n",path); exit(1); } // Write grid info fprintf(outputf,"ncols\t\t%u\n",g->ncols); fprintf(outputf,"nrows\t\t%u\n",g->nrows); fprintf(outputf,"xllcorner\t%f\n",g->x); fprintf(outputf,"yllcorner\t%f\n",g->y); fprintf(outputf,"cellsize\t%u\n",g->cellsize); fprintf(outputf,"NODATA_value\t%d\n",g->nodata); // Write data for(i=0;inrows;i++){ for(j=0;jncols;j++){ fprintf(outputf, "%d ",g->data[i][j]); } fprintf(outputf, "\n"); } // Close file fclose(outputf); } // printGrid - Print the grid info // void printGrid(GRID *g){ printf("\nGrid Info:\n\n"); printf("Name: %s\n",g->name); printf("Number of Columns: %u\n",g->ncols); printf("Number of Rows: %u\n",g->nrows); printf("Lat Lon X Corner: %f\n",g->x); printf("Lat Lon Y Corner: %f\n",g->y); printf("Cell size: %u\n",g->cellsize); printf("No data value: %d\n",g->nodata); printf("Min value: %d\n",g->min); printf("Max value: %d\n",g->max); } // freeGrid - free memory from grid // void freeGrid(GRID *g){ free(g->name); // free(g->x); //free(g->y); //free(g->cellsize); //free(g->nodata); //free(g->max); //free(g->min); register int i; for(i=0;i < g->nrows; i++) free(g->data[i]); free(g->data); //free(g->ncols); //free(g->nrows); free(g); }