Ejemplo n.º 1
1
int
main (int argc, char **argv)
{

    int             c,
                    errflg = 0;

    char           *in,
                   *out;
    int             orbin,
                    orbout;
    double          maxpkts = VERY_LARGE_NUMBER ;
    int             quit;
    char           *pktmatch = strdup(".*/pf/evtinfo"),
                   *reject = 0;
    int             nmatch;
    int             specified_after = 0;
    double          after = 0.0,
                    until = VERY_LARGE_NUMBER ;
    double          start_time,
                    end_time,
                    delta_t ;
    double          totpkts = 0,
                    totbytes = 0;
    Flags           flags;
    static int      last_pktid = -1;
    static double   last_pkttime = 0.0;
    char           *statefile = 0;
    double          last_burial = 0.0;
    double          decent_interval = 300.0;
    int             mode = PKT_NOSAMPLES;
    int             rcode;
    char            srcname[ORBSRCNAME_SIZE];
    double          pkttime = 0.0 ;
    int             pktid;
    int             nbytes;
    char           *packet = 0;
    int             packetsz = 0;
    Packet         *unstuffed = 0;
	Pf				*pf;
	Tbl				*tbl;
	Arr				*arr;
	char			*arrkey;
	char			*pffilename;

	Tbl				*channels;
	char			*net;
	char			*sta;
	char			*chan;
	char			netstachan[ORBSRCNAME_SIZE];
	Srcname			parts;
	double			maxtime,mintime,starttime,triggertime,duration,min_g,max_g,snr;
	char			*datalogger;
	int				evtfilesize,channelno,maxcts,mincts;
	char			*errors,*evtfilename,*ft,*filter,*srcid;
	char			*line;
	int				i;
	Pf				*pfnew;
	Dbptr			db;
	int 			put_tests=0;
	char 			*chanmatch=0;
	Hook			*hook=0;
	char			*tdummy=0;
	char 			*match=malloc(100);

	


    memset (&flags, 0, sizeof (flags));
    elog_init (argc, argv);
    elog_notify (0, "%s $Revision: 1.5 $ $Date: 2005/05/10 07:34:43 $\n",
		 Program_Name);

    while ((c = getopt (argc, argv, "m:n:r:S:c:tvV")) != -1) {
	switch (c) {
	  case 'm':
	    match = optarg;
		sprintf(pktmatch,"%s/pf/evtinfo",match);
	    break;
	  case 'c':
	 	chanmatch = optarg;
		break;
	  case 't':
	  	put_tests = 1;
		break;
	  case 'n':
	    maxpkts = atoi (optarg);
	    break;

	  case 'r':
	    reject = optarg;
	    break;

	  case 'S':
	    statefile = optarg;
	    break;

	  case 'v':
	    flags.verbose++;
	    break;

	  case 'V':
		flags.verbose++;
		flags.verbose++;
	    break;

	  case '?':
	    errflg++;
	}
    }

    if (errflg || argc - optind < 2 || argc - optind > 4)
	usage ();

    in = argv[optind++];
    out = argv[optind++];

    if (argc > optind) {
	after = str2epoch (argv[optind++]);
	specified_after = 1;
	if (argc > optind) {
	    until = str2epoch (argv[optind++]);
	    if (until < after) {
		until += after ;
	    }
	}
    }
    if ((orbin = orbopen (in, "r&")) < 0)
	die (0, "Can't open input '%s'\n", in);

    if (statefile != 0) {
		char           *s;
		if (exhume (statefile, &quit, RT_MAX_DIE_SECS, 0) != 0) {
	    elog_notify (0, "read old state file\n");
		}
		if (orbresurrect (orbin, &last_pktid, &last_pkttime) == 0) {
	    	elog_notify (0, "resurrection successful: repositioned to pktid #%d @ %s\n",
			 last_pktid, s = strtime (last_pkttime));
	    	free (s);
		} else {
	    	complain (0, "resurrection unsuccessful\n");
		}
    }
    if ((orbout = orbopen (out, "w&")) < 0) {
	die (0, "Can't open output '%s'\n", out);
    }
    if (pktmatch) {
	nmatch = orbselect (orbin, pktmatch);
    }
    if (nmatch < 0) {
	die (1, "select '%s' returned %d\n", pktmatch, nmatch);
    }
    if (reject) {
	nmatch = orbreject (orbin, reject);
    }
    if (nmatch < 0) {
		elog_die (1, "reject '%s' returned %d\n", reject, nmatch);
    } else {
		if (flags.verbose) {
			elog_notify (1,"%d sources selected\n", nmatch);
		}	
    }

    if (specified_after) {
	pktid = orbafter (orbin, after);
	if (pktid < 0) {
	    char           *s;
	    elog_complain (1, "seek to %s failed\n", s = strtime (after));
	    free (s);
	    pktid = forbtell (orbin);
	    elog_complain (1,"pktid is still #%d\n", pktid);
	} else {
	    if (flags.verbose) elog_notify (1,"new starting pktid is #%d\n", pktid);
	}
    }
    start_time = now ();

	db = dbtmp("rt1.0");

    while (!quit && pkttime < until && totpkts < maxpkts) {
	rcode = orbreap (orbin,
		    &pktid, srcname, &pkttime, &packet, &nbytes, &packetsz);

	switch (rcode) {
	  case 0:
	    totpkts++;
	    totbytes += nbytes;

	    if (flags.verbose>2) {
		showPkt (pktid, srcname, pkttime, packet, nbytes, stdout, mode);
	    }
	    if (statefile != 0
		    && last_pkttime - last_burial > decent_interval) {
		bury ();
		last_burial = pkttime;
	    }
	    if ((unstuffPkt (srcname, pkttime, packet, nbytes, &unstuffed))==Pkt_pf) {
		  	pf = 			unstuffed->pf;
			tbl=			pfkeys(pf);
			arrkey=			gettbl(tbl,0);
			pfget(pf,arrkey,&pfnew);
			datalogger=		pfget_string(pfnew,"datalogger");
			duration=		pfget_double(pfnew,"duration");
			errors=			pfget_string(pfnew,"errors");
			evtfilename=	pfget_string(pfnew,"evtfilename");
			evtfilesize=	pfget_int(pfnew,"evtfilesize");
			ft=				pfget_string(pfnew,"ft");
			starttime=		pfget_double(pfnew,"time");
			triggertime=	pfget_double(pfnew,"triggertime");

			channels=pfget_tbl(pfnew,"channels");
			if (strcasecmp(ft,"no")==0 || put_tests == 1) {
				for (i=0; i<maxtbl(channels);i++) {
					line=gettbl(channels,i);
					sscanf(line,"%s %d %lf %d %lf %lf %d %lf",
						netstachan,&channelno,&maxtime,&maxcts,&max_g,&mintime,&mincts,&min_g);
					split_srcname(netstachan,&parts);	
					strcpy(parts.src_suffix,"GENC");
					join_srcname(&parts,netstachan);
					if (flags.verbose>1) printf("%s,%s\n", netstachan,tdummy=strtime(triggertime));	
					if (chanmatch == 0 || 
							strmatches(parts.src_chan,chanmatch,&hook)) {
						if (flags.verbose) elog_notify(1,"putting detev for %s,%s\n", netstachan,tdummy=strtime(triggertime));	
						
						db=dblookup(db,0,"detev",0,"dbSCRATCH");
						dbputv(db,0,"sta",parts.src_sta,"chan",parts.src_chan,
							"filter",K2_FILTER,
							"time",	triggertime,
							"tron",  starttime - triggertime,
							"troff", starttime - triggertime + duration,
							"iphase","K2",
							"snr",(max_g * 1000.0  - min_g * 1000.0)/2.0,
							0);
						db2orbpkt(db,orbout);
					} else {
						if (flags.verbose>1) elog_notify(1,"ignoring %s,%s\n", netstachan,tdummy=strtime(triggertime));	

					}
				}
			}
			
	    }

	    last_pktid = pktid;
	    last_pkttime = pkttime;
	}

    }

    if (statefile != 0)
	bury ();

    end_time = now ();
    delta_t = end_time - start_time;
	if (flags.verbose>1) {
		if (totpkts > 0) {
		elog_notify (1,"\n%.0f %.2f byte packets (%.1f kbytes) in %.3f seconds\n\t%10.3f kbytes/s\n\t%10.3f kbaud\n\t%10.3f pkts/s\n",
			totpkts, totbytes / totpkts, totbytes / 1024,
			delta_t,
			totbytes / delta_t / 1024,
			totbytes / delta_t / 1024 * 8,
			totpkts / delta_t);
		} else {

		elog_notify (1,"\nno packets read\n");
		}
	}

    if (orbclose (orbin)) {
	elog_complain (1, "error closing read orb\n");
    }
    if (orbclose (orbout)) {
	elog_complain (1, "error closing write orb\n");
    }
    return 0;
}
Ejemplo n.º 2
0
static void adjtimex_status(struct timex *tx, int status)
{
	const char *const msgs[6] = {
		"clock synchronized",
		"insert leap second",
		"delete leap second",
		"leap second in progress",
		"leap second has occurred",
		"clock not synchronized",
	};
	int r;
	struct timespec now;

	tx->modes = ADJ_STATUS;
	tx->status = status;
	r = adjtimex(tx);
	now.tv_sec = tx->time.tv_sec;
	now.tv_nsec = tx->time.tv_usec * 1000;

	if ((tx->status & status) != status)
		tst_brkm(TBROK, cleanup, "adjtimex status %d not set", status);
	else if (r < 0)
		tst_brkm(TBROK | TERRNO, cleanup, "adjtimex");
	else if (r < 6)
		tst_resm(TINFO, "%s adjtimex: %s", strtime(&now), msgs[r]);
	else
		tst_resm(TINFO, "%s adjtimex: clock state %d",
			 strtime(&now), r);
}
Ejemplo n.º 3
0
static void run_leapsec(void)
{
	const struct timespec sleeptime = { 0, NSEC_PER_SEC / 2 };
	struct timespec now, leap, start;
	struct timex tx;

	clock_gettime(CLOCK_REALTIME, &now);
	start = now;
	tst_resm(TINFO, "test start at %s", strtime(&now));

	test_hrtimer_early_expiration();

	/* calculate the next leap second */
	now.tv_sec += 86400 - now.tv_sec % 86400;
	now.tv_nsec = 0;
	leap = now;
	tst_resm(TINFO, "scheduling leap second %s", strtime(&leap));

	/* start before the leap second */
	now.tv_sec -= SECONDS_BEFORE_LEAP;
	if (clock_settime(CLOCK_REALTIME, &now) < 0)
		tst_brkm(TBROK | TERRNO, cleanup, "clock_settime");
	tst_resm(TINFO, "setting time to        %s", strtime(&now));

	/* reset NTP time state */
	adjtimex_status(&tx, STA_PLL);
	adjtimex_status(&tx, 0);

	/* set the leap second insert flag */
	adjtimex_status(&tx, STA_INS);

	/* reliably sleep till after the leap second */
	while (tx.time.tv_sec < leap.tv_sec + SECONDS_AFTER_LEAP) {
		adjtimex_status(&tx, tx.status);
		clock_nanosleep(CLOCK_MONOTONIC, 0, &sleeptime, NULL);
	}

	test_hrtimer_early_expiration();

	adjtimex_status(&tx, STA_PLL);
	adjtimex_status(&tx, 0);

	/* recover from timer expiring state and restore time */
	clock_gettime(CLOCK_REALTIME, &now);
	start.tv_sec += now.tv_sec - (leap.tv_sec - SECONDS_BEFORE_LEAP);
	start.tv_nsec += now.tv_nsec;
	start.tv_sec += start.tv_nsec / NSEC_PER_SEC;
	start.tv_nsec = start.tv_nsec % NSEC_PER_SEC;
	tst_resm(TINFO, "restoring time to %s", strtime(&start));
	/* calls clock_was_set() in kernel to revert inconsistency */
	if (clock_settime(CLOCK_REALTIME, &start) < 0)
		tst_brkm(TBROK | TERRNO, cleanup, "clock_settime");

	test_hrtimer_early_expiration();
}
void Tokenizer::timeChecker(sqlite3* db, FILE* fout) {
	if (strstr(buffer, "get-time")) {
		int sec = atoi(currentTime.c_str());
		time_t tt(sec);
		struct tm* ptm = localtime(&tt);
		fprintf(fout, "get-time\tsuccessful\t%04d/%02d/%02d\n", 1900 + ptm->tm_year, 1 + ptm->tm_mon, ptm->tm_mday);
	}
	if (strstr(buffer, "set-time")) {
		firstToken;
		STR strtime(nextToken);
		int year = atoi(strtime.substr(0, 4).c_str());
		int month = atoi(strtime.substr(5, 2).c_str());
		int day = atoi(strtime.substr(8, 2).c_str());
		struct tm curtm;
		curtm.tm_year = year - 1900;
		curtm.tm_mon = month - 1;
		curtm.tm_mday = day;
		curtm.tm_hour = curtm.tm_min = curtm.tm_sec = 0;
		curtm.tm_isdst = 0;
		int tmp = (int)mktime(&curtm);
		std::stringstream ss;
		ss << tmp;
		ss >> currentTime;
		fprintf(fout, "set-time\tsuccessful\t%04d/%02d/%02d\n", year, month, day);
	}
Ejemplo n.º 5
0
static PyObject *
python_strtime( PyObject *self, PyObject *args ) {
	char	*usage = "Usage: _stock._strtime( epoch )\n";
	PyObject *obj;
	double	epoch;
	char 	*s;

	if( ! PyArg_ParseTuple( args, "d", &epoch ) ) {

		USAGE;

		return NULL;
	}

	s = strtime( epoch );

	obj = Py_BuildValue( "s", s );

	if( s ) {

		free( s );
	}

	return obj;
}
Ejemplo n.º 6
0
void boinc_info(const char* pszFormat, ...){
    static char szBuffer[4096];
    static char szDate[64];
    static char szTime[64];
    int n;

    memset(szBuffer, 0, sizeof(szBuffer));
    memset(szDate, 0, sizeof(szDate));
    memset(szTime, 0, sizeof(szTime));

    strdate(szDate);
    strtime(szTime);

    va_list ptr;
    va_start(ptr, pszFormat);

    vsnprintf(szBuffer, sizeof(szBuffer), pszFormat, ptr);

    va_end(ptr);

#if defined(_WIN32) && defined(_DEBUG)
    _CrtDbgReport(_CRT_WARN, NULL, NULL, NULL, "[%s %s] BOINCMSG: %s\n", szDate, szTime, szBuffer);
#else
    if (flags & BOINC_DIAG_TRACETOSTDERR) {
        n = fprintf(stderr, "[%s %s] BOINCMSG: %s\n", szDate, szTime, szBuffer);
        if (n > 0) stderr_file_size += n;
    }

    if (flags & BOINC_DIAG_TRACETOSTDOUT) {
        n = fprintf(stdout, "[%s %s] BOINCMSG: %s\n", szDate, szTime, szBuffer);
        if (n > 0) stdout_file_size += n;
    }
#endif
}
Ejemplo n.º 7
0
// Converts the BOINCTRACE macro into a single string and report it
//   to the CRT so it can be reported via the normal means.
//
void boinc_trace(const char *pszFormat, ...) {
    static char szBuffer[4096];
    static char szDate[64];
    static char szTime[64];
    int n;

    // Trace messages should only be reported if running as a standalone
    //   application or told too.
    if ((flags & BOINC_DIAG_TRACETOSTDERR) ||
        (flags & BOINC_DIAG_TRACETOSTDOUT)) {

        memset(szBuffer, 0, sizeof(szBuffer));
        memset(szDate, 0, sizeof(szDate));
        memset(szTime, 0, sizeof(szTime));

#ifdef _WIN32
        strdate(szDate);
        strtime(szTime);
#else
        time_t t;
        char *theCR;
    
        time(&t);
        strcpy(szTime, asctime(localtime(&t)));
        theCR = strrchr(szTime, '\n');
        if (theCR) *theCR = '\0';
        theCR = strrchr(szTime, '\r');
        if (theCR) *theCR = '\0';
#endif

        va_list ptr;
        va_start(ptr, pszFormat);

        vsnprintf(szBuffer, sizeof(szBuffer), pszFormat, ptr);

        va_end(ptr);

#if defined(_WIN32) && defined(_DEBUG)
        n = _CrtDbgReport(_CRT_WARN, NULL, NULL, NULL, "[%s %s] TRACE [%d]: %s", szDate, szTime, GetCurrentThreadId(), szBuffer);
#else
        if (flags & BOINC_DIAG_TRACETOSTDERR) {
#ifdef _WIN32
            n = fprintf(stderr, "[%s %s] TRACE [%d]: %s\n", szDate, szTime, GetCurrentThreadId(), szBuffer);
#else
            n = fprintf(stderr, "[%s] TRACE: %s\n", szTime, szBuffer);
#endif
            if (n > 0) stderr_file_size += n;
        }

        if (flags & BOINC_DIAG_TRACETOSTDOUT) {
#ifdef _WIN32
            n = fprintf(stdout, "[%s %s] TRACE [%d]: %s\n", szDate, szTime, GetCurrentThreadId(), szBuffer);
#else
            n = fprintf(stdout, "[%s] TRACE: %s\n", szTime, szBuffer);
#endif
            if (n > 0) stdout_file_size += n;
        }
#endif
    }
}
Ejemplo n.º 8
0
static int
dbrows2orb(Dbptr db, int orb, char *prefix)
{
	Packet         *pkt;
	char            srcname[ORBSRCNAME_SIZE];
	double          time;
	char           *packet;
	int             nbytes, packetsize = 0;
	Dbptr           tmpdb;
	long            t, nrecords, r, ntables;
	Arr            *records = NULL;
	Tbl            *tables = NULL, *static_tables;
	char           *thistablename;
	Stbl           *stbl;
	char           *s;

	dbuntangle(db, &records);
	tables = keysarr(records);
	ntables = maxtbl(tables);
	if (ntables > 0)
		pkt = newPkt();
	if (prefix)
		strncpy(pkt->parts.src_net, prefix, PKT_TYPESIZE);
	pkt->pkttype = suffix2pkttype("db");
	for (t = 0; t < ntables; t++) {
		thistablename = gettbl(tables, t);
		tmpdb = dblookup(db, 0, thistablename, 0, 0);
		stbl = (Stbl *) getarr(records, thistablename);
		nrecords = maxstbl(stbl);
		if (nrecords > 0) {
			for (r = 0; r < nrecords; r++) {
				tmpdb.record = (long) getstbl(stbl, r);
				pkt->db = tmpdb;
				if (stuffPkt(pkt, srcname, &time, &packet, &nbytes, &packetsize) < 0) {
					elog_complain(0, "stuffPkt fails for pf packet");
					return (-1);
				}
				if (orbput(orb, srcname, time, packet, nbytes) < 0) {
					elog_complain(0, "Couldn't send packet to orb\n");
					return (-1);
				}
			}
		}
	}
	freetbl(tables, 0);
	dbfree_untangle(records);
	freePkt(pkt);
	if (verbose) {
		elog_notify(0, "%s: %d patcket(s) sent with sourcename: %s\n", s = strtime(now()), nrecords, srcname);
		free(s);
	}
	return (0);




}
Ejemplo n.º 9
0
static int create_time_rec(const str *time_start, const str *time_end,
		const str *week_days, tmrec_p trec)
{
	int end_h, end_m;

	memset(trec, 0, sizeof(tmrec_t));

	if (strtime(time_start, &trec->ts.tm_hour, &trec->ts.tm_min) != 0
			|| strtime(time_end, &end_h, &end_m) != 0)
		return -1;

	trec->duration = (end_h * 3600 + end_m * 60) -
		(trec->ts.tm_hour * 3600 + trec->ts.tm_min * 60);
	trec->ts.tm_isdst = -1 /*daylight*/;
	trec->dtstart = trec->duration;
	trec->freq = FREQ_DAILY;

	unsigned short day_set = 0;
	int n = parse_week_days(week_days, &day_set);

	if (n == -1)
		return -1;

	if (n) {
		//TODO - byday custom init - no req needed
		trec->byday = tr_byxxx_new(SHM_ALLOC);
		if (trec->byday == NULL)
			return -1;

		if (tr_byxxx_init(trec->byday, n) < 0) {
			tr_byxxx_free(trec->byday);
			return -1;
		}

		short i, j = 0;

		for (i = 0; i < 7; ++i)
			if (day_set & 1 << i)
				trec->byday->xxx[j++] = i;
	}

	return 0;
}
Ejemplo n.º 10
0
static void get_rfc1123_date(char* out, int len)
{
   /*there is a locale problem in strftime.*/
   /*time_t t = time(NULL);
    struct tm p;

    gmtime_r(&t, &p);
    strftime(out, len, "%a, %d %b %Y %T GMT", &p);*/
   /* Thu, 29 Aug 2013 05:24:17 GMT */
   strtime(out, len);

    return;
}
Ejemplo n.º 11
0
static void test_hrtimer_early_expiration(void)
{
	struct timespec now, target;
	int r, fail;

	clock_gettime(CLOCK_REALTIME, &now);
	tst_resm(TINFO, "now is     %s", strtime(&now));

	target = now;
	target.tv_sec++;
	tst_resm(TINFO, "sleep till %s", strtime(&target));
	r = clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &target, NULL);
	if (r < 0) {
		tst_resm(TINFO | TERRNO, "clock_nanosleep");
		return;
	}

	clock_gettime(CLOCK_REALTIME, &now);
	tst_resm(TINFO, "now is     %s", strtime(&now));

	fail = !in_order(target, now);
	tst_resm(fail ? TFAIL : TINFO, "hrtimer early expiration is %s.",
		 fail ? "detected" : "not detected");
}
Ejemplo n.º 12
0
int InitializeBiosTime()
{
	uint sid = SysGetCurrentSpaceId();
	mapAddress = (size_t)SysAllocateMemory( sid, MB(1), 0, ALLOC_VIRTUAL );
	if( mapAddress==0 ){
		printf("[time]failed to allocate 1 mb memory.\n");
		return -ERR_NOMEM;
	}
	if( SysMapMemory( sid, mapAddress, MB(1), 0, 0, MAP_ADDRESS ) < 0 ){
		printf("[time]failed to map 1 mb memory.\n");
		return -ERR_NOMEM;
	}
	time_t unixTime = GetUnixTime();
	char timestr[100];
	strtime(&unixTime, timestr);
	printf("[time]System time: %s\n", timestr );
	return 0;
}
Ejemplo n.º 13
0
void wrt_last_rec ( Db_buffer *buf )
{
    int result ;
    char *s ;
    if ( buf->params->datacode  == trSEED )  {
   
	    result = csteim (buf->steim, save_seed, 0, 0) ;
	    if ( result < 0 ) 
		die ( 1, "steim compression failed to write final bytes\n" ) ;
	    else if ( result > 0 ) {
		complain ( 1, "steim compression problems for %s_%s_%s at %s\n",
			    buf->net, buf->sta, buf->chan, s=strtime(buf->crnt_time) );
		free(s) ; 
	    }
	    if ( buf->steim != 0 ) {
		freesteim ( buf->steim ) ; 
		buf->steim = stinit ( buf ) ; 
	    }
     }

}
Ejemplo n.º 14
0
void boinc_catch_signal(int signal, struct siginfo *siginfo, void *sigcontext) {
#else
void boinc_catch_signal(int signal) {
#endif
    switch(signal) {
    case SIGHUP: fprintf(stderr, "SIGHUP: terminal line hangup\n");
         return;
    case SIGINT: fprintf(stderr, "SIGINT: interrupt program\n"); break;
    case SIGILL: fprintf(stderr, "SIGILL: illegal instruction\n"); break;
    case SIGABRT: fprintf(stderr, "SIGABRT: abort called\n"); break;
#if SIGBUS != SIGSEGV
    // in case SIGBUS == SIGSEGV (e.g., Haiku)
    case SIGBUS: fprintf(stderr, "SIGBUS: bus error\n"); break;
#endif
    case SIGSEGV: fprintf(stderr, "SIGSEGV: segmentation violation\n"); break;
    case SIGSYS: fprintf(stderr, "SIGSYS: system call given invalid argument\n"); break;
    case SIGPIPE: fprintf(stderr, "SIGPIPE: write on a pipe with no reader\n");
        return;
    default: fprintf(stderr, "unknown signal %d\n", signal); break;
    }

#ifdef __GLIBC__
    void *array[64];
    size_t size;
    size = backtrace (array, 64);
//  Anything that calls malloc here (i.e *printf()) will probably fail
//  so we'll do it the hard way.
    (void) write(fileno(stderr),"Stack trace (",strlen("Stack trace ("));
    char mbuf[10];
    char *p=mbuf+9;
    int i=size;
    *(p--)=0;
    while (i) {
      *(p--)=i%10+'0';
      i/=10;
    }
    (void) write(fileno(stderr),p+1,strlen(p+1));
    (void) write(fileno(stderr)," frames):",strlen(" frames):"));
    mbuf[0]=10;
    (void) write(fileno(stderr),mbuf,1);
    backtrace_symbols_fd(array, size, fileno(stderr));
#endif

#ifdef __APPLE__
    PrintBacktrace();
#endif

#ifdef ANDROID
    // this is some dark undocumented Android voodoo that uses libcorkscrew.so
    // minimal use of library functions because they may not work in an signal
    // handler.
#define DUMP_LINE_LEN 256
    static backtrace_frame_t backtrace[64];
    static backtrace_symbol_t backtrace_symbols[64]; 
    if (unwind_backtrace_signal_arch != NULL) {
        map_info_t *map_info=acquire_my_map_info_list();
        ssize_t size=unwind_backtrace_signal_arch(siginfo,sigcontext,map_info,backtrace,0,64);
        get_backtrace_symbols(backtrace,size,backtrace_symbols);
        char line[DUMP_LINE_LEN];
        for (int i=0;i<size;i++) {
            format_backtrace_line(i,&backtrace[i],&backtrace_symbols[i],line,DUMP_LINE_LEN);
            line[DUMP_LINE_LEN-1]=0;
            if (backtrace_symbols[i].symbol_name) {
                strlcat(line," ",DUMP_LINE_LEN);
                if (backtrace_symbols[i].demangled_name) {
                   strlcat(line,backtrace_symbols[i].demangled_name,DUMP_LINE_LEN);
                }
            } else {
                symbol_table_t* symbols = NULL;
                if (backtrace_symbols[i].map_name) {
                    symbols = load_symbol_table(backtrace_symbols[i].map_name);
                } else {
                    symbols = load_symbol_table(argv0);
                }
                symbol_t* symbol = NULL;
                if (symbols) {
                    symbol = find_symbol(symbols, backtrace[i].absolute_pc);
                }
                if (symbol) {
                    int offset = backtrace[i].absolute_pc - symbol->start;
                    strlcat(line," (",DUMP_LINE_LEN);
                    strlcat(line,symbol->name,DUMP_LINE_LEN);
                    strlcat(line,"+",DUMP_LINE_LEN);
                    strlcat(line,xtoa(offset),DUMP_LINE_LEN);
                    strlcat(line,")",DUMP_LINE_LEN);
                    line[DUMP_LINE_LEN-1]=0;
                } else {
                    strlcat(line, " (\?\?\?)",DUMP_LINE_LEN);
                }
                if (symbols) free_symbol_table(symbols);
            }
            if (backtrace[i].absolute_pc) {
              strlcat(line," [",DUMP_LINE_LEN);
              strlcat(line,xtoa(*reinterpret_cast<unsigned int *>(backtrace[i].absolute_pc)),DUMP_LINE_LEN);
              strlcat(line,"]",DUMP_LINE_LEN);
            }
            strlcat(line,"\n",DUMP_LINE_LEN);
            write(fileno(stderr),line,strlen(line));
            fflush(stderr);
        }
    }
#endif // ANDROID

    fprintf(stderr, "\nExiting...\n");
    _exit(signal_exit_code);
}

#endif

//
// Diagnostics Routines common to all Platforms
//

// Converts the BOINCTRACE macro into a single string and report it
//   to the CRT so it can be reported via the normal means.
//
void boinc_trace(const char *pszFormat, ...) {
    static char szBuffer[4096];
    static char szDate[64];
    static char szTime[64];
    int n;

    // Trace messages should only be reported if running as a standalone
    //   application or told too.
    if ((flags & BOINC_DIAG_TRACETOSTDERR) ||
        (flags & BOINC_DIAG_TRACETOSTDOUT)) {

        memset(szBuffer, 0, sizeof(szBuffer));
        memset(szDate, 0, sizeof(szDate));
        memset(szTime, 0, sizeof(szTime));

#ifdef _WIN32
        strdate(szDate);
        strtime(szTime);
#else
        time_t t;
        char *theCR;
    
        time(&t);
        safe_strcpy(szTime, asctime(localtime(&t)));
        theCR = strrchr(szTime, '\n');
        if (theCR) *theCR = '\0';
        theCR = strrchr(szTime, '\r');
        if (theCR) *theCR = '\0';
#endif

        va_list ptr;
        va_start(ptr, pszFormat);

        vsnprintf(szBuffer, sizeof(szBuffer), pszFormat, ptr);

        va_end(ptr);

#if defined(_WIN32) && defined(_DEBUG)
        n = _CrtDbgReport(_CRT_WARN, NULL, NULL, NULL, "[%s %s] TRACE [%d]: %s", szDate, szTime, GetCurrentThreadId(), szBuffer);
#else
        if (flags & BOINC_DIAG_TRACETOSTDERR) {
#ifdef _WIN32
            n = fprintf(stderr, "[%s %s] TRACE [%d]: %s\n", szDate, szTime, GetCurrentThreadId(), szBuffer);
#else
            n = fprintf(stderr, "[%s] TRACE: %s\n", szTime, szBuffer);
#endif
            if (n > 0) stderr_file_size += n;
        }

        if (flags & BOINC_DIAG_TRACETOSTDOUT) {
#ifdef _WIN32
            n = fprintf(stdout, "[%s %s] TRACE [%d]: %s\n", szDate, szTime, GetCurrentThreadId(), szBuffer);
#else
            n = fprintf(stdout, "[%s] TRACE: %s\n", szTime, szBuffer);
#endif
            if (n > 0) stdout_file_size += n;
        }
#endif
    }
}


// Converts the BOINCINFO macro into a single string and report it
//   to stderr so it can be reported via the normal means.
//
#ifndef BOINC_INFOMSGS
void boinc_info(const char* /*pszFormat*/, ... ){ return; }
#else
void boinc_info(const char* pszFormat, ...){
    static char szBuffer[4096];
    static char szDate[64];
    static char szTime[64];
    int n;

    memset(szBuffer, 0, sizeof(szBuffer));
    memset(szDate, 0, sizeof(szDate));
    memset(szTime, 0, sizeof(szTime));

    strdate(szDate);
    strtime(szTime);

    va_list ptr;
    va_start(ptr, pszFormat);

    vsnprintf(szBuffer, sizeof(szBuffer), pszFormat, ptr);

    va_end(ptr);

#if defined(_WIN32) && defined(_DEBUG)
    _CrtDbgReport(_CRT_WARN, NULL, NULL, NULL, "[%s %s] BOINCMSG: %s\n", szDate, szTime, szBuffer);
#else
    if (flags & BOINC_DIAG_TRACETOSTDERR) {
        n = fprintf(stderr, "[%s %s] BOINCMSG: %s\n", szDate, szTime, szBuffer);
        if (n > 0) stderr_file_size += n;
    }

    if (flags & BOINC_DIAG_TRACETOSTDOUT) {
        n = fprintf(stdout, "[%s %s] BOINCMSG: %s\n", szDate, szTime, szBuffer);
        if (n > 0) stdout_file_size += n;
    }
#endif
}
#endif

void diagnostics_set_max_file_sizes(int stdout_size, int stderr_size) {
    if (stdout_size) max_stdout_file_size = stdout_size;
    if (stderr_size) max_stderr_file_size = stderr_size;
}

// Dump string to whatever the platform debuggers
// 
#ifndef _WIN32
int diagnostics_trace_to_debugger(const char*) {
    return 0;
}
Ejemplo n.º 15
0
	char            auth[16];
	int             commid;
	double          lddate;
}               ARRIVAL;

void 
free_arrivals(ARRIVAL * A)
{
	free(A);
}
int 
print_arrival(ARRIVAL * arrival, void *private)
{

	printf("%s:%s %s @ %s\n", arrival->sta, arrival->chan,
	       arrival->iphase, strtime(arrival->time));
	return (0);

}
int 
cmp_arrival(ARRIVAL ** a1, ARRIVAL ** a2, void *private)
{
	/* return (*a1)->time - (*a2)->time; */
	if ((*a1)->time > (*a2)->time)
		return 1;
	if ((*a2)->time > (*a1)->time)
		return -1;
	return 0;
}
int 
cmp_stachan(STACHANSTRUCT ** sc1, STACHANSTRUCT ** sc2, void *private)
Ejemplo n.º 16
0
int main(int argc, char **argv)
{
	SEGYBinaryFileHeader reel;
	SEGYTraceHeader *header;
	char *dbin;
	char *outfile;
	FILE *fp;
	Pf *pf;
	Arr *channels;  /* channel order list */
	Arr *table_list;  /* array of valid tables */
	int nchan;
	char *stest;

	float **traces;
	char text_file_header[SEGY_TEXT_HEADER_SIZE];
	Dbptr db, trdb, dbj;
	Dbptr trdbss;
	int nsamp0;
	double time0, endtime0, samprate0;
	long int nsamp;
	double samprate;
	int i,j;
	char stime[30],etime[30];
	char s[128];
	double tlength;
	double phi, theta;
	char *newchan_standard[3]={"X1","X2","X3"};
	char *trsubset="chan=~/X./";
	char *newchan[3]={"R","T","Z"};
	Tbl *sortkeys=newtbl(0);
	char sta[10],chan[10];
	double lat, lon, elev, dnorth, deast, edepth;
	char segtype;
	char refsta[10];
	int total_traces=0;
	char *time_str;
	long int evid,shotid=1;
	int rotate=0;
	long int ntraces;
        int ichan;
	int map_to_cdp;  /* logical switch to output data like cdp stacked data */
	char *fmt="%Y %j %H %M %S %s";
	char *pfname;
	int Verbose=0;
	/* New features added 2009 */
	/* this is a boolean.  If true (nonzero) it is assumed stdin will
	contain four numbers:  time,lat, lon, elev.  If false, only the
	time field is read and remainder of any input on each line is dropped.*/
	int input_source_coordinates;
	/* scale factor for source coordinates.  Needed because segy uses
	an int to store source coordinates.  Sensible choices are
	3600 for arc seconds and 10000 for a pseudodecimal. Note this
	parameter is ignored unless input_source_coordinates is true.*/
	int coordScale;
	/* If true use passcal 32 bit extension num_samps as record length.
	SEGY standard uses a 16 bit entry that easily overflows with large
	shots at long offset.  In this ase assume the 16 bit quantity is
	meaningless. */
	int use_32bit_nsamp;
	/* This is switched on by argument switch.  When set to a nonzero
	(default) the reel headers are written.  When 0 `
	the reel headers will not be written -- used by seismic unix
	and passcal*/
	int write_reel_headers=1;

	/* SEG-Y version to output. Default is original 1975 spec (rev 0) */
	int16_t segy_format = SEGY_FORMAT_REV_0;

	/* dbsubset query string */
	char *substr=NULL;

	/* text_header_description is a buffer holding a user-supplied description
	 * to be placed in the 3200-byte text header block. It is controlled by
	 * the parameter file value text_header_description or by the -d command
	 * line option, with the latter taking precedence */
	char* text_header_description=NULL;

	if(argc < 3) usage();
	dbin = argv[1];
	outfile = argv[2];
	pfname = NULL;
	for(i=3;i<argc;++i)
	{
		if(!strcmp(argv[i],"-pf"))
		{
			++i;
			pfname = argv[i];
		}
		else if(!strcmp(argv[i],"-SU"))
		{
			write_reel_headers=0;
		}
		else if(!strcmp(argv[i],"-v"))
		{
			Verbose=1;
		}
		else if(!strcmp(argv[i],"-d"))
		{
			++i;
			text_header_description = strdup(argv[i]);
		}
		else if(!strcmp(argv[i],"-ss"))
		{
			++i;
			substr=argv[i];
		}
		else if(!strcmp(argv[i],"-V"))
		{
			++i;
			if     (!strcmp(argv[i],"0")) {segy_format = SEGY_FORMAT_REV_0;}
			else if(!strcmp(argv[i],"1")) {segy_format = SEGY_FORMAT_REV_1_0;}
			else if(!strcmp(argv[i],"SU"))
			{
				segy_format = SEGY_FORMAT_SU;
				write_reel_headers=0;
			}
			else
			{
				elog_complain(0, "SEG-Y Version must be either 1 or 0");
				usage();
			}
		}
		else
		{
			usage();
		}
	}
	/* Command-line parameter sanity checking */
	if (write_reel_headers==0 && segy_format != SEGY_FORMAT_SU){
		complain(0, "The SU option cannot be used with the -V option");
		usage();
	}
	if(pfname == NULL) pfname = strdup("db2segy");

	elog_init(argc, argv);

	if(pfread(pfname,&pf)) {
		elog_die(0,"pfread error for pf file %s.pf\n",argv[0]);
	}

	/* Read the text_header_description if we weren't passed the -d option */
	if (!text_header_description) {
		text_header_description=pfget_string(pf, "text_header_description");
	}

	/* rotation parameters */
	rotate=pfget_boolean(pf,"rotate");
	if(rotate)
	{
		phi = pfget_double(pf,"phi");
		theta = pfget_double(pf,"theta");
	}
	/* This function creates the channel order list keyed by
	station channel names */
	channels = build_stachan_list(pf,&nchan,Verbose);

	map_to_cdp = pfget_boolean(pf,"map_to_cdp");
	if(map_to_cdp && Verbose)
		elog_notify(0,"Casting data as CDP stacked section\n");
	if(dbopen(dbin,"r",&db) == dbINVALID)
	{
		elog_complain(1,"Cannot open db %s\n", dbin);
		usage();
	}
	/* We grab the sample rate and trace length (in seconds) and
	use this to define global sample rates for the data.
	SEG-Y REV0 REQUIRES fixed length records and sample rates, so
	irregular sample rates will cause this program to die.
	One could add a decimate/interpolate function, but this
	is not currently implemented */
	samprate0 = pfget_double(pf,"sample_rate");
	tlength = pfget_double(pf,"trace_length");
	nsamp0 = (int)(tlength*samprate0);
	use_32bit_nsamp=pfget_boolean(pf,"use_32bit_nsamp");
	if (ntohs(segy_format) >= 0x0100 && use_32bit_nsamp) {
		elog_complain(0,"The 32-bit extension field is incompatible with SEG-Y REV 1. Ignoring 'use_32bit_nsamp' from the parameter file");
		use_32bit_nsamp=0;
	}

	/* nsamp in segy is a 16 bit field.  Handling depends on
	setting of use_32bit_nsamp boolean */
	if(nsamp0 > SEGY_MAX_NSAMP)
	{
		if(use_32bit_nsamp)
		{
			elog_notify(0,"Warning:  segy uses a 16 bit entity to store number of samples\nThat field is garbage. Using the 32 bit extension field.");
		}
		else
		{
		elog_complain(0,
		  "Warning:  segy uses a 16 bit entity to store number of samples. Requested %d samples per trace.  Trucated to %d", nsamp0, SEGY_MAX_NSAMP);
		nsamp0 = SEGY_MAX_NSAMP;
		}
	}

	/* boolean.  When nonzero set coordinates as geographic arc seconds values */
	int use_geo_coordinates=pfget_boolean(pf,"use_geo_coordinates");

	/* boolean. When nonzero, output decimal degrees instead of arcseconds if
	 * the requested output format supports it (rev1 only) */
	int prefer_decimal_degrees=pfget_boolean(pf, "prefer_decimal_degrees");

	/* We now have enough information to decide the coordUnits for all traces */
	int coordUnits = 0;
	if (!use_geo_coordinates) {
		coordUnits=SEGY_TRACE_COORDUNITS_LENGTH;
	} else if (ntohs(segy_format) >= 0x0100 && prefer_decimal_degrees) {
		coordUnits=SEGY_TRACE_COORDUNITS_DECIMAL_DEGREES;
	} else {
		coordUnits=SEGY_TRACE_COORDUNITS_ARCSECONDS;
	}
	/* We should have set our coordinate units now */
	assert(coordUnits!=0);

	input_source_coordinates=pfget_boolean(pf,"input_source_coordinates");
	if(input_source_coordinates)
	{
		coordScale=pfget_int(pf,"coordinate_scale_factor");
	}
	else if (coordUnits==SEGY_TRACE_COORDUNITS_DECIMAL_DEGREES)
	{
		/* Use a sane scalar for decimal degrees. 10000 gives four decimal
		 * places of accuracy, which matches the CSS3.0 spec for lat and lon */
		coordScale=10000;
	}
	else
	{
		coordScale=1;
	}

	/* Print a diagnostic message if the user gave a sub-optimal value for the
	 * coordScale */
	if (coordUnits == SEGY_TRACE_COORDUNITS_DECIMAL_DEGREES &&
			coordScale < 10000)
	{
		elog_alert(0,
				"The supplied parameter 'coordinate_scale_factor' value of %d is less than 10000, and will cause loss of precision for decimal degree coordinates.",
				coordScale);
	}
    else if (coordUnits == SEGY_TRACE_COORDUNITS_ARCSECONDS)
    {
        if (coordScale > 1000) {
            elog_alert(0,
                    "The supplied parameter 'coordinate_scale_factor' value of %d is greater than 1000, and will cause loss of precision for arcsecond coordinates.",
                    coordScale);
        }
    }

	/* trace_gain_type: signed int */
	int16_t trace_gain_type = pfget_int(pf,"trace_gain_type");
	if (trace_gain_type < 0)
	{
		die(0, "The trace_gain_type must be zero or greater");
	}
	else
	{
		trace_gain_type=htons(trace_gain_type);
	}


	/* check list of tables defined in pf.  Return array of
	logicals that define which tables are valid and join
	tables. */
	table_list = check_tables(db,pf);
	check_for_required_tables(table_list);
	dbj = join_tables(db,pf,table_list);
	if(dbj.record == dbINVALID) elog_die(0,"dbjoin error\n");
	if(substr!=NULL) dbj=dbsubset(dbj,substr,0);
	long int ndbrows;
	dbquery(dbj,dbRECORD_COUNT,&ndbrows);
	if(ndbrows<=0)
	{
		elog_complain(1,"Working database view is empty\n");
		if(substr!=NULL) elog_complain(0,"Subset condtion =%s a likely problem\n",
				substr);
		usage();
	}

	fp = fopen(outfile,"w");
	if(fp == NULL)
	{
		elog_complain(0,"Cannot open output file %s\n",outfile);
		usage();
	}

	/* These are needed for sort below */
	pushtbl(sortkeys,"sta");
	pushtbl(sortkeys,"chan");

    /* Set up and write the Textual File Header */
	initialize_text_header(text_file_header, segy_format,
			text_header_description);

	if(write_reel_headers){
		if ( fwrite(text_file_header,1,SEGY_TEXT_HEADER_SIZE,fp) \
				!= SEGY_TEXT_HEADER_SIZE ) {
			elog_die(1,"An error occurred writing the textual file header");
		}
	}

	/* memory allocation for trace data.  This is a large matrix
	that is cleared for each event.  This model works because of
	segy's fixed length format.*/
	traces = calloc(nchan, sizeof(float*));
	if(traces == NULL)
		elog_die(1,"out of memory");
	for (int r = 0; r < nchan; r++)
	{
		traces[r] = calloc(nsamp0, sizeof(float));
		if(traces[r] == NULL)
			elog_die(1,"out of memory");
	}
	header = (SEGYTraceHeader *)calloc((size_t)nchan,sizeof(SEGYTraceHeader));
	if(header == NULL)
			elog_die(0,"Cannot alloc memory for %d segy header workspace\n",nchan);
	if(write_reel_headers)
	{
		if (Verbose) {
			elog_debug(0,"Binary Headers - Using segy_format code 0x%04X\n", ntohs(segy_format));
		}
		initialize_binary_file_header(&reel, segy_format);

		/* now fill in the binary reel header and write it */
		reel.kjob   = htonl(1);
		reel.kline  = htonl(1);
		reel.kreel  = htonl(1);
		reel.kntr   = htons((int16_t)nchan);
		reel.knaux  = htons(0);
		reel.sr     = htons((int16_t)(1000000.0/samprate0));
		reel.kfldsr = reel.sr;
		reel.knsamp = htons((int16_t)nsamp0);
		reel.kfsamp = htons((int16_t)nsamp0);
		reel.dsfc   = htons(5);  /* This is ieee floats*/
		reel.kmfold = htons(0);
		if(map_to_cdp)
			reel.ksort = htons(2);
		else
			reel.ksort = htons(1);
		reel.kunits = htons(1);  /* This sets units to always be meters */

		if(fwrite((void *)(&reel),sizeof(SEGYBinaryFileHeader),1,fp) != 1)
		{
			elog_die(1,"Write error for binary reel header");
		}
	}

	/* Now we enter a loop over stdin reading start times.
	Program will blindly ask for data from each start time to
	time+tlength.  The trace buffer will be initialized to
	zeros at the top of the loop always.  If nothing is found
	only zeros will be written to output.
	*/
	while((stest=fgets(s,80,stdin)) != NULL)
	{
		double slat,slon,selev;  /* Used when reading source location*/
		if(Verbose)
			elog_notify(0,"Processing:  %s\n",s);
		for(i=0;i<nchan;++i)
		{
			initialize_trace_header(&(header[i]), segy_format);
			header[i].gainType = trace_gain_type;
			header[i].lineSeq = htonl(total_traces + i + 1);
			header[i].reelSeq = header[i].lineSeq;
			if(map_to_cdp)
			{
				header[i].cdpEns = htonl(i + 1);
				header[i].traceInEnsemble = htonl(1);/* 1 trace per cdp faked */
			}
			else
			{
				header[i].channel_number = htonl(i + 1);
			}
			header[i].event_number   = htonl(shotid);
			header[i].energySourcePt = htonl(shotid);
			for(j=0;j<nsamp0;++j)  traces[i][j] = htonf((Trsample)0.0);
		}
		if(input_source_coordinates)
		{
			char stmp[40];
			sscanf(s,"%s%ld%lf%lf%lf",stmp,&shotid,&slon,&slat,&selev);
			time0=str2epoch(stmp);
			if(coordUnits == SEGY_TRACE_COORDUNITS_ARCSECONDS) {
				slat*=3600.0;
				slon*=3600.0;
			}
			slat *= (double)coordScale;
			slon *= (double)coordScale;
		}
		else
		{
			time0 = str2epoch(s);
		}
		endtime0 = time0 + tlength;
		sprintf(stime,"%20.4f",time0);
		sprintf(etime,"%20.4f",endtime0);
		trdb.database = -1;
		if(trload_css(dbj,stime,etime,&trdb,0, 0) < 0)
		{
			if(Verbose)
			{
			  elog_notify(0,"trload_css failed for shotid=%ld",shotid);
			  elog_notify(0,"  No data in time range %s to %s\n",
			  	strtime(time0),strtime(endtime0) );
			  elog_notify(0,"No data written for this shotid block.");
			  elog_notify(0,"  Handle this carefully in geometry definitions.\n");
			}

			continue;
		}
		/* This does gap processing */
		repair_gaps(trdb);

		trapply_calib(trdb);

		if(rotate)
		{
			if(rotate_to_standard(trdb,newchan_standard))
				elog_notify(0,"Data loss in rotate_to_standard for event %s to %s\n",
					stime, etime);
			/* This is need to prevent collisions of channel names */
			trdbss = dbsubset(trdb,trsubset,0);
			if(trrotate(trdbss,phi,theta,newchan))
				elog_notify(0,"Data loss in trrotate for event %s to %s\n",
					stime, etime);
		}
		if(Verbose)
			elog_notify(0,"Station  chan_name  chan_number seq_number shotid  evid\n");
		trdb = dbsort(trdb,sortkeys,0,0);
		dbquery(trdb,dbRECORD_COUNT,&ntraces);
		if(Verbose) elog_debug(0,"Read %ld traces for event at time%s\n",
			ntraces,strtime(time0));
		for(trdb.record=0;trdb.record<ntraces;++trdb.record)
		{
			Trsample *trdata;
			if(dbgetv(trdb,0,
			    "evid",&evid,
			    "sta",sta,
			    "chan",chan,
			    "nsamp", &nsamp,
			    "samprate",&samprate,
			    "data",&trdata,
			    "lat", &lat,
			    "lon", &lon,
			    "elev",&elev,
			    "refsta",refsta,
			    "dnorth",&dnorth,
			    "deast",&deast,
			    "edepth",&edepth,
			    "segtype",&segtype,
			    NULL) == dbINVALID)
			{
				elog_complain(0," dbgetv error reading record %ld. Trace will be skipped for station %s and channel %s",
				trdb.record,sta,chan);
				continue;
			}
			/* Allow 1 percent samprate error before killing */
			double fsrskew=fabs((samprate-samprate0)/samprate0);
			double frskewcut=0.01;
			if(fsrskew>frskewcut)
			{
				elog_complain(0,"%s:%s sample rate %f is significantly different from base sample rate of %f. Trace skipped -- segy requires fixed sample rates",
					sta,chan,samprate,samprate0);
				continue;
			}
			if(nsamp > nsamp0)
			{
				elog_complain(0,"%s:%s trace has extra samples=%ld. Truncated to length %d",
					sta, chan, nsamp, nsamp0);
				nsamp = nsamp0;
			}
			else if(nsamp < nsamp0)
			{
				elog_complain(0,"%s:%s trace is shorter than expected %d samples. Zero padded after sample %ld",
					sta, chan, nsamp0, nsamp);
			}

			ichan = get_channel_index(channels,sta,chan);
			if(ichan > nchan)
			{
				elog_die(0,"Channel index %d outside limit of %d. Cannot continue",
					ichan, nchan);
			}
			if(ichan >= 0)
			{
				if(Verbose)
					elog_debug(0,"%s:%s\t%-d\t%-d\t%-ld\t%-ld\n",
					sta,chan,ichan+1,
					ntohl(header[ichan].reelSeq),
					shotid, evid);
				header[ichan].traceID = get_trace_id_code_from_segtype(segtype);
				for(j=0;j<nsamp;++j) {
				   traces[ichan][j] = htonf((float)trdata[j]);
				}
				/* header fields coming from trace table */
				header[ichan].samp_rate = htonl(
						(int32_t) (1000000.0/samprate0));
				/* according to the behavior specified in the man page:
				 * if use_geo_coordinates is false:
				 * - coordUnits is length (meters)
				 * - therefore, we use deast for X and dnorth for Y
				 * if use_geo_coordinates is true:
				 * - we're using either arcseconds or decimal degrees
				 * - and therefore, we use lon for X and lat for Y
				 *
				 * coordUnits is based on use_arcseconds and the requested
				 * version of segY */

				/* set the coordinate units in the trace header */
				header[ichan].coordUnits = coordUnits;

				/* Pick the source db fields for our receiver X and Y */
				double recLongOrX = 0;
				double recLatOrY  = 0;
				if (coordUnits == SEGY_TRACE_COORDUNITS_LENGTH) {
					/* Use deast and dnorth
					 * CSS3.0 Schema specifies deast and dnorth are in KM.
					 * SEG-Y specifies easting and northing as meters,
					 * hence the 1000.0 multiplier here. */
					recLongOrX = deast  * 1000.0;
					recLatOrY  = dnorth * 1000.0;
				} else if (coordUnits == SEGY_TRACE_COORDUNITS_ARCSECONDS){
					/* Use lat and lon, converted to arcseconds */
					recLongOrX = lon * 3600.0;
					recLatOrY  = lat * 3600.0;
				} else {
					/* Default case, which covers decimal degrees */
					recLongOrX = lon;
					recLatOrY  = lat;
				}

				/* Apply our coordScale - the user can specify negative numbers,
				 * but they are treated as inverting the value, not as a divisor
				 * as in the SEG-Y field usage. See below where we always treat
				 * the scalar as a divisor in the SEG-Y field */
				recLongOrX *= (double)coordScale;
				recLatOrY  *= (double)coordScale;

				/* Set the coordScale in the header.
				 * Note negative here.  This is a oddity of segy that - means
				 * divide by this to get actual.  Always make this negative in
				 * case user inputs a negative number.
				 * Don't set it -1 for cosmetic reasons */
				if (abs(coordScale) == 1)
				{
					header[ichan].coordScale = htons(1);
				} else
				{
					header[ichan].coordScale = htons(-abs(coordScale));
				}

				/* Finally, write out the X and Y */
				header[ichan].recLongOrX
					= htonl((int32_t)recLongOrX);
				header[ichan].recLatOrY
					= htonl((int32_t)recLatOrY);

				/* CSS3.0 specfies elev as being in km, SEG-Y wants it in m */
				header[ichan].recElevation = htonl((int32_t)(elev*1000.0));

				header[ichan].deltaSample = htons(
						(int16_t) (1000000.0/samprate0));
				header[ichan].sampleLength = htons((int16_t)nsamp0);
				if (ntohs(segy_format)<0x0100)
				{
					header[ichan].num_samps = htonl((int32_t)nsamp0);
				}
				/* This cracks the time fields */
				time_str = epoch2str(time0,fmt);
				int16_t hyear, hday, hhour, hminute, hsecond, hm_secs;
				hyear=hday=hhour=hminute=hsecond=hm_secs=0;
				sscanf(time_str,"%hd %hd %hd %hd %hd %hd",
						&hyear, &hday, &hhour, &hminute, &hsecond, &hm_secs);
				header[ichan].year   = htons(hyear);
				header[ichan].day    = htons(hday);
				header[ichan].hour   = htons(hhour);
				header[ichan].minute = htons(hminute);
				header[ichan].second = htons(hsecond);
				header[ichan].m_secs = htons(hm_secs);
				if (ntohs(segy_format)<0x0100)
				{
					/* These are IRIS-PASSCAL extensions */
					header[ichan].trigyear   = header[ichan].year;
					header[ichan].trigday    = header[ichan].day;
					header[ichan].trighour   = header[ichan].hour;
					header[ichan].trigminute = header[ichan].minute;
					header[ichan].trigsecond = header[ichan].second;
				}
				free(time_str);
				if(input_source_coordinates)
				{
					/* Write out our pre-scaled and optionally
					 * arcsecond-converted source lat/lon plus our elevation */
					header[ichan].sourceLongOrX = htonl((int32_t)slon);
					header[ichan].sourceLatOrY  = htonl((int32_t)slat);
					header[ichan].sourceSurfaceElevation
						= htonl((int32_t)selev);
					/* No easy way to specify both elev and depth*/
					header[ichan].sourceDepth=htonl(0);
				}
				else if(map_to_cdp)
				{
				/* When faking CDP data we make this look
				like a zero offset, single fold data set */
					header[ichan].sourceLongOrX   = header[ichan].recLongOrX;
					header[ichan].sourceLatOrY    = header[ichan].recLatOrY;
					header[ichan].sourceSurfaceElevation
					                              = header[ichan].recElevation;
					header[ichan].sourceDepth     = htonl(0);
					header[ichan].sourceToRecDist = htonl(0);
				}
				else
				{
				/* This is the mechanism for adding other
				information with added tables.  The one
				table currently supported is a "shot" table
				that holds shot coordinates.  If other tables
				were added new functions could be added with
				a similar calling sequence.  This procedure
				silently does nothing if a shot table is not
				present.*/
					set_shot_variable(db,table_list,
						evid,&header[ichan]);
				}
			}
			else
			{
				if(Verbose)
					elog_notify(0,"Station %s and channel %s skipped\n",
						sta,chan);
			}

		}
		/* Now we write the data */
		for(i=0;i<nchan;++i)
		{
			if(fwrite((void *)(&(header[i])),sizeof(SEGYTraceHeader),1,fp) != 1)
				elog_die(0,"Write error on header for trace %d\n",total_traces+i);
			if(fwrite((void *)traces[i],sizeof(float),
					(size_t)nsamp0,fp) != nsamp0)
				elog_die(0,"Write error while writing data for trace %d\n",
					total_traces+i);
		}
		total_traces += nchan;
		trdestroy(&trdb);
		if(!input_source_coordinates) ++shotid;
	}
	return 0 ;
}
Ejemplo n.º 17
0
/* Modified Dec. 2006:  added two new Tbls for resid and slowness to
compute residuals only=tapro and tupro. */
int
load_observations ( Pf *pf, Dbptr db, Arr *arr_phase, 
	    Arr **stationsp, Arr **arraysp, Tbl **tap, Tbl **tup ,
		Tbl **tapro, Tbl **tupro) 
{ 
    Station *station ;
    Seismic_Array *array ;
    Arrival *a ;
    Tbl *ta, *tu ,*taro, *turo;
    Dbptr dbarr, dbsite ;
    static Hook *hook = 0 ; 
    static Tbl *matching ;
    Tbl *arrival_tbl ;
    Arr *stations ;
    Arr *arrays ;
    int i, narr ;
    char sta[32], iphase[32], timedef[16], azdef[16], slodef[16] ;
    double time, deltim, azimuth, delaz, slow, delslo ; 
    int arid ;
    Phase_handle *phase ;
    Slowness_vector *u ;
    int nobs = 0 ;

    if ( *stationsp == 0 ) {
	*stationsp = newarr(0) ; 
	*arraysp = newarr(0) ; 
    }
    stations = *stationsp ; 
    arrays = *arraysp ; 

    ta = *tap = newtbl(0) ;
    tu = *tup = newtbl(0) ;
    taro = *tapro = newtbl(0) ;
    turo = *tupro = newtbl(0) ;

    dbarr = dblookup ( db, 0, "arrival", 0, "dbSCRATCH" ) ; 
    dbsite = dblookup ( db, 0, "site", 0, 0 ) ; 

    arrival_tbl = pfget_tbl(pf, "arrival_table");
    narr = maxtbl(arrival_tbl);
    for (i = 0; i < narr; i++) {
	sscanf(gettbl(arrival_tbl, i),
	       "%d %s %s %lf %lf %s %lf %lf %s %lf %lf %s",
	       &arid,
	       sta,
	       iphase,
	       &time,
	       &deltim,
	       timedef,
	       &azimuth,
	       &delaz,
	       azdef,
	       &slow,
	       &delslo,
	       slodef
	    );

	if ( (station = getarr ( stations, sta ) ) == 0 ) {
	    dbputv ( dbarr, 0, "sta", sta, "time", time, NULL ) ; 
	    dbmatches ( dbarr, dbsite, 0, 0, &hook, &matching ) ;
	    if ( maxtbl(matching) < 1 ) {
		char *t ;
		complain ( 0, "No site table record for %s at time %s\n", 
		    sta, t=strtime(time));
		free(t) ;
		continue ;
	    }

	    dbsite.record = (long) gettbl(matching, 0) ;
	    freetbl(matching,0) ;
	    allot ( Station *, station, 1 ) ; 
	    allot ( Seismic_Array *, array, 1 ) ; 
	    dbgetv ( dbsite, 0, 
		"sta", station->name, "lat", &station->lat, "lon", &station->lon, "elev", &station->elev, NULL ) ;
	    dbgetv ( dbsite, 0, 
		"sta", array->name, "lat", &array->lat, "lon", &array->lon, "elev", &array->elev, NULL ) ;
	    setarr (stations, sta, station ) ; 
	    setarr (arrays, sta, array ) ; 
	} else {
Ejemplo n.º 18
0
int main(int argc, char **argv)
{
	SegyReel reel;
	SegyHead *header;
	char *dbin;
	char *outfile;
	FILE *fp;
	Pf *pf;  
	Arr *channels;  /* channel order list */
	Arr *table_list;  /* array of valid tables */
	int nchan;
	char *stest;

	float **traces;
	char reel1[3200];
	Dbptr db, trdb, dbj;
	Dbptr trdbss;  
	int nsamp0;
	double time0, endtime0, samprate0;
	long int nsamp;
	double samprate;
	int i,j;
	char stime[30],etime[30];
	char s[128];
	double tlength;
	double phi, theta;
	char *newchan_standard[3]={"X1","X2","X3"};
	char *trsubset="chan=~/X./";
	char *newchan[3]={"R","T","Z"};
	Tbl *sortkeys=newtbl(0);
	char sta[10],chan[10];
	double lat, lon, elev, dnorth, deast, edepth;
	char refsta[10];
	int total_traces=0;
	char *time_str;
	long int evid,shotid=1;
	int rotate=0;
	long int ntraces;
        int ichan;
	int map_to_cdp;  /* logical switch to output data like cdp stacked data */
	char *fmt="%Y %j %H %M %S %s";
	char *pfname;
	int Verbose=0;
	/* New features added 2009 */
	/* this is a boolean.  If true (nonzero) it is assumed stdin will
	contain four numbers:  time,lat, lon, elev.  If false, only the
	time field is read and remainder of any input on each line is dropped.*/
	int input_source_coordinates;
	/* scale factor for source coordinates.  Needed because segy uses
	an int to store source coordinates.  Sensible choices are 
	3600 for arc seconds and 10000 for a pseudodecimal. Note this
	parameter is ignored unless input_source_coordinates is true.*/
	int coordScale;
	/* If true use passcal 32 bit extension num_samps as record length. 
	SEGY standard uses a 16 bit entry that easily overflows with large
	shots at long offset.  In this ase assume the 16 bit quantity is
	meaningless. */
	int use_32bit_nsamp;
	/* This is switched on by argument switch.  When set to a nonzero
	(default) the reel headers are written.  When 0 `
	the reel heades will not be written -- used by seismic unix 
r
	and passcal*/
	int write_reel_headers=1;
	char *substr=NULL;

	if(argc < 3) usage();
	dbin = argv[1];
	outfile = argv[2];
	pfname = NULL;
	for(i=3;i<argc;++i)
	{
		if(!strcmp(argv[i],"-pf"))
		{
			++i;
			pfname = argv[i];
		}
		else if(!strcmp(argv[i],"-SU"))
		{
			write_reel_headers=0;
		}
		else if(!strcmp(argv[i],"-v"))
		{
			Verbose=1;
		}
		else if(!strcmp(argv[i],"-ss"))
		{
			++i;
			substr=argv[i];
		}
		else
		{
			usage();
		}
	}
	if(pfname == NULL) pfname = strdup("db2segy");

	elog_init(argc, argv);

	if(pfread(pfname,&pf)) 
		elog_die(0,"pfread error for pf file %s.pf\n",argv[0]);
	/* rotation parameters */
	rotate=pfget_boolean(pf,"rotate");
	if(rotate)
	{
		phi = pfget_double(pf,"phi");
		theta = pfget_double(pf,"theta");
	}
	/* This function creates the channel order list keyed by
	station channel names */
	channels = build_stachan_list(pf,&nchan,Verbose);

	map_to_cdp = pfget_boolean(pf,"map_to_cdp");
	if(map_to_cdp && Verbose) 
		fprintf(stdout,"Casting data as CDP stacked section\n");
	if(dbopen(dbin,"r",&db) == dbINVALID) 
	{
		fprintf(stderr,"Cannot open db %s\n", dbin);
		usage();
	}
	/* We grab the sample rate and trace length (in seconds) and
	use this to define global sample rates for the data.  
	segy REQUIRES fixed length records and sample rates, so
	irregular sample rates will cause this program to die. 
	One could add a decimate/interpolate function, but this 
	is not currently implemented */
	samprate0 = pfget_double(pf,"sample_rate");
	tlength = pfget_double(pf,"trace_length");
	nsamp0 = (int)(tlength*samprate0);
	use_32bit_nsamp=pfget_boolean(pf,"use_32bit_nsamp");

	/* nsamp in segy is a 16 bit field.  Handling depends on
	setting of use_32bit_nsamp boolean */
	if(nsamp0 > 32767) 
	{
	    if(use_32bit_nsamp)
	    {
	    	elog_notify(0,"Warning:  segy ues a 16 bit entity to store number of samples\nThat field is garbage. Using the 32 bit extension field.\n");
	    }
	    else
	    {
		elog_complain(0,
		  "Warning:  segy uses a 16 bit entity to store number of samples\nRequested %d samples per trace.  Trucated to 32767\n",nsamp0);
		nsamp0 = 32767;
	    }
	}
	input_source_coordinates=pfget_boolean(pf,"input_source_coordinates");
	if(input_source_coordinates)
	{
		coordScale=pfget_int(pf,"coordinate_scale_factor");
	}
	else
	{
		coordScale=1;
	}
	/* boolean.  When nonzero set coordinates as geographic arc seconds values */
	int use_geo_coordinates=pfget_boolean(pf,"use_geo_coordinates");
	/* check list of tables defined in pf.  Return array of
	logicals that define which tables are valid and join 
	tables. */
	table_list = check_tables(db,pf);
	check_for_required_tables(table_list);
	dbj = join_tables(db,pf,table_list);
	if(dbj.record == dbINVALID) elog_die(0,"dbjoin error\n");
	if(substr!=NULL) dbj=dbsubset(dbj,substr,0);
	long int ndbrows;
	dbquery(dbj,dbRECORD_COUNT,&ndbrows);
	if(ndbrows<=0)
	{
		fprintf(stderr,"Working database view is empty\n");
		if(substr!=NULL) fprintf(stderr,"Subset condtion =%s a likely problem\n",
				substr);
		usage();
	}

	fp = fopen(outfile,"w");
	if(fp == NULL) 
	{
		fprintf(stderr,"Cannot open output file %s\n",outfile);
		usage();
	}

	/* These are needed for sort below */
	pushtbl(sortkeys,"sta");
	pushtbl(sortkeys,"chan");

	/*The reel1 header in true blue segy is ebcdic.  We are goingto 
	just fill it with nulls and hope for the best */
	for(i=0;i<3200;i++) reel1[i] = '\0';

	/* Just blindly write this turkey. Bad form, but tough*/
	if(write_reel_headers) fwrite(reel1,1,3200,fp);

	/* memory allocation for trace data.  This is a large matrix
	that is cleared for each event.  This model works because of
	segy's fixed length format.  This routine is a descendent of
	numerical recipes routine found in libgenloc.  This is not
	the most efficient way to do this, but it simplifies the
	algorithm a lot. */
	traces = matrix(0,nchan,0,nsamp0);
	if(traces == NULL) 
		elog_die(0,"Cannot alloc trace data matrix work space of size %d by %d\n",
			nchan, nsamp0);
	header = (SegyHead *)calloc((size_t)nchan,sizeof(SegyHead));
	if(header == NULL)
			elog_die(0,"Cannot alloc memory for %d segy header workspace\n",nchan);
	if(write_reel_headers)
	{

		/* now fill in the binary reel header and write it */
		reel.kjob = 1;
		reel.kline = 1;
		reel.kreel = 1;
		reel.kntr = (int16_t)nchan;
		reel.knaux = 0;
		reel.sr = (int16_t)(1000000.0/samprate0);
		reel.kfldsr = reel.sr;
		reel.knsamp = (int16_t)nsamp0;
		reel.kfsamp = (int16_t)nsamp0;
		reel.dsfc=5;  /* This is ieee floats*/
		reel.kmfold = 0;
		if(map_to_cdp)
			reel.ksort = 2;
		else
			reel.ksort = 1;
		reel.kunits = 1;  /* This sets units to always be meters */
		for(i=0;i<344;++i)reel.unused2[i]='\0';
	
		if(fwrite((void *)(&reel),sizeof(SegyReel),1,fp) != 1) 
		{
			fprintf(stderr,"Write error for binary reel header\n");
			exit(-2);
		}
	}

	/* Now we enter a loop over stdin reading start times.  
	Program will blindly ask for data from each start time to 
	time+tlength.  The trace buffer will be initialized to 
	zeros at the top of the loop always.  If nothing is found
	only zeros will be written to output.  
	*/
	while((stest=fgets(s,80,stdin)) != NULL)
	{
		double slat,slon,selev;  /* Used when reading source location*/
		if(Verbose)
			fprintf(stdout,"Processing:  %s\n",s);
		for(i=0;i<nchan;++i)
		{
			initialize_header(&(header[i]));
			header[i].lineSeq = total_traces + i + 1;
			header[i].reelSeq = header[i].lineSeq;
			if(map_to_cdp)
			{
				header[i].cdpEns = i + 1;
				header[i].traceInEnsemble = 1;  /* 1 trace per cdp faked */
			}
			else
			{
				header[i].channel_number = i + 1;
			}
			header[i].event_number = shotid;
			header[i].energySourcePt=shotid;
			for(j=0;j<nsamp0;++j)  traces[i][j] = (Trsample)0.0;
		}
		if(input_source_coordinates)
		{
			char stmp[40];
			sscanf(s,"%s%ld%lf%lf%lf",stmp,&shotid,&slon,&slat,&selev);
			time0=str2epoch(stmp);
		}
		else
		{
			time0 = str2epoch(s);
		}
		endtime0 = time0 + tlength;
		sprintf(stime,"%20.4f",time0);
		sprintf(etime,"%20.4f",endtime0);
		trdb.database = -1;
		if(trload_css(dbj,stime,etime,&trdb,0, 0) < 0)
		{
			if(Verbose) 
			{
			  fprintf(stdout,"trload_css failed for shotid=%ld",shotid);
			  fprintf(stdout,"  No data in time range %s to %s\n",
			  	strtime(time0),strtime(endtime0) );
			  fprintf(stdout,"No data written for this shotid block.");
			  fprintf(stdout,"  Handle this carefully in geometry definitions.\n");
			}

			continue;
		}
		/* This does gap processing */
		repair_gaps(trdb);
		
		trapply_calib(trdb);
			
		if(rotate)
		{
			if(rotate_to_standard(trdb,newchan_standard))
				elog_notify(0,"Data loss in rotate_to_standard for event %s to %s\n",
					stime, etime);
			/* This is need to prevent collisions of channel 
			names */
			trdbss = dbsubset(trdb,trsubset,0);
			if(trrotate(trdbss,phi,theta,newchan))
				elog_notify(0,"Data loss in trrotate for event %s to %s\n",
					stime, etime);
		}
		if(Verbose)
			fprintf(stdout,"Station  chan_name  chan_number seq_number shotid  evid\n");
		trdb = dbsort(trdb,sortkeys,0,0);
		dbquery(trdb,dbRECORD_COUNT,&ntraces);
		if(Verbose) fprintf(stdout,"Read %ld traces for event at time%s\n",
			ntraces,strtime(time0));
		for(trdb.record=0;trdb.record<ntraces;++trdb.record)
		{
			Trsample *trdata;
			if(dbgetv(trdb,0,
			    "evid",&evid,
			    "sta",sta,
			    "chan",chan,
			    "nsamp", &nsamp,
			    "samprate",&samprate,
			    "data",&trdata,
			    "lat", &lat,
			    "lon", &lon,
			    "elev",&elev,
			    "refsta",refsta,
			    "dnorth",&dnorth,
			    "deast",&deast,
			    "edepth",&edepth,
					NULL) == dbINVALID)
			{
				elog_complain(0," dbgetv error reading record %ld\nTrace will be skipped for station %s and channel %s\n",
				trdb.record,sta,chan);
				continue;
			}
			/* Allow 1 percent samprate error before killing */
			double fsrskew=fabs((samprate-samprate0)/samprate0);
			double frskewcut=0.01;
			if(fsrskew>frskewcut) 
			{
				elog_complain(0,"%s:%s sample rate %f is significantly different from base sample rate of %f\nTrace skipped -- segy requires fixed sample rates\n",
					sta,chan,samprate,samprate0);
				continue;
			}
			if(nsamp > nsamp0)
			{
				elog_complain(0,"%s:%s trace has extra samples=%ld\nTruncated to length %d\n",
					sta, chan, nsamp, nsamp0);
				nsamp = nsamp0;
			}
			else if(nsamp < nsamp0)
			{
				elog_complain(0,"%s:%s trace is shorter than expected %d samples\nZero padded after sample %ld\n",
					sta, chan, nsamp0, nsamp);
			}

			ichan = get_channel_index(channels,sta,chan);
			if(ichan > nchan) elog_die(0,"Channel index %d outside limit of %d\nCannot continue\n",
					ichan, nchan);
			if(ichan >= 0)
			{
				if(Verbose) 
				   fprintf(stdout,"%s:%s\t%-d\t%-d\t%-ld\t%-ld\n",
					sta,chan,ichan+1,
                                        header[ichan].reelSeq,
					shotid, evid);
				header[ichan].traceID = 1;
				for(j=0;j<nsamp;++j) 
				   traces[ichan][j] = (float)trdata[j];
				/* header fields coming from trace table */
				header[ichan].samp_rate = (int32_t)
						(1000000.0/samprate0);
				if(!use_geo_coordinates && ( coordScale==1))
				{
				  header[ichan].recLongOrX = (int32_t)(deast*1000.0);
				  header[ichan].recLatOrY = (int32_t)(dnorth*1000.0);
				}
				else
				{
				/* Note negative here.  This is a oddity
				of segy that - means divide by this to
				get actual.  Always make this negative in case 
				user inputs a negative number. */
				  header[ichan].coordScale=-abs(coordScale);
				  /* Force 2 = geographic coordinates.  Standard says when this is
				  so units are arc seconds, hence we multiply deg by 3600*coordScale */
				  if(use_geo_coordinates)
				  {
				    header[ichan].coordUnits=2;
				    header[ichan].recLongOrX
				     =(int32_t)(lon*3600.0*(double)coordScale);
				    header[ichan].recLatOrY
				     =(int32_t)(lat*3600.0*(double)coordScale);
				  }
				  else
				  {
				    header[ichan].recLongOrX
				     =(int32_t)(lon*(double)coordScale);
				    header[ichan].recLatOrY
				     =(int32_t)(lat*(double)coordScale);
				  }
				}
				header[ichan].recElevation = (int32_t)(elev*1000.0);
				header[ichan].deltaSample = (int16_t) 
						(1000000.0/samprate0);
				header[ichan].sampleLength = (int16_t)nsamp0;
				header[ichan].num_samps = (int32_t)nsamp0;
				/* This cracks the time fields */
				time_str = epoch2str(time0,fmt);
				sscanf(time_str,"%hd %hd %hd %hd %hd %hd",
					&header[ichan].year,
					&header[ichan].day,
					&header[ichan].hour,
					&header[ichan].minute,
					&header[ichan].second,
					&header[ichan].m_secs);
				/* These are PASSCAL extensions, but we'll
				go ahead and set them anyway.*/
				header[ichan].trigyear = header[ichan].year;
				header[ichan].trigday = header[ichan].day;
				header[ichan].trighour = header[ichan].hour;
				header[ichan].trigminute = header[ichan].minute;
				header[ichan].trigsecond = header[ichan].second;
				free(time_str);
				if(input_source_coordinates)
				{
				  if(use_geo_coordinates)
				  {
					slat*=3600.0;
					slon*=3600.0;
				  }
				  header[ichan].sourceLongOrX
				    =(int32_t)(slon*(double)coordScale);
				  header[ichan].sourceLatOrY
				    =(int32_t)(slat*(double)coordScale);
				  header[ichan].sourceSurfaceElevation
				             =(int32_t)selev;
				  /* No easy way to specify both elev and depth*/
				  header[ichan].sourceDepth=0;
				}
				else if(map_to_cdp)
				{
				/* When faking CDP data we make this look 
				like a zero offset, single fold data set */
				  header[ichan].sourceLongOrX = header[ichan].recLongOrX;
				  header[ichan].sourceLatOrY = header[ichan].recLatOrY;
				  header[ichan].sourceSurfaceElevation = header[ichan].recElevation;
				  header[ichan].sourceDepth = 0;
				  header[ichan].sourceToRecDist = 0;
				}
				else
				{
				/* This is the mechanism for adding other
				information with added tables.  The one
				table currently supported is a "shot" table 
				that holds shot coordinates.  If other tables
				were added new functions could be added with
				a similar calling sequence.  This procedure
				silently does nothing if a shot table is not
				present.*/
					set_shot_variable(db,table_list,
						evid,&header[ichan]);
				}
			}			
			else
			{
				if(Verbose)
					fprintf(stdout,"Station %s and channel %s skipped\n",
						sta,chan);
			}

		}
		/* Now we write the data */
		for(i=0;i<nchan;++i)
		{
			if(fwrite((void *)(&(header[i])),sizeof(SegyHead),1,fp) != 1)
				elog_die(0,"Write error on header for trace %d\n",total_traces+i);		
			if(fwrite((void *)traces[i],sizeof(float),
					(size_t)nsamp0,fp) != nsamp0)
				elog_die(0,"Write error while writing data for trace %d\n",
					total_traces+i);
		}
		total_traces += nchan;
		trdestroy(&trdb);		
		if(!input_source_coordinates) ++shotid;
	}
	return 0 ;
}
Ejemplo n.º 19
0
main ( int argc, char **argv )

{
	char orbname[20]="zagsun6";
	int orb;
	tstations_struc stations ;
	char name[5] = "ORB" ;
	char sname[5] = "Q003" ;
	short int data_mask = CSIM_DATA ;
	pclient_struc client ;
	pclient_station station ;
	pdata_user data ;
	boolean alert_flag ;
	int ret ;
	int i, j ;
	Steim *blockette;
	int *sdata, npts;
	PktChannel pktchan;
	unsigned short int quality = 0;
	unsigned short int pinno = 0;
	char *packet = NULL;
	int nbytes = 0;
	int bufsiz = 0;
	char srcname[256];
	int fix_MOTA=0;
	int fix_WATA=0;
	int fix_SQTA=0;
	/*
	double fouryears=epoch(2004000)-epoch(1996000);
	double eightyears=epoch(2004000)-epoch(1996000);
	double twelveyears=epoch(2008000)-epoch(1996000);
	double twentyyears=epoch(2016000)-epoch(1996000);
	  */
	double sixteenyears=epoch(2012000)-epoch(1996000);
    Pf *mypf;


	/* Niko, leap second July 2012 */
	/* subtract another second for the leap-second 2006-01-01 */
	/* no more... Udo corrected the time again...
	eightyears -= 1;
	sixteenyears -= 1.0;
	*/
	/*schaltsekunde 2009-01-01*/
	/*double twokohnine=epoch(2009001); */

	elog_init ( argc, argv ) ;

	if (argc < 2) {
		usage();
		exit (1);
	}
	/*strcpy(orbname,"zagsun6");*/
	/*orbname = argv[2];*/
	strncpy (sname, argv[1], 4);
	sname[4] = '\0';
	for (argc-=3,argv+=3; argc>0; argc--,argv++) {
		if (!strcmp(*argv, "-v")) {
			verbose = 1;
		} else {
			fprintf (stderr, "cs2orb: Unrecognized option '%s'.\n", *argv);
			usage();
			exit (1);
		}
	}

putenv("PFPATH=/home/comserv/pf");
    if ( pfread ( "cs2orb", &mypf ) != 0 ) 
                die ( 1, "Can't read parameter file\n" ) ; 
    fix_MOTA=pfget_int(mypf,"MOTA");
    fix_WATA=pfget_int(mypf,"WATA");
    fix_SQTA=pfget_int(mypf,"SQTA");

	/* orb setup stuff */

	orb = orbopen (orbname, "w&");
	if (orb < 0) {
		clear_register (1);
		fprintf (stderr, "cs2orb: orbopen() error for '%s'.\n", orbname);
		exit (1);
	}

	/* comserv setup stuff */

	cs_setup (&stations, name, sname, TRUE, TRUE, 10, 5, data_mask , 6000) ;
	client = cs_gen ( &stations ) ;

	/* Trace setup stuff */

	blockette = newsteim();
	blockette->record_size = 512 ;

	/* Data packet read loop */

	while (1) {
		/* Look for a packet */
		ret = cs_scan ( client , &alert_flag ) ;

		/* Sleep and loop if nothing there */
		if (ret == -1) { sleep (1); continue; }

		/* Grab the station structure pointer */
		station = (pclient_station) ((long int) client + client->offsets[ret]) ;

		/* Printout station status */
		if (alert_flag) {
			complain (0, "Station %4s status: %s\n", long_str(station->name.l), &(stats[station->status])) ;
		}

		/* Sleep and loop if no valid data */
		if (!(station->valdbuf)) { sleep (1); continue; }

		/* Grab the data buffer pointer */
		data = (pdata_user) ((long int) client + station->dbufoffset) ;

		/* Loop over number of data buffers */
		for (i=0; i<station->valdbuf; i++,data=(pdata_user) ((long int)data + station->dbufsize)) {

			/* Set data blockette record */
			blockette->record = (pvoid) &(data->data_bytes) ;

			/* Parse the SEED header */
			if ( parse_seed_data_header( blockette ) ) {
				complain ( 0, "Problems parsing SEED header or 1000 blockette.\n" ) ;
				continue ;
			}
			/* niko netzname at fuer antelope */
			strcpy (blockette->sdh.net,"OE");
			
			sprintf (srcname, "%s_%s_%s", blockette->sdh.net, blockette->sdh.sta, blockette->sdh.chan);
			if (verbose) printf ("%s:", srcname);

			/* Not a data packet */
			if (!(blockette->sdh.nsamp) || !(blockette->sdh.samprate_factor)) {
				if (verbose) printf (" No data\n");
				continue;
			}

			if (verbose) printf ("%s", strtime(blockette->sdh.epoch));

			/* Uncompress the data */
			if ( usteim (blockette, &sdata, &npts) ) {
				clear_register (1);
				continue;
			}

			if (verbose) {
				for (j=0; j<10; j++) printf (" %5d", sdata[j]);
				printf ("\n");
			}

			/* Stuff packet for orb */
			strcpy (pktchan.net, blockette->sdh.net);
			
			strcpy (pktchan.sta, blockette->sdh.sta);
			strcpy (pktchan.chan, blockette->sdh.chan);
			/* pktchan.time = blockette->sdh.epoch+eightyears; 
			pktchan.time = blockette->sdh.epoch+twelveyears; */
			pktchan.time = blockette->sdh.epoch+sixteenyears;
			/*pktchan.time = blockette->sdh.epoch+twentyyears;*/
			pktchan.samprate = blockette->sdh.samprate;
			switch (pktchan.chan[0]) {
				case 'H':	pktchan.calib = 1.589446;
						break;
				/*
				case 'E':	pktchan.calib = 0.06/0.707;
				changed to 0.257 (~0.36*0.707)
				*/
				case 'E':	pktchan.calib = 0.257;		
				/* 
				incl. dämpfung -> stimmt wenn antelope diesen wert mit TF multipl.
				*/
						break;
				default:	pktchan.calib = 1.0;
						break;
			}
			
			if (!strcmp(pktchan.sta,"GAGA")) {
				/*Uhrenkorrektur template  */
				pktchan.time -= 1.0;
			}
			if (!strcmp(pktchan.sta,"no-MOTA")) {
				/*Uhrenkorrektur MOTA  */
				pktchan.time -= 1.0;
			}
			if ( fix_MOTA != 0 && !strcmp(pktchan.sta,"MOTA")) {
				/*Uhrenkorrektur MOTA  */
				pktchan.time += (double)(fix_MOTA);
			}
			if (fix_SQTA != 0 && !strcmp(pktchan.sta,"SQTA")) {
				/*Uhrenkorrektur SQTA  */
				pktchan.time += (double)(fix_SQTA);
			}
			if ( fix_WATA !=0 && !strcmp(pktchan.sta,"WATA")) {
				/*Uhrenkorrektur WATA  */
				pktchan.time += (double)(fix_WATA);
			}
			/* solve the problem with omitted segtype, which chops the db */
			if (!strcmp(pktchan.sta,"OBKA")) {
				switch (pktchan.chan[1]) {
					case 'H':	strcpy(pktchan.segtype,"V");
						break;
					case 'L':	strcpy(pktchan.segtype,"A");
						break;
					default:	;
						break;
				}
				
			}
			/* pktchan.calib = 1.0; */
			pktchan.nsamp = blockette->sdh.nsamp;
			pktchan.data = sdata;
			pktchan.nbytes = 4*pktchan.nsamp;
			pktchan.datatype = trINT;
			if (!stuff_iwc_tracebuf ( quality, pinno, &pktchan, &packet, &nbytes, &bufsiz ) ) {
				complain (0, "stuff_iwc_tracebuf error.\n");
				exit (1);
			}

			/* Put to orb */
			if ( orbput ( orb, srcname, pktchan.time, packet, nbytes ) ) {
				complain (0, "orbput error.\n");
				exit (1);
			}
			orbflush (orb);
		}
	}
}
Ejemplo n.º 20
0
void
RYO2orbPacket_dump( FILE *fp, RYO2orbPacket *r2opkt )
{
	char	*s;
	char	enum_string[STRSZ];
	SatelliteInfo *si;
	int	isat;

	fprintf( fp, "Received RYO Packet of type %d timestamped '%s':\n",
			r2opkt->message_type, 
			s = strtime( r2opkt->time ) );

	free( s );
			
	fprintf( fp, "\t% 20s:\t%s\n", 
		     "site_id", r2opkt->site_id );

	fprintf( fp, "\t% 20s:\t%d\n", 
		     "site_index", r2opkt->site_index );

	fprintf( fp, "\t% 20s:\t%d\n", 
		     "site_count", r2opkt->site_count );

	fprintf( fp, "\t% 20s:\t%d\n", 
		     "GPS_week", r2opkt->GPS_week );

	fprintf( fp, "\t% 20s:\t%d\n", 
		     "GPS_millisecond", r2opkt->GPS_millisecond );

	fprintf( fp, "\t% 20s:\t%f\n", "ITRF X", r2opkt->XYZT[0] );
	fprintf( fp, "\t% 20s:\t%f\n", "ITRF Y", r2opkt->XYZT[1] );
	fprintf( fp, "\t% 20s:\t%f\n", "ITRF Z", r2opkt->XYZT[2] );
	fprintf( fp, "\t% 20s:\t%f\n", "ITRF T", r2opkt->XYZT[3] );

	fprintf( fp, "\t% 20s:\t%f\n", "LAT(rad)", r2opkt->lat_radians );
	fprintf( fp, "\t% 20s:\t%f\n", "LON(rad)", r2opkt->lon_radians );
	fprintf( fp, "\t% 20s:\t%f\n", "LAT(deg)", r2opkt->lat_deg );
	fprintf( fp, "\t% 20s:\t%f\n", "LON(deg)", r2opkt->lon_deg );
	fprintf( fp, "\t% 20s:\t%f\n", "HEIGHT(m)", r2opkt->height_m );

	fprintf( fp, "\t% 20s:\t%d\n", 
		     "position_byte", r2opkt->position_byte );

	fprintf( fp, "\t% 20s:\t%d\n", 
		     "flags_byte", r2opkt->flags_byte );

	switch( r2opkt->position_signal ) {
	case RYO_SIGNAL_UNDETERMINED:
		strcpy( enum_string, "Undetermined" );
		break;
	case RYO_SIGNAL_L1:
		strcpy( enum_string, "L1" );
		break;
	case RYO_SIGNAL_L1L2:
		strcpy( enum_string, "L1/L2" );
		break;
	}

	fprintf( fp, "\t% 20s:\t%s\n", "position_signal", enum_string );

	switch( r2opkt->position_method ) {
	case RYO_METHOD_UNDETERMINED:
		strcpy( enum_string, "Undetermined" );
		break;
	case RYO_METHOD_ABSCODE:
		strcpy( enum_string, "Absolute code" );
		break;
	case RYO_METHOD_RELCODE:
		strcpy( enum_string, "Relative code" );
		break;
	case RYO_METHOD_PHASEPLUSCODE:
		strcpy( enum_string, "Phase + code" );
		break;
	}

	fprintf( fp, "\t% 20s:\t%s\n", "position_method", enum_string );

	fprintf( fp, "\t% 20s:\t%d\n", 
		     "xyz_cov_present", r2opkt->xyz_cov_present );

	fprintf( fp, "\t% 20s:\t%d\n", 
		     "tropo_cov_present", r2opkt->tropo_cov_present );

	fprintf( fp, "\t% 20s:\t%d\n", 
		     "sat_info_present", r2opkt->sat_info_present );

	if( r2opkt->xyz_cov_present ) {

		fprintf( fp, "\t% 20s:\t%f\n", 
			     "variance_scale", r2opkt->variance_scale );

		fprintf( fp, "\t% 20s:\t%f\n", 
			     "variance_X", r2opkt->variance_X );

		fprintf( fp, "\t% 20s:\t%f\n", 
			     "variance_Y", r2opkt->variance_Y );

		fprintf( fp, "\t% 20s:\t%f\n", 
			     "variance_Z", r2opkt->variance_Z );

		fprintf( fp, "\t% 20s:\t%f\n", 
			     "covariance_YX", r2opkt->covariance_YX );

		fprintf( fp, "\t% 20s:\t%f\n", 
			     "covariance_YZ", r2opkt->covariance_YZ );

		fprintf( fp, "\t% 20s:\t%f\n", 
			     "covariance_ZX", r2opkt->covariance_ZX );
	}

	if( r2opkt->tropo_cov_present ) {

		fprintf( fp, "\t% 20s:\t%f\n", 
			     "variance_T", r2opkt->variance_T );

		fprintf( fp, "\t% 20s:\t%f\n", 
			     "covariance_TX", r2opkt->covariance_TX );

		fprintf( fp, "\t% 20s:\t%f\n", 
			     "covariance_TY", r2opkt->covariance_TY );

		fprintf( fp, "\t% 20s:\t%f\n", 
			     "covariance_TZ", r2opkt->covariance_TZ );
	}


	if( r2opkt->sat_info_present ) {
		
		fprintf( fp, "\t% 20s:\t%d\n", 
			     "satellite_count", r2opkt->satellite_count );
		
		fprintf( fp, "\t% 20s:\t%f\n", 
			     "pdop", r2opkt->pdop );

		fprintf( fp, "\t% 20s:\n", "satellites" );

		fprintf( fp, "\t          " );
		fprintf( fp, "% 6s  ", "SV PRN" );
		fprintf( fp, "% 5s  ", "Elev" );
		fprintf( fp, "% 5s  ", "Az" );
		fprintf( fp, "% 5s  ", "flags" );
		fprintf( fp, "% 9s ", "eph_avail" );
		fprintf( fp, "% 8s ", "L1_track" );
		fprintf( fp, "% 8s ", "L2_track" );
		fprintf( fp, "\n" );

		for( isat = 0; isat < r2opkt->satellite_count; isat++ ) {

			si = gettbl( r2opkt->satellites, isat );

			fprintf( fp, "\t          " );
			fprintf( fp, "% 6d  ", si->sv_prn );
			fprintf( fp, "% 5d  ", si->elevation );
			fprintf( fp, "% 5d  ", si->azimuth );
			fprintf( fp, "% 5d  ", si->prn_flags );
			fprintf( fp, "% 8d  ", si->ephemeris_available );
			fprintf( fp, "% 8d  ", si->L1_track );
			fprintf( fp, "% 8d  ", si->L2_track );
			fprintf( fp, "\n" );
		}
	}

	fprintf( fp, "\n" );

	return;
}
Ejemplo n.º 21
0
void
callgraph_print (int verbose)
{
  _("Call graph:\n");
  _("\n");

  const char *prefix;
  unsigned long long time = trace_get_total_runtime();

  prefix = strtime(&time);

  unsigned int nfunctions = function_get_nfunctions();

  _(" total runtime:                      %llu %sseconds\n", time, prefix);
  _(" total number of function calls:     %llu\n", function_get_total_calls());
  _(" total number of distinct functions: %u\n", nfunctions);
  _("\n");
  _("          %%           self     children\n");
  _("  index  time          time      time       called       name\n");

  function *functions = function_get_all();

  unsigned int i;
  for (i = 0; i < nfunctions; ++i)
    {
      function *f = functions + i;

      // print parents
      unsigned int j;
      for (j = 0; j < f->ncallers; ++j)
        {
          if (f->callers[j].function_id == (unsigned int)-1)
            {
              _("                                       %8lu/%-8lu      <spontaneous>\n", f->callers[j].calls, f->calls);
            }
          else
            {
              time = f->callers[j].self_time;
              prefix = strtime(&time);
              _("                   %6llu %ss ", time, prefix);

              time = f->callers[j].children_time;
              prefix = strtime(&time);
              _("%6llu %ss ", time, prefix);

              _("%8lu/%-8lu  ", f->callers[j].calls, f->calls);

              if (!strcmp(functions[f->callers[j].function_id].name, "??"))
                _("    0x%" PRIxPTR , functions[f->callers[j].function_id].address);
              else
                _("    %s", functions[f->callers[j].function_id].name);
              _(" [%u]\n", f->callers[j].function_id);
            }
        }

      // print self
      time = trace_get_total_runtime();
      _(" %6u %6.2f     ", i, (100.0 * (f->self_time + f->children_time)) / time);

      time = f->self_time;
      prefix = strtime(&time);
      _("%6llu %ss ", time, prefix);

      time = f->children_time;
      prefix = strtime(&time);
      _("%6llu %ss ", time, prefix);

      _("%8lu           ", f->calls);

      if (!strcmp(f->name, "??"))
        _("0x%" PRIxPTR , f->address);
      else
        _("%s", f->name);
      _(" [%u]\n", i);

      // print children
      for (j = 0; j < f->ncallees; ++j)
        {
          time = f->callees[j].self_time;
          prefix = strtime(&time);
          _("            %6.2f %6llu %ss ", (100.0 * (f->callees[j].self_time + f->callees[j].children_time)) / (f->self_time + f->children_time), time, prefix);

          time = f->callees[j].children_time;
          prefix = strtime(&time);
          _("%6llu %ss ", time, prefix);

          _("%8lu/%-8lu  ", f->callees[j].calls, functions[f->callees[j].function_id].calls);

          if (!strcmp(functions[f->callees[j].function_id].name, "??"))
            _("    0x%" PRIxPTR , functions[f->callees[j].function_id].address);
          else
            _("    %s", functions[f->callees[j].function_id].name);
          _(" [%u]\n", f->callees[j].function_id);
        }

      _(" -------------------------------------------------------\n");
    }

  _("\n");

  if (verbose >= 1)
    {
      _(" This table describes the call tree of the program, and was\n");
      _(" sorted by the total amount of time spent in and below each\n");
      _(" function in the call graph.\n");
      _("\n");
      _(" Each entry in this table consists of several lines. The line\n");
      _(" with the index number at the left hand margin lists the current\n");
      _(" function, and the lines above it lists the functions callers, and\n");
      _(" the functions below it list the functions callees.\n");
      _("\n");
      _(" The current function line lists:\n");
      _("   index      A unique function identifier that is also referenced\n");
      _("              in the name field of this listing.\n");
      _("\n");
      _("   %%          This is the percantage of the total time spent in and\n");
      _("   time       below this function in the call tree.\n");
      _("\n");
      _("   self       This is the total amount of time spent in this function.\n");
      _("   time       \n");
      _("\n");
      _("   children   This is the total amount of time spent in the descendants\n");
      _("   time       of this function.\n");
      _("\n");
      _("   calls      This is the number of times this function was invoked.\n");
      _("\n");
      _("   name       The name of the function.\n");
      _("\n");
      _(" For the functions callers, the fields have the following meaning:\n");
      _("   self       This is the amount of time that was propagated directly\n");
      _("   time       from the function into this caller.\n");
      _("\n");
      _("   children   This is the amount of time that was propagated from the\n");
      _("   time       functions children into this caller.\n");
      _("\n");
      _("   calls      This is the number of times this caller called the function,\n");
      _("              out of the total number this function was called.\n");
      _("\n");
      _("   name       The name of the caller.\n");
      _("\n");
      _(" If the caller of a function can not be determined, it will be registered\n");
      _(" as <spontaneous> in the name field.\n");
      _("\n");
      _(" For the functions callees, the fields have the following meaning:\n");
      _("   self       This is the amount of time that was propagated directly from\n");
      _("   time       this callee into the function.\n");
      _("\n");
      _("   children   This is the amount of time that was propagated from the\n");
      _("   time       callees children into the function.\n");
      _("\n");
      _("   calls      This is the total number of times the callee function was\n");
      _("              called from the function, of the total times the callee was\n");
      _("              called.\n");
      _("\n");
      _("   name       The name of the callee.\n");
      _("\n");
    }
}
Ejemplo n.º 22
0
int
RTMP_HashSWF(const char *url, unsigned int *size, unsigned char *hash,
             int age) {
    FILE *f = NULL;
    char *path, date[64], cctim[64];
    long pos = 0;
    time_t ctim = -1, cnow;
    int i, got = 0, ret = 0;
    unsigned int hlen;
    struct info in = {0};
    struct HTTP_ctx http = {0};
    HTTPResult httpres;
    z_stream zs = {0};
    AVal home, hpre;

    date[0] = '\0';
#ifdef _WIN32
#ifdef XBMC4XBOX
    hpre.av_val = "Q:";
    hpre.av_len = 2;
    home.av_val = "\\UserData";
#else
    hpre.av_val = getenv("HOMEDRIVE");
    hpre.av_len = strlen(hpre.av_val);
    home.av_val = getenv("HOMEPATH");
#endif
#define DIRSEP	"\\"

#else /* !_WIN32 */
    hpre.av_val = "";
    hpre.av_len = 0;
    home.av_val = getenv("HOME");
#define DIRSEP    "/"
#endif
    if (!home.av_val)
        home.av_val = ".";
    home.av_len = strlen(home.av_val);

    /* SWF hash info is cached in a fixed-format file.
     * url: <url of SWF file>
     * ctim: HTTP datestamp of when we last checked it.
     * date: HTTP datestamp of the SWF's last modification.
     * size: SWF size in hex
     * hash: SWF hash in hex
     *
     * These fields must be present in this order. All fields
     * besides URL are fixed size.
     */
    path = malloc(hpre.av_len + home.av_len + sizeof(DIRSEP ".swfinfo"));
    sprintf(path, "%s%s" DIRSEP ".swfinfo", hpre.av_val, home.av_val);

    f = fopen(path, "r+");
    while (f) {
        char buf[4096], *file, *p;

        file = strchr(url, '/');
        if (!file)
            break;
        file += 2;
        file = strchr(file, '/');
        if (!file)
            break;
        file++;
        hlen = file - url;
        p = strrchr(file, '/');
        if (p)
            file = p;
        else
            file--;

        while (fgets(buf, sizeof(buf), f)) {
            char *r1;

            got = 0;

            if (strncmp(buf, "url: ", 5))
                continue;
            if (strncmp(buf + 5, url, hlen))
                continue;
            r1 = strrchr(buf, '/');
            i = strlen(r1);
            r1[--i] = '\0';
            if (strncmp(r1, file, i))
                continue;
            pos = ftell(f);
            while (got < 4 && fgets(buf, sizeof(buf), f)) {
                if (!strncmp(buf, "size: ", 6)) {
                    *size = strtol(buf + 6, NULL, 16);
                    got++;
                }
                else if (!strncmp(buf, "hash: ", 6)) {
                    unsigned char *ptr = hash, *in = (unsigned char *) buf + 6;
                    int l = strlen((char *) in) - 1;
                    for (i = 0; i < l; i += 2)
                        *ptr++ = (HEX2BIN(in[i]) << 4) | HEX2BIN(in[i + 1]);
                    got++;
                }
                else if (!strncmp(buf, "date: ", 6)) {
                    buf[strlen(buf) - 1] = '\0';
                    strncpy(date, buf + 6, sizeof(date));
                    got++;
                }
                else if (!strncmp(buf, "ctim: ", 6)) {
                    buf[strlen(buf) - 1] = '\0';
                    ctim = make_unix_time(buf + 6);
                    got++;
                }
                else if (!strncmp(buf, "url: ", 5))
                    break;
            }
            break;
        }
        break;
    }

    cnow = time(NULL);
    /* If we got a cache time, see if it's young enough to use directly */
    if (age && ctim > 0) {
        ctim = cnow - ctim;
        ctim /= 3600 * 24;    /* seconds to days */
        if (ctim < age)        /* ok, it's new enough */
            goto out;
    }

    in.first = 1;
    HMAC_setup(in.ctx, "Genuine Adobe Flash Player 001", 30);
    inflateInit(&zs);
    in.zs = &zs;

    http.date = date;
    http.data = &in;

    httpres = HTTP_get(&http, url, swfcrunch);

    inflateEnd(&zs);

    if (httpres != HTTPRES_OK && httpres != HTTPRES_OK_NOT_MODIFIED) {
        ret = -1;
        if (httpres == HTTPRES_LOST_CONNECTION)
            RTMP_Log(RTMP_LOGERROR, "%s: connection lost while downloading swfurl %s",
                     __FUNCTION__, url);
        else if (httpres == HTTPRES_NOT_FOUND)
            RTMP_Log(RTMP_LOGERROR, "%s: swfurl %s not found", __FUNCTION__, url);
        else
            RTMP_Log(RTMP_LOGERROR, "%s: couldn't contact swfurl %s (HTTP error %d)",
                     __FUNCTION__, url, http.status);
    }
    else {
        if (got && pos)
            fseek(f, pos, SEEK_SET);
        else {
            char *q;
            if (!f)
                f = fopen(path, "w");
            if (!f) {
                int err = errno;
                RTMP_Log(RTMP_LOGERROR,
                         "%s: couldn't open %s for writing, errno %d (%s)",
                         __FUNCTION__, path, err, strerror(err));
                ret = -1;
                goto out;
            }
            fseek(f, 0, SEEK_END);
            q = strchr(url, '?');
            if (q)
                i = q - url;
            else
                i = strlen(url);

            fprintf(f, "url: %.*s\n", i, url);
        }
        strtime(&cnow, cctim);
        fprintf(f, "ctim: %s\n", cctim);

        if (!in.first) {
            HMAC_finish(in.ctx, hash, hlen);
            *size = in.size;

            fprintf(f, "date: %s\n", date);
            fprintf(f, "size: %08x\n", in.size);
            fprintf(f, "hash: ");
            for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
                fprintf(f, "%02x", hash[i]);
            fprintf(f, "\n");
        }
    }
    HMAC_close(in.ctx);
out:
    free(path);
    if (f)
        fclose(f);
    return ret;
}
Ejemplo n.º 23
0
int main (int argc,char *argv[]) {

  int arg;

  int status=0;

  struct CFitfp *cfitfp;
  gzFile gzfp=0;
  
  int yr,mo,dy,hr,mt;
  double sc;
 
  double atime;

  char *stmestr=NULL;
  char *etmestr=NULL;
  char *sdtestr=NULL;
  char *edtestr=NULL;
  char *exstr=NULL;

  double stime=-1;
  double etime=-1;
  double extime=0;
 
  double sdate=-1;
  double edate=-1;

  unsigned char vb=0;
  unsigned char help=0;
  unsigned char option=0;
  unsigned char set_channel=0;
  
  char *chnstr=NULL;
  char *cpstr=NULL;
  
  cfit=CFitMake();

  OptionAdd(&opt,"-help",'x',&help);
  OptionAdd(&opt,"-option",'x',&option);
  OptionAdd(&opt,"vb",'x',&vb);
  OptionAdd(&opt,"st",'t',&stmestr);
  OptionAdd(&opt,"et",'t',&etmestr);
  OptionAdd(&opt,"sd",'t',&sdtestr);
  OptionAdd(&opt,"ed",'t',&edtestr);
  OptionAdd(&opt,"ex",'t',&exstr);
  OptionAdd(&opt,"cp",'t',&cpstr);
  OptionAdd(&opt,"cn",'t',&chnstr);
  OptionAdd(&opt,"sc",'x',&set_channel);


  arg=OptionProcess(1,argc,argv,&opt,NULL);

  if (help==1) {
    OptionPrintInfo(stdout,hlpstr);
    exit(0);
  }


  if (option==1) {
    OptionDump(stdout,&opt);
    exit(0);
  }

  if  (argc-arg<1) {
    OptionPrintInfo(stderr,errstr);
    exit(1);
  }

  if (exstr !=NULL) extime=strtime(exstr);
  if (stmestr !=NULL) stime=strtime(stmestr);
  if (etmestr !=NULL) etime=strtime(etmestr);
  if (sdtestr !=NULL) sdate=strdate(sdtestr);
  if (edtestr !=NULL) edate=strdate(edtestr);

  if (cpstr !=NULL) cpid=atoi(cpstr);
   
  if (chnstr !=NULL) {
    if (tolower(chnstr[0])=='a') channel=1;
    if (tolower(chnstr[0])=='b') channel=2;
  }
    


  cfitfp=CFitOpen(argv[arg]);
  if (cfitfp==NULL) {
    fprintf(stderr,"File not found.\n");
    exit(-1);
  }

  if (CFitRead(cfitfp,cfit)==-1) {
    fprintf(stderr,"Error reading file\n");
    exit(-1);
  }
  atime=cfit->time;

  gzfp=gzdopen(fileno(stdout),"w");  

  /* skip here */

  if ((stime !=-1) || (sdate !=-1)) { 
    int yr,mo,dy,hr,mt;
    double sc;  
      
    if (stime==-1) stime= ( (int) atime % (24*3600));
    if (sdate==-1) stime+=atime - ( (int) atime % (24*3600));
    else stime+=sdate;


    TimeEpochToYMDHMS(stime,&yr,&mo,&dy,&hr,&mt,&sc);
    status=CFitSeek(cfitfp,yr,mo,dy,hr,mt,sc,NULL);
    if (status ==-1) {
      fprintf(stderr,"File does not contain the requested interval.\n");
      exit(-1);
    }
    if (CFitRead(cfitfp,cfit)==-1) {
      fprintf(stderr,"Error reading file\n");
      exit(-1);
    }
  } else stime=atime;
   
  if (etime !=-1) {
    if (edate==-1) etime+=atime - ( (int) atime % (24*3600));
    else etime+=edate;
  }
  if (extime !=0) etime=stime+extime;


  do {
    if ((etime !=-1) && (atime>=etime)) break;

    if ((cpid !=-1) && (cfit->cp !=cpid)) continue;
    if ((set_channel==0) &&
        (channel !=-1) && (cfit->channel !=channel)) continue;
 
    if (set_channel==1) cfit->channel=channel;
    
    status=CFitWrite(gzfp,cfit);
    
    atime=cfit->time;
    TimeEpochToYMDHMS(atime,&yr,&mo,&dy,&hr,&mt,&sc);
    if (vb==1) fprintf(stderr,"%d-%d-%d %d:%d:%d %.2d %.2d %.4d\n",
                            yr,mo,dy,hr,mt,
                            (int) sc,cfit->channel,
                            cfit->bmnum,cfit->cp);
 
  
  } while (CFitRead(cfitfp,cfit) !=-1);

  gzclose(gzfp);    
  CFitClose(cfitfp);
  return 0; 
} 
Ejemplo n.º 24
0
int sendmrc( int dasid, int timeout, int rep )

{

    int i, numdc, num;
    int nbytes;
    char buffer[64],
         echo_buf[64];
    char *iport, *s;


    /* Send DAS RC command to specific DAS  */
	     
  sprintf( &buffer[0], "RC%4dRC\0", dasid);
 
  numdc = maxtbl(DC);
  for( num = 0; num < numdc; num++ )  {

    iport = (char *) gettbl(DC, num );
    if( open_dc( iport) <= 0 )               
       elog_die(1, "Can't open command DC port\n");
		    
    for( i = 0; i < rep; i++ )  {
        nbytes = write ( Ls, (char *) buffer, LEN );
        if ( nbytes == LEN ) {
            if ( logname )
                if (fwrite (buffer, LEN, 1, fplog ) != 1)  
	              elog_die(1, "can't log a DC command  to log file %s\n", logname );
            nbytes = read( Ls, (char *) echo_buf, LEN);
            if( nbytes != LEN )  {
               elog_complain(0, "can't get an echo of a DC command - %s\n", buffer );
	       close( Ls );
	       if( open_dc( iport) <= 0 )               
	          elog_die( 1, "can't reopen DC port: %s\n", iport );
            } 
	    if( strncmp( buffer, echo_buf, strlen( buffer ))!= 0 )  {
                elog_complain(0, "echo != command (%s != %s)\n", buffer, echo_buf);
		if( strncmp( echo_buf, "EE", 2) == 0 ) {
		    elog_complain( 0, "DC rejected command:%s\n", buffer);
		    elog_complain(0, "re-sending...\n");
		} else {
		    close( Ls );
		    if( open_dc( iport) <= 0 )               
		         elog_die( 1, "can't reopen DC port: %s\n", iport );
		}
            }
            elog_complain( 0, "%s: send %s to %d on %s\n", 
	              s=strtime(now()), buffer, dasid, iport );
            free(s);

        } else { 
	   elog_complain(0, "can't send a DC command - %s on %s\n", buffer, iport );
           close( Ls );
           if( open_dc( iport) <= 0 )               
              elog_die( 1, "can't reopen DC port: %s\n", iport);
        }
        sleep(timeout); 

      }
      close(Ls);
  }
   return 1;
}
Ejemplo n.º 25
0
int
main(int argc, char **argv)
{
	double          modified_after =now() , last_lddate, last_mtime, mtime;
	char           *orbname = NULL;
	char           *dbname = NULL;
	int             orb;
	int             naptime = -1, check_lddate_interval = -1;
	Dbptr           db, dbt, dbs;
	char           *prefix = NULL;
	struct stat     filestat;
	int             i;
	Tbl            *tablenames, *tables_containing_dfile, *check_tables = NULL,
	               *ignore_tables = NULL;
	long            table_present, recc, is_view;
	char           *tablename, *schemaname;
	char           *filename;
	int             counter = 0, force_check = 0;
	char            expr[512];
	char           *statefilename = NULL, *pfname = "dbnew2orb";
	Pf             *pf = NULL;
	void           *priv_dfile = (void *) NULL;
	void           *private = (void *) NULL;
	int             pmsi;	/* poor man's string index, replacment for
				 * searchtbl... */
	char           *pmsp;
	double          lastburytime;
	Relic           relic;
	char           *s;
	Expression     *expr_lddate;
	double         *mtimes;
	double         *lddates;

	elog_init(argc, argv);

	if (argc < 2) {
		usage();
		exit(1);
	}
	for (argc--, argv++; argc > 0; argc--, argv++) {
		if (!strcmp(*argv, "-modified_after")) {
			argc--;
			argv++;
			if (argc < 1) {
				complain(0, "Need -modified_after argument.\n");
				usage();
				exit(1);
			}
			modified_after = str2epoch(*argv);
		} else if (!strcmp(*argv, "-prefix")) {
			argc--;
			argv++;
			if (argc < 1) {
				complain(0, "Need -prefix argument.\n");
				usage();
				exit(1);
			}
			prefix = *argv;
		} else if (!strcmp(*argv, "-pf")) {
			argc--;
			argv++;
			if (argc < 1) {
				complain(0, "Need -pf argument.\n");
				usage();
				exit(1);
			}
			pfname = *argv;
		} else if (!strcmp(*argv, "-state")) {
			argc--;
			argv++;
			if (argc < 1) {
				complain(0, "Need -state argument.\n");
				usage();
				exit(1);
			}
			statefilename = *argv;
		} else if (!strcmp(*argv, "-sleep")) {
			argc--;
			argv++;
			if (argc < 1) {
				complain(0, "Need -sleep argument.\n");
				usage();
				exit(1);
			}
			naptime = atoi(*argv);
		} else if (!strcmp(*argv, "-check_lddate_interval")) {
			argc--;
			argv++;
			if (argc < 1) {
				complain(0, "Need -check_lddate_interval argument.\n");
				usage();
				exit(1);
			}
			check_lddate_interval = atoi(*argv);
		} else if (!strcmp(*argv, "-v")) {
			verbose++;
		} else if (**argv != '-') {
			break;
		} else {
			complain(0, "Unrecognized argument '%s'.\n", *argv);
			usage();
			exit(1);
		}
	}


	if (pfread(pfname, &pf)) {
		elog_die(0, "parse_pf: pfread('%s') error.\n", pfname);
	}
	if (check_lddate_interval < 1) {
		if (parse_param(pf, "check_lddate_interval", P_LINT, 1, &check_lddate_interval) < 0) {
			elog_die(1, "parse_pf: sleep check_lddate_interval needed!\n");
		} else {
			if (check_lddate_interval < 0) {
				check_lddate_interval = 1;
			}
		}
	}
	if (naptime < 1) {
		if (parse_param(pf, "sleep", P_LINT, 1, &naptime) < 0) {
			elog_die(1, "parse_pf: sleep value needed!\n");
		} else {
			if (naptime < 0) {
				naptime = 1;
			}
		}
	}
	if (!prefix) {
		if (parse_param(pf, "prefix", P_STR, 0, &prefix) < 0) {
			printf("NO PREFIX!\n");
			prefix = NULL;
		}
	}
	parse_param(pf, "check_tables", P_TBL, 0, &check_tables);
	if (check_tables) {
		if (maxtbl(check_tables) < 1) {
			freetbl(check_tables, 0);
			check_tables = NULL;
		}
	}
	parse_param(pf, "ignore_tables", P_TBL, 0, &ignore_tables);
	if (ignore_tables) {
		if (maxtbl(ignore_tables) < 1) {
			freetbl(ignore_tables, 0);
			ignore_tables = NULL;
		}
	}
	/*
	 * no good here, would erase the table above pffree(pf);
	 */

	if (argc < 1) {
		complain(0, "Need db argument.\n");
		usage();
		exit(1);
	}
	dbname = *argv;

	argc--;
	argv++;
	if (argc < 1) {
		complain(0, "Need orb argument.\n");
		usage();
		exit(1);
	}
	orbname = *argv;
	argc--;
	argv++;
	if (argc > 0) {
		complain(0, "Unrecognized argument '%s'.\n", *argv);
		usage();
		exit(1);
	}
	if (dbopen(dbname, "r", &db) < 0) {
		elog_complain(0, "Can't open database");
		exit(1);
	}
	dbquery(db, dbSCHEMA_NAME, &schemaname);
	orb = orbopen(orbname, "w&");
	if (orb < 0) {
		elog_die(0, "orbopen(%s) error\n", orbname);
	}
	/*
	 * prepare for later call to dbquery(dbFIELD_TABLES) to find only
	 * tables containing lddate
	 */

	/*
	 * dbtables is much better, does not require the existence of table
	 * origin dbf = dblookup(db, 0, "origin", "lddate", "dbNULL");
	 * dbquery(dbf, dbFIELD_TABLES, &tablenames);
	 */

	dbex_compile(db, "max(lddate)", &expr_lddate, dbTIME);
	tablenames = dbtables(db, "lddate");
	tables_containing_dfile = dbtables(db, "dfile");

	/* waste a few bytes... */
	ntables = maxtbl(tablenames);
	mtimes = malloc(ntables * sizeof(double));
	lddates = malloc(ntables * sizeof(double));
	bury_times = malloc(ntables * sizeof(double));
	static_flags = malloc(ntables * sizeof(long));
	if (statefilename) {
		if (exhume(statefilename, &Stop, 10, mortician)) {
			elog_notify(0, "read old state file\n");
		} else {
			elog_complain(0, "could not read old statefile\n");
		}
	}
	for (i = 0; i < ntables; i++) {
		/*
		 * mtimes[i] = modified_after; lddates[i] = modified_after;
		 */
		static_flags[i] = NEW_TABLE;
	}
	for (;;) {
		tablenames = dbtables(db, "lddate");

		for (i = 0; i < ntables; i++) {
			tablename = gettbl(tablenames, i);
			if (!tablename) {
				continue;
			}
			dbt = dblookup(db, 0, tablename, 0, 0);
			dbquery(dbt, dbTABLE_PRESENT, &table_present);
			if (!table_present) {
				continue;
			}
			dbquery(dbt, dbTABLE_IS_VIEW, &is_view);
			if (is_view) {
				continue;
			}
			/* lastid is not a good idea (my personal choice)... */
			if (strcmp(tablename, "lastid") == 0) {
				continue;
			}
			/* remove after Dan fixed the bug with remark */
			if (strcmp(tablename, "remark") == 0) {
				continue;
			}
			if (findtbl(tablename, tables_containing_dfile)) {
				continue;
			}
			if (check_tables) {
				if (!findtbl(tablename,check_tables)) {
					if (verbose > 1 && static_flags[i]==NEW_TABLE) elog_notify(0,"ignoring table %s because it's NOT in 'check_tables'\n",tablename);
					continue;
				}
			}
			if (ignore_tables) {
				if (findtbl(tablename,ignore_tables)) {
					if (verbose > 1 && static_flags[i]==NEW_TABLE) elog_notify(0,"ignoring table %s because it's in 'ignore_tables'\n",tablename);
					continue;
				}
			}
			dbquery(dbt, dbRECORD_COUNT, &recc);
			if (recc < 1) {
				continue;
			}
			if (statefilename) {
			if (static_flags[i] == NEW_TABLE) {
				relic.dp = &bury_times[i];
				if (resurrect(tablename, relic, TIME_RELIC) == 0) {
					mtimes[i] = bury_times[i];
					lddates[i] = bury_times[i];
					if (verbose > 1) {
						elog_notify(0, "resurrection successful: check %s after %s\n", tablename, s = strtime(bury_times[i]));
						free(s);
					}
				} else {
					bury_times[i] = modified_after;
					mtimes[i] = modified_after;
					lddates[i] = modified_after;
					if (verbose > 1) {
						elog_notify(0, "resurrection unsuccessful: check %s after %s\n", tablename, s = strtime(modified_after));
						free(s);
					}
				}
				static_flags[i] = TABLE_SEEN;
			}
			} else {
				if (static_flags[i] == NEW_TABLE) {
					bury_times[i] = modified_after;
					mtimes[i] = modified_after;
					lddates[i] = modified_after;
					static_flags[i] = TABLE_SEEN;
				}
			}
			dbquery(dbt, dbTABLE_FILENAME, &filename);
			if (stat(filename, &filestat) < 0) {
				elog_die(1, "stat(%s) error.\n", filename);
			}
			last_mtime = mtimes[i];
			last_lddate = lddates[i];

			mtime = filestat.st_mtime;
			/*
			 * the whole mtime stuff is not soo good: mtime is
			 * typically > lddate, so setting modified_after to
			 * mtime will certainly ignore the last value. To get
			 * everything, I will have to keep 2 arrays: mtimes
			 * to detect file modifications and lddates to get
			 * the actual entries...
			 */
			if (force_check || mtime > last_mtime) {
				sprintf(expr, "lddate > %f", last_lddate);
				dbs = dbsubset(dbt, expr, 0);
				dbquery(dbs, dbRECORD_COUNT, &recc);
				if (recc > 0) {
					if (dbrows2orb(dbs, orb, prefix) == 0) {
						/*
						 * dbex_evalstr(dbs,
						 * "max(lddate)", dbTIME,
						 * &lddates[i]);
						 */
						dbex_eval(dbs, expr_lddate, 0, &lddates[i]);
						mtimes[i] = mtime;
						bury_times[i] = lddates[i];
					}
				}
				dbfree(dbs);
			}
			/*
			 * a call to dbfree(dbt) would remove it from the
			 * list of tablenames, all later calls to tablename
			 * would return NIL...
			 */
			if (Stop) {
				bury();
				return (0);
			}
		}
		sleep(naptime);
		if ((counter + 1) >= check_lddate_interval) {
			counter = 0;
			force_check = 1;
		} else {
			force_check = 0;
			counter++;
		}
		if (statefilename) {
			double          nowtime;

			nowtime = now();
			if (nowtime - lastburytime > 600.0) {
				lastburytime = nowtime;
				bury();
			}
		}
	}
}
Ejemplo n.º 26
0
int main (int argc,char *argv[]) {

  int arg=0;


  int status=0;
  double atime;

  char *stmestr=NULL;
  char *etmestr=NULL;
  char *sdtestr=NULL;
  char *edtestr=NULL;
  char *exstr=NULL;

  double stime=-1;
  double etime=-1;
  double extime=0;

  double sdate=-1;
  double edate=-1;

  int yr,mo,dy,hr,mt;
  double sc;
  unsigned char vb=0;
  unsigned char help=0;
  unsigned char option=0;


  FILE *fp=NULL;

  int n;

  prm=RadarParmMake();
  iq=IQMake();

  OptionAdd(&opt,"-help",'x',&help);
  OptionAdd(&opt,"-option",'x',&option);


  OptionAdd(&opt,"vb",'x',&vb);
  OptionAdd(&opt,"st",'t',&stmestr);
  OptionAdd(&opt,"et",'t',&etmestr);
  OptionAdd(&opt,"sd",'t',&sdtestr);
  OptionAdd(&opt,"ed",'t',&edtestr);
  OptionAdd(&opt,"ex",'t',&exstr);

  arg=OptionProcess(1,argc,argv,&opt,NULL);

  if (help==1) {
    OptionPrintInfo(stdout,hlpstr);
    exit(0);
  }

  if (option==1) {
    OptionDump(stdout,&opt);
    exit(0);
  }

  if (exstr !=NULL) extime=strtime(exstr);
  if (stmestr !=NULL) stime=strtime(stmestr);
  if (etmestr !=NULL) etime=strtime(etmestr);
  if (sdtestr !=NULL) sdate=strdate(sdtestr);
  if (edtestr !=NULL) edate=strdate(edtestr);



  if ((argc-arg)>1) {
    fp=fopen(argv[arg+1],"r");
    if (fp==NULL) {
      fprintf(stderr,"Index not found.\n");
      exit(-1);
    }
    inx=IQIndexFload(fp);
   
    fclose(fp);
    if (inx==NULL) {
      fprintf(stderr,"Error loading index.\n");
      exit(-1);
    }
  }
  if (arg==argc) fp=stdin;
  else fp=fopen(argv[arg],"r");
  if (fp==NULL) {
    fprintf(stderr,"File not found.\n");
    exit(-1);
  }
  

  if (IQFread(fp,prm,iq,&badtr,&samples)==-1)  {
    fprintf(stderr,"Error reading file\n");
    exit(-1);
  }

  atime=TimeYMDHMSToEpoch(prm->time.yr,
	   	           prm->time.mo,
                           prm->time.dy,
                           prm->time.hr,
		           prm->time.mt,
                           prm->time.sc+prm->time.us/1.0e6);

   /* skip here */

    if ((stime !=-1) || (sdate !=-1)) { 
      /* we must skip the start of the files */
      int yr,mo,dy,hr,mt;
      double sc; 
      if (stime==-1) stime= ( (int) atime % (24*3600));
      if (sdate==-1) stime+=atime - ( (int) atime % (24*3600));
      else stime+=sdate;

      TimeEpochToYMDHMS(stime,&yr,&mo,&dy,&hr,&mt,&sc);
      status=IQFseek(fp,yr,mo,dy,hr,mt,sc,NULL,inx); 
    
      if (status ==-1) {
        fprintf(stderr,"File does not contain the requested interval.\n");
        exit(-1);
      }
      if (IQFread(fp,prm,iq,&badtr,&samples)==-1)  {
         fprintf(stderr,"Error reading file\n");
         exit(-1);
      }
  
    } else stime=atime;
   
    if (etime !=-1) {
       if (edate==-1) etime+=atime - ( (int) atime % (24*3600));
       else etime+=edate;
    }

   if (extime !=0) etime=stime+extime;
 
   do {

     fprintf(stderr,"%s\n",prm->origin.time);
     fprintf(stderr,"%s\n",prm->origin.command);
     fprintf(stderr,"%s\n",prm->combf);
     fprintf(stderr,"%d:",prm->mppul);
     for (n=0;n<prm->mppul;n++) fprintf(stderr,"%d ",prm->pulse[n]);
     fprintf(stderr,"\n");
     fprintf(stderr,"%d\n",prm->mplgs);
     for (n=0;n<=prm->mplgs;n++) fprintf(stderr,"%d,%d ",
          prm->lag[0][n],prm->lag[1][n]);
     fprintf(stderr,"\n");


         
     IQFwrite(stdout,prm,iq,badtr,samples);
     
     atime=TimeYMDHMSToEpoch(prm->time.yr,
		    prm->time.mo,
                    prm->time.dy,
                    prm->time.hr,
		    prm->time.mt,
                    prm->time.sc+prm->time.us/1.0e6);
     TimeEpochToYMDHMS(atime,&yr,&mo,&dy,&hr,&mt,&sc);
     if (vb==1) fprintf(stderr,"%d-%d-%d %d:%d:%d\n",yr,mo,dy,hr,mt,(int) sc);

      if ((etime !=-1) && (atime>=etime)) break;
      status=IQFread(fp,prm,iq,&badtr,&samples);
 
  } while (status !=-1);  
 
  if (fp !=stdin) fclose(fp);
  return 0;


}
Ejemplo n.º 27
0
int
main( int argc, char **argv )
{
	int	c;
	int	errflag = 0;
	int	orb;
	int	stop = 0;
	long	nrecs;
	char	*match = ".*/pf/st";
	char	*from = 0;
	char	*statefile = 0;
	char	*pfname = "orb2rrdc";
	char	*orbname;
	char	*dbcache;
	char	*rrdtool;
	char	command[STRSZ];
	char	net[STRSZ];
	char	sta[STRSZ];
	char	rrdvar[STRSZ];
	char	key[STRSZ];
	char	path[FILENAME_MAX];
	Dbptr	db;
	Dbptr	dbt;
	Pf	*pf;
	char	*Default_network;
	Tbl	*dlslines;
	Arr	*Dls_vars_dsparams;
	Arr	*Dls_vars_rras;
	Tbl	*Dls_vars_keys;
	char	*line;
	char	*dls_var;
	char	*dsparams;
	Tbl	*rras;
	int	i;
	int	j;
	OrbreapThr *ort;
	int	pktid;
	char	srcname[ORBSRCNAME_SIZE];
	double	time = 0;
	char	*packet = 0;
	int	nbytes = 0;
	int	bufsize = 0;
	Packet	*pkt = 0;
	int	rc;
	char	*s;
	Pf	*dlspf;
	Tbl	*dlspfkeys;
	char	*element;
	Tbl	*parts;
	double	val;
	Pf	*pfval = 0;

	elog_init( argc, argv );

	while( ( c = getopt( argc, argv, "vVd:s:p:m:f:" ) ) != -1 ) {

		switch( c ) {

		case 'd':
			CacheDaemon = optarg;
			break;

		case 'f':
			from = optarg;
			break;

		case 'm':
			match = optarg;
			break;

		case 'p': 
			pfname = optarg;
			break;

		case 's':
			statefile = optarg;
			break;
			
		case 'v':
			Verbose++;
			break;

		case 'V':
			VeryVerbose++;
			Verbose++;
			break;
		
		default:
			elog_complain( 0, "Unknown option '%c'\n", c );
			errflag++;
			break;
		}
	}

	if( errflag || argc - optind != 2 ) {

		usage();
	}

	if( Verbose ) {

		elog_notify( 0, "Starting at %s (%s $Revision$ $Date$)\n", 
				zepoch2str( str2epoch( "now" ), "%D %T %Z", "" ),
				Program_Name );
	}

	orbname = argv[optind++];
	dbcache = argv[optind++];

	pfread( pfname, &pf );

	rrdtool = pfget_string( pf, "rrdtool" );

	if( rrdtool == NULL || ! strcmp( rrdtool, "" ) ) {

		elog_die( 0, "Error: no rrdtool executable name specified in parameter file\n" );

	} else if( ( rrdtool[0] == '/' && ! is_present( rrdtool ) ) || ( rrdtool[0] != '/' && ! datafile( "PATH", rrdtool ) ) ) {

		elog_die( 0, "Error: can't find rrdtool executable by name of '%s' (check PATH environment " 
			"variable, or absolute path name if given)\n", rrdtool );

	} else if( rrdtool[0] == '/' ) {

		sprintf( command, "%s -", rrdtool );

	} else {

		sprintf( command, "rrdtool -" );
	}

	Suppress_egrep = pfget_string( pf, "suppress_egrep" );

	if( Suppress_egrep != NULL && strcmp( Suppress_egrep, "" ) ) {
		
		if( ! datafile( "PATH", "egrep" ) ) {

			elog_complain( 0, "Ignoring suppress_egrep parameter: can't find egrep on path\n" ); 

		} else {

			sprintf( command, "%s 2>&1 | egrep -v '%s'", command, Suppress_egrep );
		}
	}

	if( VeryVerbose ) {

		elog_notify( 0, "Executing command: %s\n", command );
	}

	Rrdfp = popen( command, "w" );

	if( Rrdfp == (FILE *) NULL ) {

		elog_die( 0, "Failed to open socket to rrdtool command\n" );
	}

	orb = orbopen( orbname, "r&" );

	if( orb < 0 ) {

		elog_die( 0, "Failed to open orb '%s' for reading. Bye.\n", orbname );
	}

	orbselect( orb, match );

	if( from != NULL && statefile == NULL ) {

		pktid = orbposition( orb, from );

		if( Verbose ) {

			elog_notify( 0, "Positioned to packet %d\n", pktid );
		}

	} else if( from != NULL ) {

		elog_complain( 0, "Ignoring -f in favor of existing state file\n" );
	}

	if( statefile != NULL ) {

		stop = 0;

		exhume( statefile, &stop, 15, 0 );

		orbresurrect( orb, &pktid, &time );

		if( Verbose ) {

			elog_notify( 0, "Resurrecting state to pktid %d, time %s\n",
				pktid, s = strtime( time ) );

			free( s );
		}

		orbseek( orb, pktid );
	}

	dbopen( dbcache, "r+", &db );

	if( db.database < 0 ) {
		
		elog_die( 0, "Failed to open cache database '%s'. Bye.\n", dbcache );

	} else {
		
		db = dblookup( db, "", "rrdcache", "", "" );

		if( db.table < 0 ) {

			elog_die( 0, "Failed to lookup 'rrdcache' table in '%s'. Bye.\n", dbcache );
		}
	}

	dbcrunch( db );

	dbt = dbsubset( db, "endtime == NULL", NULL );

	Rrd_files = newarr( 0 );

	dbquery( dbt, dbRECORD_COUNT, &nrecs );

	for( dbt.record = 0; dbt.record < nrecs; dbt.record++ ) {

		dbgetv( dbt, 0, "net", &net, "sta", &sta, "rrdvar", &rrdvar, NULL );

		dbfilename( dbt, (char *) &path );

		sprintf( key, "%s:%s:%s", net, sta, rrdvar );

		if( ! is_present( path ) ) {
			
			elog_complain( 0, "WARNING: rrd file '%s', listed in database, does not exist. "
				"Removing database entry.\n", path );

			dbmark( dbt );

		} else {

			setarr( Rrd_files, key, strdup( path ) );

			if( VeryVerbose ) {

				elog_notify( 0, "Re-using rrd file '%s' for '%s'\n", path, key );
			}
		}
	}

	Rrdfile_pattern = pfget_string( pf, "rrdfile_pattern" );
	Status_stepsize_sec = pfget_double( pf, "status_stepsize_sec" );
	Default_network = pfget_string( pf, "default_network" );
	dlslines = pfget_tbl( pf, "dls_vars" );

	Dls_vars_dsparams = newarr( 0 );
	Dls_vars_rras = newarr( 0 );

	for( i = 0; i < maxtbl( dlslines ); i++ ) {
		
		line = gettbl( dlslines, i );
		
		strtr( line, "\t", " " );
		rras = split( line, ' ' );

		dls_var = shifttbl( rras );
		dsparams = shifttbl( rras );

		setarr( Dls_vars_dsparams, dls_var, dsparams );
		setarr( Dls_vars_rras, dls_var, rras );
	}

	ort = orbreapthr_new( orb, -1., 0 );

	for( ; stop == 0; ) {

		orbreapthr_get( ort, &pktid, srcname, &time, &packet, &nbytes, &bufsize );

		if( statefile ) {

			rc = bury();

			if( rc < 0 ) {

				elog_complain( 0, "Unexpected failure of bury command! " 
					"(are there two orb2rrdc's running with the same state" 
					"file?)\n" );

				clear_register( 1 );
			}
		}

		rc = unstuffPkt( srcname, time, packet, nbytes, &pkt );

		if( rc == Pkt_pf ) {

			if( VeryVerbose ) {

				/* Parameter files generally too big for elog */

				fprintf( stderr, "Received a parameter-file '%s' at %s\n%s\n\n", 
						srcname, 
						s = strtime( time ), 
						pf2string( pkt->pf ) );

				free( s );

			} else if( Verbose ) {

				elog_notify( 0, "Received a parameter-file '%s' at %s\n", 
						srcname, s = strtime( time ) );

				free( s );
			}

			pfmorph( pkt->pf );

			if( VeryVerbose ) {

				fprintf( stderr, "Morphed parameter-file '%s' to interpret 'opt':\n%s\n\n", 
						srcname, 
						pf2string( pkt->pf ) );
			}

			pfget( pkt->pf, "dls", (void **) &dlspf );

			dlspfkeys = pfkeys( dlspf );
			Dls_vars_keys = keysarr( Dls_vars_dsparams );

			for( i = 0; i < maxtbl( dlspfkeys ); i++ ) {
			   
			   element = gettbl( dlspfkeys, i );

			   if( strcontains( element, "_", 0, 0, 0 ) ) {

				parts = split( (s = strdup( element )), '_' );

				sprintf( net, "%s", (char *) gettbl( parts, 0 ) );
				sprintf( sta, "%s", (char *) gettbl( parts, 1 ) );

				free( s );
				freetbl( parts, 0 );

			   } else {

				sprintf( net, "%s", Default_network );

				sprintf( sta, "%s", element );
			   }

			   for( j = 0; j < maxtbl( Dls_vars_keys ); j++ ) {

			   	dls_var = gettbl( Dls_vars_keys, j );

				sprintf( key, "%s{%s}", element, dls_var );

				if( pfresolve( dlspf, key, 0, &pfval ) < 0 ) {

					elog_complain( 0, "Unable to extract variable '%s' "
						"(not present or wrong type) from element '%s' "
						"in packet from '%s', timestamped '%s'; Skipping\n",
						key, element, srcname, s = strtime( time ) );

					free( s );

					pfval = 0;

					continue;

				} else if( pfval != (Pf *) NULL &&
					   pfval->value.s != (char *) NULL &&
					   ! strcmp( pfval->value.s, "-" ) ) {

					if( VeryVerbose ) {

						elog_notify( 0, "Non-floating point value '-' in variable '%s', "
							"in packet from '%s', timestamped '%s'; Skipping data point\n",
							key, srcname, s = strtime( time ) );

						free( s );
					}

					continue;

				} else {

					val = pfget_double( dlspf, key );
				}

				archive_dlsvar( db, net, sta, dls_var, 
						(char *) getarr( Dls_vars_dsparams, dls_var ),
						(Tbl *) getarr( Dls_vars_rras, dls_var ),
						time, val );
			   }

			}

			freetbl( dlspfkeys, 0 );
			freetbl( Dls_vars_keys, 0 );

		} else if( rc == Pkt_stash ) {

			; /* Do nothing */

		} else {

			if( Verbose ) {

				elog_notify( 0, "Received a packet that's not a parameter file " 
					"(type '%d' from unstuffPkt); skipping\n", rc );
			}
		}
	}
}
Ejemplo n.º 28
0
int main(int argc,char *argv[]) {

  int s=0;

  int arg;
  
  char *cfname=NULL;
  FILE *fp;
  

  int wdt=540,hgt=540;

  unsigned char help=0; 
  unsigned char option=0; 


  MapTransform  tfunc;
  unsigned char flip=0;
  unsigned char gvp=0;
  unsigned char ortho=0;
  unsigned char stereo=0;
  unsigned char cylind=0;
  float lat=90,lon=0;
  float latmin=50.0;
  float sf=1.0;

  unsigned char sqflg=0;


  unsigned char magflg=0;
  unsigned char rotflg=0;

  unsigned char lstflg=0;
  unsigned char smflg=0;

  float marg[4];


  int x,y;

  float e;

  char *tmetxt=NULL;
  char *dtetxt=NULL;

  double tval=-1;
  double dval=-1;

  int yr,mo,dy,hr,mt;
  double sc;
  int yrsec;
  float tme_shft;
 
  float glat,glon;
  float fx,fy;
  int px,py;

  float ka=0.8;
  float kd=0.3;
  float ks=0.4;
  float sn=4;

  double LsoT,LT,Hangle,dec,eqt,mlon;

  float minlat,minlon,maxlat,maxlon;

  float Lvec[3]={-1.0,0.0,0.5}; /* lighting vector */
 
  OptionAdd(&opt,"-help",'x',&help);
  OptionAdd(&opt,"-option",'x',&option);

  OptionAdd(&opt,"cf",'t',&cfname);

  OptionAdd(&opt,"wdt",'i',&wdt);
  OptionAdd(&opt,"hgt",'i',&hgt);

  OptionAdd(&opt,"square",'x',&sqflg);


  OptionAdd(&opt,"ortho",'x',&ortho);
  OptionAdd(&opt,"stereo",'x',&stereo);
  OptionAdd(&opt,"gvp",'x',&gvp);

  OptionAdd(&opt,"lat",'f',&lat);
  OptionAdd(&opt,"lon",'f',&lon);
  OptionAdd(&opt,"latmin",'f',&latmin);
  OptionAdd(&opt,"sf",'f',&sf);
  OptionAdd(&opt,"mag",'x',&magflg);
  OptionAdd(&opt,"rotate",'x',&rotflg);
  OptionAdd(&opt,"flip",'x',&flip);

  OptionAdd(&opt,"lst",'x',&lstflg);
 
  OptionAdd(&opt,"t",'t',&tmetxt);
  OptionAdd(&opt,"d",'t',&dtetxt);
  
  OptionAdd(&opt,"smooth",'x',&smflg);

  OptionAdd(&opt,"ka",'f',&ka); 
  OptionAdd(&opt,"kd",'f',&kd);
  OptionAdd(&opt,"ks",'f',&ks);
  OptionAdd(&opt,"n",'f',&sn);
 


  arg=OptionProcess(1,argc,argv,&opt,NULL);  

  if (cfname !=NULL) { /* load the configuration file */
    int farg;
    do {
      fp=fopen(cfname,"r");
      if (fp==NULL) break;
      free(cfname);
      cfname=NULL;
      optf=OptionProcessFile(fp);
      if (optf !=NULL) {
        farg=OptionProcess(0,optf->argc,optf->argv,&opt,NULL);
        OptionFreeFile(optf);
       }   
       fclose(fp);
    } while (cfname !=NULL);
  }

  if (help==1) {
    OptionPrintInfo(stdout,hlpstr);
    exit(0);
  }

  if (option==1) {
    OptionDump(stdout,&opt);
    exit(0);
  }


  
  if (argc==arg) {
    OptionPrintInfo(stderr,errstr);
    exit(-1);
  }


  fp=fopen(argv[arg],"r");
  if (fp==NULL) {
    fprintf(stderr,"File not found.\n");
    exit(-1);
  }

  s=ElevationLoad(fp,&eldata);
  fclose(fp);

  if (s !=0) {
    fprintf(stderr,"Error loading elevation data.\n");
    exit(-1);
  }
  
  if (tmetxt !=NULL) tval=strtime(tmetxt);
  if (dtetxt !=NULL) {
    dval=strdate(dtetxt);
    tval+=dval;
  }
  TimeEpochToYMDHMS(tval,&yr,&mo,&dy,&hr,&mt,&sc);
  yrsec=TimeYMDHMSToYrsec(yr,mo,dy,hr,mt,sc);

  if ((ortho==0) && (stereo==0) && (gvp==0)) cylind=1;

  if ((lat<0) && (latmin>0)) latmin=-latmin;
  if ((lat>0) && (latmin<0)) latmin=-latmin;

  tfunc=MapCylindrical;
  if (ortho) tfunc=MapOrthographic;
  if (stereo) tfunc=MapStereographic;
  if (gvp) tfunc=MapGeneralVerticalPerspective;


  marg[0]=lat;
  marg[1]=lon;
  
  if ((ortho) || (gvp)) marg[2]=sf;
  else if (stereo) marg[2]=1.25*0.5*sf*90.0/(90-fabs(latmin));
  else marg[2]=1;
  marg[3]=flip;

  SZASolarLoc(yr,yrsec,&mlon,&dec);
  eqt=SZAEqOfTime(mlon,yr);

  if (magflg) tme_shft=-AACGMConvertMLT(yr,yrsec,0.0)*15.0; 
    else {
      if (lstflg) {
        LsoT=(hr*3600+mt*60+sc)+eqt;
        Hangle=15*(LsoT/3600);
        tme_shft=-Hangle;
      } else {
        LT=(hr*3600+mt*60+sc);
        Hangle=15*(LT/3600);
        tme_shft=-Hangle;
      }
    }

  if (rotflg)  marg[1]=lon+tme_shft;

  if ((wdt==0) || (hgt==0)) {
    fprintf(stderr,"invalid plot size.\n");
    exit(-1);
  }
      
  if (cylind) {
    marg[1]=0;
    marg[2]=0;
  }
 
  GeoMap(wdt,hgt,tfunc,marg,&ilat,&ilon);
  
  zbuf=malloc(sizeof(float)*wdt*hgt);

  minlat=eldata.lat+eldata.latsec/3600.0;
  minlon=eldata.lon+eldata.lonsec/3600.0;
  maxlat=minlat+eldata.numlat*eldata.latstp/36000.0;
  maxlon=minlon+eldata.numlon*eldata.lonstp/36000.0;
 
  if ((cylind) || (sqflg)) fbclp=NULL;
  else fbclp=fbclip(wdt,hgt);

  for (x=0;x<wdt;x++) {
    for (y=0;y<hgt;y++) {
      zbuf[y*wdt+x]=-1e6;
      if ((fbclp !=NULL) && (fbclp->clp[y*wdt+x]==0)) continue;
      if ((ilat[y*wdt+x]<-90.0) || (ilat[y*wdt+x]>90)) continue;
      glat=ilat[y*wdt+x];
      glon=ilon[y*wdt+x];

      if (magflg) {
	double mlat,mlon,rho;
        s=AACGMConvert(glat,glon,300.0,&mlat,&mlon,&rho,1);
        glat=mlat;
        glon=mlon;
      }

      if (cylind) {
        if (rotflg) glon+=lon+tme_shft;
        else glon+=lon;
      }
      if (glon>180) glon-=360;

      if (glat<minlat) continue;
      if (glon<minlon) continue;
      if (glat>=maxlat) continue;
      if (glon>=maxlon) continue;

      fy=(glat-minlat)/(maxlat-minlat);
      fx=(glon-minlon)/(maxlon-minlon);
     
      px=eldata.numlon*fx;
      py=eldata.numlat*fy;
 
      if (smflg) {    
        float l,r,b,t;
        l=eldata.data[px*eldata.numlat+py];
        if (px<eldata.numlon-1) r=eldata.data[(px+1)*eldata.numlat+py];
        else r=l;
        b=l+(r-l)*(eldata.numlon*fx-px);
        if (py<eldata.numlat-1) {
          l=eldata.data[px*eldata.numlat+py+1];
          if (px<eldata.numlon-1) r=eldata.data[(px+1)*eldata.numlat+py+1];
          else r=l;
	  t=l+(r-l)*(eldata.numlon*fx-px);
	} else t=b;
        e=b+(t-b)*(eldata.numlat*fy-py);
      } else e=eldata.data[px*eldata.numlat+py];
      zbuf[y*wdt+x]=e;
    }
  }
  PhongModel(wdt,hgt,0,zbuf,Lvec,kd,ks,sn,&dbuf,&sbuf); 
  ConvertFwriteInt(stdout,wdt);
  ConvertFwriteInt(stdout,hgt);
  for (y=0;y<hgt;y++) {
    for (x=0;x<wdt;x++) {
      ConvertFwriteFloat(stdout,zbuf[y*wdt+x]);
    }
  }
  
  for (y=0;y<hgt;y++) {
    for (x=0;x<wdt;x++) {
      ConvertFwriteFloat(stdout,ka+dbuf[y*wdt+x]);
    }
  }

  for (y=0;y<hgt;y++) {
    for (x=0;x<wdt;x++) {
      ConvertFwriteFloat(stdout,sbuf[y*wdt+x]);
    }
  }

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



#ifdef _XLIB_
  int xdf=0;
  int xd=0;
  struct XwinDisplay *dp;
  struct XwinWindow *win;
  char *display_name=NULL;
  char *wname="fov_plot";
  int xdoff=-1;
  int ydoff=-1;
#endif

  struct FrameBuffer *img=NULL;
  struct PostScript *psdata=NULL;
  FILE *fontfp=NULL;
  char *fntdbfname=NULL;
  struct FrameBufferFontDB *fontdb=NULL;
  unsigned int bgcol;
  unsigned int txtcol;

  int arg;

  char *envstr=NULL;
  char *cfname=NULL;
  FILE *fp;



  float wdt=540,hgt=540;
  float pad=0;

  char *fontname=NULL;
  float fontsize=10.0;
  char *dfontname="Helvetica";

  float width=0.5;

  struct Plot *plot=NULL;
  struct Splot *splot=NULL;

  float xpoff=40,ypoff=40;
  unsigned char psflg=0;
  unsigned char xmlflg=0;
  unsigned char ppmflg=0;
  unsigned char ppmxflg=0;
  unsigned char pngflg=0;

  unsigned char gflg=0;
  unsigned char pflg=0;


  unsigned char help=0; 
  unsigned char option=0; 

  char *bgcol_txt=NULL;
  char *txtcol_txt=NULL;


  unsigned char sqflg=0;
  MapTFunction  tfunc;

  unsigned char flip=0;
  unsigned char gvp=0;
  unsigned char ortho=0;
  unsigned char stereo=0;
  unsigned char cylind=0;

  float lat=90,lon=0;
  float latmin=50.0;
  float sf=1.0;
  float alt=0.0; 

  unsigned char magflg=0;
  unsigned char rotflg=0;

  unsigned char mapflg=0;
  unsigned char fmapflg=0;
  unsigned char bndflg=0;
  unsigned char grdflg=0;
  unsigned char tmkflg=0;
  unsigned char tlblflg=0;
  unsigned char ofovflg=0;
  unsigned char fofovflg=0;

  unsigned char cfovflg=0;
  unsigned char fcfovflg=0;

  unsigned char fovflg=0;
  unsigned char ffovflg=0;

  unsigned char grdontop=0;

  unsigned char dotflg=0;

  int tmtick=3;

  unsigned char lstflg=0;
  unsigned char trmflg=0;
  unsigned char ftrmflg=0;

  char *grdcol_txt=NULL;
  char *cstcol_txt=NULL;
  char *bndcol_txt=NULL;
  char *lndcol_txt=NULL;
  char *seacol_txt=NULL;
  char *trmcol_txt=NULL;
  char *ftrmcol_txt=NULL;
  char *tmkcol_txt=NULL;
  char *ofovcol_txt=NULL;
  char *fofovcol_txt=NULL;
  char *fovcol_txt=NULL;
  char *ffovcol_txt=NULL;

  char *cfovcol_txt=NULL;
  char *fcfovcol_txt=NULL;


  unsigned int grdcol;
  unsigned int cstcol;
  unsigned int bndcol;
  unsigned int lndcol;
  unsigned int seacol;
  unsigned int trmcol;
  unsigned int ftrmcol;
  unsigned int tmkcol;
  unsigned int ofovcol;
  unsigned int fofovcol;
  unsigned int fovcol;
  unsigned int ffovcol;

  unsigned int cfovcol;
  unsigned int fcfovcol;
  

  FILE *mapfp;
  float marg[4];
  int i;

  char *tmetxt=NULL;
  char *dtetxt=NULL;

  double tval=-1;
  double dval=-1;

  int yr,mo,dy,hr,mt;
  double sc;
  int yrsec;
  float tme_shft;



  double LsoT,LT,Hangle,dec,eqt;
  
  float dotr=2; 
 
  int stid=-1;
  char *ststr=NULL;
  int stnum=0;

  char tsfx[16];


  envstr=getenv("MAPDATA");

  mapfp=fopen(envstr,"r");
  map=MapFread(mapfp);
  fclose(mapfp);   

  envstr=getenv("BNDDATA");
  mapfp=fopen(envstr,"r");
  bnd=MapBndFread(mapfp);
  fclose(mapfp);

 envstr=getenv("SD_RADAR");
  if (envstr==NULL) {
    fprintf(stderr,"Environment variable 'SD_RADAR' must be defined.\n");
    exit(-1);
  }

  fp=fopen(envstr,"r");

  if (fp==NULL) {
    fprintf(stderr,"Could not locate radar information file.\n");
    exit(-1);
  }

  network=RadarLoad(fp);
  fclose(fp); 
  if (network==NULL) {
    fprintf(stderr,"Failed to read radar information.\n");
    exit(-1);
  }

  envstr=getenv("SD_HDWPATH");
  if (envstr==NULL) {
    fprintf(stderr,"Environment variable 'SD_HDWPATH' must be defined.\n");
    exit(-1);
  }

  RadarLoadHardware(envstr,network);


  bgcol=PlotColor(0xff,0xff,0xff,0xff);
  txtcol=PlotColor(0x00,0x00,0x00,0xff);

  grdcol=PlotColor(0x20,0x40,0x60,0xff);
  cstcol=PlotColor(0xa0,0xa0,0xa0,0xff);
  bndcol=PlotColor(0x80,0x80,0x80,0xff);
  lndcol=PlotColor(0xff,0xff,0xf0,0xff);
  seacol=PlotColor(0xe0,0xf0,0xff,0xff);
  tmkcol=PlotColor(0x00,0x00,0x00,0xff);
  ofovcol=PlotColor(0x00,0x00,0x00,0xff);
  fofovcol=PlotColor(0xff,0xff,0xff,0xff);
  fovcol=PlotColor(0x00,0x00,0x00,0xff);
  ffovcol=PlotColor(0xc0,0x00,0x00,0xff);
  trmcol=PlotColor(0x80,0x80,0x80,0xff);
  ftrmcol=PlotColor(0x80,0x80,0x80,0xff);

  cfovcol=PlotColor(0x00,0x00,0x00,0xff);
  fcfovcol=PlotColor(0xff,0xff,0xff,0xff);
 
  OptionAdd(&opt,"-help",'x',&help);
  OptionAdd(&opt,"-option",'x',&option);

  OptionAdd(&opt,"cf",'t',&cfname);


#ifdef _XLIB_ 
  OptionAdd(&opt,"x",'x',&xd);
  OptionAdd(&opt,"display",'t',&display_name);
  OptionAdd(&opt,"xoff",'i',&xdoff);
  OptionAdd(&opt,"yoff",'i',&ydoff);
#endif

  OptionAdd(&opt,"ppm",'x',&ppmflg);
  OptionAdd(&opt,"ppmx",'x',&ppmxflg);
  OptionAdd(&opt,"xml",'x',&xmlflg);
  OptionAdd(&opt,"png",'x',&pngflg);
  OptionAdd(&opt,"ps",'x',&psflg); 

  OptionAdd(&opt,"xp",'f',&xpoff);
  OptionAdd(&opt,"yp",'f',&ypoff);
  OptionAdd(&opt,"wdt",'f',&wdt);
  OptionAdd(&opt,"hgt",'f',&hgt);
  OptionAdd(&opt,"pad",'f',&pad);

  OptionAdd(&opt,"bgcol",'t',&bgcol_txt);
  OptionAdd(&opt,"txtcol",'t',&txtcol_txt);

  OptionAdd(&opt,"square",'x',&sqflg);

  OptionAdd(&opt,"ortho",'x',&ortho);
  OptionAdd(&opt,"stereo",'x',&stereo);
  OptionAdd(&opt,"gvp",'x',&gvp);

  OptionAdd(&opt,"lat",'f',&lat);
  OptionAdd(&opt,"lon",'f',&lon);
  OptionAdd(&opt,"latmin",'f',&latmin);
  OptionAdd(&opt,"sf",'f',&sf);
  OptionAdd(&opt,"mag",'x',&magflg);
  OptionAdd(&opt,"rotate",'x',&rotflg);
  OptionAdd(&opt,"alt",'f',&alt);
  OptionAdd(&opt,"flip",'x',&flip);

  OptionAdd(&opt,"coast",'x',&mapflg);
  OptionAdd(&opt,"fcoast",'x',&fmapflg);
  OptionAdd(&opt,"bnd",'x',&bndflg);
  OptionAdd(&opt,"grd",'x',&grdflg);
  OptionAdd(&opt,"tmk",'x',&tmkflg);

 OptionAdd(&opt,"grdontop",'x',&grdontop);


  OptionAdd(&opt,"fov",'x',&fovflg);
  OptionAdd(&opt,"ffov",'x',&ffovflg);

  OptionAdd(&opt,"ofov",'x',&ofovflg);
  OptionAdd(&opt,"fofov",'x',&fofovflg);

  OptionAdd(&opt,"cfov",'x',&cfovflg);
  OptionAdd(&opt,"fcfov",'x',&fcfovflg);

  OptionAdd(&opt,"tmtick",'i',&tmtick);
  OptionAdd(&opt,"lst",'x',&lstflg);
  OptionAdd(&opt,"term",'x',&trmflg);
  OptionAdd(&opt,"fterm",'x',&ftrmflg);

  OptionAdd(&opt,"grdcol",'t',&grdcol_txt);
  OptionAdd(&opt,"cstcol",'t',&cstcol_txt);
  OptionAdd(&opt,"bndcol",'t',&bndcol_txt);
  OptionAdd(&opt,"lndcol",'t',&lndcol_txt);
  OptionAdd(&opt,"seacol",'t',&seacol_txt);
  OptionAdd(&opt,"trmcol",'t',&trmcol_txt);
  OptionAdd(&opt,"tmkcol",'t',&tmkcol_txt);
 
  OptionAdd(&opt,"fovcol",'t',&fovcol_txt);
  OptionAdd(&opt,"ffovcol",'t',&ffovcol_txt);
  OptionAdd(&opt,"ofovcol",'t',&ofovcol_txt);
  OptionAdd(&opt,"fofovcol",'t',&fofovcol_txt);

  OptionAdd(&opt,"cfovcol",'t',&cfovcol_txt);
  OptionAdd(&opt,"fcfovcol",'t',&fcfovcol_txt);

  OptionAdd(&opt,"st",'t',&ststr);

  OptionAdd(&opt,"t",'t',&tmetxt);
  OptionAdd(&opt,"d",'t',&dtetxt);
  
  OptionAdd(&opt,"tmlbl",'x',&tlblflg);

  OptionAdd(&opt,"fontname",'t',&fontname);
  OptionAdd(&opt,"fontsize",'f',&fontsize);
  OptionAdd(&opt,"lnewdt",'f',&width);

  OptionAdd(&opt,"dotr",'f',&dotr);
  OptionAdd(&opt,"dot",'x',&dotflg);


  arg=OptionProcess(1,argc,argv,&opt,NULL);  

  if (cfname !=NULL) { /* load the configuration file */
    int farg;
    do {
      fp=fopen(cfname,"r");
      if (fp==NULL) break;
      free(cfname);
      cfname=NULL;
      optf=OptionProcessFile(fp);
      if (optf !=NULL) {
        farg=OptionProcess(0,optf->argc,optf->argv,&opt,NULL);
        OptionFreeFile(optf);
       }   
       fclose(fp);
    } while (cfname !=NULL);
  }

  if (help==1) {
    OptionPrintInfo(stdout,hlpstr);
    exit(0);
  }

  if (option==1) {
    OptionDump(stdout,&opt);
    exit(0);
  }


  if (tmetxt !=NULL) tval=strtime(tmetxt);
  if (dtetxt !=NULL) dval=strdate(dtetxt);

  tval+=dval;
  TimeEpochToYMDHMS(tval,&yr,&mo,&dy,&hr,&mt,&sc);
  yrsec=TimeYMDHMSToYrsec(yr,mo,dy,hr,mt,sc);

  if (magflg) {
    MapModify(map,AACGMtransform,NULL);
    MapModify(bnd,AACGMtransform,NULL);
  }

  fov=make_fov(tval,network,alt); 

  if (magflg) MapModify(fov,AACGMtransform,NULL);


  if (tmtick<1) tmtick=1;
  if (tmtick>6) tmtick=6;

  if ((ortho==0) && (stereo==0)) cylind=1;

  if (grdflg) grd=make_grid(15,10,cylind);   
 
  if (tmkflg) tmk=make_grid(30*tmtick,10,cylind);

  if ((lat<0) && (latmin>0)) latmin=-latmin;
  if ((lat>0) && (latmin<0)) latmin=-latmin;

  if (trmflg || ftrmflg) {
    if ((cylind) || (ortho) | (gvp))
       trm=SZATerminator(yr,mo,dy,hr,mt,sc,0,magflg,
                           1.0,90.0);
     else if (lat>0) trm=SZATerminator(yr,mo,dy,hr,mt,sc,1,magflg,
                                     1.0,90.0);
     else trm=SZATerminator(yr,mo,dy,hr,mt,sc,-1,magflg,1.0,90.0);
  }
 
  marg[0]=lat;
  marg[1]=lon;

  tfunc=MapCylindrical;
  if (ortho) tfunc=MapOrthographic;
  if (stereo) tfunc=MapStereographic;
  if (gvp) tfunc=MapGeneralVerticalPerspective;

  if ((ortho) || (gvp)) marg[2]=sf;
  else if (stereo) marg[2]=1.25*0.5*sf*90.0/(90-fabs(latmin));
  else marg[2]=1;
  marg[3]=flip;

  strcpy(tsfx,"LT");
  if (magflg) strcpy(tsfx,"MLT");
  else if (lstflg) strcpy(tsfx,"LST");

  dec=SZASolarDec(yr,mo,dy,hr,mt,sc);
  eqt=SZAEqOfTime(yr,mo,dy,hr,mt,sc);

  if (magflg) tme_shft=-MLTConvertYrsec(yr,yrsec,0.0)*15.0; 
    else {
      if (lstflg) {
        LsoT=(hr*3600+mt*60+sc)+eqt;
        Hangle=15*(LsoT/3600);
        tme_shft=-Hangle;
      } else {
        LT=(hr*3600+mt*60+sc);
        Hangle=15*(LT/3600);
        tme_shft=-Hangle;
      }
    }
  if (lat<0) tme_shft+=180.0;

  if (rotflg)  marg[1]=lon+tme_shft;
  
  if ((cylind) || (sqflg)) clip=MapSquareClip(); 
  else clip=MapCircleClip(10); 

  if (mapflg || fmapflg) {
     nmap=MapTransform(map,2*sizeof(float),PolygonXYbbox,
                           tfunc,marg);
     if (cylind) nmap=wrap(nmap);
     pmap=PolygonClip(clip,nmap); 
  }
  if (bndflg) {
     nbnd=MapTransform(bnd,2*sizeof(float),PolygonXYbbox,
                      tfunc,marg);
     if (cylind) nbnd=wrap(nbnd);
     pbnd=PolygonClip(clip,nbnd);
  }
  if (grdflg) {
     ngrd=MapTransform(grd,2*sizeof(float),PolygonXYbbox,
                      tfunc,marg);
     if (cylind) ngrd=wrap(ngrd);
     pgrd=PolygonClip(clip,ngrd);
  }
  if (trmflg || ftrmflg) {
     ntrm=MapTransform(trm,2*sizeof(float),PolygonXYbbox,
                           tfunc,marg);
     if (cylind) ntrm=wrap(ntrm);
     ptrm=PolygonClip(clip,ntrm); 
  }

  nfov=MapTransform(fov,2*sizeof(float),PolygonXYbbox,
                     tfunc,marg);
  if (cylind) nfov=wrap(nfov);
  pfov=PolygonClip(clip,nfov);

  if (tmkflg) {
     float tmp;
     tmp=marg[1];
     if (rotflg) marg[1]=0;
     else marg[1]=lon-tme_shft;
     ntmk=MapTransform(tmk,2*sizeof(float),PolygonXYbbox,
                        tfunc,marg);
     ptmk=PolygonClip(clip,ntmk);
     marg[1]=tmp;
  }


  if (bgcol_txt !=NULL) bgcol=PlotColorStringRGBA(bgcol_txt);
  if (txtcol_txt !=NULL) txtcol=PlotColorStringRGBA(txtcol_txt);

  if (grdcol_txt !=NULL) grdcol=PlotColorStringRGBA(grdcol_txt);
  if (cstcol_txt !=NULL) cstcol=PlotColorStringRGBA(cstcol_txt);
  if (bndcol_txt !=NULL) bndcol=PlotColorStringRGBA(bndcol_txt);
  if (lndcol_txt !=NULL) lndcol=PlotColorStringRGBA(lndcol_txt);
  if (seacol_txt !=NULL) seacol=PlotColorStringRGBA(seacol_txt);
  if (trmcol_txt !=NULL) trmcol=PlotColorStringRGBA(trmcol_txt);
  if (ftrmcol_txt !=NULL) ftrmcol=PlotColorStringRGBA(ftrmcol_txt);

  if (tmkcol_txt !=NULL) tmkcol=PlotColorStringRGBA(tmkcol_txt);

  if (fovcol_txt !=NULL) fovcol=PlotColorStringRGBA(fovcol_txt);
  if (ofovcol_txt !=NULL) ofovcol=PlotColorStringRGBA(ofovcol_txt);
  if (cfovcol_txt !=NULL) cfovcol=PlotColorStringRGBA(cfovcol_txt);
 
  if (ffovcol_txt !=NULL) ffovcol=PlotColorStringRGBA(ffovcol_txt);
  if (fofovcol_txt !=NULL) fofovcol=PlotColorStringRGBA(fofovcol_txt);
  if (fcfovcol_txt !=NULL) fcfovcol=PlotColorStringRGBA(fcfovcol_txt);


  if ((wdt==0) || (hgt==0)) {
    fprintf(stderr,"invalid plot size.\n");
    exit(-1);
  }


  if (tlblflg) pad=10+fontsize;
  
  if (fontname==NULL) fontname=dfontname;

  fntdbfname=getenv("FONTDB");
  fontfp=fopen(fntdbfname,"r");
  if (fontfp !=NULL) {
   fontdb=FrameBufferFontDBLoad(fontfp);
   fclose(fontfp);
  }
 
  if (fontdb==NULL) {
   fprintf(stderr,"Could not load fonts.\n");
   exit(-1);
  }


  if (ststr !=NULL) stid=RadarGetID(network,ststr);
  for (stnum=0;stnum<network->rnum;stnum++) 
     if (stid==network->radar[stnum].id) break;  
  if (stnum==network->rnum) stnum=0;



  /* now determine our output type */

  if (psflg) pflg=1;
  if (xmlflg) gflg=1;
  if (ppmflg) gflg=1;
  if (ppmxflg) gflg=1;
  if (pngflg) gflg=1;

#ifdef _XLIB_ 
   if (xd !=0) {
     pflg=0; 
     gflg=1;
   }
#endif

  if (pflg) gflg=0;
  if ((!gflg) && (!pflg)) pflg=1;

  plot=PlotMake();
  splot=SplotMake();
  SplotSetPlot(plot,splot);

  if (gflg) SplotSetFrameBuffer(splot,&img,fontdb,NULL,NULL);
  if (pflg) {
    psdata=PostScriptMake();
    PostScriptSetText(psdata,stream,stdout);
    SplotSetPostScript(splot,psdata,0,xpoff,ypoff);
  }



  PlotDocumentStart(plot,"fov_plot",NULL,wdt,hgt,24);
  PlotPlotStart(plot,"fov_plot",wdt,hgt,24);

  PlotRectangle(plot,NULL,0,0,wdt,hgt,1,bgcol,0x0f,0,NULL);
     
  if (fmapflg) {
      if ((cylind) || (sqflg)) PlotRectangle(plot,NULL,pad,pad,
                               wdt-2*pad,hgt-2*pad,  
                             1,seacol,0x0f,0,NULL);
      PlotEllipse(plot,NULL,wdt/2,hgt/2,wdt/2-pad,hgt/2-pad,
                   1,seacol,0x0f,0,NULL);
  }

  if ((grdflg) && (!grdontop)) {
    MapPlotPolygon(plot,NULL,pad,pad,wdt-2*pad,hgt-2*pad,0,
                                grdcol,0x0f,width,NULL,
                                pgrd,1);
  }

  if (fmapflg) {
    MapPlotPolygon(plot,NULL,pad,pad,wdt-2*pad,hgt-2*pad,1,
                   lndcol,0x0f,0,NULL,pmap,1);
  
    MapPlotPolygon(plot,NULL,pad,pad,wdt-2*pad,hgt-2*pad,1,
                   lndcol,0x0f,0,NULL,pmap,3);
  
    MapPlotPolygon(plot,NULL,pad,pad,wdt-2*pad,hgt-2*pad,1,
                   seacol,0x0f,0,NULL,pmap,0);
  }

  if (ftrmflg) MapPlotPolygon(plot,NULL,pad,pad,wdt-2*pad,hgt-2*pad,
                             1,ftrmcol,0x0f,0,NULL,ptrm,1);

  
  if (fofovflg) {
    for (i=0;i<network->rnum;i++) {
      if (network->radar[i].id==stid) continue;
      if (network->radar[i].status !=1) continue;
      MapPlotPolygon(plot,NULL,pad,pad,
                   wdt-2*pad,hgt-2*pad,1,fofovcol,0x0f,0,NULL,pfov,i); 
    }
  }

  if (fcfovflg) {
    for (i=0;i<network->rnum;i++) {
      if (network->radar[i].id==stid) continue;
      if (network->radar[i].status!=0) continue;
      MapPlotPolygon(plot,NULL,pad,pad,wdt-2*pad,hgt-2*pad,1,
                       fcfovcol,0x0f,0,NULL,pfov,i); 
    }
  }


   if (ffovflg) {
    MapPlotPolygon(plot,NULL,pad,pad,
                 wdt-2*pad,hgt-2*pad,1,ffovcol,0x0f,0,NULL,pfov,stnum); 
   }
  

  if (mapflg) {
     MapPlotPolygon(plot,NULL,pad,pad,wdt-2*pad,hgt-2*pad,0,cstcol,0x0f,
                    width,NULL,
                    pmap,1);
  
     MapPlotOpenPolygon(plot,NULL,pad,pad,wdt-2*pad,hgt-2*pad,cstcol,0x0f,
                    width,NULL,
                    pmap,2);
  
     MapPlotPolygon(plot,NULL,pad,pad,wdt-2*pad,hgt-2*pad,0,cstcol,0x0f,
                    width,NULL,
                    pmap,0);
  }

  if (ofovflg)  {
    for (i=0;i<network->rnum;i++) {
      if (network->radar[i].id==stid) continue;
      if (network->radar[i].status !=1) continue;
      MapPlotPolygon(plot,NULL,pad,pad,wdt-2*pad,hgt-2*pad,0,
                    ofovcol,0x0f,width,NULL,
                    pfov,i);
    } 
  }

 if (cfovflg)  {
   
    for (i=0;i<network->rnum;i++) {
      if (network->radar[i].id==stid) continue;
      if (network->radar[i].status !=0) continue;
      MapPlotPolygon(plot,NULL,pad,pad,wdt-2*pad,hgt-2*pad,0,
                    cfovcol,0x0f,width,NULL,
                    pfov,i);
    } 
  }

 if (dotflg) {
   int s=0;
   struct RadarSite *site; 
   float pnt[2]; 
   if (cfovflg | fcfovflg)  {
     for (i=0;i<network->rnum;i++) {
       if (network->radar[i].id==stid) continue;
       if (network->radar[i].status !=0) continue;
       site=RadarYMDHMSGetSite(&(network->radar[i]),yr,mo,dy,hr,mt,sc);
       pnt[0]=site->geolat;
       pnt[1]=site->geolon; 
       s=(*tfunc)(sizeof(float)*2,pnt,2*sizeof(float),pnt,marg);
       if (s==0) PlotEllipse(plot,NULL,pad+pnt[0]*(wdt-2*pad),
                    pad+pnt[1]*(hgt-2*pad),dotr,dotr,
                    1,fcfovcol,0x0f,0,NULL);
           
     } 
   }
   if (ofovflg | fofovflg)  {
     for (i=0;i<network->rnum;i++) {
       if (network->radar[i].id==stid) continue;
       if (network->radar[i].status !=1) continue;
       site=RadarYMDHMSGetSite(&(network->radar[i]),yr,mo,dy,hr,mt,sc);
       pnt[0]=site->geolat;
       pnt[1]=site->geolon; 
       s=(*tfunc)(sizeof(float)*2,pnt,2*sizeof(float),pnt,marg);
       if (s==0) PlotEllipse(plot,NULL,pad+pnt[0]*(wdt-2*pad),
                    pad+pnt[1]*(hgt-2*pad),dotr,dotr,
                    1,fofovcol,0x0f,0,NULL);
           
     } 
   }

   if (fovflg) {
     
     site=RadarYMDHMSGetSite(&(network->radar[stnum]),yr,mo,dy,hr,mt,sc);
     pnt[0]=site->geolat;
     pnt[1]=site->geolon; 
     s=(*tfunc)(sizeof(float)*2,pnt,2*sizeof(float),pnt,marg);
     if (s==0) PlotEllipse(plot,NULL,pad+pnt[0]*(wdt-2*pad),
                    pad+pnt[1]*(hgt-2*pad),dotr,dotr,
                    1,ffovcol,0x0f,0,NULL);
   }


 }

  if (fovflg) MapPlotPolygon(plot,NULL,pad,pad,wdt-2*pad,hgt-2*pad,0,
                    fovcol,0x0f,width,NULL,
                    pfov,stnum);

  if (bndflg) MapPlotOpenPolygon(plot,NULL,pad,pad,wdt-2*pad,hgt-2*pad,
                                bndcol,0x0f,width,NULL,
                                pbnd,-1);

  if (trmflg) MapPlotOpenPolygon(plot,NULL,pad,pad,wdt-2*pad,hgt-2*pad,
                                trmcol,0x0f,width,NULL,
                                ptrm,1);

  if (tmkflg) MapPlotPolygon(plot,NULL,pad,pad,wdt-2*pad,hgt-2*pad,0,
                                tmkcol,0x0f,width,NULL,
                                ptmk,1);

  if ((grdflg) && (grdontop)) {
    MapPlotPolygon(plot,NULL,0,0,wdt-2*pad,hgt-2*pad,0,
                                grdcol,0x0f,width,NULL,
                                pgrd,1);
  }


  if ((cylind) || (sqflg)) 
     PlotRectangle(plot,NULL,pad,pad,wdt-2*pad,hgt-2*pad,
               0,grdcol,0x0f,width,NULL);
  else PlotEllipse(plot,NULL,wdt/2,hgt/2,wdt/2-pad,hgt/2-pad,
               0,grdcol,0x0f,width,NULL);

  if (tlblflg){
      if (lat>0) plot_time_label(plot,pad,pad,wdt-2*pad,hgt-2*pad,
				 90,flip,tsfx,
                                 lon-tme_shft*(! rotflg),
                                 (wdt/2)-pad,6,
                                 txtcol,0x0f,fontname,fontsize,fontdb);
      else plot_time_label(plot,pad,pad,wdt-2*pad,hgt-2*pad,
			   -90,flip,tsfx,
                           lon-tme_shft*(! rotflg),
                           (wdt/2)-pad,6,
                           txtcol,0x0f,fontname,fontsize,fontdb);
  }

  PlotPlotEnd(plot);  
  PlotDocumentEnd(plot);

  if (!gflg) exit(0);
  if (img==NULL) {
    fprintf(stderr,"Nothing to plot.\n");
    exit(-1);
  }

#ifdef _XLIB_
  if (xd !=0) {
    dp=XwinOpenDisplay(display_name,&xdf);
 
    if (dp==NULL) {
      fprintf(stderr,"Could not open display.\n");
      exit(-1);
    }

    if (xdoff==-1) xdoff=(dp->wdt-img->wdt)/2;
    if (ydoff==-1) ydoff=(dp->hgt-img->hgt)/2;


    win=XwinMakeWindow(xdoff,ydoff,img->wdt,img->hgt,0,
                       dp,wname,
                       wname,argv[0],wname,argc,argv,&xdf);
    if (win==NULL) {
      fprintf(stderr,"Could not create window.\n");
      exit(-1);
    }

    XwinFrameBufferWindow(img,win);

    XwinShowWindow(win);

    XwinDisplayEvent(dp,1,&win,1,NULL);

    XwinFreeWindow(win);
    XwinCloseDisplay(dp);
  } else {
    if (xmlflg==1) FrameBufferSaveXML(img,stream,stdout);
    else if (ppmflg==1) FrameBufferSavePPM(img,stdout);
    else if (ppmxflg==1)  FrameBufferSavePPMX(img,stdout);
    else FrameBufferSavePNG(img,stdout);
  }
  #else 
    if (xmlflg==1) FrameBufferSaveXML(img,stream,stdout);
    else if (ppmflg==1) FrameBufferSavePPM(img,stdout);
    else if (ppmxflg==1) FrameBufferSavePPMX(img,stdout);
    else FrameBufferSavePNG(img,stdout); 
  #endif
    return 0;
}  
Ejemplo n.º 30
0
int main(int argc,char *argv[]) {
    int arg=0,farg;
    int yr,mo,dy,hr,mt,isc,usc;
    double sc;
    int st=0;
    FILE *fp;
    char *envstr;
    char *tmetxt=NULL,*dtetxt=NULL;
    double tval=0,dval=0;



    char *nlab[2]= {"","name:"};
    char *slab[2]= {"","status:"};
    char *olab[2]= {"","operator:"};
    char *clab[2]= {"","code:"};
    char *ilab[2]= {"","id:"};
    char *hlab[2]= {"","location:"};
    char *plab[2]= {"","pole:"};

    unsigned char nflg=0;
    unsigned char sflg=0;
    unsigned char oflg=0;
    unsigned char cflg=0;
    unsigned char iflg=0;
    unsigned char hflg=0;
    unsigned char pflg=0;
    unsigned char lflg=0;

    unsigned char aflg=0;

    unsigned char stflg=0;
    unsigned char edflg=0;

    unsigned char vb=0;
    unsigned char help=0;
    unsigned char option=0;

    int status,c;

    char *tmp=NULL;
    char ststr[1024];
    int stid[256];
    int stcnt=0;

    char *nldstr="\n";
    char *tdstr="\t";
    char *dstr=NULL;

    OptionAdd(&opt,"-help",'x',&help);
    OptionAdd(&opt,"-option",'x',&option);

    OptionAdd(&opt,"vb",'x',&vb);
    OptionAdd(&opt,"n",'x',&nflg);
    OptionAdd(&opt,"s",'x',&sflg);
    OptionAdd(&opt,"o",'x',&oflg);
    OptionAdd(&opt,"c",'x',&cflg);
    OptionAdd(&opt,"i",'x',&iflg);
    OptionAdd(&opt,"h",'x',&hflg);
    OptionAdd(&opt,"p",'x',&pflg);

    OptionAdd(&opt,"st",'x',&stflg);
    OptionAdd(&opt,"ed",'x',&edflg);

    OptionAdd(&opt,"l",'x',&lflg);

    OptionAdd(&opt,"a",'x',&aflg);

    OptionAdd(&opt,"t",'t',&tmetxt);
    OptionAdd(&opt,"d",'t',&dtetxt);

    OptionAdd(&opt,"delim",'t',&dstr);

    farg=OptionProcess(1,argc,argv,&opt,NULL);

    if (help==1) {
        OptionPrintInfo(stdout,hlpstr);
        exit(0);
    }

    if (option==1) {
        OptionDump(stdout,&opt);
        exit(0);
    }

    if (arg==argc) {
        OptionPrintInfo(stdout,errstr);
        exit(-1);
    }




    if (tmetxt !=NULL) tval=strtime(tmetxt);
    if (dtetxt !=NULL) dval=strdate(dtetxt);

    tval+=dval;

    if (tval !=0) TimeEpochToYMDHMS(tval,&yr,&mo,&dy,&hr,&mt,&sc);
    else {
        TimeReadClock(&yr,&mo,&dy,&hr,&mt,&isc,&usc);
        sc=isc;
        tval=TimeYMDHMSToEpoch(yr,mo,dy,hr,mt,sc);
    }

    if (dstr==NULL) {
        if (lflg) dstr=tdstr;
        else dstr=nldstr;
    }

    envstr=getenv("SD_RADAR");
    if (envstr==NULL) {
        fprintf(stderr,"Environment variable 'SD_RADAR' must be defined.\n");
        exit(-1);
    }

    fp=fopen(envstr,"r");

    if (fp==NULL) {
        fprintf(stderr,"Could not locate radar information file.\n");
        exit(-1);
    }

    network=RadarLoad(fp);
    fclose(fp);
    if (network==NULL) {
        fprintf(stderr,"Failed to read radar information.\n");
        exit(-1);
    }

    envstr=getenv("SD_HDWPATH");
    if (envstr==NULL) {
        fprintf(stderr,"Environment variable 'SD_HDWPATH' must be defined.\n");
        exit(-1);
    }


    RadarLoadHardware(envstr,network);

    for (arg=farg; arg<argc; arg++) {
        strcpy(ststr,argv[arg]);
        tmp=strtok(ststr,",");
        do {
            if (isdigit(tmp[0])) stid[stcnt]=atoi(tmp);
            else stid[stcnt]=RadarGetID(network,tmp);
            if (stid[stcnt] !=-1) stcnt++;
        } while ((tmp=strtok(NULL,",")) !=NULL);
    }

    if (stcnt==0) {
        stcnt=network->rnum;
        for (st=0; st<stcnt; st++) stid[st]=network->radar[st].id;
    }

    for (st=0; st<stcnt; st++) {


        status=RadarGetStatus(network,stid[st]);
        /* if ((aflg) && (status !=1)) continue; */

        radar=RadarGetRadar(network,stid[st]);
        if (radar==NULL) continue;

        if (aflg) {
            if (radar->st_time==-1) continue;
            if (tval<radar->st_time) continue;
            if ((radar->ed_time !=-1) && (tval>radar->ed_time)) continue;
        }

        if (iflg==1) fprintf(stdout,"%s%d%s",ilab[vb],stid[st],dstr);

        if (cflg==1) {
            fprintf(stdout,"%s",clab[vb]);
            for (c=0; (c<RadarGetCodeNum(network,stid[st])); c++)
                if (c !=0) fprintf(stdout,",%s",RadarGetCode(network,stid[st],c));
                else fprintf(stdout,"%s",RadarGetCode(network,stid[st],c));
            fprintf(stdout,"%s",dstr);
        }

        if (nflg==1)
            fprintf(stdout,"%s\"%s\"%s",nlab[vb],RadarGetName(network,stid[st]),
                    dstr);

        if (sflg==1) {
            fprintf(stdout,"%s",slab[vb]);
            if (status==1) fprintf(stdout,"active");
            else if (status==0) fprintf(stdout,"under construction");
            else if (status==-1) fprintf(stdout,"defunct");
            fprintf(stdout,"%s",dstr);
        }

        if (oflg==1) fprintf(stdout,"%s\"%s\"%s",olab[vb],
                                 RadarGetOperator(network,stid[st]),dstr);

        if (stflg) {
            if (radar->st_time !=-1) {
                TimeEpochToYMDHMS(radar->st_time,&yr,&mo,&dy,&hr,&mt,&sc);
                fprintf(stdout,"%.4d%.2d%.2d%s",yr,mo,dy,dstr);
            } else fprintf(stdout,"-%s",dstr);
        }


        if (edflg) {
            if (radar->ed_time !=-1) {
                TimeEpochToYMDHMS(radar->ed_time,&yr,&mo,&dy,&hr,&mt,&sc);
                fprintf(stdout,"%.4d%.2d%.2d%s",yr,mo,dy,dstr);
            } else fprintf(stdout,"-%s",dstr);

        }



        TimeEpochToYMDHMS(tval,&yr,&mo,&dy,&hr,&mt,&sc);
        site=RadarYMDHMSGetSite(RadarGetRadar(network,stid[st]),
                                yr,mo,dy,hr,mt,(int) sc);



        if (hflg) {
            if (site !=NULL) fprintf(stdout,"%s%g,%g,%g,%g%s",hlab[vb],
                                         site->geolat,site->geolon,
                                         site->alt,
                                         site->boresite,dstr);
            else fprintf(stdout,"unknown%s",dstr);
        }
        if (pflg) {
            if (site !=NULL) {
                if (site->geolat>0) fprintf(stdout,"%snorth",plab[vb]);
                else fprintf(stdout,"%ssouth",plab[vb]);
            } else if (radar->site !=NULL) {
                if (radar->site[0].geolat>0) fprintf(stdout,"%snorth",plab[vb]);
                else fprintf(stdout,"%ssouth",plab[vb]);
            } else fprintf(stdout,"unknown");

            fprintf(stdout,"%s",dstr);
        }
        if (lflg) fprintf(stdout,"\n");
    }
    return 0;
}