Пример #1
0
/* Routine to test the extra bytes at the end of file */ 
   void  test_end(fitsfile *infits, 
		  FILE *out) 

{   
   int status = 0; 
   LONGLONG headstart, datastart, dataend;
   int hdutype;

   /* check whether there are any HDU left */ 
   fits_movrel_hdu(infits,1, &hdutype, &status);
   if (!status) {
       wrtout(out,"< End-of-File >");
       sprintf(errmes, 
    "There are extraneous HDU(s) beyond the end of last HDU.");
       wrterr(out,errmes,2);
       wrtout(out," ");
       return;
   }

   if (status != END_OF_FILE) { 
      wrtserr(out,"Bad HDU? ",&status,2);
      return;
   } 

   status = 0;  
   fits_clear_errmsg();
   if(ffghadll(infits, &headstart, &datastart, &dataend, &status)) 
       wrtferr(out, "",&status,1);

   /* try to move to the last byte of this extension.  */
   if (ffmbyt(infits, dataend - 1,0,&status))
   {
       sprintf(errmes, 
   "Error trying to read last byte of the file at byte %ld.", (long) dataend);
       wrterr(out,errmes,2);
       wrtout(out,"< End-of-File >");
       wrtout(out," ");
       return;
   } 

   /* try to move to what would be the first byte of the next extension. 
     If successfull, we have a problem... */

   ffmbyt(infits, dataend,0,&status);
   if(status == 0) { 
       wrtout(out,"< End-of-File >");
       sprintf(errmes, 
     "File has extra byte(s) after last HDU at byte %ld.", (long) dataend);
       wrterr(out,errmes,2);
       wrtout(out," ");
   } 

   return;
}
Пример #2
0
int cfits_movrel_hdu (int nmove, cfitsfile *fptr)
{
   int status = 0;
   int *hdutype = NULL;

   (void) fits_movrel_hdu((fitsfile *) fptr, nmove, hdutype, &status);
   cfits_report_error (status);

   if (status != 0) return -1;
   return 0;
}
Пример #3
0
int main(int argc, char **argv)  {
  const char *prog_name = argv[0];

  if (argc <= 1) usage(prog_name, EXIT_FAILURE);

  struct option const long_opts[] = {
    GETOPT_HV_OPTIONS_STR,
    {NULL, 0, NULL, 0}
  };
  
  /* loop over arguments */
  int c;
  while ((c = getopt_long(argc, argv, "", long_opts, NULL)) != -1) {
    switch (c) {
      
    case 0:  /* long option */
      break;
      
      GETOPT_HV_OPTIONS_CASE(prog_name);

    default: 
      usage(prog_name,EXIT_FAILURE);
    }
  }

  int status, i, nrelhdu;
  fitsfile *fptr;

  /* loop over file names */
  while (optind<argc) { 

    fptr = fits_init(argv[optind++], READONLY, &nrelhdu, &status);
    if (!fptr) continue;

    /* print main HDU header */
    fits_print_header(fptr, &status);

    /* loop over other HDUs */
    for (i=0; i<nrelhdu; i++) {
      fits_movrel_hdu(fptr, 1, NULL, &status);
      fits_print_header(fptr, &status);
    }

    fits_close(fptr, &status);
  }
  
  return EXIT_SUCCESS;
}
Пример #4
0
/* Wrapper to fits_movabs_hdu */
SEXP
cfitsio_movrel_hdu (SEXP fits_object,
		    SEXP hdu_num)
{
    fits_file_t * fits = R_ExternalPtrAddr (fits_object);

    if (NULL != fits && NULL != fits->cfitsio_ptr)
    {
	int hdu_type;

	fits_movrel_hdu (fits->cfitsio_ptr, asInteger (hdu_num),
			 &hdu_type, &(fits->status));
	return mkString (hdu_type_name (hdu_type));
    }
    else
	return mkString (ERROR_STR);
}
Пример #5
0
/**
 * Function: get_num_extensions
 * The function determines the number of extensions in
 * the fits file. Here the primary extension does not count.
 *
 * Parameters:
 * @param  spectral_models_file - pathname to the spectral models file
 *
 * Returns:
 * @return n_models              - the number of spectral models
 */
int
get_num_extensions(const char spectral_models_file[])
{
  int n_ext=0;
  int n_models=0;
  int i;
  int f_status=0;


  fitsfile *s_models;

  // open the fits file
  // report any error
  fits_open_file (&s_models, spectral_models_file, READONLY, &f_status);
  if (f_status)
    {
      ffrprt (stderr, f_status);
      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
		   "aXe_PETCONT: " "Could not open file: %s",
		   spectral_models_file);
    }

  // do until a fits error occurs
  while (!f_status)
    {
      // move one extension forward
      fits_movrel_hdu (s_models, 1, NULL, &f_status);

      // count up
      n_ext++;
    }
  
  // close the fits file
  fits_close_file (s_models, &f_status);

  // the zeroth extension
  // does nnot count!!
  n_models = n_ext - 1;
  
  // return the 
  return n_models;
}
Пример #6
0
int main(int argc, char **argv)
{

  int             i_file,i_scan,i_chan,i_bin,n_omit,status=0;
  int             NFirstTable, NumHDU, NDumps, TotDumps=0, hdutype;
  // int             OutChans;
  int             spk;
  int             got_bins=0, got_mjd1=0; //, zeroed_outprofs=0;
  long            NPtsProf=0, FirstNPtsProf=0;
  float           Weight=1.0, TotWeight=0.;
  // int             ProfSum=0;
  double          x, ptype;
  double          MJD_first=0., MJD_last=0., MJD_mid;
  double          IMJDMid, MJDSecsMid;
  double          SBase,Srms,Duty,SPeak,FinalMask[NBINMAX];
  double          OutFreq;
  char            ProgName[32];
  char            Outfile[128];
  char            Header[256];  
  struct ASPHdr   *Hdr;
  struct SubHdr   Subhdr;
  struct StdProfs *InProfile, OutProfile;
  struct RunVars  RunMode;
  fitsfile        **Fin;
  FILE            *Fout, *Fcheck;
  Cmdline         *Cmd;


  /* Get command line variables */
  Cmd = parseCmdline(argc, argv);  

  /* Normally use this somewhere, and not showOptionValues */
  Cmd->tool = Cmd->tool;

  strcpy(ProgName, argv[0]);

  Fin = (fitsfile **)malloc(Cmd->InfileC*sizeof(fitsfile));
  Hdr = (struct ASPHdr *)malloc(Cmd->InfileC*sizeof(struct ASPHdr));

  /* Dynamically allocate RunMode variables */
  if (AllocRunMode(&RunMode) < 0){
    printf("Could not allocate RunMode structure.  Exiting...\n");
    exit(2);
  }
  strcpy(RunMode.Infile,Cmd->Infile); 
  

 //    if(!zeroed_outprofs) {
      /*     if(Cmd->SortChansP){
	     OutChans=Hdr[0].obs.NChan;
	     } 
	     else{ */
  // OutChans=1;
  // }
  // OutProfile=(struct StdProfs *)malloc(OutChans*sizeof(struct StdProfs));
  // TotWeight=(float *)malloc(OutChans*sizeof(float));
  
  /* Zero out profiles */
  //     for(i_chan=0;i_chan<OutChans;i_chan++){
  FZero(OutProfile.rstds,NBINMAX);
  FZero(OutProfile.rstdq,NBINMAX);
  FZero(OutProfile.rstdu,NBINMAX);
  FZero(OutProfile.rstdv,NBINMAX);
  // }
  //zeroed_outprofs=1;
      //    }

  /* Create an output file to check omissions if in vebose mode */
  if (Cmd->VerboseP || Cmd->CheckOmitP){
    if((Fcheck = fopen("check_omit.dat","w")) == 0)
       { printf("Cannot open %s. Exiting...\n",Outfile); exit(1); }   
  }


  /* read in all input files and add each to the final profile */

  /* read in all input file headers */
  NPtsProf=0;
  for (i_file=0;i_file<Cmd->InfileC;i_file++){
    n_omit=0;
    status=0;    
    if(fits_open_file(&Fin[i_file], Cmd->Infile[i_file], READONLY, &status)){
      printf("Error opening FITS file %s !!!\n", Cmd->Infile[i_file]);
      exit(1);
    }
    if(ReadASPHdr(&Hdr[i_file], Fin[i_file]) < 0){
      printf("%s> Unable to read Header from file %s.  Exiting...\n",
	     ProgName,Cmd->Infile[i_file]);
      exit(1);
    }

    /* Write file name in verbose-mode omit check file */
    if(Cmd->VerboseP || Cmd->CheckOmitP) 
      fprintf(Fcheck, "\n%s\n",Cmd->Infile[i_file]);


    /* for now just check if all files have same number of channels */
    /* if(Cmd->SortChansP)
        if(i_file>0 && Hdr[i_file].obs.NChan!=Hdr[0].obs.NChan){
        fprintf(stderr,"%s> Different numbers of channels in different files:\n\n",
        ProgName);
        fprintf(stderr,"%s: %d channels,  %s: %d channels\n",
	Cmd->Infile[0],Hdr[0].obs.NChan,
	Cmd->Infile[i_file],Hdr[i_file].obs.NChan);
	} */
    
    /* now find the number of dumps in the file */    
    fits_get_num_hdus(Fin[i_file], &NumHDU, &status);
    if(!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0")){
      NDumps = NumHDU-3;  /* the "3" is temporary, depending on how 
				   many non-data tables we will be using */
    }
    else if(!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0.1")){
      NDumps = (NumHDU-3)/2;
    }
    else{
      fprintf(stderr,"%s> Do not recognize FITS file version in header.\n",
	      ProgName);
      fprintf(stderr,"This header is %s. Exiting...\n",Hdr[i_file].gen.HdrVer);
      exit(1);
    }

    printf("File %s:\n",Cmd->Infile[i_file]);
    printf("     Number of channels:  %d\n",Hdr[i_file].obs.NChan) ;
    printf("     Number of dumps:     %d\n",NDumps);

    /* Move to the first data table HDU in the fits file */
    if(!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0"))
      fits_movnam_hdu(Fin[i_file], BINARY_TBL, "STOKES0", 0, &status);
    else if (!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0.1"))
      fits_movnam_hdu(Fin[i_file], ASCII_TBL, "DUMPREF0", 0, &status);

    /* Get the current HDU number */
    fits_get_hdu_num(Fin[i_file], &NFirstTable);

    /* Set up Profile structure size */


    for(i_scan=0;i_scan<NDumps;i_scan++){
      
      InProfile=(struct StdProfs *)malloc(Hdr[i_file].obs.NChan*
					sizeof(struct StdProfs));
     /* move to next dump's data */
      if(!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0")){
	fits_movabs_hdu(Fin[i_file], NFirstTable+i_scan, &hdutype, &status); 
      }
      else if(!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0.1")){
	/* if we've reached the end of the FITS file then increase FileNo */
	fits_movabs_hdu(Fin[i_file],NFirstTable+(i_scan%MAXDUMPS)*2+1,&hdutype,
			&status);
	fits_get_num_rows(Fin[i_file], &NPtsProf, &status);status=0; 
	fits_movrel_hdu(Fin[i_file], -1, NULL, &status);
      }
      
      /* IF not done so, use number of bins from first file to compare to 
	 the rest of the files */
      if(got_bins==0){
	FirstNPtsProf=NPtsProf;  
	got_bins=1;
      }

      /**********  FIX:  SKIP THIS WITHOUT DOING THE OMIT THING ***********/
      /**********         AND DON'T ADD TO NUMBER COUNT  ************/
      if(NPtsProf != FirstNPtsProf) {
	fprintf(stderr,"Warning: Skipping scan %d (%ld bins ",
		i_scan,NPtsProf);
	fprintf(stderr,"vs. %ld bins in others).\n",FirstNPtsProf);
		
	n_omit += Hdr[i_file].obs.NChan;
      }
      else{
	
	/* find NPtsProf */
	ReadASPStokes(&Hdr[i_file], &Subhdr, Fin[i_file], NPtsProf, 
		      InProfile, i_scan, Cmd->VerboseP);
	
	
	/* Add this profile onto running output profile */
	
	for(i_chan=0;i_chan<Hdr[i_file].obs.NChan;i_chan++){
	  
	  /* Bad scans are zeroed so if summ of the profile is zero, it's 
	     not to be used in summation */
	  //	  ProfSum = FSum(&InProfile[i_chan].rstds[0], NPtsProf);
	  //	  ProfSum = 0;
	  // ProfSum = ArrayZero(InProfile[i_chan].rstds, NPtsProf);
	  //	  if(ProfSum != 0.0) { // i.e. good data
	  /* Test that all bins in current profile are not zeroed */
	  if(!ArrayZero(InProfile[i_chan].rstds, NPtsProf)) { // i.e. good data
	    //	  if(InProfile[i_chan].rstds[0] > -99998.) { // i.e. good data
	    
	    /* If first MJD has not been registered, then do so since this 
	       would be the first non-omitted scan */
	    if (got_mjd1==0) {
	      MJD_first = (double)Hdr[i_file].obs.IMJDStart + 
		Subhdr.DumpMiddleSecs/86400.;
	      got_mjd1=1;
	    }
	    if (i_scan==NDumps-1) {
	      /* Just keep overwriting MJD_last every i_file -- that way we 
		 ensure getting the last MJD of the FINAL non-omitted scan 
		 used */
	      MJD_last = (double)Hdr[i_file].obs.IMJDStart + 
		Subhdr.DumpMiddleSecs/86400.;
	    }

	    /* Get SNR for each Profile if we want to use weighting; 
	       otherwise weights will all be 1.0 */
	    if(Cmd->WeightP) {
	      Duty = DutyLookup(Hdr[i_file].target.PSRName);
	      BMask(InProfile[i_chan].rstds,&Hdr[i_file].redn.RNBinTimeDump,
		    &Duty,FinalMask);
	      Baseline(InProfile[i_chan].rstds,FinalMask,
		       &Hdr[i_file].redn.RNBinTimeDump,&SBase,&Srms);
	      SPeak =  FindPeak(InProfile[i_chan].rstds,
				&Hdr[i_file].redn.RNBinTimeDump,&spk);
	      InProfile[i_chan].SNR = SPeak*Srms;
	      //	      Weight = InProfile[i_chan].SNR;
	      Weight = Srms; // which is actually 1/RMS.
	    }
	    // printf("SNR %d = %lf\n",i_chan,InProfile[i_chan].SNR);
	    
	    /* Need to figure out how to organize input channels to match 
	     *  output channels */
	    /* if(Cmd->SortChansP){
	          for(i_bin=0;i_bin<NPtsProf;i_bin++) {
	             OutProfile[i_chan].rstds[i_bin] +=
		     Weight*InProfile[i_chan].rstds[i_bin];
		     OutProfile[i_chan].rstdq[i_bin] +=
		     Weight*InProfile[i_chan].rstdq[i_bin];
		     OutProfile[i_chan].rstdu[i_bin] +=
		     Weight*InProfile[i_chan].rstdu[i_bin];
		     OutProfile[i_chan].rstdv[i_bin] +=
		     Weight*InProfile[i_chan].rstdv[i_bin];
		  }
	       } 
	       else{ */
	    for(i_bin=0;i_bin<NPtsProf;i_bin++) {
	      OutProfile.rstds[i_bin] += 
		Weight*InProfile[i_chan].rstds[i_bin];
	      OutProfile.rstdq[i_bin] += 
		Weight*InProfile[i_chan].rstdq[i_bin];
	      OutProfile.rstdu[i_bin] += 
		Weight*InProfile[i_chan].rstdu[i_bin];
	      OutProfile.rstdv[i_bin] += 
		Weight*InProfile[i_chan].rstdv[i_bin];  
	      //   printf("%f\n",OutProfile[0].rstds[i_bin]);fflush(stdout);
	    }
	    //  }
	    TotWeight += Weight;  // for now keep at zero index
	    /* Print profile weights for each scan, for each channel */
	    if(RunMode.Verbose) {
	      if(i_chan==0) printf("Profile weights -- scan %d: \n   ",i_scan);
	      printf("%6.2f  ",Weight);
	      if(i_chan==Hdr[i_file].obs.NChan-1) printf("\n");fflush(stdout);
	    }
	  }
	  else {
	    n_omit++;
	    if(Cmd->VerboseP || Cmd->CheckOmitP){
	      fprintf(Fcheck, "%6d     %.1lf\n",
		      i_scan,Hdr[i_file].obs.ChanFreq[i_chan]);
	 /* printf("File %d, Dump %d, Channel %d (%lf MHz) were found to be\n",
		   i_file,i_scan,i_chan,Hdr[i_file].obs.ChanFreq[i_chan]);
	    printf("  zeroed and so are not included.\n");fflush(stdout); */
	    }
	  }
	  //    if(i_chan==0) {for(i=0;i<50;i++) printf("%lf  ",OutProfile[0].rstds[i]);printf("\n\n");fflush(stdout);};
	}
	
	/*****************/
	
	/*     }  */
	
	
      } /* else from positive check on NPtsProf */
     free(InProfile);
    }    
    /****** maybe bring this inside the ELSE where entire scans aren't being omitted ******/
    /* if (Cmd->SortChansP) 
      TotDumps += (NDumps - n_omit);
      else */ 
    TotDumps += (NDumps*Hdr[i_file].obs.NChan - n_omit); 
    //free(InProfile);
    
    printf("Reading of file %s complete and successful.\n",
	     Cmd->Infile[i_file]);
    printf("%d scans omitted.\n\n",n_omit);fflush(stdout);
  }

  if(Cmd->VerboseP || Cmd->CheckOmitP) fclose(Fcheck);

  /* Appease the format of the MakePol routine by making up these RunMode 
     structure members */
  strcpy(RunMode.Source,Hdr[0].target.PSRName);
  RunMode.Verbose = Cmd->VerboseP;
  RunMode.FlipPA = 0;
  RunMode.NoBase = Cmd->NoBaseP;
  /* divide out total number of dumps to get the average */
  // for(i_chan=0;i_chan<OutChans;i_chan++){
   
  printf("Totdumps = %d\n",TotDumps);
  fflush(stdout);
  
  for(i_bin=0;i_bin<NPtsProf;i_bin++) {
    OutProfile.rstds[i_bin] /= TotWeight;
    OutProfile.rstdq[i_bin] /= TotWeight;
    OutProfile.rstdu[i_bin] /= TotWeight;
    OutProfile.rstdv[i_bin] /= TotWeight;
  }
  
  MakePol(&RunMode, (int)NPtsProf, &OutProfile);
  /* Open file for writing */
  sprintf(Outfile,"AddProf.out");
  
  /* now write the output ascii added profile */
  if ((Fout = fopen(Outfile,"w")) == 0)
    { printf("Cannot open %s. Exiting...\n",Outfile); exit(1); }
  
  /* take average MJD of first to last scan */
  MJD_mid = (MJD_first + MJD_last)/2.;
  IMJDMid = floor(MJD_mid);
  MJDSecsMid = (MJD_mid - IMJDMid)*86400.;
  
  printf("MJD_mid = %lf, IMJDMid = %lf, MJDSecsMid = %lf\n",MJD_mid,IMJDMid,MJDSecsMid);fflush(stdout); 

  /* to choose a channel to put in the header for now, ust use the average 
     of the first datafile's channels */ 
  OutFreq=0.;
  for(i_chan=0; i_chan<Hdr[0].obs.NChan; i_chan++){
    OutFreq += Hdr[0].obs.ChanFreq[i_chan];
  }
  OutFreq /= Hdr[0].obs.NChan;

  /* Create and print header line for output file(s) */
  sprintf(Header,"# %.1f %.7f %.10f %ld %.3f %.3f %d %s %d %9s %.10f",
	  IMJDMid, 
	  MJDSecsMid, 
	  //	  Subhdr.DumpRefPeriod[i_chan],
	  0.,
	  (long)1, OutFreq,
	  //	    Hdr[0].obs.DM, Hdr[i_file].redn.RNBinTimeDump,
	  Hdr[0].obs.DM, (int)NPtsProf,
	  Hdr[0].obs.ObsvtyCode, 1, Hdr[0].target.PSRName, 
	  0.);             
  //	  Subhdr.DumpRefPhase[i_chan]);             
  fprintf(Fout,"%s\n",Header);
  
  for(i_bin=0;i_bin<NPtsProf;i_bin++) {
    /* see how strong the linear polarization is */
    x = OutProfile.stdlin[i_bin]*OutProfile.Srms; 
    ptype = 43.1;
    if (x > 1.) ptype=43.2;
    if (x > 2.) ptype=43.3;
    if (x > 3.) ptype=43.4;
    if (x > 4.) ptype=43.5;
    if (x > 5.) ptype=43.6;
    fprintf(Fout,"%5d%15.7f%15.7f%15.7f%15.7f%15.7f%15.7f%15.7f%6.1f\n",i_bin,
	    OutProfile.rstds[i_bin],OutProfile.rstdq[i_bin],
	    OutProfile.rstdu[i_bin],
	    OutProfile.rstdv[i_bin],
	    /* phi in degrees */
	    OutProfile.stdlin[i_bin],
	    OutProfile.stdphi[i_bin]*180.0/TWOPI, 
	    OutProfile.stdphierr[i_bin]*180.0/TWOPI,ptype);
  }
  printf("Created output file %s\n",Outfile);
  fclose(Fout);
  // }
  
  /* Write all this to file */
  
  
  printf("\nCompleted successfully.\n\n");fflush(stdout);
  
  exit(0);

}
Пример #7
0
int main(int argc, char *argv[])
{
  fitsfile *fptr;         /* FITS file pointer, defined in fitsio.h */
  char card[FLEN_CARD];   /* Standard string lengths defined in fitsio.h */
  int status = 0;   /* CFITSIO status value MUST be initialized to zero! */
  int single = 0, hdupos = 0, nkeys = 0, ii = 0;

  int printhelp = (argc == 2 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0));

  if (printhelp || argc != 2) {
    fprintf(stderr, "Usage:  %s filename[ext] \n", argv[0]);
    fprintf(stderr, "\n");
    fprintf(stderr, "List the FITS header keywords in a single extension, or, if \n");
    fprintf(stderr, "ext is not given, list the keywords in all the extensions. \n");
    fprintf(stderr, "\n");
    fprintf(stderr, "Examples: \n");
    fprintf(stderr, "   %s file.fits      - list every header in the file \n", argv[0]);
    fprintf(stderr, "   %s file.fits[0]   - list primary array header \n", argv[0]);
    fprintf(stderr, "   %s file.fits[2]   - list header of 2nd extension \n", argv[0]);
    fprintf(stderr, "   %s file.fits+2    - same as above \n", argv[0]);
    fprintf(stderr, "   %s file.fits[GTI] - list header of GTI extension\n", argv[0]);
    fprintf(stderr, "\n");
    fprintf(stderr, "Note that it may be necessary to enclose the input file\n");
    fprintf(stderr, "name in single quote characters on the Unix command line.\n");
    return (0);
  }

#if defined(PAGER) && defined(HAVE_POPEN) && defined(HAVE_PCLOSE)
  FILE *fout = popen(PAGER, "w");
  if (fout == NULL) {
    fprintf(stderr, "Could not execute '%s'\n", PAGER);
    return (1);
  }
#else
  FILE *fout = stdout;
#endif

  if (!fits_open_file(&fptr, argv[1], READONLY, &status)) {
    fits_get_hdu_num(fptr, &hdupos);  /* Get the current HDU position */

    /* List only a single header if a specific extension was given */
    if (hdupos != 1 || strchr(argv[1], '[')) {
      single = 1;
    }

    for (; !status; hdupos++) { /* Main loop through each extension */
      fits_get_hdrspace(fptr, &nkeys, NULL, &status); /* get # of keywords */

      fprintf(fout, "Header listing for HDU #%d:\n", hdupos);

      for (ii = 1; ii <= nkeys; ii++) { /* Read and print each keywords */

        if (fits_read_record(fptr, ii, card, &status)) {
          break;
        }
        fprintf(fout, "%s\n", card);
      }
      fprintf(fout, "END\n\n");  /* terminate listing with END */

      if (single) {
        break;  /* quit if only listing a single header */
      }

      fits_movrel_hdu(fptr, 1, NULL, &status);  /* try to move to next HDU */
    }

    if (status == END_OF_FILE) {
      status = 0;  /* Reset after normal error */
    }

    fits_close_file(fptr, &status);
  }

#if defined(PAGER) && defined(HAVE_POPEN) && defined(HAVE_PCLOSE)
  pclose(fout);
#endif

  if (status) {
    fits_report_error(stderr, status);  /* print any error message */
  }
  return (status);
}
Пример #8
0
int main(int argc, char **argv)
{

  int      i, j, indx, n_file, special_key, knul=0, anynull, hdutype, status=0;
  int      LastSlashIndex;
  int      NDump, NChan, NumHDU;
  long     nrows=0;
  double   ChanFreq, BW, CentFreq, DM;
  double   TDump, StartTime, DumpMiddleSecs, ScanLen;
  char     KeyValue[32], err_text[256];
  char     cur_file[256], cur_file_short[64];
  char     HdrVer[16];
  char     aspoutstr[11], dumprefstr[11];
  fitsfile *Fin;
  Cmdline  *Cmd;


  /* Get command line variables */
  Cmd = parseCmdline(argc, argv);  

  /* Normally use this somewhere, and not showOptionValues */
  Cmd->tool = Cmd->tool;

  /*  InfileP = (argc > 1); printf("InfileP = %d\n", InfileP);
  InfileC = (argc - 1); printf("InfileC = %d\n", InfileC);
  Infile = (char **)malloc(InfileC);
  for (i=0; i<InfileC; i++) {
    Infile[i] = (char *)malloc(256);
    if (strlen(argv[i+1]) > 255) {
      fprintf(stderr, "Error: argument %d is too long.\n", i+1);
      exit(1);
    }
    else{
      strcpy(Infile[i], argv[i+1]);
    }
    printf("Argument %d:  %s = %s\n", i+1, Infile[i], argv[i+1]);
    } */
  
  /************* Keyword list output  **************/

  if (Cmd->ListP) {
    if (argc > 2) {
      fprintf(stderr,"\n-list option must be used alone.  Exiting...\n");
      exit(1);
    }
    else{
      printf("\nSome available keywords/info options useable with the ");
      printf("-key flag:\n");
      printf("\nObserving frequency-related options:\n");
      printf("\nNCHAN:       No. of channels\n");
      printf("CFRQ:        Centre frequecy\n");
      printf("BW:          Bandwidth\n");
      printf("STARTCHAN:   First (0th) frequency channel\n");
      printf("ENDCHAN:     Last (NCHAN-th) frequency channel\n");
      printf("ALLCHAN:     List all channels (ALLCHAN keyword output does\n");
      printf("             not follow convention of -col flag)\n");
     
      printf("\nIntegration-related options:\n");
      printf("\nNDUMP:       No. of integrations\n");
      printf("TDUMP:       Individual integration time (s)\n");
      printf("SCANLEN:     Full scan length of input file (s)\n");
      printf("NPTSPROF:    No. of bins in integrated profiles\n");

      printf("\nOther options:\n");

      printf("\nSRC_NAME:    Source Name\n");
      printf("DM:          Dispersion measure\n");
      printf("OBS_MODE:    PSR/CAL -- normal or calibration scan\n");
      printf("OBSVTY:      Observatory code\n");
      printf("FD_POLN:     Polarisation basis (e.g. L or C for linear or\n");
      printf("             circular, respectively)\n");
      printf("RA:          Right ascension of source\n");
      printf("DEC:         Declination of source\n");
      
      printf("\nNote that all -key arguments are NOT case-sensitive.\n");
    }
  }
  else if(Cmd->TDiffP) {
    if (Cmd->KeywordP) {
      fprintf(stderr,"\n-tdiff option must be used alone.  Exiting...\n");
      exit(1);
    }
  }
  else{
    if(!Cmd->KeywordP){
      printf("Must use -key option with appropriate arguments if not\n");
      printf("using -list or -tdiff flag\n");
      exit(1);
    }
    if(!Cmd->InfileP){
      printf("Must use -infile option with input file arguments if not\n");
      printf("using -list or -tdiff flag\n");
      exit(1);
    }
  }


  /*************************************************/


  /* Print header line */
  if(Cmd->KeywordP && Cmd->ColumnP) {
    printf("%s  ","File");
    for(i=0;i<Cmd->KeywordC;i++)
      printf("%s  ",Cmd->Keyword[i]);
    printf("\n");
  }
  else if(Cmd->TDiffP){  // for Tdiff
    printf("File                        Source     MJD              TDIFF [ns]\n");
  }



  for(n_file=0;n_file<Cmd->InfileC;n_file++){
    strcpy(cur_file,Cmd->Infile[n_file]);
    /* Open fits file */
    if(fits_open_file(&Fin, cur_file, READONLY, &status)){
      printf("\nError opening FITS file %s\n",
	     cur_file);
      fits_get_errstatus(status, err_text);
      printf("FITS Error status %d: %s\n",status,err_text);
      exit(1);
    }
    status=0;

    /* get rid of everthing before and including last forward slash 
       in the filename for printing to screen: */
    LastSlashIndex = -1;
    for(i=strlen(cur_file)-1;i>0;i--){
      if(!strncasecmp(&cur_file[i],"/",1)){
	LastSlashIndex = i;
	break;
      }
    }

    strncpy(cur_file_short,&cur_file[LastSlashIndex+1],strlen(cur_file)-LastSlashIndex);


    if(Cmd->TDiffP){

      /******************** TDIFF ***********************/
      
      int    i_dump;
      int    IMJDStart, SMJDStart;
      double StartMJD, MJD, TDiff;
      char   ObsCode[4], psr[12];
      
      /* Check this is Nancay data */
      fits_read_key(Fin, TSTRING, "OBSVTY", ObsCode, NULL, &status); 
      if(strncmp(ObsCode,"f",1)) {
	printf("\nError: File %s does not contain Nancay data (obs code = %s).",
	       cur_file_short,ObsCode);
	printf("  Cannot extract TDIFF from this file.  Exiting.\n");
	exit(2);
      }

      /* Get pulsar name */
      fits_read_key(Fin, TSTRING, "SRC_NAME", psr, NULL, &status); 
   

      /* Calculate start MJD */
      fits_read_key(Fin, TINT, "STT_IMJD", 
		    &(IMJDStart),NULL, &status); status = 0;
      fits_read_key(Fin, TINT, "STT_SMJD", 
		    &(SMJDStart),NULL, &status); status = 0;

      StartMJD = (double)IMJDStart + (double)SMJDStart/86400.;

      /* Find nuber of dumps in this file */
      fits_get_num_hdus(Fin, &NumHDU, &status);
      NDump = NumHDU-3;  // Nancay data is always Ver1.0
      
      /* Loop through each dump and pick out time stamp and phase */
      fits_movnam_hdu(Fin, BINARY_TBL, "ASPOUT0", 0, &status);
    
      for (i_dump=0;i_dump<NDump;i_dump++){
	fits_movrel_hdu(Fin, 1, NULL, &status);
	fits_read_key(Fin, TDOUBLE, "DUMPMIDSECS", 
		      &(DumpMiddleSecs),NULL, &status); status = 0;
	fits_read_key(Fin, TDOUBLE, "DUMPTDIFF", 
		      &(TDiff),NULL, &status); status = 0;
	
	MJD = StartMJD + DumpMiddleSecs/86400.;
	
	printf("%s  ",cur_file_short);
	printf("%s  ",psr);
	printf("%14.8lf   ",MJD);
	printf("%7.3lf   \n",TDiff);
      }

    
    }
    // else





    if(Cmd->ColumnP) printf("%s  ",cur_file_short);
    else printf("\nKeywords in %s:\n\n", cur_file_short);
    
    /* For each keyword requested... */
    for(i=0;i<Cmd->KeywordC;i++){
      special_key=0;
     
      /* Clear Keyword */
      strcpy(KeyValue,"\0");

      /**************** Channel-based keywords: *****************/
      if(!strcasecmp(Cmd->Keyword[i],"NChan") ||      // # of channels
	 !strncasecmp(Cmd->Keyword[i],"CFRQ",4) ||    // centre frequency
	 !strncasecmp(Cmd->Keyword[i],"BW",2) ||      // bandwidth in MHz
	 !strcasecmp(Cmd->Keyword[i],"StartChan") ||  // first channel (MHz)
	 !strcasecmp(Cmd->Keyword[i],"EndChan") ||    // last channel (MHz)
	 !strcasecmp(Cmd->Keyword[i],"AllChan")){     // all channels (MHz)
	/* move to channel table */
	fits_movnam_hdu(Fin, ASCII_TBL, "BECONFIG", 0, &status);
	ffgnrw(Fin, &nrows, &status);

	indx = 1;
	fits_read_col(Fin, TINT, indx++, 1, 1, 1, &knul,
		      &NChan, &anynull, &status); 

	/* Write heading for AllChans keyword if requested */
	if (!strcasecmp(Cmd->Keyword[i],"AllChan")) 
	  printf("\nAll Channels:\n");
	/* Read NChans number, copy to keyword */
	if (!strcasecmp(Cmd->Keyword[i],"NChan")) 
	  sprintf(KeyValue,"%d",NChan);
	
	/* Initialize BW and CentFreq variables */
	BW=CentFreq=0.;
	for (j=0; j<NChan; j++) {
	  /* read each channel in succession */
	  fits_read_col(Fin, TDOUBLE, indx++, 1, 1, 1, NULL, 
			&ChanFreq, &anynull, &status);
	  /* Take not of first channel if StartChan keyword is requested */
	  if (!strcasecmp(Cmd->Keyword[i],"StartChan") && j==0)
	    sprintf(KeyValue,"%6.1lf",ChanFreq);
	  /* Calculate bandwidth or centre frequency using first and last
	     channels */
	  if((!strncasecmp(Cmd->Keyword[i],"BW",2) || 
	      !strncasecmp(Cmd->Keyword[i],"CFRQ",4))){
	    if (j==0)
	      BW = CentFreq = ChanFreq;
	    if (j==NChan-1) {
	      /* +4 because we are subtracting centres of channels, 
		 so this includes the edges...  */
	      BW = fabs(ChanFreq-BW)+4.;  
	      CentFreq = 0.5*(CentFreq + ChanFreq);
	    }
	  }
	  /* Print each channel separately if AllChans keyword is requestes */
	  if (!strcasecmp(Cmd->Keyword[i],"AllChan")) 
	    printf("%6.1lf    ",ChanFreq);
	}
	/* Take note of last channel if requested */
	if (!strcasecmp(Cmd->Keyword[i],"EndChan"))
	  sprintf(KeyValue,"%6.1lf",ChanFreq);
	/* Copy centre frequency and bandwidth keywords to keyword variable 
	   if requested */
	if (!strncasecmp(Cmd->Keyword[i],"CFRQ",4)) 
	  sprintf(KeyValue,"%6.1lf",CentFreq);
	if(!strncasecmp(Cmd->Keyword[i],"BW",2))
	   sprintf(KeyValue,"%6.1lf",BW);
	/* If AllChans is requested, print newline */
	if (!strcasecmp(Cmd->Keyword[i],"AllChan")) {
	  special_key=1;
	  printf("\n");
	}
	
	/* Move file pointer back to beginning of file */
	fits_movrel_hdu(Fin, -1, NULL, &status);

      /**************** End channel-based keywords: *****************/
	
      }

      /**************** DM keyword: *****************/

      else if(!strcasecmp(Cmd->Keyword[i],"DM")) {
	//	special_key=1;
	fits_movnam_hdu(Fin, ASCII_TBL, "COHDDISP", 0, &status);
	ffgnrw(Fin, &nrows, &status);
	indx = 1;
	fits_read_col(Fin, TDOUBLE, indx, 1, 1, 1, NULL, 
		      &DM, &anynull, &status);
	sprintf(KeyValue,"%8.5lf",DM);
	fits_movrel_hdu(Fin, -2, NULL, &status);

      /**************** End DM keyword: *****************/

      }
 
     /**************** NDUMPS or SCANLEN keyword: *****************/

      else if(!strcasecmp(Cmd->Keyword[i],"NDUMP") ||  // # of dumps
	      !strcasecmp(Cmd->Keyword[i],"NDUMPS") ||
	      !strcasecmp(Cmd->Keyword[i],"TDUMP") ||  // dump length in secs
	      !strcasecmp(Cmd->Keyword[i],"SCANLEN")){  // length of scans in secs

	/* Get the number of dumps.  this depensd on version of asp file code */
	fits_get_num_hdus(Fin, &NumHDU, &status);
	fits_read_key(Fin, TSTRING, "HDRVER", HdrVer, NULL, &status); 
	status=0;
	
	if(!strcasecmp(HdrVer,"Ver1.0")){
	  /* divided by 2 since half the tables are phase/period vs. freq 
	     before each data table */
	  NDump = NumHDU-3;  
	}
	else if(!strcasecmp(HdrVer,"Ver1.0.1")){
	  /* the "3" is temporary, depending on how many non-data tables we 
	     will be using */	  
	  NDump = (NumHDU-3)/2;
	}
	else{
	  printf("Do not recognize FITS file version number in header.\n");
	  printf("This header %s. Exiting...\n",HdrVer);
	  exit(3);
	}
	
	if (!strncasecmp(Cmd->Keyword[i],"NDUMP",4)) { // covers NDUMPS also...
	  sprintf(KeyValue,"%d",NDump);
	}
	// if need TDUMP or Total Scan Length (SCANLEN):
	if (!strcasecmp(Cmd->Keyword[i],"TDUMP") ||  // dump length in secs
	    !strcasecmp(Cmd->Keyword[i],"SCANLEN")) {  
	  
	  /* Get time between successive scans */

	  /* Get start time */
	  fits_read_key(Fin, TDOUBLE, "STT_SMJD", &StartTime, NULL, &status); 

	  if (NDump > 1) {

	    sprintf(aspoutstr,"ASPOUT%d",NDump-2);
	    sprintf(dumprefstr,"DUMPREF%d",NDump-2);
	    //	    printf ("\n%s   %s\n",aspoutstr,dumprefstr);
	    /* Move to first data table , get central time stamp */
	    if(!strcasecmp(HdrVer,"Ver1.0")) {
	      fits_movnam_hdu(Fin, BINARY_TBL, "ASPOUT0", 0, &status);
	      fits_read_key(Fin, TDOUBLE, "DUMPMIDSECS", 
			    &(DumpMiddleSecs),NULL, &status); status = 0;
	    }
	    else if (!strcasecmp(HdrVer,"Ver1.0.1")) {
	      fits_movnam_hdu(Fin, ASCII_TBL, "DUMPREF0", 0, &status);
	      fits_read_key(Fin, TDOUBLE, "MIDSECS", &(DumpMiddleSecs), 
			    NULL, &status); status = 0;
	    }
	    TDump = DumpMiddleSecs;
	    
	    /* Move to second data table , get central time stamp */
	    sprintf(aspoutstr,"ASPOUT%d",234);
	    sprintf(dumprefstr,"DUMPREF%d",234);
	    //	    printf ("\n%s   %s\n",aspoutstr,dumprefstr);
	    if(!strcasecmp(HdrVer,"Ver1.0")) {
	      fits_movnam_hdu(Fin, BINARY_TBL, "ASPOUT1", 0, &status);
	      fits_read_key(Fin, TDOUBLE, "DUMPMIDSECS", 
			    &(DumpMiddleSecs),NULL, &status); status = 0;
	    }
	    else if (!strcasecmp(HdrVer,"Ver1.0.1")) {
	      fits_movnam_hdu(Fin, ASCII_TBL, "DUMPREF1", 0, &status);
	      fits_read_key(Fin, TDOUBLE, "MIDSECS", &(DumpMiddleSecs), 
			    NULL, &status); status = 0;
	    }
	    if(DumpMiddleSecs < TDump) DumpMiddleSecs += 86400.;

	    //	    printf("First = %lf,  Second = %lf\n", TDump, DumpMiddleSecs);
	    TDump = DumpMiddleSecs - TDump;
	    
	  }
	  else {
	    /* We may have switched over to the next MJD, so take care of 
	       this if it's the case */
	    if (DumpMiddleSecs < StartTime) DumpMiddleSecs += 86400.;
	    
	    /* TDump is twice the difference between the middle time stamp 
	       and the start time */
	    TDump = 2.* ((double)floor(DumpMiddleSecs) - StartTime);
	  }
	  
	  if (!strncasecmp(Cmd->Keyword[i],"TDUMP",4)) {
	    sprintf(KeyValue,"%9.3lf",TDump);
	  }
	  if (!strcasecmp(Cmd->Keyword[i],"SCANLEN")) {
	    ScanLen = NDump*TDump;
	    sprintf(KeyValue,"%7.1lf",ScanLen);
	  }

	  /* Move back to first HDU again */

	  fits_movabs_hdu(Fin,1,&hdutype,&status);status = 0;
	}

      }


      /**************** Other keywords: *****************/
      else{
	fits_read_key(Fin, TSTRING, Cmd->Keyword[i], KeyValue, NULL, &status); 
	if(status == VALUE_UNDEFINED || !strcasecmp(KeyValue,"")) {
	  sprintf(KeyValue,"<not_found>");
	}

	/**************** End other keywords: *****************/
      }
            
      /* The only special keyword is AllChans. If it's not, do the following */
      if(!special_key){
	/* Column format */
	if(Cmd->ColumnP) {
	  printf("%s  ",KeyValue);
	  if(i==Cmd->KeywordC-1 && n_file<Cmd->InfileC-1)  printf("\n");
	}
	/* Non-column format */
	else {
	  printf("%15s:  %s\n",Cmd->Keyword[i],KeyValue);
	}
      }

    }
    status=0;

   
    fits_close_file(Fin, &status);
  }
  printf("\n");
  fflush(stdout);
  exit(0);
}
Пример #9
0
bool WMAPSource::initFile( )
{
  bool bRetVal = true;
  int iResult = 0;

  _numFrames = 0;

  if( !_filename.isNull( ) && !_filename.isEmpty( ) )
  {
    QString   str;
    fitsfile* ffits;
    int       iStatus = 0;

    iResult = fits_open_file( &ffits, _filename.ascii( ), READONLY, &iStatus );
    if( iResult == 0 )
    {
      int iNumHeaderDataUnits;

      if( fits_get_num_hdus( ffits, &iNumHeaderDataUnits, &iStatus ) == 0 )
      {
        long lNumBaseRows = 0;
        long lNumRows;
        int iHDUType;
        int i;

        //
        // determine the number of frames...
        //
        for( i=0; i<iNumHeaderDataUnits-1; i++ )
        {
          if( iStatus == 0 )
          {
            fits_get_hdu_type( ffits, &iHDUType, &iStatus );
            if( iHDUType == BINARY_TBL || iHDUType == ASCII_TBL )
            {
              iResult = fits_get_num_rows( ffits, &lNumRows, &iStatus );
              if( iResult == 0 )
              {
                if( lNumBaseRows == 0 )
                {
                  lNumBaseRows = lNumRows;
                }
                else if( lNumRows != 1 )
                {
                  if( lNumRows < lNumBaseRows )
                  {
                    lNumBaseRows = lNumRows;
                  }
                }
              }
            }

            fits_movrel_hdu( ffits, 1, &iHDUType, &iStatus );
          }
        }

        fits_movabs_hdu( ffits, 1, &iHDUType, &iStatus);

        field *fld = new field;

        fld->table = 0;
        fld->column = 0;
        fld->entry = 0;
        fld->entries = 0;
        fld->numSamplesPerFrame = 1;
        fld->numFrames = lNumBaseRows;

        _fields.insert( "INDEX", fld );
        _fieldList.append( "INDEX" );

        //
        // add the fields and metadata...
        //
        for( i=0; i<iNumHeaderDataUnits-1; i++ )
        {
          if( iStatus == 0 )
          {
            addToMetadata( ffits, iStatus );

            //
            // create the field entries...
            //
            fits_get_hdu_type( ffits, &iHDUType, &iStatus );
            if( iStatus == 0 )
            {
              if( iHDUType == BINARY_TBL || iHDUType == ASCII_TBL )
              {
                int iNumCols;
  
                iResult = fits_get_num_cols( ffits, &iNumCols, &iStatus );
                if( iResult == 0 )
                {
                  iResult = fits_get_num_rows( ffits, &lNumRows, &iStatus );
                  if( iResult == 0 )
                  {
                    if( lNumRows > 1 )
                    {
                      addToFieldList( ffits, iNumCols, lNumRows, lNumBaseRows, iStatus );
                    }
                    else if( lNumRows == 1 )
                    {
                      addToMetadata( ffits, iNumCols, iStatus );
                    }
                  }
                }
              }
            }

            fits_movrel_hdu( ffits, 1, &iHDUType, &iStatus);
          }
        }
      }

      iStatus = 0;

      updateNumFramesScalar( );

      fits_close_file( ffits, &iStatus );
    }
  }

  return bRetVal;
}
Пример #10
0
/* Print all the extension informations. */
void
fits_print_extension_info(struct fitsparams *p)
{
  uint16_t *ui16;
  fitsfile *fptr;
  gal_data_t *cols=NULL, *tmp;
  char **tstra, **estra, **sstra;
  size_t i, numext, *dsize, ndim;
  int j, nc, numhdu, hdutype, status=0, type;
  char *msg, *tstr=NULL, sstr[1000], extname[FLEN_VALUE];


  /* Open the FITS file and read the first extension type, upon moving to
     the next extension, we will read its type, so for the first we will
     need to do it explicitly. */
  fptr=gal_fits_hdu_open(p->filename, "0", READONLY);
  if (fits_get_hdu_type(fptr, &hdutype, &status) )
    gal_fits_io_error(status, "reading first extension");


  /* Get the number of HDUs. */
  if( fits_get_num_hdus(fptr, &numhdu, &status) )
    gal_fits_io_error(status, "finding number of HDUs");
  numext=numhdu;


  /* Allocate all the columns (in reverse order, since this is a simple
     linked list). */
  gal_list_data_add_alloc(&cols, NULL, GAL_TYPE_STRING, 1, &numext, NULL, 1,
                          p->cp.minmapsize, "HDU_SIZE", "name", "Size of "
                          "image or table number of rows and columns.");
  gal_list_data_add_alloc(&cols, NULL, GAL_TYPE_STRING, 1, &numext, NULL, 1,
                          p->cp.minmapsize, "HDU_TYPE", "name", "Image "
                          "data type or `table' format (ASCII or binary).");
  gal_list_data_add_alloc(&cols, NULL, GAL_TYPE_STRING, 1, &numext, NULL, 1,
                          p->cp.minmapsize, "EXTNAME", "name",
                          "Extension name of this HDU (EXTNAME in FITS).");
  gal_list_data_add_alloc(&cols, NULL, GAL_TYPE_UINT16, 1, &numext, NULL, 1,
                          p->cp.minmapsize, "HDU_INDEX", "count", "Index "
                          "(starting from zero) of each HDU (extension).");


  /* Keep pointers to the array of each column for easy writing. */
  ui16  = cols->array;
  estra = cols->next->array;
  tstra = cols->next->next->array;
  sstra = cols->next->next->next->array;

  cols->next->disp_width=15;
  cols->next->next->disp_width=15;


  /* Fill in each column. */
  for(i=0;i<numext;++i)
    {
      /* Work based on the type of the extension. */
      switch(hdutype)
        {
        case IMAGE_HDU:
          gal_fits_img_info(fptr, &type, &ndim, &dsize, NULL, NULL);
          tstr=gal_type_name(type , 1);
          break;

        case ASCII_TBL:
        case BINARY_TBL:
          ndim=2;
          tstr = hdutype==ASCII_TBL ? "table_ascii" : "table_binary";
          dsize=gal_data_malloc_array(GAL_TYPE_SIZE_T, 2, __func__, "dsize");
          gal_fits_tab_size(fptr, dsize+1, dsize);
          break;

        default:
          error(EXIT_FAILURE, 0, "%s: a bug! the `hdutype' code %d not "
                "recognized", __func__, hdutype);
        }


      /* Read the extension name*/
      fits_read_keyword(fptr, "EXTNAME", extname, NULL, &status);
      switch(status)
        {
        case 0:
          gal_fits_key_clean_str_value(extname);
          break;

        case KEY_NO_EXIST:
          sprintf(extname, "%s", GAL_BLANK_STRING);
          status=0;
          break;

        default:
          gal_fits_io_error(status, "reading EXTNAME keyword");
        }
      status=0;


      /* Write the size into a string. `sprintf' returns the number of
         written characters (excluding the `\0'). So for each dimension's
         size that is written, we add to `nc' (the number of
         characters). Note that FITS allows blank extensions, in those
         cases, return "0". */
      if(ndim>0)
        {
          nc=0;
          for(j=ndim-1;j>=0;--j)
            nc += sprintf(sstr+nc, "%zux", dsize[j]);
          sstr[nc-1]='\0';
          free(dsize);
        }
      else
        {
          sstr[0]='0';
          sstr[1]='\0';
        }


      /* Write the strings into the columns. */
      j=0;
      for(tmp=cols; tmp!=NULL; tmp=tmp->next)
        {
          switch(j)
            {
            case 0: ui16[i]=i;                                    break;
            case 1: gal_checkset_allocate_copy(extname, estra+i); break;
            case 2: gal_checkset_allocate_copy(tstr, tstra+i);    break;
            case 3: gal_checkset_allocate_copy(sstr, sstra+i);    break;
            }
          ++j;
        }


      /* Move to the next extension if we aren't on the last extension. */
      if( i!=numext-1 && fits_movrel_hdu(fptr, 1, &hdutype, &status) )
        {
          asprintf(&msg, "moving to hdu %zu", i+1);
          gal_fits_io_error(status, msg);
        }
    }


  /* Print the resutls. */
  if(!p->cp.quiet)
    {
      printf("%s\nRun on %s-----\n", PROGRAM_STRING, ctime(&p->rawtime));
      printf("HDU (extension) information: `%s'.\n", p->filename);
      printf(" Column 1: Index (counting from 0, usable with `--hdu').\n");
      printf(" Column 2: Name (`EXTNAME' in FITS standard, usable with "
             "`--hdu').\n");
      printf(" Column 3: Image data type or `table' format (ASCII or "
             "binary).\n");
      printf(" Column 4: Size of data in HDU.\n");
      printf("-----\n");
    }
  gal_table_write(cols, NULL, GAL_TABLE_FORMAT_TXT, NULL, NULL);
  gal_list_data_free(cols);
}
int move_to_hdu_rel(fitsfile * fptr, int rel_num)
{
    fits_movrel_hdu(fptr, rel_num, NULL, &fitsio_status);
    return fitsio_status == 0;
}
Пример #12
0
bool PLANCKIDEFSource::initFile( )
{
  bool bRetVal = true;
  int iResult = 0;

  _numFrames = 0;

  if( !_filename.isNull( ) && !_filename.isEmpty( ) )
  {
    QString   str;
    fitsfile* ffits;
    int       iStatus = 0;

    iResult = fits_open_file( &ffits, _filename.ascii( ), READONLY, &iStatus );
    if( iResult == 0 )
    {
      int iNumHeaderDataUnits;

      if( fits_get_num_hdus( ffits, &iNumHeaderDataUnits, &iStatus ) == 0 )
      {
        long lNumRows;
        int iHDUType;
        int i;

        //
        // determine the number of frames...
        //
        if( iNumHeaderDataUnits > 1 )
        {
          if( fits_movabs_hdu( ffits, 2, &iHDUType, &iStatus ) == 0 )
          {
            if( fits_get_hdu_type( ffits, &iHDUType, &iStatus ) == 0 )
            {
              if( iHDUType == BINARY_TBL )
              {
                iResult = fits_get_num_rows( ffits, &lNumRows, &iStatus );
                if( iResult == 0 )
                {
                  _numFrames = lNumRows;
                }
              }
            }
          }
        }

        if( _numFrames > 0 )
        {
          fits_movabs_hdu( ffits, 1, &iHDUType, &iStatus );

          field *fld = new field;

          fld->table = 0;
          fld->column = 0;

          _fields.insert( "INDEX", fld );
          _fieldList.append( "INDEX" );

          //
          // add the fields and metadata...
          //
          for( i=0; i<iNumHeaderDataUnits-1; i++ )
          {
            if( iStatus == 0 )
            {
              addToMetadata( ffits, iStatus );

              //
              // the first table never contains data...
              //
              if( i > 0 )
              {
                //
                // create the time entries if necessary...
                //
                if( _fields.find( "TIME_ABSOLUTE" ) == 0L &&
                    _fields.find( "TIME_RELATIVE" ) == 0L )
                {
                  char comment[FLEN_COMMENT];
                  int iStatusDelta = 0;
                  int iStatusZero = 0;

                  fits_read_key( ffits, TDOUBLE, "DELTA_T", &_dTimeDelta, comment, &iStatusDelta );
                  fits_read_key( ffits, TDOUBLE, "TIMEZERO", &_dTimeZero, comment, &iStatusZero );

                  if( iStatusDelta == 0 )
                  {
                    if( iStatusZero == 0 )
                    {
                      field *fld = new field;

                      fld->table = 0;
                      fld->column = 0;

                      _fields.insert( "TIME_ABSOLUTE", fld );
                      _fieldList.append( "TIME_ABSOLUTE" );
                    }
                    else
                    {
                      field *fld = new field;

                      fld->table = 0;
                      fld->column = 0;

                      _fields.insert( "TIME_RELATIVE", fld );
                      _fieldList.append( "TIME_RELATIVE" );
                    }
                  }
                }

                //
                // create the field entries...
                //
                fits_get_hdu_type( ffits, &iHDUType, &iStatus );
                if( iStatus == 0 )
                {
                  if( iHDUType == BINARY_TBL || iHDUType == ASCII_TBL )
                  {
                    int iNumCols;

                    iResult = fits_get_num_cols( ffits, &iNumCols, &iStatus );
                    if( iResult == 0 )
                    {
                      iResult = fits_get_num_rows( ffits, &lNumRows, &iStatus );
                      if( iResult == 0 )
                      {
                        addToFieldList( ffits, iNumCols, iStatus );
                      }
                    }
                  }
                }
              }

              fits_movrel_hdu( ffits, 1, &iHDUType, &iStatus);
            }
          }
        }
      }

      iStatus = 0;

      updateNumFramesScalar( );

      fits_close_file( ffits, &iStatus );
    }
  }

  return bRetVal;
}
Пример #13
0
int main(int argc, char *argv[])
{
  fitsfile *fptr = 0;         /* FITS file pointer, defined in fitsio.h */
  char keyname[FLEN_KEYWORD], colname[FLEN_VALUE], coltype[FLEN_VALUE];
  int status = 0;   /* CFITSIO status value MUST be initialized to zero! */
  int single = 0, hdupos = 0, hdutype = 0, bitpix = 0, naxis = 0, ncols = 0, ii = 0;
  long naxes[10], nrows = 0;

  int printhelp = (argc == 2 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0));

  if (printhelp || argc != 2) {
    fprintf(stderr, "Usage:  %s filename[ext] \n", argv[0]);
    fprintf(stderr, "\n");
    fprintf(stderr, "List the structure of a single extension, or, if ext is \n");
    fprintf(stderr, "not given, list the structure of the entire FITS file.  \n");
    fprintf(stderr, "\n");
    fprintf(stderr, "Note that it may be necessary to enclose the input file\n");
    fprintf(stderr, "name in single quote characters on the Unix command line.\n");
    return (0);
  }

  FILE *fout = popen(PAGER, "w");
  if (fout == NULL) {
    fprintf(stderr, "Could not execute '%s'\n", PAGER);
    return (1);
  }

  if (!fits_open_file(&fptr, argv[1], READONLY, &status)) {
    fits_get_hdu_num(fptr, &hdupos);  /* Get the current HDU position */

    /* List only a single structure if a specific extension was given */
    if (strchr(argv[1], '[') || strchr(argv[1], '+')) {
      single++;
    }

    for (; !status; hdupos++) { /* Main loop for each HDU */
      fits_get_hdu_type(fptr, &hdutype, &status);  /* Get the HDU type */

      fprintf(fout, "\nHDU #%d  ", hdupos);
      if (hdutype == IMAGE_HDU) { /* primary array or image HDU */
        fits_get_img_param(fptr, 10, &bitpix, &naxis, naxes, &status);

        fprintf(fout, "Array:  NAXIS = %d,  BITPIX = %d\n", naxis, bitpix);
        for (ii = 0; ii < naxis; ii++) {
          fprintf(fout, "   NAXIS%d = %ld\n",ii+1, naxes[ii]);
        }
      } else { /* a table HDU */
        fits_get_num_rows(fptr, &nrows, &status);
        fits_get_num_cols(fptr, &ncols, &status);

        if (hdutype == ASCII_TBL) {
          fprintf(fout, "ASCII Table:  ");
        } else {
          fprintf(fout, "Binary Table:  ");
        }

        fprintf(fout, "%d columns x %ld rows\n", ncols, nrows);
        fprintf(fout, " COL NAME             FORMAT\n");

        for (ii = 1; ii <= ncols; ii++) {
          fits_make_keyn("TTYPE", ii, keyname, &status); /* make keyword */
          fits_read_key(fptr, TSTRING, keyname, colname, NULL, &status);
          fits_make_keyn("TFORM", ii, keyname, &status); /* make keyword */
          fits_read_key(fptr, TSTRING, keyname, coltype, NULL, &status);

          fprintf(fout, " %3d %-16s %-16s\n", ii, colname, coltype);
        }
      }

      if (single) {
        break;  /* quit if only listing a single HDU */
      }

      fits_movrel_hdu(fptr, 1, NULL, &status);  /* try move to next ext */
    }

    if (status == END_OF_FILE) {
      status = 0;  /* Reset normal error */
    }
    fits_close_file(fptr, &status);
  }

  pclose(fout);

  if (status) {
    fits_report_error(stderr, status);  /* print any error message */
  }
  return (status);
}
Пример #14
0
int main(int argc, char *argv[])
{
    fitsfile *infptr, *outfptr;   /* FITS file pointers defined in fitsio.h */
    int status = 0, ii = 1, iteration = 0, single = 0, hdupos;
    int hdutype, bitpix, bytepix, naxis = 0, nkeys, datatype = 0, anynul;
    long naxes[9] = {1, 1, 1, 1, 1, 1, 1, 1, 1};
    long first, totpix = 0, npix;
    double *array, bscale = 1.0, bzero = 0.0, nulval = 0.;
    char card[81];

    if (argc != 3)
    {
 printf("\n");
 printf("Usage:  imcopy inputImage outputImage[compress]\n");
 printf("\n");
 printf("Copy an input image to an output image, optionally compressing\n");
 printf("or uncompressing the image in the process.  If the [compress]\n");
 printf("qualifier is appended to the output file name then the input image\n");
 printf("will be compressed using the tile-compressed format.  In this format,\n");
 printf("the image is divided into rectangular tiles and each tile of pixels\n");
 printf("is compressed and stored in a variable-length row of a binary table.\n");
 printf("If the [compress] qualifier is omitted, and the input image is\n");
 printf("in tile-compressed format, then the output image will be uncompressed.\n");
 printf("\n");
 printf("If an extension name or number is appended to the input file name, \n");
 printf("enclosed in square brackets, then only that single extension will be\n");
 printf("copied to the output file.  Otherwise, every extension in the input file\n");
 printf("will be processed in turn and copied to the output file.\n");
 printf("\n");
 printf("Examples:\n");
 printf("\n");
 printf("1)  imcopy image.fit 'cimage.fit[compress]'\n");
 printf("\n");
 printf("    This compresses the input image using the default parameters, i.e.,\n");
 printf("    using the Rice compression algorithm and using row by row tiles.\n");
 printf("\n");
 printf("2)  imcopy cimage.fit image2.fit\n");
 printf("\n");
 printf("    This uncompress the image created in the first example.\n");
 printf("    image2.fit should be identical to image.fit if the image\n");
 printf("    has an integer datatype.  There will be small differences\n");
 printf("    in the pixel values if it is a floating point image.\n");
 printf("\n");
 printf("3)  imcopy image.fit 'cimage.fit[compress GZIP 100,100;4]'\n");
 printf("\n");
 printf("    This compresses the input image using the following parameters:\n");
 printf("         GZIP compression algorithm;\n");
 printf("         100 X 100 pixel compression tiles;\n");
 printf("         noise_bits = 4 (only used with floating point images)\n");
 printf("\n");
 printf("The full syntax of the compression qualifier is:\n");
 printf("    [compress ALGORITHM TDIM1,TDIM2,...; NOISE_BITS]\n");
 printf("where the allowed ALGORITHM values are Rice, GZIP, PLIO, \n");
 printf("and TDIMn is the size of the compression tile in each dimension,\n");
 printf("and NOISE_BITS = 1, 2, 3, or 4 and controls the amount of noise\n");
 printf("suppression when compressing floating point images. \n");
 printf("\n");
 printf("Note that it may be necessary to enclose the file names\n");
 printf("in single quote characters on the Unix command line.\n");
      return(0);
    }

    /* Open the input file and create output file */
    fits_open_file(&infptr, argv[1], READONLY, &status);
    fits_create_file(&outfptr, argv[2], &status);

    if (status != 0) {    
        fits_report_error(stderr, status);
        return(status);
    }

    fits_get_hdu_num(infptr, &hdupos);  /* Get the current HDU position */

    /* Copy only a single HDU if a specific extension was given */ 
    if (hdupos != 1 || strchr(argv[1], '[')) single = 1;

    for (; !status; hdupos++)  /* Main loop through each extension */
    {

      fits_get_hdu_type(infptr, &hdutype, &status);

      if (hdutype == IMAGE_HDU) {

          /* get image dimensions and total number of pixels in image */
          for (ii = 0; ii < 9; ii++)
              naxes[ii] = 1;

          fits_get_img_param(infptr, 9, &bitpix, &naxis, naxes, &status);

          totpix = naxes[0] * naxes[1] * naxes[2] * naxes[3] * naxes[4]
             * naxes[5] * naxes[6] * naxes[7] * naxes[8];
      }

      if (hdutype != IMAGE_HDU || naxis == 0 || totpix == 0) { 

          /* just copy tables and null images */
          fits_copy_hdu(infptr, outfptr, 0, &status);

      } else {

          /* Explicitly create new image, to support compression */
          fits_create_img(outfptr, bitpix, naxis, naxes, &status);
          if (status) {
                 fits_report_error(stderr, status);
                 return(status);
          }
	  	    
          /* copy all the user keywords (not the structural keywords) */
          fits_get_hdrspace(infptr, &nkeys, NULL, &status); 

          for (ii = 1; ii <= nkeys; ii++) {
              fits_read_record(infptr, ii, card, &status);
              if (fits_get_keyclass(card) > TYP_CMPRS_KEY)
                  fits_write_record(outfptr, card, &status);
          }

          switch(bitpix) {
              case BYTE_IMG:
                  datatype = TBYTE;
                  break;
              case SHORT_IMG:
                  datatype = TSHORT;
                  break;
              case LONG_IMG:
                  datatype = TINT;
                  break;
              case FLOAT_IMG:
                  datatype = TFLOAT;
                  break;
              case DOUBLE_IMG:
                  datatype = TDOUBLE;
                  break;
          }

          bytepix = abs(bitpix) / 8;

          npix = totpix;
          iteration = 0;

          /* try to allocate memory for the entire image */
          /* use double type to force memory alignment */
          array = (double *) calloc(npix, bytepix);

          /* if allocation failed, divide size by 2 and try again */
          while (!array && iteration < 10)  {
              iteration++;
              npix = npix / 2;
              array = (double *) calloc(npix, bytepix);
          }

          if (!array)  {
              printf("Memory allocation error\n");
              return(0);
          }

          /* turn off any scaling so that we copy the raw pixel values */
          fits_set_bscale(infptr,  bscale, bzero, &status);
          fits_set_bscale(outfptr, bscale, bzero, &status);

          first = 1;
          while (totpix > 0 && !status)
          {
             /* read all or part of image then write it back to the output file */
             fits_read_img(infptr, datatype, first, npix, 
                     &nulval, array, &anynul, &status);

             fits_write_img(outfptr, datatype, first, npix, array, &status);
             totpix = totpix - npix;
             first  = first  + npix;
          }
          free(array);
      }

      if (single) break;  /* quit if only copying a single HDU */
      fits_movrel_hdu(infptr, 1, NULL, &status);  /* try to move to next HDU */
    }

    if (status == END_OF_FILE)  status = 0; /* Reset after normal error */

    fits_close_file(outfptr,  &status);
    fits_close_file(infptr, &status);

    /* if error occurred, print out error message */
    if (status)
       fits_report_error(stderr, status);
    return(status);
}
Пример #15
0
  int understands_wmap( KConfig*, const QString& filename )
  {
    fitsfile* ffits;
    int       iStatus = 0;
    int       iRetVal = 0;

    //
    // determine if it is a WMAP file...
    //
    if( fits_open_file( &ffits, filename.ascii( ), READONLY, &iStatus ) == 0 )
    {
      int iNumHeaderDataUnits;

      if( fits_get_num_hdus( ffits, &iNumHeaderDataUnits, &iStatus ) == 0 )
      {
        if( iNumHeaderDataUnits == 6 )
        {
          char  value[FLEN_VALUE];
          char  comment[FLEN_COMMENT];
          int   iHDUType;
          int   iColNum;
          int   i;
          int   j;

          for( i=0; i<iNumKeywords; ++i )
          {
            if( iStatus == 0 )
            {
              fits_read_keyword( ffits, keywords[i], value, comment, &iStatus );
            }
            else  
            {
              break;
            }
          }

          if( iStatus == 0 )
          {
            char **entries = metaDataHeaders;
            int iNumEntries = iNumMetaDataHeaders;

            for( i=0; i<iNumHeaderDataUnits-1; i++ )
            {
              switch (i)
              {
                case 0:
                  iNumEntries = iNumMetaDataHeaders;
                  entries = metaDataHeaders;
                  break;
                case 1:
                  iNumEntries = iNumScienceDataHeaders;
                  entries = scienceDataHeaders;
                  break;
                case 2:
                  iNumEntries = iNumAIHKDataHeaders;
                  entries = AIHKDataHeaders;
                  break;
                case 3:
                  iNumEntries = iNumDIHKDataHeaders;
                  entries = DIHKDataHeaders;
                  break;
                case 4:
                  iNumEntries = iNumLOSDataHeaders;
                  entries = LOSDataHeaders;
                  break;
                default:
                  iNumEntries = iNumMetaDataHeaders;
                  entries = metaDataHeaders;
                  break;
              }

              fits_movrel_hdu( ffits, 1, &iHDUType, &iStatus);
              if( iStatus == 0 && iHDUType == BINARY_TBL )
              {
                for( j=0; j<iNumEntries; ++j )
                {
                  if( iStatus == 0 )
                  {
                    fits_get_colnum( ffits, 0, entries[j], &iColNum, &iStatus );
                    if( strchr( entries[j], '#' ) != 0L &&  iStatus == COL_NOT_UNIQUE )
                    {
                      iStatus = 0;
                    }
                  }
                  else  
                  {
                    break;
                  }
                }
              }
            }
          }

          if( iStatus == 0 )
          {
            iRetVal = 99;
          }
        }
      }

      iStatus = 0;

      fits_close_file( ffits, &iStatus );
    }
    else
    {
      //
      // failed to open the file, so we can't understand it...
      //
    }

    return iRetVal;
  }
Пример #16
0
/**
 * Function: get_ALL_from_next_in_SPC
 * The function creates and fills a full spectrum structure with
 * the content of a SPC table extension. This is only done when,
 * according to the beam ID, this beam should be corrected.
 * For extensions with higher order beams which are not corrected
 * an emply structure is returned.
 *
 * Parameters:
 * @param SPCn_ptr - pointer to the opened SPC file
 * @param aperID   - pointer to aperture identification number
 * @param beamID   - pointer to beam identification number
 *
 * Returns:
 * @return SPC - the full spectrum structure
 */
full_spectr *
get_ALL_from_next_in_SPC(fitsfile *SPC_ptr, int *aperID, int *beamID)
{
  int f_status=0, hdutype;

  long tmp;
  //long nrows=0;
  char comment[FLEN_COMMENT];

  full_spectr *SPC;


  fits_movrel_hdu (SPC_ptr, 1, &hdutype, &f_status);

  if (f_status)
    {
      *aperID = -1;
      *beamID = -1;
      SPC = NULL;
      return SPC;
    }


  // read the beam ID number
  fits_read_key_lng (SPC_ptr, "BEAMID", &tmp, comment, &f_status);
  if (f_status)
    {
      ffrprt (stderr, f_status);
      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
		   "get_ALL_from_next_in_SPC: Error getting index keyword OBJECTID");
    }
  *beamID = (int)tmp;

  // check whether this beam should be correct
  if (*beamID > CORRMAX)
    {
      // set it to NULL and return
      SPC = NULL;
      //      fprintf (stdout, "aXe_PETFF: Skipping beam: %c.\n", BEAM(*beamID));
      return SPC;
    }

  // the beam shall be corrected and
  // first must be read in
  SPC = (full_spectr *) malloc (sizeof (full_spectr ));

  // transfer the beam ID
  SPC->beamID = (int)tmp;

  // read the aperture number
  fits_read_key_lng (SPC_ptr, "OBJECTID", &tmp, comment, &f_status);
  if (f_status)
    {
      ffrprt (stderr, f_status);
      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
		   "get_ALL_from_next_in_SPC: Error getting index keyword OBJECTID");
    }
  // transfer the aperture ID
  *aperID = (int)tmp;
  SPC->aperID = (int)tmp;


  // Get the number of rows
  fits_get_num_rows (SPC_ptr, &tmp, &f_status);
  if (f_status) {
    ffrprt (stderr, f_status);
    aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
		 "get_ALL_from_next_in_SPC: "
		 "Could not determine the number of rows in"
		 " correction function table!");
  }
  SPC->nelems = (int)tmp;

  // load the background subtracted object spectrum
  SPC->obj_spec = get_spectrum_from_SPC(SPC_ptr, "COUNT", "ERROR", SPC->nelems);

  // load the total object spectrum
  SPC->fgr_spec = get_spectrum_from_SPC(SPC_ptr, "TCOUNT", "TERROR", SPC->nelems);

  // load the background spectrum
  SPC->bck_spec = get_spectrum_from_SPC(SPC_ptr, "BCOUNT", "BERROR", SPC->nelems);

  // return the filled structure
  return SPC;
}
Пример #17
0
int ReadASPData(struct ASPHdr *hdr, struct SubHdr *subhdr, 
		 struct RunVars *RunMode, fitsfile *Fin, int nscan, 
		 int NPtsProf, double **ASquared, double **BSquared, 
		 double **ReAconjB, double **ImAconjB, long **SampleCount)
{

  int  i, j, status=0, datacolnum, refcolnum, anynull;
  int  NColumns;
  
  char Rawfile[100];

  FILE *s;


  fits_get_num_cols(Fin, &NColumns, &status);status=0;


  /* malloc array for each channel based on profile size */
  for(i=0;i<hdr->obs.NChan;i++){
    ASquared[i]    = (double *)malloc(NPtsProf*sizeof(double));
    DZero(&ASquared[i][0], NPtsProf);
    BSquared[i]    = (double *)malloc(NPtsProf*sizeof(double));
    DZero(&BSquared[i][0], NPtsProf);
    ReAconjB[i]    = (double *)malloc(NPtsProf*sizeof(double));
    DZero(&ReAconjB[i][0], NPtsProf);
    ImAconjB[i]    = (double *)malloc(NPtsProf*sizeof(double));
    DZero(&ImAconjB[i][0], NPtsProf);
    SampleCount[i] = (long   *)malloc(NPtsProf*sizeof(long));
    LZero(&SampleCount[i][0], NPtsProf);
  }


  /* get middle dump time  */
  if(!strcmp(hdr->gen.HdrVer,"Ver1.0")) 
    fits_read_key(Fin, TDOUBLE, "DUMPMIDSECS", &(subhdr->DumpMiddleSecs), 
		  NULL, &status); status = 0;
  

  /* move to ref table for newer version */
  if(!strcmp(hdr->gen.HdrVer,"Ver1.0.1")) {
    fits_read_key(Fin, TDOUBLE, "MIDSECS", &(subhdr->DumpMiddleSecs), 
		  NULL, &status); status = 0;
    refcolnum = 0;
    fits_read_col(Fin, TDOUBLE, ++refcolnum, 1, 1, (long)hdr->obs.NChan, NULL, 
		  subhdr->DumpRefPhase,  &anynull, &status); 
    fits_read_col(Fin, TDOUBLE, ++refcolnum, 1, 1, (long)hdr->obs.NChan, NULL, 
		  subhdr->DumpRefPeriod, &anynull, &status); 


   if(RunMode->Verbose){
      printf("Dump %d:  TIME OF DUMP = %lf\n",nscan,subhdr->DumpMiddleSecs); 
      printf("          CHANNEL (MHz)   REF. PHASE   REF. PERIOD (s)\n");
      printf("          -------------   ----------   ---------------\n");
      for(i=0;i<hdr->obs.NChan;i++) 
	printf("          %13.1lf%13.8lf%18.11lf\n", hdr->obs.ChanFreq[i],
	       subhdr->DumpRefPhase[i], subhdr->DumpRefPeriod[i]);       
      fflush(stdout);
    }

    /* Move to next HDU, i.e. data table for this dump */
    fits_movrel_hdu(Fin, 1, NULL, &status);
  }


  datacolnum = 0;

  for(i=0;i<hdr->obs.NChan;i++) {

    fits_read_col(Fin, TDOUBLE,  ++datacolnum, 1, 1, NPtsProf, NULL, 
		  &ASquared[i][0],    &anynull, &status); 
    fits_read_col(Fin, TDOUBLE,  ++datacolnum, 1, 1, NPtsProf, NULL, 
		  &BSquared[i][0],    &anynull, &status); 
    fits_read_col(Fin, TDOUBLE,  ++datacolnum, 1, 1, NPtsProf, NULL, 
		  &ReAconjB[i][0],    &anynull, &status); 
    fits_read_col(Fin, TDOUBLE,  ++datacolnum, 1, 1, NPtsProf, NULL, 
		  &ImAconjB[i][0],    &anynull, &status); 
    if(!RunMode->OldFits)
      fits_read_col(Fin, TLONG,  ++datacolnum, 1, 1, NPtsProf, NULL, 
		    &SampleCount[i][0], &anynull, &status); 

/* Normalize */
    
    if(!RunMode->OldFits){
      for(j=0;j<NPtsProf;j++){
        ASquared[i][j] /= (double)SampleCount[i][j];
        BSquared[i][j] /= (double)SampleCount[i][j];
        ReAconjB[i][j] /= (double)SampleCount[i][j];
        ImAconjB[i][j] /= (double)SampleCount[i][j];

      }
    }

  }


  for(i=0;i<hdr->obs.NChan;i++) {

   /* read in reference phase, period if old version */


    if(!strcmp(hdr->gen.HdrVer,"Ver1.0")){
      fits_read_key(Fin, TDOUBLE, "DUMPREFPER",   &(subhdr->DumpRefPeriod[i]),  
		    NULL, &status); status = 0;
      fits_read_key(Fin, TDOUBLE, "DUMPREFPHASE", &(subhdr->DumpRefPhase[i]),   
		    NULL, &status); status = 0; 
                                                                              
      if(RunMode->Verbose && i==0){
	printf("Dump %d:  TIME OF DUMP = %lf\n",nscan, subhdr->DumpMiddleSecs);
	printf("          REF. PHASE = %lf, REF. PERIOD = %lf s\n", 
	       subhdr->DumpRefPhase[i], subhdr->DumpRefPeriod[i]);fflush(stdout);
      }
    }


    /*
   sprintf(HeadLine[i],"# %.1f %.7f %.10f %ld %.3f %.3f %d %s %d %s %.10f",
	    (double)hdr->obs.IMJDStart, subhdr->DumpMiddleSecs, 
	    subhdr->DumpRefPeriod[i], (long)1,hdr->obs.ChanFreq[i], hdr->obs.DM, 
	    RunMode->NBinsOut, hdr->obs.ObsvtyCode, 1, hdr->target.PSRName, 
	    subhdr->DumpRefPhase[i]);

    if (RunMode->MakeRaw){
      sprintf(Rawfile,"%s.%4.4d.%4.4d.prof.raw.asc",RunMode->OutfileRoot,
	      (int)(hdr->obs.ChanFreq[i]),nscan);
      s = fopen(Rawfile, "w");
      if (s==NULL) {
	printf("ASPFitsReader: Can't open file %s\n",Rawfile);
	fflush(stdout);
	exit(1);
      }

      fprintf(s,"%s\n",HeadLine[i]);

      for (j=0; j<NPtsProf; j++) {
 	fprintf(s,"%d  %lf  %lf  %lf  %lf  %d\n",j, 
		ASquared[i][j], BSquared[i][j], ReAconjB[i][j], ImAconjB[i][j],
		SampleCount[i][j]); 
      }
      fclose(s);

    }
    */

  }

  return 1;

}