Ejemplo n.º 1
0
/****from year,mon,day converted to days since STARTYEAR-01-01****/
int get_indays(int year,int mon,int day, int year_start, int leap_year){
        int inday=0;
        int i;
        if(year<year_start){
			fprintf(stderr,"time is earlier than netcdf file start year\n");
			return -1;
			}
		if (leap_year == 1) {
			for(i=year_start;i<year;i++){
                if(LEAPYR(i)) inday += 366;
                else inday += 365;
				}
			}
		else {
			for(i=year_start;i<year;i++){
                inday += 365;
			}
		}
        if(LEAPYR(year)) monthdays[1] = 29;
        else monthdays[1] = 28;
        for(i=1;i<mon;i++){
                inday += monthdays[i-1];
				}
        inday += (day-1);
        return inday;
}
Ejemplo n.º 2
0
/*
 * This algorithm is simple and cribbed from NetBSD.
 * It sets the values of "tm" according to "tt", an epoch value.
 * It's truncated below at the zero epoch.
 */
static void
kutil_epoch2time(int64_t tt, struct tm *tm)
{
        time_t 	 	 time = (time_t)tt;
        uint64_t	 dayclock, dayno, year;

	memset(tm, 0, sizeof(struct tm));
	
	/* Bound below. */
	if (tt < 0) 
		return;
        
	/* 
	 * This is easy: time of day is the number of seconds within a
	 * 24-hour period and the day of week (the epoch was on
	 * Thursday, seven days reliably per week).
	 */

        dayclock = time % (24 * 60 * 60);
        dayno = time / (24 * 60 * 60);

	/*
	 * Compute the time of day quite easily.
	 * Same for the weekday.
	 */

        tm->tm_sec = dayclock % 60;
        tm->tm_min = (dayclock % 3600) / 60;
        tm->tm_hour = dayclock / 3600;
        tm->tm_wday = (dayno + 4) % 7;

	/*
	 * More complicated: slough away the number of years.
	 * XXX this takes time proportionate to the year, but is easier
	 * to audit (and understand).
	 */

	year = 1970;
        while (dayno >= YEARDAY(year)) {
                dayno -= YEARDAY(year);
                year++;
        }

        tm->tm_year = year - 1900;
        tm->tm_yday = dayno;
        tm->tm_mon = 0;

	/*
	 * Similar computation as the year: increment ahead the day of
	 * the month depending on our month value.
	 */

        while (dayno >= monthdays[LEAPYR(year)][tm->tm_mon]) {
                dayno -= monthdays[LEAPYR(year)][tm->tm_mon];
                tm->tm_mon++;
        }

        tm->tm_mday = dayno + 1;
        tm->tm_isdst = 0;
}
Ejemplo n.º 3
0
void get_next_time_step(int *year, 
			int *month, 
			int *day, 
			int *hr, 
			int *jday, 
			int dt) {
  
  int    days[12]={31,28,31,30,31,30,31,31,30,31,30,31};
  int daymax;
  
  *hr += dt;
  if(*hr >= 24) {
    *hr=0;
    *day += 1;
    *jday += 1;
    
    if(LEAPYR(*year)) days[1] = 29;
    else days[1] = 28;
    
    if(*day > days[*month-1]) {
      *day = 1;
      *month += 1;
      if(*month == 13){
	*month = 1;
	*jday  = 1;
	*year += 1;
      }
    } 
  }
  
}
Ejemplo n.º 4
0
int num_days(int year, int index_year, int index_mo)
  /* num of days to index month */
  /* index_mo is numbered 1-12 */
{
  int ndays,LPP;
  int days_nlp[] = {0,31,59,90,120,151,181,212,243,273,304,334,365};
  int days_lp[] = {0,31,60,91,121,152,182,213,244,274,305,335,366};

  if(LEAPYR(year)) LPP=1;
  else LPP=0;

  if(year==index_year) {
    if(LEAPYR(year)) ndays=days_lp[index_mo];
    else ndays=days_nlp[index_mo];
  }
  else ndays = 365+LPP;

  return ndays;
}
Ejemplo n.º 5
0
short getdoy(short year,short month,short day)
{
    int dayatmonth[]=
        {0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
    int jdate;

    jdate = day + dayatmonth[month];
    if (!LEAPYR(year) && month >= MARCH)
        jdate--;
    return(jdate);
}
Ejemplo n.º 6
0
int getdaymonth(short year,short doy,short *month,short *day)
{
    int i;
    int daysinmonth[]=
        {0,31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    short totaldays=0;

    if (LEAPYR(year))
        daysinmonth[2]=29;
		
    for (i=1;(i<=12)&&(totaldays < doy);i++)
        totaldays += daysinmonth[i];

    if ((totaldays < doy)||(doy<=0))
        return -1;
		
    totaldays -= daysinmonth[i-1];
    *month=(short)i-1;
    *day=doy-totaldays;

    return(0);
}
Ejemplo n.º 7
0
int main(int argc, char *argv[]) 
{
 int syear, smo, sday, mo,year,lines,day;
 //float dly[MAXRECS][9], year_mo,dec_mo;
 float dly[MAXRECS][11], year_mo,dec_mo; // Array size for dly flux variables has been extended to 11; we don't care about the last 2 variables Shrad 20110518
 float monthly[(int)(MAXRECS/30)+12][9]; //9 is for output fields
 int DaysInMonth[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
 int cnt, n, offset, pstartmon, pendmon, cmo, i, y;
 FILE *fpinp, *fpout;

 if(argc!=6) {
   printf("\tThis routine reformats special VIC daily output into month summary files\n");
   printf("Usage: %s <dly infile> <mon outfile> <pstartmon> <pendmon> <lines>\n",argv[0]);
   printf("\tpstartmon, pendmon:  define period to print monthly summaries\n");
   printf("\tmonthly summaries have p, et, ro, bf, tavg, moist1-3, swe\n");
   exit(0);
 }
 if((fpinp=fopen(argv[1],"r"))==NULL) {
   printf("ERROR: Unable to open %s\n",argv[1]);
   exit(0);    }

 if((fpout=fopen(argv[2],"w"))==NULL) {
   printf("ERROR: Unable to open %s\n",argv[2]);
   exit(0);    }
 pstartmon = atoi(argv[3]);
 pendmon = atoi(argv[4]);
 lines = atoi(argv[5]);

 // initialize
 for(n=0;n<(int)(MAXRECS/30)+12;n++)   
   for(i=0;i<9;i++) 
     monthly[n][i] = 0;

 for(n=0;n<lines;n++)   {
   //get new data
   fscanf(fpinp,
     "%d %d %d %f %f %f %f %f %f %f %f %f %f %f",
     &year, &mo, &day, 
     &dly[n][0],&dly[n][1],&dly[n][2],&dly[n][3],
     &dly[n][4],&dly[n][5],&dly[n][6],&dly[n][7],&dly[n][8],&dly[n][9], &dly[n][10]);

   if(n==0) {
     offset = cnt = day-1;
     syear=year;
     smo=mo;
     cmo=mo;
   }
   if(LEAPYR(year))
     DaysInMonth[2]=29;
   else
     DaysInMonth[2]=28;
   cnt++;

   for(i=0;i<9;i++) 
     monthly[cmo][i] += dly[n][i];   /* add the new flow */

   if(mo == 12 && day == 31)  {       // if the end of the year ... 
     //     printf("done with year %d\n",year);
     for(i=4;i<9;i++) 
       monthly[cmo][i] = monthly[cmo][i]/(cnt-offset);   //avg monthly
     offset = 0;
     cnt = 0;
     cmo++;

   } else if (day == DaysInMonth[mo])  {  // if the end of the month 
     for(i=4;i<9;i++) 
       monthly[cmo][i] = monthly[cmo][i]/(cnt-offset);  // avg monthly
     cnt = 0;
     offset = 0;
     cmo++;
   }

 }   /* end of aggregating loop */

 if (cnt > 0)  {       /* last value maybe not averaged yet */
   for(i=4;i<9;i++) 
     monthly[cmo][i] = monthly[cmo][i]/(cnt-offset);    //  month averages
   cmo++;
 }

/* now write out monthly file */

 for(y=syear;y<year+1;y++) {
   fprintf(fpout, "%d\t",y);
   for(mo=1;mo<13;mo++) 
     if(mo >= pstartmon && mo <= pendmon) { //print output
       cmo = (y-syear)*12+mo;
       fprintf(fpout,"%7.3f ",monthly[cmo][0]); 
       for(i=1;i<5;i++) 
         fprintf(fpout,"%6.3f ",monthly[cmo][i]); 
       for(i=5;i<9;i++) 
         fprintf(fpout,"%6.1f ",monthly[cmo][i]); 
       fprintf(fpout, "\t");
     }
   fprintf(fpout, "\n");
 }

 fclose(fpout);
 fclose(fpinp);
}
Ejemplo n.º 8
0
dmy_struct *make_dmy(global_param_struct *global)
/**********************************************************************
	make_dmy	Dag Lohmann		January 1996

  This subroutine creates an array of structures that contain 
  information about the day, month and year of each time step.

  modifications:
  7-25-96  Added hour count, so that model can run on less than
           a daily time step.					KAC
  5-17-99  Modified routine to use LEAPYR function, make use of 
           simulation ending dates, and to skip over initial 
	  forcing data records so that the model can be run on
	  subsets of more complete data records.            KAC
  8-19-99  Modified routine to estimate the number of records
           that should be skipped before starting to write
	   model output, based on the number of years defined
	   with the SKIPYEAR global variable.               KAC
  3-14-00  Fixed problem with accounting for number of days in
           February.  If last simulation year was a leap year,
           number of days in February was not reset to 28 after
	   working out number of records and before working out
	   the number of forcing file records to skip.      KAC

**********************************************************************/
{
  extern param_set_struct param_set;

  dmy_struct *temp;
  int    hr, year, day, month, jday, ii, daymax;
  int    days[12]={31,28,31,30,31,30,31,31,30,31,30,31};
  int    endmonth, endday, endyear, skiprec, i, offset;
  int    tmpmonth, tmpday, tmpyear, tmphr, tmpjday, step;
  char   DONE;
  char   ErrStr[MAXSTRING];

  hr    = global->starthour;
  year  = global->startyear;
  day   = global->startday;
  month = global->startmonth;
  
  /** Check if user defined end date instead of number of records **/
  if(global->nrecs < 0) {
    if((global->endyear < 0) || (global->endmonth < 0) 
       || (global->endday < 0)) {
      nrerror("The model global file MUST define EITHER the number of records to simulate (NRECS), or the year (ENDYEAR), month (ENDMONTH), and day (ENDDAY) of the last full simulation day");
    }
    endday   = global->endday;
    endmonth = global->endmonth;
    endyear  = global->endyear;
    if(LEAPYR(endyear)) days[1] = 29;
    else days[1] = 28;
    if(endday <= days[global->endmonth-1]-1) endday++;
    else {
      endday = 1;
      endmonth++;
      if(endmonth > 12) {
	endmonth = 1;
	endyear++;
      }
    }

    DONE = FALSE;
    ii   = 0;

    tmpyear  = year;
    tmpmonth = month;
    tmpday   = day;
    tmphr    = hr;
    while(!DONE) {
      get_next_time_step(&tmpyear,&tmpmonth,&tmpday,&tmphr,
			 &tmpjday,global->dt);
      ii++;
      if(tmpyear == endyear)
	if(tmpmonth == endmonth)
	  if(tmpday == endday)
	    DONE = TRUE;
    }
    global->nrecs = ii;

  }
  else {
    offset = 0;
    tmphr  = hr;
    while (tmphr != 0) {
      tmphr += global->dt;
      offset++;
      if(tmphr >= 24) tmphr = 0;
    }
    if( ((global->dt * (global->nrecs - offset)) % 24) != 0 ) {
      sprintf(ErrStr,"Nrecs must be defined such that the model ends after completing a full day.  Currently Nrecs is set to %i, while %i and %i are allowable values.", global->nrecs, ((global->dt * (global->nrecs - offset)) / 24) * 24, ((global->dt * (global->nrecs - offset)) / 24) * 24 + 24);
      nrerror(ErrStr);
    }
  }


  temp = (dmy_struct*) calloc(global->nrecs, sizeof(dmy_struct));

  /** Create Date Structure for each Modeled Time Step **/
  jday = day;
  if( LEAPYR(year) ) days[1] = 29;
  else days[1] = 28;
  for ( ii = 0; ii < month-1; ii++ ) 
    jday += days[ii];
  
  DONE = FALSE;
  ii   = 0;
  
  while(!DONE) {
    temp[ii].hour = hr;
    temp[ii].day   = day;
    temp[ii].month = month;
    temp[ii].year  = year;
    temp[ii].day_in_year = jday;

    get_next_time_step(&year,&month,&day,&hr,&jday,global->dt);

    ii++;
    if(ii == global->nrecs) DONE=TRUE;

  }

  /** Determine number of forcing records to skip before model start time **/
  for(i=0;i<2;i++) {
    if(param_set.FORCE_DT[i] != MISSING) {
      if(global->forceyear[i] > 0) {
	tmpyear  = global->forceyear[i];
	tmpmonth = global->forcemonth[i];
	tmpday   = global->forceday[i];
	tmphr    = global->forcehour[i];
	tmpjday  = tmpday;
	if ( LEAPYR(tmpyear) ) days[1] = 29;
	else days[1] = 28;
	for ( ii = 0; ii < tmpmonth-1; ii++) 
	  tmpjday += days[ii];
	
	step     = (int)(1./((float)global->dt/24.));
	while(tmpyear < temp[0].year || 
	      (tmpyear == temp[0].year && tmpjday < temp[0].day_in_year)) {
	  
	  get_next_time_step(&tmpyear,&tmpmonth,&tmpday,&tmphr,
			     &tmpjday,global->dt);
	  
	  global->forceskip[i] ++;

	}
      }
    }
  }

  /** Determine the number of records to skip before starting output files **/
  skiprec = 0;
  for(i=0;i<global->skipyear;i++) {
    if(LEAPYR(temp[skiprec].year)) skiprec += 366 * 24 / global->dt;
    else skiprec += 365 * 24 / global->dt;
  }
  global->skipyear = skiprec;

  return temp;
}
Ejemplo n.º 9
0
void main(int argc, char *argv[])
{

FILE *fu, *fv, *fposlat, *fposlon, *fm, *fpout,*fpflist,*fpmean;
char ufile[100], vfile[100],str1[200],out_dir[200],mask[200];
char old_out_dir[200], s1[200], maskfile[200],in_dir[200],old_in_dir[200];
char uftemp[100], vftemp[100];
int MASKROWS, MASKCOLS;
float MASKRES, void_nr,high,low, xll, yll, maskulong, maskulat;
int i,j,k,l,t;
long int count;
int lon, lat, min_lat, max_lat, min_lon, max_lon, skipdays;
float **uwnd, **vwnd,sum_wind, **maskx;
int ROWS,COLUMNS,SIZEM;
int twind, ii,cell_no;
int year, start_year, start_mo, end_year, end_mo, days_per_year,active_cells;
double ***wspeed,**cell_wind;
float *latitude, *longitude, uinterp, vinterp, dum;
float reflat, reflon,avg_wind;
double vertdist, reldist, hordist;
float newuleft, newvleft, newuright, newvright;
short int vic_wind, cellavg;

  if(argc!=12)
    {
      printf("\nUsage: %s <start_year> <start_mo> <end_year> <end_mo> <min_lat> <max_lat> <min_lon> <max_lon> <mask> <in_dir> <out_dir>\n",argv[0]);
      printf("See code for more details\n");
      exit(8);
    }

  printf("Assigning command line inputs to variables...\n\n");

   start_year = atoi(argv[1]); printf("start_year %d \n",start_year);
   start_mo = atoi(argv[2]);   printf("start_mo %d \n",start_mo);
   end_year = atoi(argv[3]);   printf("end_year %d \n",end_year);
   end_mo = atoi(argv[4]);     printf("end_mo %d \n",end_mo);
   min_lat = atoi(argv[5]);    printf("gauss_t62 coords:\nmin_lat %d \n",min_lat);
   max_lat = atoi(argv[6]);    printf("max_lat %d \n",max_lat);
   min_lon = atoi(argv[7]);    printf("min_lon %d \n",min_lon);
   max_lon = atoi(argv[8]);    printf("max_lon %d \n",max_lon);
   strcpy(mask,argv[9]);       printf("mask %s \n",mask);
   strcpy(in_dir,argv[10]); strcpy(old_in_dir,in_dir);
   strcpy(out_dir,argv[11]); strcpy(old_out_dir,out_dir); 
                printf("out_dir %s \n\n",old_out_dir);

  printf("Creating output file list %s\n",flist);
  strcpy(maskfile,mask);
  make_flist(mask);     /* Generates a filelist that will be used later  */
  printf("Making Output Files\n");
  make_outfiles(old_out_dir);/* Open all files in write mode and closes them again */
  ROWS=max_lat - min_lat +1; /* rows in reanalysis grid */
  COLUMNS=max_lon - min_lon + 1; /* columns in reanalysis grid */
  if((fpflist = fopen(flist,"r"))==NULL) {  
    printf("Cannot open file %s \n",flist);exit(0);} 

  /*------------------------------------------------------*/
  /* FIRST READ IN HEADER FOR MASK FILE (ARC/INFO STYLE)  */
  /*------------------------------------------------------*/
  if((fm = fopen(maskfile,"r")) == NULL) {
    printf("Cannot open/read mask\n"); exit(0); }
    fscanf(fm,"%*s %s",str1); MASKCOLS = atoi(str1);
    fscanf(fm,"%*s %s",str1); MASKROWS = atoi(str1);
    fscanf(fm,"%*s %s",str1); xll = atof(str1);
    fscanf(fm,"%*s %s",str1); yll = atof(str1);
    fscanf(fm,"%*s %s",str1); MASKRES = atof(str1);
    fscanf(fm,"%*s %s",str1); void_nr = atof(str1);
    high=void_nr+0.001;
    low=void_nr-0.001;

    /* convert to deg. east and make cell centered */
    maskulong = (xll+360.0)+MASKRES/2.0;
    /* upper left corner latitude cell center */
    maskulat = yll+(MASKROWS*MASKRES)-(MASKRES/2.0);
    /* initialize days_per_year for memory allocation */
    days_per_year=366;
    active_cells=0;
    SIZEM = MASKCOLS*MASKROWS;

    /*----------------------------*/
    /* ALLOCATE MEMORY TO ARRAYS  */
    /*----------------------------*/

  if(!(longitude = (float*) calloc(COLUMNS+1,sizeof(float)))) {
    printf("Cannot allocate memory to first record: BASIN\n");
    exit(8); }
  
  if(!(latitude = (float*) calloc(ROWS,sizeof(float)))) {
    printf("Cannot allocate memory to first record: BASIN\n");
    exit(8); }
  
  if(!(uwnd = (float**) calloc(ROWS,sizeof(float*)))) {
    printf("Cannot allocate memory to first record: BASIN\n");
    exit(8); }
  for(i=0; i<ROWS;i++) {
  if(!(uwnd[i]= (float*) calloc(COLUMNS,sizeof(float)))) {
    printf("Cannot allocate memory to first record: BASIN\n");
    exit(8); } }

  if(!(maskx = (float**) calloc(MASKROWS,sizeof(float*)))) {
    printf("Cannot allocate memory to first record: BASIN\n");
    exit(8); }
  for(i=0; i<MASKROWS;i++) {
  if(!(maskx[i] = (float*) calloc(MASKCOLS,sizeof(float)))) {
    printf("Cannot allocate memory to first record: BASIN\n");
    exit(8); } }

 if(!(vwnd = (float**) calloc(ROWS,sizeof(float*)))) {
    printf("Cannot allocate memory to first record: BASIN\n");
    exit(8); }
  for(i=0; i<ROWS;i++) {
  if(!(vwnd[i] = (float*) calloc(COLUMNS,sizeof(float)))) {
    printf("Cannot allocate memory to first record: BASIN\n");
    exit(8); } }
  
  if(!(wspeed = (double***) calloc(days_per_year,sizeof(double**)))) {
    printf("Cannot allocate memory to first record: WSPEED\n");
    exit(8); }
  for(j=0; j<days_per_year;j++) {
    if(!(wspeed[j] = (double**) calloc(MASKROWS,sizeof(double*)))) {
      printf("Cannot allocate memory to first record: BASIN\n");
      exit(8); }
    for(i=0; i<MASKROWS;i++) {
      if(!(wspeed[j][i] = (double*) calloc(MASKCOLS,sizeof(double)))) {
	printf("Cannot allocate memory to first record: BASIN\n");
	exit(8); } } }

  if(!(cell_wind = (double**) calloc(SIZEM,sizeof(double*)))) {
    printf("Cannot allocate memory to first record: CELL_WIND\n");
    exit(8); }
  for(j=0; j<SIZEM;j++) {
    if(!(cell_wind[j] = (double*) calloc(days_per_year,sizeof(double)))) {
      printf("Cannot allocate memory to first record: CELL_WIND\n");
      exit(8); } } 


  /*--------------------------------------------*/
  /* READ IN REMAINDER OF MASK FILE             */
  /*--------------------------------------------*/
    printf("reading mask file\n\n");
  for(i=0; i<MASKROWS;i++) {
    for(j=0; j<MASKCOLS; j++) {
      fscanf(fm,"%f",&maskx[i][j]);
      if(maskx[i][j]>high || maskx[i][j]<low ) active_cells++;
    }
  }
  fclose(fm);
  printf("%d active cells\n",active_cells);

  /*------------------------------------------------------*/
  /* BEGIN LOOP FOR EACH YEAR                             */
  /*------------------------------------------------------*/

  for(year=start_year;year<=end_year;year++) {
    printf("Processing year %d\n",year);
    count = 0; sum_wind = 0.0;

  /* NAMES OF REANALYSIS U-WIND AND V-WIND DATA FILES FOR CURRENT YEAR */

  sprintf(uftemp,"uwnd.%d.asc",year);
  sprintf(vftemp,"vwnd.%d.asc",year);
  strcat(in_dir,uftemp);
  strcpy(ufile,in_dir);
  strcpy(in_dir,old_in_dir);
  strcat(in_dir,vftemp);
  strcpy(vfile,in_dir);
  strcpy(in_dir,old_in_dir);
  printf("files %s and %s\n",ufile, vfile);
  days_per_year= num_days(year,end_year,end_mo);
  printf("days_per_year= %d\n",days_per_year);
  /* if (LEAPYR(year)) */
  /*  days_per_year=366; */
  /* else */
  /*  days_per_year=365; */

  /*--------------------------------------------*/
  /* OPEN REANALYSIS WIND FILES                 */
  /*--------------------------------------------*/

  if((fu = fopen(ufile,"r")) == NULL) {
    printf("Cannot open/read %s\n",ufile);
    exit(8); }

  if((fv = fopen(vfile,"r")) == NULL) {
    printf("Cannot open/read %s\n",vfile);
    exit(8); }

  if((fposlat = fopen(ncar_lat, "r")) == NULL) {
    printf("Cannot open/read %s\n",ncar_lat);
    exit(8); }
  if((fposlon = fopen(ncar_lon, "r")) == NULL) {
    printf("Cannot open/read %s\n",ncar_lon);
    exit(8); }
 
/*  printf("Files successfully opened...\n\n"); */

  /*----------------------------------------------------*/
  /* READ LAT/LON FILES -- POSITION IN REANALYSIS GRID  */
  /*----------------------------------------------------*/
  /* move to starting position for min lat and long (using reanalysis numbers 
             for coordinates in each file */
  for(i=1; i<min_lat;i++) fscanf(fposlat,"%f",&dum);
  for(i=1; i<min_lon;i++) fscanf(fposlon,"%f",&dum);

  for(i=0; i<ROWS;i++) 
    fscanf(fposlat,"%f",&latitude[i]);

  for(i=0; i<COLUMNS+1;i++) 
    fscanf(fposlon,"%f",&longitude[i]);
  
  fclose(fposlat);
  fclose(fposlon);


  /*-----------------------------------------------------------------*/
  /* READ IN REANALYSIS WIND GRID -- RUN FOR ALL DAYS IN ONE YEAR    */
  /*-----------------------------------------------------------------*/
  for(t=0; t<days_per_year;t++) {
      for(i=0; i<ROWS;i++) {
	for(j=0; j<COLUMNS;j++) {
	  fscanf(fu, "%d", &twind);
	  uwnd[i][j]= (float)twind*SCALE + OFFSET;
	  fscanf(fv, "%d", &twind);
	  vwnd[i][j]= (float)twind*SCALE + OFFSET;
	}
      }

      for(j=0; j<MASKROWS; j++) {
	reflat = maskulat - (float)j*MASKRES;
	for(i=0; i<MASKCOLS; i++) {
	  reflon = maskulong + (float)i*MASKRES;
	  lat=lon=9999;

      if(maskx[j][i]>high || maskx[j][i]<low) { /* if active cell,interpolate */

	  for(k=0; k<ROWS;k++) {
	    if(reflat<=latitude[k] && reflat>latitude[k+1]){
	      lat = k;
	    }
	  }
	  for(l=0; l<COLUMNS+1; l++) {
	    if(reflon>=longitude[l] && reflon<longitude[l+1]){
	      lon=l;
	    }
	  }
	  if(lat==9999 || lon==9999) {
	    printf("reflat/lon not in range\n");
	    exit(0);
	  }
	  
	  /*-----------------------------------*/
	  /* VERTICAL INTERPOLATION            */
	  /*-----------------------------------*/
	  vertdist=get_dist(latitude[lat], longitude[lon], latitude[lat+1],
			    longitude[lon]);
	  reldist=get_dist(latitude[lat],longitude[lon], reflat, longitude[lon]);

	  newuleft=((uwnd[lat][lon]*(1-(reldist/vertdist)))+(reldist/vertdist)
	    *uwnd[lat+1][lon]);
	  newvleft=((vwnd[lat][lon]*(1-(reldist/vertdist)))+(reldist/vertdist)
	    *vwnd[lat+1][lon]);

	  if(lon==COLUMNS) {
	     newuright=((uwnd[lat][0]*(1-(reldist/vertdist)))+
		     (reldist/vertdist)*uwnd[lat+1][0]);
	     newvright=((vwnd[lat][0]*(1-(reldist/vertdist)))+
		     (reldist/vertdist)*vwnd[lat+1][0]);
	  }
	  else {
	    newuright=((uwnd[lat][lon+1]*(1-(reldist/vertdist)))+
		       (reldist/vertdist)*uwnd[lat+1][lon+1]);
	    newvright=((vwnd[lat][lon+1]*(1-(reldist/vertdist)))+
		       (reldist/vertdist)*vwnd[lat+1][lon+1]);
	  }
	  /*-----------------------------------*/
	  /* HORIZONTAL INTERPOLATION          */
	  /*-----------------------------------*/

	  hordist=get_dist(reflat,longitude[lon],reflat,longitude[lon+1]);
	  reldist=get_dist(reflat,longitude[lon],reflat,reflon);

	  uinterp=newuleft*(1-(reldist/hordist)) + newuright*(reldist/hordist);
	  vinterp=newvleft*(1-(reldist/hordist)) + newvright*(reldist/hordist);
	  wspeed[t][j][i] = sqrt((double) (uinterp*uinterp + vinterp*vinterp));
      } /* end of if statement for interpolation only for active cell */
	} /* end loop for MASKCOLS */ 
      } /* end loop for MASKROWS */
  }    /* end loop for days per year */

  /*--------------------------------------------------*/
  /* OUTPUT TIMESERIES FOR EACH CELL IN MASK          */
  /*--------------------------------------------------*/
  printf("Writing output\n");
  skipdays=num_days( year, start_year, start_mo-1);
  if(year!=start_year) skipdays=0;
  printf("skipdays = %d\n",skipdays);
  cell_no=0;
  for(j=0; j<MASKROWS; j++) {
    for(i=0; i<MASKCOLS; i++) {
      if( maskx[j][i]>high || maskx[j][i]<low ) { /* if active cell, write */
	    fscanf(fpflist,"%s",s1);    
	    strcpy(out_dir,old_out_dir);
	    strcat(out_dir,s1);          /* create file name for grid cell */
	    if((fpout = fopen(out_dir,"ab"))==NULL) {
              printf("error opening output file %s\n",out_dir);exit(0);}
	    /* convert wind to short int values -- multiplying by 100 */
	    for(t=skipdays;t<days_per_year;t++) {
	      sum_wind += wspeed[t][j][i]; count+=1; /* calc sum for gross average */
	      vic_wind= (short int) (wspeed[t][j][i]*100);
	      fwrite(&vic_wind,sizeof(short int),1,fpout);
	    }
	    ii=skipdays;
	    for(t=skipdays;t<days_per_year;t++) {  /*avg daily wind for each cell */
      	      if( !(LEAPYR(year)) || t !=59){ /* skip feb 29 data for daily avg */
		cell_wind[cell_no][ii]+=wspeed[t][j][i]; /* for each active cell, sum for each day */
		ii++;}
	    }
	    cell_no++;
      fclose(fpout);
      }
    }
  }
  avg_wind = sum_wind/(float)count; /* gross average wind speed for year */
  printf("Average Daily Wind Speed Year %d = %.2f m/s\n\n",year,avg_wind);
  rewind(fpflist);

 fclose(fu); /* close reanalysis data files for the current year */
 fclose(fv);
  }  /* end year loop */
 /* write file with 365 daily averages for each cell */
  if((fpmean = fopen("cell_avg.out","wb")) == NULL) {
    printf("Cannot open cell_avg.out\n"); exit(0); }
  for(i=0;i<active_cells;i++){
    for(j=0;j<365;j++){
              cellavg = (short int) (cell_wind[i][j]/(end_year-start_year+1)*100);
	      fwrite(&cellavg,sizeof(short int),1,fpmean);
    }
  }
  fclose(fpmean);

} /* end main program */