예제 #1
0
파일: Unix_time.c 프로젝트: erget/wgrib2
int f_unix_time(ARG0) {
    time_t rtx, vtx;
    struct tm timeinfo;
    int year, month, day, hour, minute, second;
    if (mode >= 0) {
        reftime(sec, &year, &month, &day, &hour, &minute, &second);
	timeinfo.tm_year = year - 1900;
	timeinfo.tm_mon = month- 1;
	timeinfo.tm_mday = day;
	timeinfo.tm_hour = hour;
	timeinfo.tm_min = minute;
	timeinfo.tm_sec = second;
	rtx=my_timegm(&timeinfo);

	if (verftime(sec, &(timeinfo.tm_year), &(timeinfo.tm_mon), &(timeinfo.tm_mday), &(timeinfo.tm_hour), 
		&(timeinfo.tm_min), &(timeinfo.tm_sec)) == 0) {
	    timeinfo.tm_year -= 1900;
	    timeinfo.tm_mon -= 1;
	    vtx=my_timegm(&timeinfo);
	}
	else vtx=-1;
	sprintf(inv_out,"unix_rt=%d:unix_vt=%d",(int) rtx, (int) vtx);
    }
    return 0;
}
예제 #2
0
/*
 * HEADER:400:VT:inv:0:verf time = reference_time + forecast_time (YYYYMMDDHHMMSS)
 */
int f_VT(ARG0) {

    int year, month, day, hour, minute, second;

    if (mode >= 0) {
        if (verftime(sec, &year, &month, &day, &hour, &minute, &second) == 0) {
            sprintf(inv_out,"vt=%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d", year,month,day,hour,minute,second);
        }
        else {
            sprintf(inv_out,"vt=?");
       }
    }
    return 0;
}
예제 #3
0
파일: Fcst_ave.c 프로젝트: mmase/wgrib2
static int add_to_ave_struct(struct ave_struct *save, unsigned char **sec, float *data, int ndata,int missing) {

    int i;

    if (save->n_sum != ndata) fatal_error("add_to_ave: dimension mismatch","");

   /* the data needs to be translated from we:sn to raw, need to
       do it now, translation[] may be different if called from finalized phase */

    if (translation == NULL) {
        for (i = 0; i < ndata; i++) {
            if (DEFINED_VAL(data[i]) && DEFINED_VAL(save->sum[i])) {
                save->sum[i] += data[i];
                save->n[i]++;
            }
        }
    }
    else {
        for (i = 0; i < ndata; i++) {
            if (DEFINED_VAL(data[i]) && DEFINED_VAL(save->sum[i])) {
                save->sum[translation[i]] += data[i];
                save->n[translation[i]]++;
            }
        }
    }

    save->n_fields += 1;
    if (save->n_fields == 1) {
	save->nx = nx;
	save->ny = ny;
	save->use_scale = use_scale;
	save->dec_scale = dec_scale;
	save->bin_scale = bin_scale;
	save->wanted_bits = wanted_bits;
	save->max_bits = max_bits;
	save->grib_type = grib_type;
    }
    save->n_missing += missing;

    // update current verf time
    if (verftime(sec, &save->year2, &save->month2, &save->day2, &save->hour2, &save->minute2, &save->second2) != 0) {
	fatal_error("add_to_ave_struct: could not find verification time","");
    }
    return 0;
}
예제 #4
0
/*
 * HEADER:400:vt:inv:0:verf time = reference_time + forecast_time, -v2 for alt format
 * 9/2006  w.ebisuzaki
 * 1/2007  check error code on verftime
 */
int f_vt(ARG0) {

    int year, month, day, hour, minute, second;

    if (mode >= 0) {
        if (verftime(sec, &year, &month, &day, &hour, &minute, &second) == 0) {
	    if (mode != 2) {
	        sprintf(inv_out,"%4.4d%2.2d%2.2d%2.2d", year,month,day,hour);
	    }
	    else {
               sprintf(inv_out,"vt=%2.2dZ%2.2d%c%c%c%4.4d", hour,day,months[month*3-3],
		months[month*3-2], months[month*3-1], year);
	    }
        }
        else {
           sprintf(inv_out,"vt=?");
        }
    }
    return 0;
}
예제 #5
0
int f_csv(ARG1) {

    char new_inv_out[STRING_SIZE];
    char name[100], desc[100], unit[100];
    FILE *out;

    unsigned int j;
    char vt[20],rt[20];
    int year, month, day, hour, minute, second;
	
    /* initialization phase */

    if (mode == -1) {
        WxText = decode = latlon = 1;
        if ((*local = (void *) ffopen(arg1,file_append ? "a" : "w")) == NULL)
		fatal_error("csv could not open file %s", arg1);  
	return 0;
    }

    /* cleanup phase */

    if (mode == -2) return 0;

    /* processing phase */

    if (lat == NULL || lon == NULL) {
	fprintf(stderr,"csv: latitude/longitude not defined, record skipped\n");
	return 0;
    }

    out = (FILE *) *local;

    /*Collect runtime and validtime into vt and rt*/

    reftime(sec, &year, &month, &day, &hour, &minute, &second);
    sprintf(rt, "%4.4d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d", year,month,day,hour,minute,second);

    vt[0] = 0;
    if (verftime(sec, &year, &month, &day, &hour, &minute, &second) == 0) {
        sprintf(vt,"%4.4d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d", year,month,day,hour,minute,second);
    }

    /*Get levels, parameter name, description and unit*/

    *new_inv_out = 0;
    f_lev(call_ARG0(new_inv_out,NULL));

    if (strcmp(new_inv_out, "reserved")==0) return 0;
//    getName(sec, mode, NULL, name, desc, unit);
    getExtName(sec, mode, NULL, name, desc, unit,".","_");
//	fprintf(stderr,"Start processing of %s at %s\n", name, new_inv_out);
//	fprintf(stderr,"Gridpoints in data: %d\n", ndata);
//	fprintf(stderr,"Description: %s, Unit %s\n", desc,unit);

     /* Lage if-setning rundt hele som sjekker om alt eller deler skal ut*/

    if (WxNum > 0) {
        for (j = 0; j < ndata; j++) {
            if (!UNDEFINED_VAL(data[j])) {
	        fprintf(out,"\"%s\",\"%s\",\"%s\",\"%s\",%g,%g,\"%s\"\n",rt,vt,name,
		    new_inv_out,lon[j] > 180.0 ?  lon[j]-360.0 : lon[j],lat[j],WxLabel(data[j]));
	    }
	}
    }
    else {
        for (j = 0; j < ndata; j++) {
            if (!UNDEFINED_VAL(data[j])) {
	        fprintf(out,"\"%s\",\"%s\",\"%s\",\"%s\",%g,%g,%lg\n",rt,vt,name,
		    new_inv_out,lon[j] > 180.0 ?  lon[j]-360.0 : lon[j],lat[j],data[j]);
	    }
	}
    }
    if (flush_mode) fflush(out);
    return 0;
}
예제 #6
0
int f_mysql(ARG5) {

    char sql[300];
    char server[100];
    char user[100];
    char password[100]; 
    char database[100];
    char table[100];

    char name[100], desc[100], unit[100], level_buf[100];
    int year, month, day, hour, minute, second;
	
    char vt[20],rt[20];
//    unsigned char *p;
	
    int j;
    double longitude,latitude;
	
    struct local_struct {
        MYSQL *conn;
        char filename[200];
    };
    struct local_struct *save;

    FILE *file;
    int tempfile;

    strcpy(server,arg1);
    strcpy(user,arg2);
    strcpy(password,arg3);
    strcpy(database,arg4);
    strcpy(table,arg5);


    /* initialization phase */

    if (mode == -1) {
        decode = latlon = 1;
            
	*local = save = (struct local_struct *) malloc(sizeof(struct local_struct));
	if (save == NULL) fatal_error("mysql memory allocation ","");

	save->conn = mysql_init(NULL);

	/* Connect to database */
	if (!mysql_real_connect(save->conn, server, user, password, database, 0, NULL, 0))
	    fatal_error("mysql error %s", mysql_error(save->conn));
    }

    /* cleanup phase */
    else if (mode == -2) {
    	save = *local;
    	mysql_close(save->conn);
	free(save);
    }

    /* processing phase */
    else if (mode >= 0) {
	save = *local;

        /*Collect runtime and validtime into vt and rt*/
        reftime(sec, &year, &month, &day, &hour, &minute, &second);
//	p = sec[1];
//	sprintf(rt, "%4.4d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d", (p[12]<<8)+p[13], p[14],p[15],p[16],p[17],p[18]);
        sprintf(rt, "%4.4d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d", year,month,day,hour,minute,second);

        if (verftime(sec, &year, &month, &day, &hour, &minute, &second) == 0) {
            sprintf(vt,"%4.4d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d", year,month,day,hour,minute,second);
        }

	/* Get levels, parameter name, description and unit*/
        f_lev(mode, sec, data, ndata, level_buf, local);
   
        if (strcmp(level_buf, "reserved") == 0) return 0;

        strcpy(save->filename, "/tmp/wgrib2_mysqlXXXXXX");
        if ((tempfile = mkstemp(save->filename)) == -1) fatal_error("mysql filename setup","");

        fprintf(stdout, "\nUsing temporary pathname %s\n", save->filename);
        if ((file = fdopen(tempfile, "w")) == NULL ) fatal_error("mysql: error opening temporary filename: %s", save->filename);

        getName(sec, mode, NULL, name, desc, unit);
	fprintf(stderr,"Start processing of %s at %s\n", name, level_buf);
	fprintf(stderr,"Gridpoints in data: %d\n", ndata);
	fprintf(stderr,"Description: %s, Unit %s\n", desc,unit);
	
	printf("Inserting into database, table=%s, runtime=%s, validtime=%s, parameter=%s, level=%s \n",table,rt,vt,name,level_buf);
	
	for (j = 0; j < ndata; j++) {
	    if (!UNDEFINED_VAL(data[j])) {
		longitude = lon[j];
		latitude = lat[j];
		if (longitude > 180) longitude -= 360;
		fprintf(file,"\"%s\",\"%s\",%g,%g,\"%s\",\"%s\",%lg\n",rt,vt,latitude,longitude,name,level_buf,data[j]);
	    }
	}
	fclose(file);
	sprintf(sql,"LOAD DATA LOCAL INFILE '%s' INTO TABLE %s FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\\n'",save->filename,table);
	printf("%s \n",sql);
	/* send SQL query */
	if (mysql_query(save->conn, sql)) fatal_error("mysql: %s", mysql_error(save->conn));

//      unlink = POSIX, remove = ANSI
//        unlink(save->filename);
        remove(save->filename);
    }
    return 0;
}
예제 #7
0
int f_mysql_speed(ARG7) {

    char temp_pathname[STRING_SIZE];
    char sql[1500];
    char server[100];
    char user[100];
    char password[100]; 
    char database[100];
    char table[100];
    MYSQL_RES *res;
    MYSQL_ROW row;

    char name[100], desc[100], unit[100], level_buf[100];
    int year, month, day, hour, minute, second;
	
    char vt[20],rt[20];
//    unsigned char *p;
   		
    int i,j;
    double longitude,latitude,value;

    char new_level[50];
    char new_name[50];
    char conv[50];
    char precision[10];
    char last;
    char param[50];
    int ctr;
    int level;
    unsigned int load_local_infile;

    struct local_struct {
        MYSQL *conn;
        FILE *temp_fileptr;
        unsigned int npts;
        char *rows[MAX_NXNY];
	char has_value[MAX_NXNY];
        char *params;
        unsigned int isset;
        unsigned int wlon;
        unsigned int remove_unlikely;
        char runtime[20], validtime[20];
	int last_GDS_change_no;
    };
    struct local_struct *save;

    strcpy(server,arg1);
    strcpy(user,arg2);
    strcpy(password,arg3);
    strcpy(database,arg4);
    strcpy(table,arg5);

    /* initialization phase */

    if (mode == -1) {
        decode = latlon = 1;
        
	*local = save = (struct local_struct *) malloc( sizeof(struct local_struct));
	if (save == NULL) fatal_error("mysql_speed memory allocation ","");

        for (i = 0; i < MAX_NXNY; i++) {
	    save->rows[i] = NULL;
	    save->has_value[i] = 0;
	}
	save->last_GDS_change_no = 0;
	save->conn = mysql_init(NULL);
	save->temp_fileptr= NULL;
	save->params = (char *)  malloc(1500*sizeof(char));
	sprintf(save->params,"%s","");
	save->isset = 0;
	save->runtime[0] = 0;
	save->validtime[0] = 0;
	load_local_infile = 1;		// 1 = LOAD LOCAL INFILE,  0 = do not LOAD LOCAL INFILE

	if (sscanf(arg6,"%d", &save->wlon) != 1) {
            fatal_error("Argument 6, use western longitudes, has to be 0 or 1, error parsing %s", arg6);
        }
        if (sscanf(arg7,"%d", &save->remove_unlikely) != 1) {
            fatal_error("Argument 7, remove unlikely values, has to be 0 or 1, error parsing %s", arg7);
        }
	
	/* Set options for database */
	mysql_options(save->conn,MYSQL_OPT_LOCAL_INFILE, (char *) &load_local_infile);

	/* Connect to database */
	if (!mysql_real_connect(save->conn, server, user, password, database, 0, NULL, 0)) {
	   fatal_error("f_mysql_speed: could not connect to %s", mysql_error(save->conn));
	} 
	return 0;
    }

    /* cleanup phase */

    if (mode == -2) {
    	save = (struct local_struct *) *local;
    	
    	strcpy(temp_pathname, "/tmp/wgrib2_mysqlXXXXXX");
    	if ( -1 == (load_local_infile = mkstemp(temp_pathname)) ) {
	    fatal_error("f_mysql_speed: error making temporary filename","");
	}
	if ( !(save->temp_fileptr = fdopen(load_local_infile, "w")) ) {
	    fatal_error("f_mysql_speed: error making temporary filename","");
	}

    	fprintf(stdout, "Columns to insert: rt,vt,lat,lon%s\n", save->params);
    	fprintf(save->temp_fileptr,"rt,vt,lat,lon%s\n",save->params);
    	for (j = 0; j < save->npts; j++) {
	    if (save->has_value[j] == 1) fprintf(save->temp_fileptr,"%s\n",save->rows[j]);
	}
	fflush(save->temp_fileptr);
	sprintf(sql,"LOAD DATA LOCAL INFILE '%s' INTO TABLE %s FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\\n' IGNORE 1 LINES (rt,vt,lat,lon%s)",temp_pathname,table,save->params);
	printf("Inserting into database, table=%s \n",table);
	printf("%s\n",sql);
	/* send SQL query */
	if (mysql_query(save->conn, sql)) {	
	    fatal_error("f_mysql_speed: connection error %s", mysql_error(save->conn));
	}
	fclose(save->temp_fileptr);
	remove(temp_pathname);
    	mysql_close(save->conn);
    	return 0;
    }

    /* processing phase */

    save = (struct local_struct *) *local;
  	
//    if (new_GDS && save->isset == 0 ) {
    if ((save->last_GDS_change_no != GDS_change_no) && save->isset == 0 ) {
  	//save->npts = GB2_Sec3_npts(sec);
  	save->npts = ndata;
  	if (ndata > MAX_NXNY) fatal_error_i("f_mysql_speed: MAX_NXNY exceeded %d", MAX_NXNY);

	for (i = 0; i < ndata; i++) {
	    if (save->rows[i] == NULL) {
		save->rows[i] = (char *)  malloc(1500*sizeof(char));
		if (save->rows[i] == NULL) fatal_error("f_mysql_speed: memory allocation problem","");
	    }
	    save->rows[i][0] = '\0';
	}

	save->isset = 1;
//    } else if (new_GDS) {
    } else if (save->last_GDS_change_no != GDS_change_no) {
	fatal_error("f_mysql_speed, grid definition has to be the same for all fields","");
   }
   save->last_GDS_change_no = GDS_change_no;
 
    /*Collect runtime and validtime into vt and rt*/

    reftime(sec, &year, &month, &day, &hour, &minute, &second);
//  p = sec[1];
//  sprintf(rt, "%4.4d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d", (p[12]<<8)+p[13], p[14],p[15],p[16],p[17],p[18]);
    sprintf(rt, "%4.4d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d", year,month,day,hour,minute,second);

    if (verftime(sec, &year, &month, &day, &hour, &minute, &second) == 0) {
        sprintf(vt,"%4.4d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d", year,month,day,hour,minute,second);
    }
    /*Check that runtimes are equal and validtimes are equal*/
    if (save->runtime[0] != 0 && strcmp(save->runtime,rt) != 0) {
	fprintf(stderr, "Error, runtime has to be equal for all fields\n");
    }
    strcpy(save->runtime,rt);

    if (save->validtime[0] != 0 && strcmp(save->validtime,vt) != 0) {
	fprintf(stderr, "Error, validtime has to be equal for all fields\n");
    }
    strcpy(save->validtime,vt);
	
    /*Get levels, parameter name, description and unit*/
    // f_lev(mode, sec, data, ndata, level_buf, local);
    f_lev(call_ARG0(level_buf, NULL));
    //if (ndata != save->npts && save->npts>0) fprintf(stderr,"ERROR: fields do not contain equally many gridpoints, %d , %d \n",save->npts,ndata);
 	   
    if (strcmp(level_buf, "reserved") == 0) return(0);
    getName(sec, mode, NULL, name, desc, unit);
    fprintf(stderr,"Start processing of %s at %s, runtime=%s, validtime=%s \n", name, level_buf,rt,vt);

    ctr = GB2_Center(sec);

    sprintf(sql,"select * from wgrib2_parameter_mapping where center_id=%d and wgrib_param_name='%s' and wgrib_param_levelname='%s'", ctr, name, level_buf);
    fprintf(stderr,"SQL: %s\n", sql);
    if (mysql_query(save->conn, sql)) {	
	fatal_error("f_mysql_speed: mysql error %s", mysql_error(save->conn));
    }
    sprintf(new_level,"%s", "None");
    sprintf(conv,"%s", "None");
    sprintf(precision, "%s", "2");
    printf("\nCenter_id: %d \n", ctr);
    res = mysql_use_result(save->conn);
    while ( (row = mysql_fetch_row(res) ) != NULL) {
	printf("our_name: %s \n", row[3]);
	sprintf(new_name,"%s", row[3]);
	sprintf(new_level,"%s", row[4]);
	sprintf(conv,"%s", row[5]);
	sprintf(precision, "%s", row[6]);
    }

    printf("val_precision: %s \n", precision);
    printf("conversion: %s \n", conv);
    printf("our_levelname: %s \n", new_level);
	
    if (strcmp(new_level,"None") != 0) {
	fprintf(stderr,"Sets level %s as level %s\n", level_buf, new_level);
	sprintf(param, "%s_%s", new_name, new_level);
    } else {
	if (strcmp(level_buf,"surface") == 0) {
	    sprintf(param, "%s_0", name);
	} else {		
	    sscanf(level_buf,"%d %s", &level, &last);
 	    sprintf(param, "%s_%d", name, level);
	}
    }
	
    mysql_free_result(res);

    strcat(save->params,",");
    strcat(save->params,param);
	
    fprintf(stderr,"Gridpoints in data: %d\n", ndata);
    fprintf(stderr, "Gridpoints for insert: %d\n", save->npts);

    fprintf(stderr, "Remove unlikely: %d\n", save->remove_unlikely);
    fprintf(stderr, "Western longitudes: %d\n", save->wlon);

    for (j = 0; j < ndata; j++) {
	longitude = lon[j];
	if (longitude > 180 && save->wlon==1) longitude-=360;
	latitude = lat[j];
	value = data[j];
	if (save->remove_unlikely == 1 && value>0 && value<10e-8) value=0; 			
	if (save->remove_unlikely == 1 && (strcmp(name,"APCP")==0 || strcmp(name,"ASNOW")==0 || strcmp(name,"ACPCP")==0 ) && value==1) value=0;
	value = convunit(value, conv);
	if (strlen(save->rows[j]) < 2) 	{
	    if (!UNDEFINED_VAL(data[j])) {
		save->has_value[j] = 1;
		sprintf(save->rows[j],"\"%s\",\"%s\",%g,%g,%lg",rt,vt,latitude,longitude,value);
	    } else {
		sprintf(save->rows[j],"\"%s\",\"%s\",%g,%g,NULL",rt,vt,latitude,longitude);
	    }
	} else {
	    if (!UNDEFINED_VAL(data[j])) {
		save->has_value[j] = 1;
		sprintf(sql,",%lg",value);
	    } else {
		sprintf(sql,",NULL");
	    }
	    strcat(save->rows[j],sql);
	}

    }
    return 0;
}
예제 #8
0
int f_AAIG(ARG0) {

    int grid_template;
    double cellsize;
    char *save_inv_out, level[STRING_SIZE], file[STRING_SIZE], name[STRING_SIZE];
    int year0, month0, day0, hour0, minute0, second0;
    int year, month, day, hour, minute, second, i, j;
    FILE *out;

    if (mode == -1) {
        decode = latlon = 1;
        return 0;
    }
    if (mode < 0) return 0;

    if (lat == NULL || lon == NULL) {
        fprintf(stderr,"f_AAIG does nothing, no lat-lon information\n");
        return 0;
    }
    if (output_order != wesn) {
        fprintf(stderr,"f_AAIG does nothing, not in we:sn order\n");
        return 0;
    }

    grid_template = code_table_3_1(sec);
    if (grid_template != 0) {
        fprintf(stderr,"f_AAIG does nothing, not lat-lon grid\n");
        return 0;
    }
    if (nx == -1 || ny == -1) {
        fprintf(stderr,"f_AAIG does nothing, found thinned lat-lon grid\n");
        return 0;
    }
    cellsize = -1.0;
    if (nx > 1) {
	cellsize = lon[1] - lon[0];
	if ( fabs(lat[nx]-lat[0] - cellsize) > 0.0001*cellsize) {
            fprintf(stderr,"f_AAIG does nothing, dlon != dlat\n");
            return 0;
	}
    }
    else {
	cellsize = lat[nx] - lat[0];
    }

    if (getName(sec, mode, NULL, name, NULL, NULL) != 0) {
        fprintf(stderr,"f_AAIG does nothing, no name\n");
        return 0;
    }

    save_inv_out = inv_out;
    inv_out = level;
    f_lev(CALL_ARG0);
    inv_out = save_inv_out;

    save_inv_out = level;
    while (*save_inv_out) {
        if (*save_inv_out == ' ') *save_inv_out = '_';
	save_inv_out++;
    }

    reftime(sec, &year0, &month0, &day0, &hour0, &minute0, &second0);

    if (verftime(sec, &year, &month, &day, &hour, &minute, &second) != 0) {
        fprintf(stderr,"f_AAIG no verf time\n");
	year = year0;
	month = month0;
	day = day0;
	hour = hour0;
    }
    if (year == year0 && month == month0 && day == day0 && hour == hour0) {
        sprintf(file,"%s.%s.%4.4d%2.2d%2.2d%2.2d.asc",name,level,year,month,day,hour);
    } 
    else {
        sprintf(file,"%s.%s.%4.4d%2.2d%2.2d%2.2d_%4.4d%2.2d%2.2d%2.2d.asc",
		name,level,year0,month0,day0,hour0,year,month,day,hour);
    }

    if ((out = fopen(file,"w")) == NULL) {
        fprintf(stderr,"f_AAIG could not open raster file %s\n",file);
        return 0;
    }

    fprintf(stderr, "raster file: %s\n", file);

    fprintf(out,"ncols %d\n", nx);
    fprintf(out,"nrows %d\n", ny);
    fprintf(out,"xllcenter %lf\n", lon[0] > 180.0 ? lon[0]-180.0 : lon[0]);
    fprintf(out,"yllcenter %lf\n", lat[0]);
    fprintf(out,"cellsize %lf\n", cellsize);
    fprintf(out,"NODATA_VALUE 9.999e20\n");
    for (j = ny-1; j >= 0; j--) {
	for (i = 0; i < nx; i++) {
	    fprintf(out,"%f\n", data[i+j*nx]);
	}
    }
    fclose(out);
    return 0;
}
예제 #9
0
파일: Fcst_ave.c 프로젝트: mmase/wgrib2
int f_fcst_ave(ARG2) {

    struct ave_struct *save;

    int i, pdt, new_type;
    int year, month, day, hour, minute, second;
    int tyear, tmonth, tday, thour, tminute, tsecond;
    int missing;
    char string[10];

    // initialization

    if (mode == -1) {
        save_translation = decode = 1;

	// allocate static structure

        *local = save = (struct ave_struct *) malloc( sizeof(struct ave_struct));
        if (save == NULL) fatal_error("memory allocation fcst_ave","");

	i = sscanf(arg1, "%d%2s", &save->dt,string);
	if (i != 2) fatal_error("fcst_ave: delta-time: (int)(2 characters) %s", arg1);
	save->dt_unit = -1;
	if (strcmp(string,"hr") == 0) save->dt_unit = 1;
	else if (strcmp(string,"dy") == 0) save->dt_unit = 2;
	else if (strcmp(string,"mo") == 0) save->dt_unit = 3;
	else if (strcmp(string,"yr") == 0) save->dt_unit = 4;
	if (save->dt_unit == -1) fatal_error("fcst_ave: unsupported time unit %s", string);

        if ((save->output = ffopen(arg2, file_append ? "ab" : "wb")) == NULL) {
	    fatal_error("fcst_ave: could not open file %s", arg2);
	}

	save->has_val = 0;
	save->n = NULL;
	save->sum = NULL;
        init_sec(save->first_sec);
        init_sec(save->next_sec);

	return 0;
    }

    save = (struct ave_struct *) *local;

    if (mode == -2) {			// cleanup
	if (save->has_val == 1) {
	    do_ave(save);
	}
	ffclose(save->output);
	free_ave_struct(save);
	return 0;
    }

    // if data
    if (mode >= 0) {
	// 1/2015 use_scale = 0;
	pdt = GB2_ProdDefTemplateNo(sec);

if (mode == 98) fprintf(stderr,"fcst_ave: pdt=%d\n",pdt);
	// only support pdt == 0, 1 and 8
	if (pdt != 0 && pdt != 1 && pdt != 8) return 0;

	// first time through .. save data and return


	if (save->has_val == 0) {		// new data: write and save
	    init_ave_struct(save,ndata);
	    add_to_ave_struct(save, sec, data, ndata, 0);

	    // copy sec
            copy_sec(sec, save->first_sec);
            copy_sec(sec, save->next_sec);

	    // get reference time and save it
            get_time(sec[1]+12,&save->ref_year, &save->ref_month, &save->ref_day, &save->ref_hour, &save->ref_minute, &save->ref_second);

	    if (start_ft(sec, &save->fcst_year, &save->fcst_month, &save->fcst_day, &save->fcst_hour, 
			&save->fcst_minute, &save->fcst_second) != 0) {
		fatal_error("fcst_ave: could not determine the start FT time","");
	    }

	    // get verf time and save it
	    if (verftime(sec, &save->year2, &save->month2, &save->day2, &save->hour2, &save->minute2, &save->second2) != 0) {
		fatal_error("fcst_ave: could not determine the verification time","");
	    }

	    save->has_val = 1;
	    return 0;
	}

	// check to see if new variable

        new_type = 0;

	// get the reference time of field
	get_time(sec[1]+12, &year, &month, &day, &hour, &minute, &second);

	// see if reference time has not changed
        if (year != save->ref_year) new_type = 1;
        else if (month != save->ref_month) new_type = 1;
        else if (day != save->ref_day) new_type = 1;
        else if (hour != save->ref_hour) new_type = 1;
        else if (minute != save->ref_minute) new_type = 1;
        else if (second != save->ref_second) new_type = 1;

        if (new_type == 0) {
	    if (same_sec0(sec,save->first_sec) == 0 ||
                same_sec1_not_time(sec,save->first_sec) == 0 ||
                same_sec3(sec,save->first_sec) == 0 ||
                same_sec4_not_time(sec,save->first_sec) == 0) 
	        new_type = 1;
if (mode == 98) fprintf(stderr, "fcst_ave: testsec %d %d %d %d\n", same_sec0(sec,save->first_sec),
                same_sec1_not_time(sec,save->first_sec),
                same_sec3(sec,save->first_sec),
                same_sec4_not_time(sec,save->first_sec));
        }
if (mode == 98) fprintf(stderr, "fcst_ave: new_type %d\n", new_type);

	// unlike f_ave, assume no missing .. it is a fcst not observations
	// check to see if verification date is expected value

	if (new_type == 0) {
	    tyear = save->fcst_year;
	    tmonth = save->fcst_month;
	    tday = save->fcst_day;
	    thour = save->fcst_hour;
	    tminute = save->fcst_minute;
	    tsecond = save->fcst_second;
            add_time(&tyear, &tmonth, &tday, &thour, &tminute, &tsecond, save->dt, save->dt_unit);
	    if (start_ft(sec, &year, &month, &day, &hour, &minute, &second) != 0) 
		fatal_error("fcst_ave: could not determine the start_ft time","");
            if (cmp_time(year,month,day,hour,minute,second,tyear,tmonth,tday,thour,tminute,tsecond)) {
		new_type = 1;
if (mode == 98) fprintf(stderr, "fcst_ave: unexpected verf time, new_type=1\n");
	    }
	    else {
	        save->fcst_year = year;
	        save->fcst_month = month;
	        save->fcst_day = day;
	        save->fcst_hour = hour;
	        save->fcst_minute = minute;
	        save->fcst_second = second;
	    }
	}

	// check to see if verification date is expected value

        missing = 0;
	if (new_type == 0) {
	    if (verftime(sec, &year, &month, &day, &hour, &minute, &second) != 0) 
		fatal_error("fcst_ave: could not determine the verification time","");
	    tyear = save->year2;
	    tmonth = save->month2;
	    tday = save->day2;
	    thour = save->hour2;
	    tminute = save->minute2;
	    tsecond = save->second2;
            add_time(&tyear, &tmonth, &tday, &thour, &tminute, &tsecond, save->dt, save->dt_unit);
            if (cmp_time(year,month,day,hour,minute,second,tyear,tmonth,tday,thour,tminute,tsecond) != 0) new_type = 1;
	    else {
	        save->year2 = year;
	        save->month2 = month;
	        save->day2 = day;
	        save->hour2 = hour;
	        save->minute2 = minute;
	        save->second2 = second;
	    }
	}

	// if data is the same as the previous, update the sum

if (mode == 98) fprintf(stderr, "fcst_ave ave: before update_sum  new_type %d\n", new_type);

	if (new_type == 0) {		// update sum
if (mode == 98) fprintf(stderr, "fcst_ave: update sum\n");
	    add_to_ave_struct(save, sec, data, ndata, missing);
	    return 0;
	}

	// new field, do grib output and save current data

	do_ave(save);
        init_ave_struct(save, ndata);
	add_to_ave_struct(save, sec, data, ndata, 0);
        copy_sec(sec, save->first_sec);
        copy_sec(sec, save->next_sec);

        // get reference time and save it
        get_time(sec[1]+12,&save->ref_year, &save->ref_month, &save->ref_day, &save->ref_hour, &save->ref_minute, &save->ref_second);
        if (start_ft(sec, &save->fcst_year, &save->fcst_month, &save->fcst_day, &save->fcst_hour,
                     &save->fcst_minute, &save->fcst_second) != 0) {
           fatal_error("fcst_ave: could not determine the start FT time","");
        }

        // get verf time and save it
        if (verftime(sec, &save->year2, &save->month2, &save->day2, &save->hour2, &save->minute2, &save->second2) != 0) {
            fatal_error("fcst_ave: could not determine the verification time","");
        }

        save->has_val = 1;
	return 0;
    }
    return 0;
}