コード例 #1
0
ファイル: sdiff.c プロジェクト: 0mp/freebsd
static void
perror_fatal (char const *msg)
{
  int e = errno;
  checksigs ();
  error (0, e, "%s", msg);
  exiterr ();
}
コード例 #2
0
ファイル: pxl.c プロジェクト: olgamiller/pxl
void resize_video(int w, int h)
{
	if(!screen || (screen->w != w || screen->h != h))
	{
		if(screen)
			SDL_FreeSurface(screen);

		screen = SDL_SetVideoMode(w, h, 32, SDL_HWSURFACE | SDL_RESIZABLE | SDL_DOUBLEBUF);

		if(!screen)
			exiterr("Unable to set video.\n");
		if(screen->format->BitsPerPixel != 32)
			exiterr("Could not init 32 bit format.\n");
		if(screen->w != w || screen->h != h)
			exiterr("Could not get %dx%d window.\n", w, h);
	}

	set_default_caption();
}
コード例 #3
0
ファイル: cachedel.c プロジェクト: cubicdaiya/nocache
int run(char *fn, int n, double r)
{
    int i, fd;
    struct stat st;
    off_t l;

    fd = open(fn, O_RDONLY);

    if(fd == -1) {
        exiterr("open");
    }

    if(fstat(fd, &st) == -1) {
        exiterr("fstat");
    }

    if(!S_ISREG(st.st_mode)) {
        fprintf(stderr, "%s: S_ISREG: not a regular file", fn);
        return FALSE;
    }

    if(st.st_size == 0) {
        fprintf(stderr, "%s: file size is 0!\n", fn);
        return FALSE;
    }

    if (r < 0.0 || r > 1.0) {
        fprintf(stderr, "%f: rate should be less than 1.0\n", r);
        return FALSE;
    }

    l = (off_t)(st.st_size * r);

    for(i = 0; i < n; i++) {
        if(posix_fadvise(fd, 0, l, POSIX_FADV_DONTNEED) == -1) {
            exiterr("posix_fadvise");
        }
    }

    return TRUE;
}
コード例 #4
0
ファイル: cachedel.c プロジェクト: Danyboy/nocache
int main(int argc, char *argv[])
{
    int i, n = 1;
    int fd;
    char *fn;
    struct stat st;

    if(argc == 4 && !strcmp("-n", argv[1])) {
            n = atoi(argv[2]);
            fn = argv[3];
    } else if(argc != 2) {
        fprintf(stderr, "usage: %s [-n <n>] <file> "
            "-- call fadvise(DONTNEED) <n> times on file", argv[0]);
        exit(1);
    } else {
        fn = argv[1];
    }

    fd = open(fn, O_RDONLY);
    if(fd == -1)
        exiterr("open");

    if(fstat(fd, &st) == -1)
        exiterr("fstat");
    if(!S_ISREG(st.st_mode)) {
        fprintf(stderr, "%s: S_ISREG: not a regular file", fn);
        return EXIT_FAILURE;
    }
    if(st.st_size == 0) {
        fprintf(stderr, "%s: file size is 0!\n", fn);
        return EXIT_FAILURE;
    }

    for(i = 0; i < n; i++)
        if(posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED) == -1)
            exiterr("posix_fadvise");

    return EXIT_SUCCESS;
}
コード例 #5
0
ファイル: pxl.c プロジェクト: olgamiller/pxl
void read_image(int direction)
{
	int i = 0;
	struct stat sb;

	set_filename(direction);

	while(stat(filename, &sb) == -1 || !read_ppm_P6(filename, &img))
	{
		set_filename(direction);

		if(i == args_num)
			exiterr("No file is readable.\n");
		i++;
	}

	last_mtime = sb.st_mtime;
}
コード例 #6
0
ファイル: sdiff.c プロジェクト: DonCN/haiku
static void
ck_editor_status (int errnum, int status)
{
  if (errnum | status)
    {
      char const *failure_msgid = N_("subsidiary program `%s' failed");
      if (! errnum && WIFEXITED (status))
	switch (WEXITSTATUS (status))
	  {
	  case 126:
	    failure_msgid = N_("subsidiary program `%s' not executable");
	    break;
	  case 127:
	    failure_msgid = N_("subsidiary program `%s' not found");
	    break;
	  }
      error (0, errnum, _(failure_msgid), editor_program);
      exiterr ();
    }
}
コード例 #7
0
ファイル: sdiff.c プロジェクト: 0mp/freebsd
static void
check_child_status (int werrno, int wstatus, int max_ok_status,
		    char const *subsidiary_program)
{
  int status = (! werrno && WIFEXITED (wstatus)
		? WEXITSTATUS (wstatus)
		: INT_MAX);

  if (max_ok_status < status)
    {
      error (0, werrno,
	     _(status == 126
	       ? "subsidiary program `%s' could not be invoked"
	       : status == 127
	       ? "subsidiary program `%s' not found"
	       : status == INT_MAX
	       ? "subsidiary program `%s' failed"
	       : "subsidiary program `%s' failed (exit status %d)"),
	     subsidiary_program, status);
      exiterr ();
    }
}
コード例 #8
0
ファイル: dialog.c プロジェクト: BackupTheBerlios/geoirc
static void
Usage(char *msg)
{
    exiterr("Error: %s.\nUse --help to list options.\n\n", msg);
}
コード例 #9
0
ファイル: sdiff.c プロジェクト: 0mp/freebsd
int
main (int argc, char *argv[])
{
  int opt;
  char const *prog;

  exit_failure = EXIT_TROUBLE;
  initialize_main (&argc, &argv);
  program_name = argv[0];
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);
  c_stack_action (cleanup);

  prog = getenv ("EDITOR");
  if (prog)
    editor_program = prog;

  diffarg (DEFAULT_DIFF_PROGRAM);

  /* parse command line args */
  while ((opt = getopt_long (argc, argv, "abBdEHiI:lo:stvw:W", longopts, 0))
	 != -1)
    {
      switch (opt)
	{
	case 'a':
	  diffarg ("-a");
	  break;

	case 'b':
	  diffarg ("-b");
	  break;

	case 'B':
	  diffarg ("-B");
	  break;

	case 'd':
	  diffarg ("-d");
	  break;

	case 'E':
	  diffarg ("-E");
	  break;

	case 'H':
	  diffarg ("-H");
	  break;

	case 'i':
	  diffarg ("-i");
	  break;

	case 'I':
	  diffarg ("-I");
	  diffarg (optarg);
	  break;

	case 'l':
	  diffarg ("--left-column");
	  break;

	case 'o':
	  output = optarg;
	  break;

	case 's':
	  suppress_common_lines = true;
	  break;

	case 't':
	  diffarg ("-t");
	  break;

	case 'v':
	  version_etc (stdout, "sdiff", PACKAGE_NAME, PACKAGE_VERSION,
		       "Thomas Lord", (char *) 0);
	  check_stdout ();
	  return EXIT_SUCCESS;

	case 'w':
	  diffarg ("-W");
	  diffarg (optarg);
	  break;

	case 'W':
	  diffarg ("-w");
	  break;

	case DIFF_PROGRAM_OPTION:
	  diffargv[0] = optarg;
	  break;

	case HELP_OPTION:
	  usage ();
	  check_stdout ();
	  return EXIT_SUCCESS;

	case STRIP_TRAILING_CR_OPTION:
	  diffarg ("--strip-trailing-cr");
	  break;

	case TABSIZE_OPTION:
	  diffarg ("--tabsize");
	  diffarg (optarg);
	  break;

	default:
	  try_help (0, 0);
	}
    }

  if (argc - optind != 2)
    {
      if (argc - optind < 2)
	try_help ("missing operand after `%s'", argv[argc - 1]);
      else
	try_help ("extra operand `%s'", argv[optind + 2]);
    }

  if (! output)
    {
      /* easy case: diff does everything for us */
      if (suppress_common_lines)
	diffarg ("--suppress-common-lines");
      diffarg ("-y");
      diffarg ("--");
      diffarg (argv[optind]);
      diffarg (argv[optind + 1]);
      diffarg (0);
      execvp (diffargv[0], (char **) diffargv);
      perror_fatal (diffargv[0]);
    }
  else
    {
      char const *lname, *rname;
      FILE *left, *right, *out, *diffout;
      bool interact_ok;
      struct line_filter lfilt;
      struct line_filter rfilt;
      struct line_filter diff_filt;
      bool leftdir = diraccess (argv[optind]);
      bool rightdir = diraccess (argv[optind + 1]);

      if (leftdir & rightdir)
	fatal ("both files to be compared are directories");

      lname = expand_name (argv[optind], leftdir, argv[optind + 1]);
      left = ck_fopen (lname, "r");
      rname = expand_name (argv[optind + 1], rightdir, argv[optind]);
      right = ck_fopen (rname, "r");
      out = ck_fopen (output, "w");

      diffarg ("--sdiff-merge-assist");
      diffarg ("--");
      diffarg (argv[optind]);
      diffarg (argv[optind + 1]);
      diffarg (0);

      trapsigs ();

#if ! (HAVE_WORKING_FORK || HAVE_WORKING_VFORK)
      {
	size_t cmdsize = 1;
	char *p, *command;
	int i;

	for (i = 0;  diffargv[i];  i++)
	  cmdsize += quote_system_arg (0, diffargv[i]) + 1;
	command = p = xmalloc (cmdsize);
	for (i = 0;  diffargv[i];  i++)
	  {
	    p += quote_system_arg (p, diffargv[i]);
	    *p++ = ' ';
	  }
	p[-1] = 0;
	errno = 0;
	diffout = popen (command, "r");
	if (! diffout)
	  perror_fatal (command);
	free (command);
      }
#else
      {
	int diff_fds[2];
# if HAVE_WORKING_VFORK
	sigset_t procmask;
	sigset_t blocked;
# endif

	if (pipe (diff_fds) != 0)
	  perror_fatal ("pipe");

# if HAVE_WORKING_VFORK
	/* Block SIGINT and SIGPIPE.  */
	sigemptyset (&blocked);
	sigaddset (&blocked, SIGINT);
	sigaddset (&blocked, SIGPIPE);
	sigprocmask (SIG_BLOCK, &blocked, &procmask);
# endif
	diffpid = vfork ();
	if (diffpid < 0)
	  perror_fatal ("fork");
	if (! diffpid)
	  {
	    /* Alter the child's SIGINT and SIGPIPE handlers;
	       this may munge the parent.
	       The child ignores SIGINT in case the user interrupts the editor.
	       The child does not ignore SIGPIPE, even if the parent does.  */
	    if (initial_handler (handler_index_of_SIGINT) != SIG_IGN)
	      signal_handler (SIGINT, SIG_IGN);
	    signal_handler (SIGPIPE, SIG_DFL);
# if HAVE_WORKING_VFORK
	    /* Stop blocking SIGINT and SIGPIPE in the child.  */
	    sigprocmask (SIG_SETMASK, &procmask, 0);
# endif
	    close (diff_fds[0]);
	    if (diff_fds[1] != STDOUT_FILENO)
	      {
		dup2 (diff_fds[1], STDOUT_FILENO);
		close (diff_fds[1]);
	      }

	    execvp (diffargv[0], (char **) diffargv);
	    _exit (errno == ENOENT ? 127 : 126);
	  }

# if HAVE_WORKING_VFORK
	/* Restore the parent's SIGINT and SIGPIPE behavior.  */
	if (initial_handler (handler_index_of_SIGINT) != SIG_IGN)
	  signal_handler (SIGINT, catchsig);
	if (initial_handler (handler_index_of_SIGPIPE) != SIG_IGN)
	  signal_handler (SIGPIPE, catchsig);
	else
	  signal_handler (SIGPIPE, SIG_IGN);

	/* Stop blocking SIGINT and SIGPIPE in the parent.  */
	sigprocmask (SIG_SETMASK, &procmask, 0);
# endif

	close (diff_fds[1]);
	diffout = fdopen (diff_fds[0], "r");
	if (! diffout)
	  perror_fatal ("fdopen");
      }
#endif

      lf_init (&diff_filt, diffout);
      lf_init (&lfilt, left);
      lf_init (&rfilt, right);

      interact_ok = interact (&diff_filt, &lfilt, lname, &rfilt, rname, out);

      ck_fclose (left);
      ck_fclose (right);
      ck_fclose (out);

      {
	int wstatus;
	int werrno = 0;

#if ! (HAVE_WORKING_FORK || HAVE_WORKING_VFORK)
	wstatus = pclose (diffout);
	if (wstatus == -1)
	  werrno = errno;
#else
	ck_fclose (diffout);
	while (waitpid (diffpid, &wstatus, 0) < 0)
	  if (errno == EINTR)
	    checksigs ();
	  else
	    perror_fatal ("waitpid");
	diffpid = 0;
#endif

	if (tmpname)
	  {
	    unlink (tmpname);
	    tmpname = 0;
	  }

	if (! interact_ok)
	  exiterr ();

	check_child_status (werrno, wstatus, EXIT_FAILURE, diffargv[0]);
	untrapsig (0);
	checksigs ();
	exit (WEXITSTATUS (wstatus));
      }
    }
  return EXIT_SUCCESS;			/* Fool `-Wall'.  */
}
コード例 #10
0
ファイル: sdiff.c プロジェクト: 0mp/freebsd
static void
fatal (char const *msgid)
{
  error (0, 0, "%s", _(msgid));
  exiterr ();
}
コード例 #11
0
ファイル: cachestats.c プロジェクト: CitizenB/nocache
int main(int argc, char *argv[])
{
    int i, j;
    int pages;
    int PAGESIZE;

    int quiet = 0;
    int verbose = 0;

    int fd;
    struct stat st;
    void *file = NULL;
    unsigned char *pageinfo = NULL;

    PAGESIZE = getpagesize();

    if(argc > 1) {
        if(!strcmp("-v", argv[1]))
            verbose = 1;
        else if(!strcmp("-q", argv[1]))
            quiet = 1;
    } else {
        fprintf(stderr, "usage: %s [-qv] <file> "
            "-- print out cache statistics\n", argv[0]);
        fprintf(stderr, "\t-v\tprint verbose cache map\n");
        fprintf(stderr, "\t-q\texit code tells if file is fully cached\n");
        exit(1);
    }

    if(quiet || verbose)
        argv++;

    fd = open(argv[1], O_RDONLY);
    if(fd == -1)
        exiterr("open");

    if(fstat(fd, &st) == -1)
        exiterr("fstat");
    if(!S_ISREG(st.st_mode)) {
        fprintf(stderr, "%s: S_ISREG: not a regular file", argv[1]);
        return EXIT_FAILURE;
    }
    if(st.st_size == 0) {
        fprintf(stderr, "%s: file size is 0!\n", argv[1]);
        return EXIT_FAILURE;
    }

    pages = (st.st_size + PAGESIZE - 1) / PAGESIZE;
    pageinfo = calloc(sizeof(*pageinfo), pages);
    if(!pageinfo)
        exiterr("calloc");

    file = mmap(NULL, st.st_size, PROT_NONE, MAP_SHARED, fd, 0);
    if(file == MAP_FAILED)
        exiterr("mmap");
    if(mincore(file, st.st_size, pageinfo) == -1)
        exiterr("mincore");

    i = j = 0;
    while(i < pages)
        if(pageinfo[i++] & 1)
            j++;

    if(quiet) {
        if(j == i)
            return EXIT_SUCCESS;
        return EXIT_FAILURE;
    }

    printf("pages in cache: %d/%d (%.1f%%)  [filesize=%.1fK, "
        "pagesize=%dK]\n", j, i, 100.0 * j / i,
        1.0 * st.st_size / 1024, PAGESIZE / 1024);

#define PAGES_PER_LINE 32
    if(verbose) {
        printf("\ncache map:\n");
        for(i = 0; i <= (pages - 1) / PAGES_PER_LINE; i++) {
            printf("%6d: |", i * PAGES_PER_LINE);
            for(j = 0; j < PAGES_PER_LINE; j++) {
                if(i * PAGES_PER_LINE + j == pages)
                    break;
                printf("%c|",
                    pageinfo[i * PAGES_PER_LINE + j] & 1 ? 'x' : ' ');
            }
            printf("\n");
        }
    }

    munmap(file, st.st_size);
    return EXIT_SUCCESS;
}
コード例 #12
0
int main(int argc, char** argv)
{
    //reading data values 
    int fd;
    int ctr_numhits=0;
    int num_records=0;
    ssize_t numbytes;
    int compare = 1;
    off_t offset = 0;
    char error_buf[ERROR_BUF_SIZE];
    int headersize=DR_HEAER_SIZE;
    int next_buffer_size=1;
    int datasize=next_buffer_size;
    char *header = (char *) malloc(DR_HEAER_SIZE);
    char *data = (char *) malloc(MAX_DATA_SIZE);

    //plotting variables
    int maxbin = 0;
    int maxvalue = 0;
    int xmax = (int) BINS;

    //data values
    int finebin = 0 ;
    int bytesread = 1;
    int value;
    int pfb_bin = 0;
    int fft_bin = 0;
    int fft_bin_loc= 0;
    int over_thresh = 0;
    int blank = 0;
    int event = 0;
    unsigned int pfb_fft_power = 0;
    unsigned int fields;
    long int i = 0;
    int j = 0;
    int k = 0;
    int ctr = 0;
    int counter=0;
    int beamnum = 0;
    double fstep,fscoarse = 0.0;
    double rfmin,rfctr = 0.0;
    double freq_fft_bin = 0.0;
    double bary_freq = 0.0;
    char rawfile[] = "largefile_MMMDDYYYY_HHMM";
    int gooddata=1;
    int goodfreq=1;

    long int fileposition=0;   //position in input file
    long int filesize;   //position in input file

    FILE *fout;
    //create buffers
    struct spectral_data spectra;

    struct data_vals *data_ptr;
    data_ptr = (struct data_vals *)data;

    //create header structure
    struct setidata frame;

    // create time structure
    tm hittime;
    double spec_time;

    // create SQL structures
    unsigned long int specid;
    //strcpy(def_password, argv[2]);
    char sqlquery[1024];
    char hitquery[1024];

    // file variables
    FILE *datatext;


    // connect to mySQL database
    dbconnect();

#ifdef GRACE
    // Initialize grace plotting windows
    grace_init();
//    grace_open_deux(8192);
//    grace_init_deux(maxbin,maxvalue,xmax);
#endif

    //check for error opening file
    fd = open(argv[1], O_RDONLY);

    if(fd==-1)
    {
        snprintf(error_buf, ERROR_BUF_SIZE, "Error opening file %s", argv[1]);
        perror(error_buf);
        return 0;
    }

    //if we can't find a header, nothing to be done
    if(find_first_header(fd)==-1) return 0;

    //read header
    //make sure we are reading as much data as expected, otherwise might be at eof
    while(headersize==DR_HEAER_SIZE && datasize==next_buffer_size)
    {
        k = k+1;
	//reset dataflag to "good"
	gooddata=1;

	// read in the header data
        headersize = read(fd, (void *) header, DR_HEAER_SIZE);
	fileposition+=headersize;

//        int iii=0;
//        for(iii=0; iii<DR_HEAER_SIZE; iii++)
//            printf("%c", header[iii]);

	//get the size of spectra and parse header values
        next_buffer_size = read_header(header);

        read_header_data(header, &frame);

	//Read in data
        datasize = read(fd, (void *) data, next_buffer_size);
	fileposition+=datasize;

//        printf("Buffersize, datasize: %d %d\n", next_buffer_size, datasize);
//	int iii=0;
//	printf("Printing data header\n");
//	for(iii=0; iii<datasize; iii++)
//		printf("%c", data[iii]);

	//Parse data header
        beamnum = read_beam(data, datasize);
        read_data_header(data, &frame);

	//Convert to RA and Dec
        scramAzZatoRaDec(frame.agc_systime, frame.agc_time, frame.agc_az, frame.agc_za, 
                frame.alfashm_alfamotorposition, beamnum/2, 0, &frame.ra, &frame.dec,  &hittime);

	get_filename(argv[1], rawfile);
//	printf("%s\n", rawfile);

	//Calculate MJD
	spec_time = time2mjd(frame.agc_systime, frame.agc_time);

        // creates query to config table
        // set digital_lo and board to be constants, because we figured we knew
        // what they were and that they weren't changing
        char bid[] = "B2";
        sprintf(sqlquery, "INSERT INTO config (thrscale, thrlimit, fftshift, pfbshift, beamnum, obstime, ra, decl, digital_lo, board, AGC_SysTime, AGC_Time, AGC_Az, AGC_Za, AlfaFirstBias, AlfaSecondBias, AlfaMotorPosition, IF1_rfFreq, synI_freqHz, IF1_synI_ampDB, IF1_if1FrqMHz, IF1_alfaFb, TT_TurretEncoder, TT_TurretDegrees, rawfile) VALUES (%ld, %ld, %ld, %ld, %d, %lf, %lf, %lf, %ld, '%s', %ld, %ld, %lf, %lf, %ld, %ld, %lf, %9.1lf, %9.1lf, %ld, %lf, %ld, %ld, %lf, '%s')", 
                frame.thrscale, frame.thrlimit, frame.fft_shift, frame.pfb_shift,
                beamnum, (double) ((int) spec_time), frame.ra, frame.dec, 200000000, bid, frame.agc_systime, frame.agc_time, 
                frame.agc_az, frame.agc_za, frame.alfashm_alfafirstbias, frame.alfashm_alfasecondbias, 
                frame.alfashm_alfamotorposition, frame.if1_rffreq, frame.if1_syni_freqhz_0, frame.if1_syni_ampdb_0, 
                frame.if1_if1frqmhz, frame.if1_alfafb, frame.tt_turretencoder, frame.tt_turretdegrees, rawfile);

#ifndef DEBUG
        // insert header data into serendipvv config table
        if (mysql_query(conn, sqlquery)) {
            fprintf(stderr, "Error inserting data into sql database... \n");
            exiterr(3);
        }

        // saves specid to be inserted at index in other sql tables
        if ((res = mysql_store_result(conn))==0 && mysql_field_count(conn)==0 && mysql_insert_id(conn)!=0) {
            specid = (unsigned long int) mysql_insert_id(conn);
        }
#endif

#ifdef DEBUG
	printf("%s\n", sqlquery);
	printf("Spec id: %d\n", specid);
#endif
        //doesn't do any bounds checking yet...
        spectra.numhits = read_data(data, datasize) - 4096;

	//printf("size of spectra %d\n",spectra.numhits);
	//header,data
	data_ptr = (struct data_vals *) (data+SETI_HEADER_SIZE_IN_BYTES);

    //======================== TEST FILE DATA DUMP ================

    /*
        FILE *datafile;
        char dataf[100];
        sprintf(dataf,"datafiles/datafile%d.dat",counter);
        datafile = fopen(dataf,"wb");
        fwrite(data,spectra.numhits,1,(FILE *)datafile);
        fflush(datafile);
        fclose(datafile);  
    */

		
    //==============================================

        num_records = read_data(data,datasize);
	ctr_numhits=0;

        //create file spectraldata and print file header
/*        char filename[BUFSIZ];
        sprintf(filename, "spectraldata%d", beamnum);
        datatext = fopen(filename,"w");
        fprintf(datatext, "specnum,beamnum,coarsebin,coarsepower,hitpower,fftbin\n");
*/
        //Calc values for freq_topo calc
        //Freq chan resolution
        fstep = 200000000.0/134217728;
        fscoarse = 200000000.0/4096;
	//Center of the BEE2 bandpass
        rfctr = frame.if1_rffreq - 50000000.0;
	//Right edge of the last bin is the lowest freq
	//because the RF band is flipped in the IF
//	rfmin=rfctr-0.5*fscoarse;
        rfmin=rfctr+0.5*fscoarse;

	//Check to see if there are too many hits
	if(num_records>0.9*frame.thrlimit*4096) {
	    gooddata=0;
	    fprintf(stderr, "Data bad...more than %5.0lf hits.\n",  0.9*frame.thrlimit*4096);
	}

//****OPEN FILE TO WRITE HITS TO
        fout=fopen("hits_list.txt", "w");
//============================
//         LOOP OVER HITS
//=============================
	for(i=0;i< num_records ;i++)
	{
	    goodfreq=1;
	    fields = ntohl(data_ptr->raw_data);
	    fft_bin = slice(fields,15,0);
	    pfb_bin = slice(fields,12,15);
	    over_thresh = slice(fields,1,27);
	    blank = slice(fields,3,28);
	    event = slice(fields,1,31);
	    
	    pfb_fft_power = ntohl(data_ptr->overflow_cntr); //32.0
//	    pfb_fft_power = data_ptr->overflow_cntr; //32.0

	    //Rearrange the bins
	    //1) Reorder the FFT output order
	    //2) Reverse bins due to RF/IF flip
            pfb_bin = (pfb_bin + 2048) % 4096;
//	    pfb_bin = 4096 - pfb_bin;
	    pfb_bin = 4095 - pfb_bin;
	    fft_bin = (fft_bin + 16384) % 32768;
//	    fft_bin = 32768 - fft_bin;
	    fft_bin = 32767 - fft_bin;
            fft_bin_loc = fft_bin;
            fft_bin+=pfb_bin*32768;

	    freq_fft_bin =  rfmin + fstep*fft_bin;

	    //Check that the freq of the hit falls within the valid ranges
	    if(frame.if1_alfafb==1){
	        if(freq_fft_bin < NBF_FREQ_LO || freq_fft_bin > NBF_FREQ_HI)  goodfreq=0;
	    }
	    else if(frame.if1_alfafb==0){
                if(freq_fft_bin < ALFA_FREQ_LO || freq_fft_bin > ALFA_FREQ_HI)  goodfreq=0;
	    }
           
            value = (int) (pfb_fft_power);
            //printf("%d %d %d %d %d %d\n", pfb_bin, fft_bin, pfb_fft_power, blank, event, over_thresh);

	    if(value < 1)
	    {
                value = 1;
	    }

	    if(value > maxvalue)
	    {
                maxvalue = value;
                maxbin = fft_bin;
	    }

	   //populate coarse bin power
	    if(fft_bin_loc==16383)
	    {
                spectra.coarse_spectra[pfb_bin] = value;
	    }

            //Only generate string and insert into database if hit valid
	    if(fft_bin_loc!=16383 && goodfreq==1 && gooddata==1)
	    {
//                spectra.hits[ctr_numhits][0] = value;  
//                spectra.hits[ctr_numhits][1] = fft_bin;  

		//Calculate the frequency of the fine bins and barycenter
		bary_freq=freq_fft_bin+seti_dop_FreqOffsetAtBaryCenter(freq_fft_bin, 
			spec_time+2400000.5, frame.ra, frame.dec, 2000.0, AO_LAT, AO_LONG, AO_ELEV);


                //Prepare mysql query to insert hits
                sprintf(hitquery, "INSERT INTO hit (eventpower, meanpower, binnum, topocentric_freq, barycentric_freq, specid) VALUES (%f, %e, %d, %lf, %lf, %ld)", (double) value, (double) spectra.coarse_spectra[pfb_bin], fft_bin, freq_fft_bin, bary_freq, specid);

                //Write row to tmp file
                fprintf(fout, "\\N\t %f\t %e\t %d\t %lf\t %lf\t 0\t 0\t 0\t 0\t 0\t %ld\t \n", (double) value, (double) spectra.coarse_spectra[pfb_bin], fft_bin, freq_fft_bin, bary_freq, specid);
/*
#ifndef DEBUG
                // insert header data into serendipvv config table
                if (mysql_query(conn, hitquery)) {
                    fprintf(stderr, "Error inserting data into sql database... \n");
                    exiterr(3);
                }
#endif */

            }

            // fill spectraldata with available data and close file
//            fprintf(datatext, "%d, %d, %d, %e, %f, %d\n", k, beamnum, pfb_bin, (double) spectra.coarse_spectra[pfb_bin], (double) value, fft_bin);
	
            ctr_numhits++;
	    data_ptr++;
	    ctr++;		
	}//for(i=0; i<num_records; i++)

        fclose(fout);

        sprintf(hitquery, "LOAD DATA LOCAL INFILE 'hits_list.txt' INTO TABLE hit");
//        printf("%s\n", hitquery);

        if (mysql_query(conn, hitquery)) {
            fprintf(stderr, "Error inserting data into sql database... \n");
            exiterr(3);
        }

//        fclose(datatext);
#ifndef DEBUG
       if(load_blob(conn, specid, spectra.coarse_spectra)!=0)
       {
               fprintf(stderr, "Blob not loaded\n");
               specid=0;
       }
#endif

//	GracePrintf("autoticks");
//	GracePrintf("redraw");
//	GracePrintf("updateall");
//	GracePrintf("kill g0.s0");
//	GracePrintf("saveall \"plots/sample%d.agr\"",counter);
//	grace_init_deux(maxbin,log10(maxvalue),xmax);	

	counter++;
        
        for(i=0;i<4094;i++) {
            spectra.coarse_spectra[i] = spectra.coarse_spectra[i+1];
        }

#ifdef GRACE	
    	plot_beam(&spectra,beamnum);
        printf("num_records: %d spectra.numhits %d\n",num_records,spectra.numhits);
        usleep(200000);
    
	if(counter%10 == 0) { 
            printf("autoscaling...\n");
            GracePrintf("redraw");
            GracePrintf("updateall");
            GracePrintf("autoscale");

            /*
            //output pdf via grace

            GracePrintf("HARDCOPY DEVICE \"EPS\"");
            printf("start eps create\n");
            GracePrintf("PAGE SIZE 600, 600");
            GracePrintf("saveall \"sample.agr\"");
            GracePrintf("PRINT TO \"%s\"", "plot.eps");
            GracePrintf("PRINT");
            */

	}
#endif
    }
//=====================================================
/*
    // play with some text 
    for(i=0; i<10; i++){
         GracePrintf("WITH STRING %d", i);
         GracePrintf("STRING COLOR 0");
         GracePrintf("STRING FONT 8");

         GracePrintf("STRING DEF \"TEST\"");
         GracePrintf("STRING ON");

         GracePrintf("STRING LOCTYPE view");
         GracePrintf("STRING 0.70, %f", 0.95 - (((float) i) / 40.0) );
    }

    GracePrintf("redraw");

    sleep(5);
*/
//===========================================================

#ifdef GRACE
     if (GraceIsOpen()) {
         //Flush the output buffer and close Grace 
         GraceClose();
         // We are done 
         exit(EXIT_SUCCESS);
     } else {
         exit(EXIT_FAILURE);
     }
#endif

    //close file
    close(fd);
    
    return 0;
}