Exemplo n.º 1
0
int get_fqtable(fitsfile *fptr, int hdu, struct uvf_header *header)
{
  int status = 0, i;
  int hdutype, col_iff, type_iff;
  long nrows, rpt_iff, wid_iff;
  double f;

  fits_movabs_hdu(fptr, hdu, &hdutype, &status);
  fits_get_num_rows(fptr, &nrows,  &status);
  fits_get_colnum(fptr, CASEINSEN, "IF FREQ", &col_iff, &status);
  fits_get_coltype(fptr, col_iff, &type_iff, &rpt_iff, &wid_iff,
		   &status);
  if (status || type_iff != TDOUBLE || nrows != 1 || rpt_iff !=
      header->nif)
    fprintf(stderr, "    Warning: Invalid AIPS frequency table\n");
  for (i=0; i < rpt_iff; i++) {
    fits_read_col(fptr, TDOUBLE, col_iff, 1, i+1, 1,
		  NULL, &f, NULL, &status);
    header->iffreq[i] = header->freq + f;
  }
  fprintf(stderr, "    %d IFs ", header->nif);
  for (i=0; i < header->nif; i++)
    fprintf(stderr, " %.2f", header->iffreq[i]*1e-9);
  fprintf(stderr, "\n");
  return status ? 1 : 0;
}
Exemplo n.º 2
0
int get_subint ( char *name )
{  
//double *read_arrival_time( char *input, long *nrows )
    fitsfile *fptr;       // pointer to the FITS file, defined in fitsio.h 
    int status;
    long int nrows;

    status = 0;

    if ( fits_open_file(&fptr, name, READONLY, &status) )          // open the file
    {
        printf( "error while openning file\n" );
    }

    if ( fits_get_num_rows(fptr, &nrows, &status) )           // get the row number
    {
        printf( "error while getting the row number\n" );
    }
    printf ("number of subint: %ld\n", nrows);
    
	///////////////////////////////////////////////////////////////////////////

    if ( fits_close_file(fptr, &status) )
    {
        printf( " error while closing the file " );
    }

    return nrows;
}
Exemplo n.º 3
0
int FitsFile::GetRowCount()
{
	CheckOpen();
	long rowCount;
	int status = 0;
	fits_get_num_rows(_fptr, &rowCount, &status);
	CheckStatus(status);
	return rowCount;
}
Exemplo n.º 4
0
float *
supcam_read_data( fitsfile * fits, size_t * numRows, size_t * numChans, int * status ) {

  int colnum = 0;    /* DATA column */
  int fitsStatus = 0; /* CFITSIO status */
  long nRows = 0;
  long nChans = 0;
  long dummy;
  float * data = NULL;
  int typecode = 0;

  /* Initialise the return values */
  *numChans = 0;
  *numRows = 0;

  if (*status != SAI__OK) return NULL;

  /* Prepare to read the Binary Table */
  /* Check number of rows */
  CALLCFITSIO( fits_get_num_rows(fits, &nRows, &fitsStatus), "Error getting number of rows" );

  /* Find DATA column and check its repeat count */
  /* cast because cfitsio does not use const */
  CALLCFITSIO( fits_get_colnum(fits, CASEINSEN, (char *)"DATA", &colnum, &fitsStatus),
               "Error getting column number for DATA" );
  CALLCFITSIO( fits_get_coltype(fits, colnum, &typecode, &nChans, &dummy, &fitsStatus),
               "Error getting column information" );
  if (*status != SAI__OK) return NULL;

  /* Get some memory */
  data = astMalloc( nChans * nRows * sizeof(*data) );

  /* Read DATA column */
  CALLCFITSIO( fits_read_col(fits, TFLOAT, colnum, 1, 1,
                             nChans*nRows, NULL, data, NULL, &fitsStatus),
               "Error reading spectra from Binary Column DATA" );

  if (*status == SAI__OK) {

    /* It looks like there is a bad value of (-1)*VAL__BADI */
    size_t i;
    size_t nelems = nChans * nRows;
    for (i = 0; i < nelems; i++ ) {
      if (data[i] >= (float)(VAL__MAXI - 1)) {
        data[i] = VAL__BADR;
      }
    }

    *numChans = nChans;
    *numRows = nRows;
  }

  return data;
}
long InputFileFITS::getNRows() {
	int status = 0;

	if(!isOpened())
		throwException("Error in InputFileFITS::getNRows() ", status);

	long nrows;
	fits_get_num_rows(infptr, &nrows, &status);

	if (status)
		throwException("Error in InputFileFITS::getNRows() ", status);

	return nrows;
}
Exemplo n.º 6
0
int get_antable(fitsfile *fptr, int hdu, struct uvf_header *header)
{
  int status = 0, i;
  int hdutype, col_name, col_xyz, type_name, type_xyz;
  long nrows, rpt_name, rpt_xyz, wid_name, wid_xyz;
  char *string[1];
  int anynull;

  fits_movabs_hdu(fptr, hdu, &hdutype, &status);
  fits_get_num_rows(fptr, &nrows,  &status);
  header->n_antennas = (int) nrows;
  fits_get_colnum(fptr, CASEINSEN, "ANNAME", &col_name, &status);
  fits_get_coltype(fptr, col_name, &type_name, &rpt_name, &wid_name,
		   &status);
  fits_get_colnum(fptr, CASEINSEN, "STABXYZ", &col_xyz, &status);
  fits_get_coltype(fptr, col_xyz, &type_xyz, &rpt_xyz, &wid_xyz,
		   &status);
  if (status || type_name != TSTRING ||
                type_xyz != TDOUBLE || rpt_xyz != 3)
    fprintf(stderr, "    Warning: Invalid AIPS antenna table: %d %ld %d %ld\n",
	    type_name, rpt_name, type_xyz, rpt_xyz);
  for (i=0; i < nrows; i++) {
    string[0] = header->antenna[i].name;
    fits_read_col(fptr, TSTRING, col_name, i+1, 1, 1,
		  "NONAME", string, &anynull, &status);
    fits_read_col(fptr, TDOUBLE, col_xyz, i+1, 1, 1,
		  NULL, &(header->antenna[i].x), NULL, &status);
    fits_read_col(fptr, TDOUBLE, col_xyz, i+1, 2, 1,
		  NULL, &(header->antenna[i].y), NULL, &status);
    fits_read_col(fptr, TDOUBLE, col_xyz, i+1, 3, 1,
		  NULL, &(header->antenna[i].z), NULL, &status);
    if (DEBUG)
      fprintf(stderr, "    %s %8.3f %8.3f %8.3f\n", header->antenna[i].name,
	      header->antenna[i].x, header->antenna[i].y, header->antenna[i].z);
  }
  fprintf(stderr, "    %d antennas ", (int) nrows);
  for (i=0; i < nrows; i++)
    fprintf(stderr, " %s", header->antenna[i].name);
  fprintf(stderr, "\n");
  return status ? 1 : 0;
}
Exemplo n.º 7
0
// filterTableToImage: filter a binary table, create a temp image
fitsfile *filterTableToImage(fitsfile *fptr, char *filter, char **cols,
			     int *dims, double *cens, int bin, int *status){
  int i, dim1, dim2;
  int imagetype=TINT, naxis=IDIM, recip=0;
  int tstatus;
  long nirow, norow;
  float weight=1;
  float xcen, ycen;
  double dvalue;
  double minin[IDIM], maxin[IDIM], binsizein[IDIM];
  char comment[81];
  char *rowselect=NULL;
  char *outfile=IFILE;
  char wtcol[FLEN_VALUE];
  char colname[IDIM][FLEN_VALUE];
  char minname[IDIM][FLEN_VALUE];
  char maxname[IDIM][FLEN_VALUE];
  char binname[IDIM][FLEN_VALUE];
  int colnum[IDIM];
  long haxes[IDIM];
  float amin[IDIM];
  float amax[IDIM];
  float binsize[IDIM];
  fitsfile *ofptr;

  // set up defaults
  if( !bin ) bin = 1;
  wtcol[0] = '\0';
  if( cols && cols[0] && cols[1] ){
    strcpy(colname[0], cols[0]);
    strcpy(colname[1], cols[1]);
  } else {
    colname[0][0] = '\0';
    colname[1][0] = '\0';
  }
  for(i=0; i<IDIM; i++){
    minin[i] = DOUBLENULLVALUE;
    maxin[i] = DOUBLENULLVALUE;
    binsizein[i] = (double)bin;
    minname[i][0] = '\0';
    maxname[i][0] = '\0';
    binname[i][0] = '\0';
  }
  // get total number of rows in input file
  fits_get_num_rows(fptr, &nirow, status);
  // and allocate memory for selected rows array
  rowselect = malloc(nirow+1);
  // filter the input file and generate selected rows array
  if( filter && *filter ){
    fits_find_rows(fptr, filter, 0, nirow, &norow, rowselect,  status);
  } else {
    for(i=0; i<nirow+1; i++){
      rowselect[i] = TRUE;
    }
  }
  // get binning parameters so we can know the image dims for these cols
  // and from that, get the default center of the image
  fits_calc_binning(fptr, naxis, colname, minin, maxin, binsizein, 
		    minname, maxname, binname,
		    colnum, haxes, amin, amax, binsize, status);
  // why truncate to int? otherwise, cfitsio is 0.5 pixels off from js9 ...
  xcen = (int)(amax[0] - amin[0])/2;
  ycen = (int)(amax[1] - amin[1])/2;
  dim1 = haxes[0];
  dim2 = haxes[0];
  // get limits of extracted section
  if( dims && dims[0] && dims[1] ){
    // read image section
    if( cens && cens[0] && cens[1] ){
      xcen = cens[0];
      ycen = cens[1];
      dim1 = dims[0];
      dim2 = dims[1];
    } else {
      if( haxes[0] >= dims[0] ){
	dim1 = dims[0];
      }
      if( haxes[1] >= dims[1] ){
	dim2 = dims[1];
      }
    }
    minin[0] = (int)(xcen - ((dim1+1)/2) + 1);
    minin[1] = (int)(ycen - ((dim2+1)/2) + 1);
    maxin[0] = (int)(xcen + (dim1/2));
    maxin[1] = (int)(ycen + (dim2/2));
  }
  // make 2D section histogram from selected rows
  ofptr = ffhist3(fptr, outfile, imagetype, naxis, colname, 
		  minin, maxin, binsizein, minname, maxname, binname,
		  weight, wtcol, recip, rowselect, status);

  // update/add LTM and LTV header params
  dvalue = 0.0; *comment = '\0'; tstatus = 0;
  fits_read_key(fptr, TDOUBLE, "LTV1", &dvalue, comment, &tstatus); 
  dvalue = (dim1 / 2) - xcen; tstatus = 0;
  fits_update_key(ofptr, TDOUBLE, "LTV1", &dvalue, comment, &tstatus);

  dvalue = 0.0; *comment = '\0'; tstatus = 0;
  fits_read_key(fptr, TDOUBLE, "LTV2", &dvalue, comment, &tstatus); 
  dvalue = (dim2 / 2) - ycen; tstatus = 0;
  fits_update_key(ofptr, TDOUBLE, "LTV2", &dvalue, comment, &tstatus);

  dvalue = 1.0 / bin; *comment = '\0'; tstatus = 0;
  fits_read_key(fptr, TDOUBLE, "LTM1_1", &dvalue, comment, &tstatus); 
  tstatus = 0;
  fits_update_key(ofptr, TDOUBLE, "LTM1_1", &dvalue, comment, &tstatus);

  dvalue = 0.0; *comment = '\0'; tstatus = 0;
  fits_read_key(fptr, TDOUBLE, "LTM1_2", &dvalue, comment, &tstatus); 
  tstatus = 0;
  fits_update_key(ofptr, TDOUBLE, "LTM1_2", &dvalue, comment, &tstatus);

  dvalue = 0.0; *comment = '\0'; tstatus = 0;
  fits_read_key(fptr, TDOUBLE, "LTM2_1", &dvalue, comment, &tstatus); 
  tstatus = 0;
  fits_update_key(ofptr, TDOUBLE, "LTM2_1", &dvalue, comment, &tstatus);

  dvalue = 1.0 / bin; *comment = '\0'; tstatus = 0;
  fits_read_key(fptr, TDOUBLE, "LTM2_2", &dvalue, comment, &tstatus); 
  tstatus = 0;
  fits_update_key(ofptr, TDOUBLE, "LTM2_2", &dvalue, comment, &tstatus);

  // return the center and dims used
  if( dims ){
    dims[0] = dim1;
    dims[1] = dim2;
  }
  if( cens ){
    cens[0] = xcen;
    cens[1] = ycen;
  }
  // free up space
  if( rowselect ) free(rowselect);
  // return new file pointer
  return ofptr;
}
Exemplo n.º 8
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);

}
Exemplo n.º 9
0
int psrfits_write_polycos(struct psrfits *pf, struct polyco *pc, int npc) {

    // Usual setup
    int *status = &(pf->status);

    // If mode!=fold, exit?

    // Save current HDU, move to polyco table
    int hdu;
    fits_get_hdu_num(pf->fptr, &hdu);
    fits_movnam_hdu(pf->fptr, BINARY_TBL, "POLYCO", 0, status);

    int itmp;
    double dtmp;
    char datestr[32], ctmp[32];
    char *cptr;
    fits_get_system_time(datestr, &itmp, status);
    int i, col, n_written=0; 
    long row;
    fits_get_num_rows(pf->fptr, &row, status); // Start at end of table
    for (i=0; i<npc; i++) {

        // Only write polycos that were used
        if (!pc[i].used) continue; 

        // Go to next row (1-based index)
        row++;

        cptr = datestr;
        fits_get_colnum(pf->fptr,CASEINSEN,"DATE_PRO",&col,status);
        fits_write_col(pf->fptr,TSTRING,col,row,1,1,&cptr,status);

        sprintf(ctmp, "11.005"); // Tempo version?
        cptr = ctmp;
        fits_get_colnum(pf->fptr,CASEINSEN,"POLYVER",&col,status);
        fits_write_col(pf->fptr,TSTRING,col,row,1,1,&cptr,status);

        fits_get_colnum(pf->fptr,CASEINSEN,"NSPAN",&col,status);
        fits_write_col(pf->fptr,TINT,col,row,1,1,&(pc[i].nmin),status);

        fits_get_colnum(pf->fptr,CASEINSEN,"NCOEF",&col,status);
        fits_write_col(pf->fptr,TINT,col,row,1,1,&(pc[i].nc),status);

        sprintf(ctmp,"%d", pc[i].nsite); // XXX convert to letter?
        cptr = ctmp;
        fits_get_colnum(pf->fptr,CASEINSEN,"NSITE",&col,status);
        fits_write_col(pf->fptr,TSTRING,col,row,1,1,&cptr,status);

        fits_get_colnum(pf->fptr,CASEINSEN,"REF_FREQ",&col,status);
        fits_write_col(pf->fptr,TFLOAT,col,row,1,1,&(pc[i].rf),status);

        // XXX needs to be accurate??
        dtmp=0.0;
        fits_get_colnum(pf->fptr,CASEINSEN,"PRED_PHS",&col,status);
        fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&dtmp,status);

        dtmp = (double)pc[i].mjd + pc[i].fmjd;
        fits_get_colnum(pf->fptr,CASEINSEN,"REF_MJD",&col,status);
        fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&dtmp,status);

        fits_get_colnum(pf->fptr,CASEINSEN,"REF_PHS",&col,status);
        fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&(pc[i].rphase),status);

        fits_get_colnum(pf->fptr,CASEINSEN,"REF_F0",&col,status);
        fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&(pc[i].f0),status);

        // XXX don't parse this yet
        dtmp=-6.0;
        fits_get_colnum(pf->fptr,CASEINSEN,"LGFITERR",&col,status);
        fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&dtmp,status);

        fits_get_colnum(pf->fptr,CASEINSEN,"COEFF",&col,status);
        fits_write_col(pf->fptr,TDOUBLE,col,row,1,pc[i].nc,pc[i].c,status);

        n_written++;
    }

    // Update polyco block count, only if new info was added
    if (n_written) {
        itmp = row;
        fits_get_colnum(pf->fptr,CASEINSEN,"NPBLK",&col,status);
        for (i=1; i<=row; i++) 
            fits_write_col(pf->fptr,TINT,col,i,1,1,&itmp,status);
    }

    // Flush buffers (so files are valid as they are created)
    fits_flush_file(pf->fptr, status);

    // Go back to orig HDU
    fits_movabs_hdu(pf->fptr, hdu, NULL, status);

    return *status;
}
Exemplo n.º 10
0
int main(int argc, char *argv[]) {
    fitsfile *infile;
    int ii, jj, kk, status = 0;
    int nchan, nchan2, npol, wgts_col, offs_col;
    long nrows;
    float *weights, *offsets;
    char comment[120];

    // Read the weights and offsets
    read_wgts_and_offs(argv[1], &nchan, &weights, &offsets);
    printf("Read in %d channels of weights and offsets from\n\t'%s'\n", 
           nchan, argv[1]);

    // Step through the FITS files
    for (ii = 0 ; ii < argc-2 ; ii++) {
        printf("Updating '%s'\n", argv[ii+2]);
        
        // Is the file a PSRFITS file?
        if (!is_PSRFITS(argv[ii+2])) {
            fprintf(stderr,
                    "  Error!  '%s' does not appear to be PSRFITS!\n",
                    argv[ii+2]);
            exit(1);
        }
        
        // Open the PSRFITS file
        fits_open_file(&infile, argv[ii+2], READWRITE, &status);
        if (status) {
            printf("  Error!  Cannot open '%s'!\n", argv[ii+2]);
            exit(1);
        }

        // Move to the SUBINT HDU
        fits_movnam_hdu(infile, BINARY_TBL, "SUBINT", 0, &status);
        if (status) {
            printf("  Warning!  Cannot find NPOL in '%s'!  Assuming NPOL=1\n", 
                   argv[ii+2]);
            status = 0;
        }

        // Read the number of channels and polarizations
        fits_read_key(infile, TINT, "NCHAN", &nchan2, comment, &status); \
        if (status) {
            printf("  Warning!  Cannot find NCHAN in '%s'!\n", argv[ii+2]);
            status = 0;
        } else if (nchan != nchan2) {
            printf("  Error!  The number of channels in '%s'\n", argv[1]);
            printf("          and in '%s' do not match!\n", argv[ii+2]);
            exit(1);
        }
        fits_read_key(infile, TINT, "NPOL", &npol, comment, &status); \
        if (status) {
            printf("  Warning!  Cannot find NPOL in '%s'!  Assuming NPOL=1\n", 
                   argv[ii+2]);
            npol = 1;
            status = 0;
        }
        
        // How many rows are there?
        fits_get_num_rows(infile, &nrows, &status);
        if (status) {
            printf("  Error!  Cannot read the number of rows in '%s'!\n", 
                   argv[ii+2]);
            exit(1);
        }

        // Get the column numbers for the weights
        fits_get_colnum(infile, 0, "DAT_WTS", &wgts_col, &status);
        if (status==COL_NOT_FOUND) {
            printf("  Warning!:  Can't find the channel weights!\n");
            status = 0;
        } else {
            // update the weights, row by row
            for (jj = 1 ; jj < nrows+1 ; jj++)
                fits_write_col(infile, TFLOAT, wgts_col, jj, 
                               1L, nchan, weights, &status);
        }
        
        // Get the column numbers for the offsets
        if (0) {
            fits_get_colnum(infile, 0, "DAT_OFFS", &offs_col, &status);
            if (status==COL_NOT_FOUND) {
                printf("  Warning!:  Can't find the channel offsets!\n");
                status = 0;
            } else {
                // update the offsets, row by row
                for (jj = 1 ; jj < nrows+1 ; jj++)
                    for (kk = 0 ; kk < npol ; kk++)
                        fits_write_col(infile, TFLOAT, offs_col, jj, 
                                       kk*nchan+1L, nchan, offsets, &status);
            }
        }
        
        // Close the file
        fits_close_file(infile, &status);
        if (status) {
            printf("  Warning!:  Cannot properly close '%s' (status=%d)!\n", 
                   argv[ii+2], status);
            status = 0;
        }
    }
    free(weights);
    free(offsets);
    printf("Finished.\n");
    exit(0);
}
Exemplo n.º 11
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;
}
Exemplo n.º 12
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;
}
Exemplo n.º 13
0
int main(int argc, char *argv[])
{

    static struct option long_opts[] = {
        {"start",  1, NULL, 's'},
        {"end",    1, NULL, 'e'},
	{0,0,0,0}
    };	

    fitsfile *infptr, *outfptr;   /* FITS file pointers defined in fitsio.h */
    int opt, opti;
    int i, status = 0, ii = 1, jj=1;       /* status must always be initialized = 0  */
    int lo_row, hi_row;
    unsigned char *buffer = 0;

    long nrows;
    int ncols;
    int tfields;
    long  pcount;
    char  extname[FLEN_VALUE];
    char  *ttype[NFIELDS_I];
    char  *tform[NFIELDS_I];
    char  *tunit[NFIELDS_I];
    char  *tcomm[NFIELDS_I];

    float start=0.0, end=1.0;
    while ((opt=getopt_long(argc,argv,"s:e:h",long_opts,&opti))!=-1) {
        switch (opt) {
	    case 's':
	        start = atof(optarg);
		break;
	    case 'e':
	        end = atof(optarg);
		break;
	    case 'h':
	    default:
	        usage();
		exit(0);
		break;
	}	

    }

    if (argc < 3)
    {
      usage();
      return(0);
    }

    //printf("> %s %s\n", argv[1], argv[2]);
    //printf("> %s %s\n", argv[optind], argv[2]);


   /* Allocate space for the table parameters and initialize */
   for (i=0; i<NFIELDS_I; i++)
   {
      ttype[i] = (char *) malloc(FLEN_VALUE*sizeof(char));
      tform[i] = (char *) malloc(FLEN_VALUE*sizeof(char));
      tunit[i] = (char *) malloc(FLEN_VALUE*sizeof(char));
      tcomm[i] = (char *) malloc(FLEN_CARD*sizeof(char));
      strcpy(ttype[i], " ");
   }


    /* Open the input file */
    if ( !fits_open_file(&infptr, argv[optind], READONLY, &status) )
    {
      /* Create the output file */
      if ( !fits_create_file(&outfptr, argv[optind+1], &status) )
      {
        /* Copy every HDU until we get an error */
        //while( !fits_movabs_hdu(infptr, ii++, NULL, &status) )
	
	/* Copy first HDU */
        fits_copy_hdu(infptr, outfptr, 0, &status);

	fits_movnam_hdu(infptr, BINARY_TBL, "SUBINT", 0, &status);

	fits_get_num_rows(infptr, &nrows, &status);
	printf("Number of rows = %ld\n", nrows);
	
	fits_get_num_cols(infptr, &ncols, &status);
	printf("Number of cols = %d\n", ncols);
		
	long width;
	fits_read_key(infptr, TLONG, "NAXIS1", &width, NULL, &status);
	printf("Width = %ld\n", width);
	buffer = (unsigned char *) malloc(width);
	
	/* Copy the fits header */
	fits_copy_header(infptr, outfptr, &status);

//#if 0
	/* Determine low and high row number ot copy */
	lo_row = 1 + start * nrows;
	hi_row = end * nrows;
	printf("lo_row=%d hi_row=%d\n", lo_row, hi_row);

	for (ii=lo_row, jj=1; ii<=hi_row; ii++, jj++) {
	    printf("\rRead %d/%ld", ii, nrows);
	    fits_read_tblbytes( infptr,  ii, 1, width, buffer, &status);

	    fits_write_tblbytes(outfptr, jj, 1, width, buffer, &status);
	}
	nrows = (hi_row-lo_row)+1;
	fits_update_key(outfptr, TLONG, "NAXIS2", &nrows, 0, &status);
	printf("\nDone\n");
//#endif
        /* Reset status after normal error */
        //if (status == END_OF_FILE) status = 0;

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

    /* if error occured, print out error message */
    if (status) fits_report_error(stderr, status);
    return(status);
}
int quickfits_read_map_header(const char* filename , fitsinfo_map* fitsi)
{

/*
    Read in map header information
 
	INPUTS:
		char* tfilename : c string = name of FITS file to be read
	OUTPUTS:
		ra = right ascention
		dec = declination
		object = name of source
		freq = frequency
		cell =  cellsize (degrees)
		dim = image size
		bmaj, bmin, bpa = beam information (degrees)
*/
	fitsfile *fptr;

	int status,i,j;
	int err;
	char comment[FLEN_VALUE];
	char key_name[FLEN_VALUE];
	char key_type[FLEN_VALUE];
	char beamhdu[]="AIPS CG ";
	char cchdu[]="AIPS CC ";
	char bmajname[]="BMAJ";
	char bminname[]="BMIN";
	char bpaname[]="BPA";
	int colnum;
	double temp;
	float floatbuff;
	float float_null=0;
	int int_null=0;
	long longbuff;


	status = 0;	// for error processing
	err=0;



	if ( fits_open_file(&fptr,filename, READONLY, &status) )	// open file and make sure it's open
	{
		printf("ERROR : quickfits_read_map_header --> Error opening FITS file, error = %d\n",status);
		return(status);
	}

	if (fits_movabs_hdu(fptr,1,&i,&status))		// move to main AIPS image HDU (assuming it's the first one)
	{
		printf("ERROR : quickfits_read_map_header --> Error locating AIPS ACSII table extension, error = %d\n",status);
		printf("ERROR : quickfits_read_map_header --> Did you remember to use the AIPS FITAB task instead of FITTP?\n");
		return(status);
	}

	// read in some optional keys (these may fail on strange files - but are not that important)

	fits_read_key(fptr,TSTRING,"OBJECT",fitsi[0].object,comment,&status);
	fits_read_key(fptr,TSTRING,"OBSERVER",fitsi[0].observer,comment,&status);
	fits_read_key(fptr,TSTRING,"TELESCOP",fitsi[0].telescope,comment,&status);
	fits_read_key(fptr,TDOUBLE,"EQUINOX",&fitsi[0].equinox,comment,&status);
	fits_read_key(fptr,TSTRING,"DATE-OBS",fitsi[0].date_obs,comment,&status);
	
	//	Now iterate through CTYPE coords to get important information about RA, DEC, cellsize etc.
	//  Most of this data is important - at least notify the user if some is missing
	
	i=1;
	status=0;
	j=0;
	while(status!=KEY_NO_EXIST)
	{
		if(status != 0) {
			printf("ERROR : quickfits_read_map_header -->  Error reading from %s\n", filename);
			printf("ERROR : quickfits_read_map_header -->  FITSIO error code: %d\n", status);
			return(1);
		}
		sprintf(key_name,"CTYPE%d",i);
		fits_read_key(fptr,TSTRING,key_name,key_type,comment,&status);

		if( !strncmp(key_type,"RA---SIN",8) )
		{
			j++;
			
			sprintf(key_name,"CRVAL%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&fitsi[0].ra,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing RA information %s\n",key_name);
				status= 0;
			}
			
			sprintf(key_name,"CDELT%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&temp,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing RA information %s\n",key_name);
				status= 0;
			}
			else
			{
				fitsi[0].cell_ra=fabs(temp);
			}
			
			sprintf(key_name,"CRPIX%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&temp,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing RA information %s\n",key_name);
				status= 0;
			}
			else
			{
				fitsi[0].centre_shift[0]=temp;
			}
			
			sprintf(key_name,"CROTA%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&temp,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing RA information %s\n",key_name);
				status= 0;
			}
			else
			{
				fitsi[0].rotations[0]=temp;
			}
		}

		if( !strncmp(key_type,"DEC--SIN",8) )
		{
			j++;
			
			sprintf(key_name,"CRVAL%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&fitsi[0].dec,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing DEC information %s\n",key_name);
				status = 0;
			}
			
			sprintf(key_name,"CDELT%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&temp,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing RA information %s\n",key_name);
				status= 0;
			}
			else
			{
				fitsi[0].cell_dec=fabs(temp);
			}

			sprintf(key_name,"CRPIX%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&temp,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing DEC information %s\n",key_name);
				status = 0;
			}
			else
			{
				fitsi[0].centre_shift[1]=temp;
			}
			
			sprintf(key_name,"CROTA%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&temp,comment,&status);			
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing DEC information %s\n",key_name);
				status = 0;
			}
			else
			{
				fitsi[0].rotations[1]=temp;
			}
		}
		
		if( !strncmp(key_type,"FREQ",4) )
		{
			j++;
			
			sprintf(key_name,"CRVAL%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&fitsi[0].freq,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing FREQ information %s\n",key_name);
				status = 0;
			}

			sprintf(key_name,"CDELT%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&fitsi[0].freq_delta,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing FREQ information %s\n",key_name);
				status = 0;
			}
		}

		if( !strncmp(key_type,"STOKES",6) )
		{
			sprintf(key_name,"CRVAL%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&temp,comment,&status);

			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing Stokes information %s\n",key_name);
				status = 0;
			}
			else
			{
				fitsi[0].stokes=(int)(temp);
			}
		}
		i++;
	}
	status=0;
	if(j!=3)
	{
		printf("WARNING : quickfits_read_map_header --> Error reading RA, DEC, FREQ information\n");
		printf("\t Only %d out of 3 read.\n",j);
	}


	fits_read_key(fptr,TDOUBLE,"NAXIS1",&temp,comment,&status);
	fitsi[0].imsize_ra=(int)(temp);	// dim is stored as a double in the FITS file
	
	fits_read_key(fptr,TDOUBLE,"NAXIS2",&temp,comment,&status);
	fitsi[0].imsize_dec=(int)(temp);	// dim is stored as a double in the FITS file

	if(status!=0)
	{
		printf("ERROR : quickfits_read_map_header --> Error reading image size from NAXIS1, error = %d\n",err);
		return(err);
	}

	fitsi[0].have_beam = true; 	// assume true until proved otherwise
	fits_read_key(fptr,TDOUBLE,"BMAJ",&fitsi[0].bmaj,comment,&status);
	err += status;
	fits_read_key(fptr,TDOUBLE,"BMIN",&fitsi[0].bmin,comment,&status);
	err += status;
	fits_read_key(fptr,TDOUBLE,"BPA",&fitsi[0].bpa,comment,&status);
	err += status;
	
	if(err!=0)	// if the beam information isn't in the main header, move to AIPS CG HDU for beam information
	{
		status=0;
		if (fits_movnam_hdu(fptr,BINARY_TBL,beamhdu,0,&status))		// move to beam information hdu
		{
			printf("WARNING : quickfits_read_map_header --> No beam information found.\n");
			fitsi[0].bmaj = 0.0;
			fitsi[0].bmin = 0.0;	// changed this because model files don't have any beam information. Should check to make sure beam info is valid in other code
			fitsi[0].bpa = 0.0;
			fitsi[0].have_beam = false;
		}
		else
		{
			fits_get_colnum(fptr,CASEINSEN,bmajname,&colnum,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map_header -->  Error locating BMAJ information, error = %d\n",status);
				return(err);
			}
			fits_read_col(fptr,TFLOAT,colnum,1,1,1,&float_null,&floatbuff,&int_null,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map_header -->  Error reading BMAJ information, error = %d\n",status);
				return(err);
			}
			else
			{
				fitsi[0].bmaj=(double)(floatbuff);
			}

			fits_get_colnum(fptr,CASEINSEN,bminname,&colnum,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map_header -->  Error locating BMIN information, error = %d\n",status);
				return(err);
			}
			fits_read_col(fptr,TFLOAT,colnum,1,1,1,&float_null,&floatbuff,&int_null,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map_header -->  Error reading BMIN information, error = %d\n",status);
				return(err);
			}
			else
			{
				fitsi[0].bmin=(double)(floatbuff);
			}

			fits_get_colnum(fptr,CASEINSEN,bpaname,&colnum,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map_header -->  Error locating BPA information, error = %d\n",status);
				return(err);
			}
			fits_read_col(fptr,TFLOAT,colnum,1,1,1,&float_null,&floatbuff,&int_null,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map_header -->  Error reading BPA information, error = %d\n",status);
				return(err);
			}
			else
			{
				fitsi[0].bpa=(double)(floatbuff);
			}
		}
	}






	// move to AIPS CC HDU for clean component information if requested. Read, or give error if a failure occurs. Allow for possibility of the outdated "A3DTABLE" table type 6 as well as normal BINARY_TBL

	if (fitsi[0].cc_table_version >=0 )
	{
		fits_movnam_hdu(fptr,ANY_HDU,cchdu,fitsi[0].cc_table_version,&status);
		if (status==0)		// move to main AIPS UV hdu
		{
			fits_get_num_rows(fptr,&longbuff,&status);
			fitsi[0].ncc=longbuff;
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map_header -->  Error reading number of clean components, error = %d\n",status);
				return(status);
			}
		}
		else
		{
			printf("WARNING : quickfits_read_map_header -->  No clean component table detected.\n");
			fitsi[0].ncc=0;
			return(status);
		}
	}
	else
	{
		fitsi[0].ncc=0;
	}


	

	status=0;
	if ( fits_close_file(fptr, &status) )
	{
		printf("ERROR : quickfits_read_map_header --> Error closing FITS file, error = %d\n",status);
		return(status);
	}

	return(status);
}
Exemplo n.º 15
0
/**
 * Function: load_SED_from_fitsext
 * The function creates a energy distribution from the data stored
 * in a fits file extension. The data must be stored in the columns
 * "wavelength" and "flux".
 *
 * Parameters:
 * @param  spectral_models_file - pathname to the spectral models file
 * @param  s_models             - pointer to the fits file extension
 *
 * Returns:
 * @return sed - the energy distribution created 
 */
energy_distrib *
load_SED_from_fitsext(const char spectral_models_file[], fitsfile *s_models)
{
  int f_status=0;
  int anynul;
  long nrows=0;
  int colnum1;
  int colnum2;
  
  energy_distrib *sed;
  double *sed_wavs;
  double *sed_flux;

  // allocate memory for the energy distribution
  sed = (energy_distrib *) malloc(sizeof(energy_distrib));

  // get number of rows
  fits_get_num_rows (s_models, &nrows, &f_status);
  if (f_status) {
    ffrprt (stderr, f_status);
    aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
		 "load_SED_from_fitsext: "
		 "Could not determine the number of rows in"
		 " table %s",spectral_models_file);
  }

  // allocate memory for the data
  sed_wavs = (double *) malloc(nrows*sizeof(double));
  if (!sed_wavs) { 
    aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
		 "Memory allocation failed");
  }
  sed_flux = (double *) malloc(nrows*sizeof(double));
  if (!sed_flux) {
    aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
		 "Memory allocation failed");
  }

  // get the column number for the wavelength
  fits_get_colnum (s_models, CASEINSEN, "WAV_NM", &colnum1, &f_status);
  if (f_status)
    {
      ffrprt (stderr, f_status);
      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
		   "create_interp_ftable: "
		   "Could not determine column %s in "
		   " table %s", "WAV_NM", spectral_models_file);
    }
  // read the wavelength
  fits_read_col (s_models, TDOUBLE, colnum1, 1, 1, nrows, NULL, sed_wavs,
                    &anynul, &f_status);
  if (f_status)
    {
      ffrprt (stderr, f_status);
      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
		   "load_SED_from_fitsext: "
		   "Could not read content of WAVELENGTH column "
		   " from BINARY table %s", spectral_models_file);
    }

  // get the column number for the flux
  fits_get_colnum (s_models, CASEINSEN, "FLUX", &colnum2, &f_status);
  if (f_status)
    {
      ffrprt (stderr, f_status);
      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
  		   "create_interp_ftable: "
  		   "Could not determine column %s in "
  		   " table %s", "FLUX", spectral_models_file);
    }
  // read the flux column 
  fits_read_col (s_models, TDOUBLE, colnum2, 1, 1, nrows, NULL, sed_flux,
                    &anynul, &f_status);
  if (f_status)
    {
      ffrprt (stderr, f_status);
      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
		   "load_SED_from_fitsext: "
		   "Could not read content of FLUX column "
		   " from BINARY table %s", spectral_models_file);
    }

  // transfer the vector and length information
  // to the SED object
  sed->npoints    = nrows;
  sed->wavelength = sed_wavs ;
  sed->flux       = sed_flux;

  // allocate some structures for the interpolator
  sed->interp     = gsl_interp_alloc (SMODEL_INTERP_TYPE, (size_t)sed->npoints );
  sed->accel      = gsl_interp_accel_alloc ();

  // initialize the iterpolator
  gsl_interp_init (sed->interp, sed->wavelength, sed->flux, (size_t)sed->npoints);

  // return the energy distribution
  return sed;
}
Exemplo n.º 16
0
str FITSloadTable(Client cntxt, MalBlkPtr mb, MalStkPtr stk, InstrPtr pci)
{
	mvc *m = NULL;
	sql_schema *sch;
	sql_table *fits_fl, *fits_tbl, *tbl = NULL;
	sql_column *col;
	sql_subtype tpe;
	fitsfile *fptr;
	str tname = *(str*)getArgReference(stk, pci, 1);
	str fname;
	str msg = MAL_SUCCEED;
	oid rid = oid_nil, frid = oid_nil;
	int status = 0, cnum = 0, fid, hdu, hdutype, i, j, anynull = 0, mtype;
	int *tpcode = NULL;
	long *rep = NULL, *wid = NULL, rows;
	char keywrd[80], **cname, nm[FLEN_VALUE];
	ptr nilptr;

	msg = getSQLContext(cntxt, mb, &m, NULL);
	if (msg)
		return msg;
	sch = mvc_bind_schema(m, "sys");

	fits_tbl = mvc_bind_table(m, sch, "fits_tables");
	if (fits_tbl == NULL) {
		msg = createException(MAL, "fits.loadtable", "FITS catalog is missing.\n");
		return msg;
	}

	tbl = mvc_bind_table(m, sch, tname);
	if (tbl) {
		msg = createException(MAL, "fits.loadtable", "Table %s is already created.\n", tname);
		return msg;
	}

	col = mvc_bind_column(m, fits_tbl, "name");
	rid = table_funcs.column_find_row(m->session->tr, col, tname, NULL);
	if (rid == oid_nil) {
		msg = createException(MAL, "fits.loadtable", "Table %s is unknown in FITS catalog. Attach first the containing file\n", tname);
		return msg;
	}

	/* Open FITS file and move to the table HDU */
	col = mvc_bind_column(m, fits_tbl, "file_id");
	fid = *(int*)table_funcs.column_find_value(m->session->tr, col, rid);

	fits_fl = mvc_bind_table(m, sch, "fits_files");
	col = mvc_bind_column(m, fits_fl, "id");
	frid = table_funcs.column_find_row(m->session->tr, col, (void *)&fid, NULL);
	col = mvc_bind_column(m, fits_fl, "name");
	fname = (char *)table_funcs.column_find_value(m->session->tr, col, frid);
	if (fits_open_file(&fptr, fname, READONLY, &status)) {
		msg = createException(MAL, "fits.loadtable", "Missing FITS file %s.\n", fname);
		return msg;
	}

	col = mvc_bind_column(m, fits_tbl, "hdu");
	hdu = *(int*)table_funcs.column_find_value(m->session->tr, col, rid);
	fits_movabs_hdu(fptr, hdu, &hdutype, &status);
	if (hdutype != ASCII_TBL && hdutype != BINARY_TBL) {
		msg = createException(MAL, "fits.loadtable", "HDU %d is not a table.\n", hdu);
		fits_close_file(fptr, &status);
		return msg;
	}

	/* create a SQL table to hold the FITS table */
	/*	col = mvc_bind_column(m, fits_tbl, "columns");
	   cnum = *(int*) table_funcs.column_find_value(m->session->tr, col, rid); */
	fits_get_num_cols(fptr, &cnum, &status);
	tbl = mvc_create_table(m, sch, tname, tt_table, 0, SQL_PERSIST, 0, cnum);

	tpcode = (int *)GDKzalloc(sizeof(int) * cnum);
	rep = (long *)GDKzalloc(sizeof(long) * cnum);
	wid = (long *)GDKzalloc(sizeof(long) * cnum);
	cname = (char **)GDKzalloc(sizeof(char *) * cnum);

	for (j = 1; j <= cnum; j++) {
		/*		fits_get_acolparms(fptr, j, cname, &tbcol, tunit, tform, &tscal, &tzero, tnull, tdisp, &status); */
		snprintf(keywrd, 80, "TTYPE%d", j);
		fits_read_key(fptr, TSTRING, keywrd, nm, NULL, &status);
		if (status) {
			snprintf(nm, FLEN_VALUE, "column_%d", j);
			status = 0;
		}
		cname[j - 1] = GDKstrdup(toLower(nm));
		fits_get_coltype(fptr, j, &tpcode[j - 1], &rep[j - 1], &wid[j - 1], &status);
		fits2subtype(&tpe, tpcode[j - 1], rep[j - 1], wid[j - 1]);

		/*		mnstr_printf(cntxt->fdout,"#%d %ld %ld - M: %s\n", tpcode[j-1], rep[j-1], wid[j-1], tpe.type->sqlname); */

		mvc_create_column(m, tbl, cname[j - 1], &tpe);
	}

	/* data load */
	fits_get_num_rows(fptr, &rows, &status);
	mnstr_printf(cntxt->fdout,"#Loading %ld rows in table %s\n", rows, tname);
	for (j = 1; j <= cnum; j++) {
		BAT *tmp = NULL;
		int time0 = GDKms();
		mtype = fits2mtype(tpcode[j - 1]);
		nilptr = ATOMnil(mtype);
		col = mvc_bind_column(m, tbl, cname[j - 1]);

		tmp = BATnew(TYPE_void, mtype, rows);
		if ( tmp == NULL){
			GDKfree(tpcode);
			GDKfree(rep);
			GDKfree(wid);
			GDKfree(cname);
			throw(MAL,"fits.load", MAL_MALLOC_FAIL);
		}
		BATseqbase(tmp, 0);
		if (rows > (long)REMAP_PAGE_MAXSIZE)
			BATmmap(tmp, STORE_MMAP, STORE_MMAP, STORE_MMAP, STORE_MMAP, 0);
		if (mtype != TYPE_str) {
			fits_read_col(fptr, tpcode[j - 1], j, 1, 1, rows, nilptr, (void *)BUNtloc(bat_iterator(tmp), BUNfirst(tmp)), &anynull, &status);
			BATsetcount(tmp, rows);
			tmp->tsorted = 0;
			tmp->trevsorted = 0;
		} else {
/*			char *v = GDKzalloc(wid[j-1]);*/
			int bsize = 50;
			int tm0, tloadtm = 0, tattachtm = 0;
			int batch = bsize, k;
			char **v = (char **) GDKzalloc(sizeof(char *) * bsize);
			for(i = 0; i < bsize; i++)
				v[i] = GDKzalloc(wid[j-1]);
			for(i = 0; i < rows; i += batch) {
				batch = rows - i < bsize ? rows - i: bsize;
				tm0 = GDKms();
				fits_read_col(fptr, tpcode[j - 1], j, 1 + i, 1, batch, nilptr, (void *)v, &anynull, &status);
				tloadtm += GDKms() - tm0;
				tm0 = GDKms();
				for(k = 0; k < batch ; k++)
					BUNappend(tmp, v[k], TRUE);
				tattachtm += GDKms() - tm0;
			}
			for(i = 0; i < bsize ; i++)
				GDKfree(v[i]);
			GDKfree(v);
			mnstr_printf(cntxt->fdout,"#String column load %d ms, BUNappend %d ms\n", tloadtm, tattachtm);
		}

		if (status) {
			char buf[FLEN_ERRMSG + 1];
			fits_read_errmsg(buf);
			msg = createException(MAL, "fits.loadtable", "Cannot load column %s of %s table: %s.\n", cname[j - 1], tname, buf);
			break;
		}
		mnstr_printf(cntxt->fdout,"#Column %s loaded for %d ms\t", cname[j-1], GDKms() - time0);
		store_funcs.append_col(m->session->tr, col, tmp, TYPE_bat);
		mnstr_printf(cntxt->fdout,"#Total %d ms\n", GDKms() - time0);
		BBPunfix(tmp->batCacheid);
	}

	GDKfree(tpcode);
	GDKfree(rep);
	GDKfree(wid);
	GDKfree(cname);

	fits_close_file(fptr, &status);
	return msg;
}
Exemplo n.º 17
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;
}
Exemplo n.º 18
0
long table::get_num_rows(){
  long nrows;
  fits_get_num_rows(fptr, &nrows, &status);
  return nrows;
}
long get_num_of_rows(fitsfile * fptr)
{
    long result = 0;
    fits_get_num_rows(fptr, &result, &fitsio_status);
    return result;
}
Exemplo n.º 20
0
KstObject::UpdateType LFIIOSource::update( int u ) 
{
  Q_UNUSED( u )

  KstObject::UpdateType updateType =  KstObject::NO_CHANGE;
  QString               strTemplate;
  QString               strName;
  fitsfile*             ffits;
  char                  charTemplate[ FLEN_CARD ];
  char                  charName[ FLEN_CARD ];
  long                  lNumFrames;
  long                  lMaxRepeat = 1;
  long                  lRepeat;
  long                  lWidth;
  int                   iColNumber;
  int                   iNumCols;
  int                   iStatus = 0;
  int                   iResult = 0;
  int                   iTypeCode;
  int                   i;

  _valid  = false;

  if( !_filename.isNull( ) && !_filename.isEmpty( ) )
  {
    iResult = fits_open_table( &ffits, _filename.ascii( ), READONLY, &iStatus );
    if( iResult == 0 )
    {
      //
      // determine size of data...
      //
      iResult = fits_get_num_cols( ffits, &iNumCols, &iStatus );
      if( iResult == 0 )
      {
        iResult = fits_get_num_rows( ffits, &lNumFrames, &iStatus );
        if( iResult == 0 )
        {
          _strListColNames.clear( );

          _valid = true;

          //
	        // need to multiply lNumFrames by the maximum value of the vector repeat value...
	        //
          for( i=0; i<iNumCols; i++ )
          {
            iStatus = 0;
            
            sprintf( charTemplate, "%d", i+1 );
            iResult = fits_get_colname( ffits, CASEINSEN, charTemplate, charName, &iColNumber, &iStatus );
            if( iResult == 0 )
            { 
              strName = charName;
              _strListColNames.append( strName );
            }
            else
            {
              strName.setNum( i );
              _strListColNames.append( strName );
            }
              
            iStatus = 0;
            iResult = fits_get_coltype( ffits, i+1, &iTypeCode, &lRepeat, &lWidth, &iStatus );
            if( iResult == 0 )
            {
              if( lRepeat > lMaxRepeat )
              {
                lMaxRepeat = lRepeat;
              }
            }
          }

          if( lNumFrames * lMaxRepeat != _numFrames )
	        {
            _numCols   = iNumCols;
            _numFrames = lNumFrames * lMaxRepeat;
            updateType = KstObject::UPDATE;
          }
        }
      }
      iStatus = 0;
      fits_close_file( ffits, &iStatus );   
    }
  }
  
  return updateType;
}
Exemplo n.º 21
0
Kst::Object::UpdateType LFIIOSource::update() {

  Kst::Object::UpdateType updateType = Kst::Object::NO_CHANGE;
  QString               strTemplate;
  QString               strName;
  fitsfile*             ffits;
  char                  charTemplate[FLEN_CARD];
  char                  charName[FLEN_CARD];
  long                  lNumFrames;
  long                  lMaxRepeat = 1;
  long                  lRepeat;
  long                  lWidth;
  int                   iColNumber;
  int                   iNumCols;
  int                   iStatus = 0;
  int                   iResult = 0;
  int                   iTypeCode;
  int                   i;
  int                   newNF = 0;

  _valid  = false;

  if(!_filename.isNull() && !_filename.isEmpty()) {
    iResult = fits_open_table( &ffits, _filename.ascii(), READONLY, &iStatus );
    if(iResult == 0) {
      // determine size of data...
      iResult = fits_get_num_cols( ffits, &iNumCols, &iStatus );
      if(iResult == 0) {
        iResult = fits_get_num_rows( ffits, &lNumFrames, &iStatus );
        if(iResult == 0) {
          _fieldList.clear();
          _fieldList.append("INDEX");

          _valid = true;
          _bHasTime = false;

          // need to multiply lNumFrames by the maximum value of the vector repeat value...
          for(i = 0; i<iNumCols; i++) {
            iStatus = 0;

            sprintf(charTemplate, "%d", i+1);
            iResult = fits_get_colname( ffits, CASEINSEN, charTemplate, charName, &iColNumber, &iStatus );
            if(iResult == 0) {
              int iOffset = i;
              strName = charName;

              // ensure that we don't add duplicates to the _fieldList...
              while(_fieldList.findIndex(strName) != -1) {
                strName = QString("%1[%2]").arg(charName).arg(iOffset);
                iOffset++;
              }
            } else {
              strName.setNum(i);
            }

            _fieldList.append(strName);

            iStatus = 0;
            iResult = fits_get_coltype( ffits, i+1, &iTypeCode, &lRepeat, &lWidth, &iStatus );
            if(iResult == 0) {
              if(lRepeat > lMaxRepeat) {
                lMaxRepeat = lRepeat;
              }
            }
          }

          // check if we have a time field defined by the header keys TIMEZERO and DELTA_T.
          //  If so then we create a new field called $TIME_FIELD, unless such a field already
          //  exists, in which case we do nothing...
          char charTimeZero[] = "TIMEZERO";

          iStatus = 0;
          iResult = fits_read_key( ffits, TDOUBLE, charTimeZero, &_dTimeZero, 0L, &iStatus );
          if(iResult == 0) {
            char charTimeDelta[] = "DELTA_T";

            iResult = fits_read_key( ffits, TDOUBLE, charTimeDelta, &_dTimeDelta, 0L, &iStatus );
            if(iResult == 0) {
              if(_fieldList.find(QString(TIME_FIELD)) == _fieldList.end()) {
                _bHasTime = true;
                _fieldList.append(TIME_FIELD);
              }
            }
          }

          if(lNumFrames * lMaxRepeat != _numFrames) {
            _numCols   = iNumCols;
            newNF = lNumFrames * lMaxRepeat;
            updateType = Kst::Object::UPDATE;
          }
        }
      }
      iStatus = 0;
      fits_close_file( ffits, &iStatus );
    }
  }

  bool isnew = newNF != _numFrames;

  _numFrames = newNF;

  return (isnew ? Kst::Object::UPDATE : Kst::Object::NO_CHANGE);
}
Exemplo n.º 22
0
int countsmalibur(AG_params & params) {

	int numcol = 0;
	long nrows = 0; 
	int status = 0;
	double l = 0, b = 0;	
	double x = 0, y = 0;	
	int i = 0, ii = 0;	
	double the = 0;	
	long mxdim= params.mxdim; // dimension (in pixels) of the map
	unsigned short A[mxdim][mxdim];

	for (i = 0; i < mxdim; i++)
	{   for (ii = 0; ii < mxdim; ii++)
		{
			A[i][ii] = 0;
		}
	}	

	double baa = params.ba * D2R;
	double laa = params.la * D2R;
	
	int bitpix   =  USHORT_IMG; /* 16-bit unsigned short pixel values       */
	long naxis    =   2;  /* 2-dimensional image                            */    
	long naxes[2] = { mxdim, mxdim };   /* image is 300 pixels wide by 200 rows */		
	
	fitsfile * evtFits;
	char tempname[FLEN_FILENAME];
	strcpy(tempname, tmpnam(NULL));
	if ( fits_create_file(&evtFits, tempname, &status) != 0 ) {
		printf("Errore in apertura file %s\n",tempname);
		return status;
	}	
	
	char expr[1024];
	strcpy(expr,params.evtexpr().c_str());
	
	std::cout << std::endl << "AG_ctsmapgen....................................adding events files"<< std::endl;
	status = addfile(evtFits, params.evtfile, expr, params.tmin, params.tmax);
	std::cout << "AG_ctsmapgen....................................addfile exiting STATUS : "<< status<< std::endl << std::endl ;	
	

	fitsfile * mapFits;
	if ( fits_create_file(&mapFits, params.outfile, &status) != 0 ) {
		printf("Errore in apertura file '%s'\n",params.outfile);
		return status;
	}	

	
	fits_movabs_hdu(evtFits, 2, NULL, &status);	
	fits_get_num_rows(evtFits, &nrows, &status);
	cout << nrows << endl;

	double ra, dec;
	double dummy;
	switch (params.projection) {
	    case AG_params::ARC:
		for (long k = 0; k<nrows; ++k) {
			fits_get_colnum(evtFits, 1, "RA", &numcol, &status);
			fits_read_col(evtFits, TDOUBLE, numcol, k+1, 1, 1, NULL, &ra, NULL, &status);
			fits_get_colnum(evtFits, 1, "DEC", &numcol, &status);
			fits_read_col(evtFits, TDOUBLE, numcol, k+1, 1, 1, NULL, &dec, NULL, &status);

		    eulerold(ra, dec, &l, &b, 1);
		    l*=D2R;
		    b*=D2R;
		    the = sin(b)*sin(baa)+cos(b)*cos(baa)*cos(l-laa);
		    if (the < -1.0) {
			    the = PI;
		    } else if (the > 1.0) {
			    the = 0.0;
		    } else {
			    the = acos(the);
		    }
		    x = R2D/Alikesinaa(the) * cos(b)*sin(l-laa);
		    y = R2D/Alikesinaa(the) * (sin(b)*cos(baa) - cos(b)*sin(baa)*cos(l-laa));

		    i=(int)floor(((-x+(params.mdim/2.))/params.mres));
		    ii=(int)floor(((y+(params.mdim/2.))/params.mres));

		    if (params.inmap(i,ii)) {
			    A[ii][i]+=1;
			}
		}
		break;
		
	    case AG_params::AIT:
		for (long k = 0; k<nrows; ++k) {
			fits_get_colnum(evtFits, 1, "RA", &numcol, &status);
			fits_read_col(evtFits, TDOUBLE, numcol, k+1, 1, 1, NULL, &ra, NULL, &status);
			fits_get_colnum(evtFits, 1, "DEC", &numcol, &status);
			fits_read_col(evtFits, TDOUBLE, numcol, k+1, 1, 1, NULL, &dec, NULL, &status);
		    eulerold(ra, dec, &l, &b, 1);
		    l*=D2R;
		    b*=D2R;
		    the = sin(b)*sin(baa)+cos(b)*cos(baa)*cos(l-laa);
		    if (the < -1.0) {
			    the = PI;
		    } else if (the > 1.0) {
			    the = 0.0;
		    } else {
			    the = acos(the);
		    }
		    l=l-laa;

		    if ( l < PI  ) { 
		      l=-l; 
		    }
		    else { 
		      l=2*PI -l; 
		    }

		    x=R2D*(sqrt(2.0)*2.0*cos(b)*sin(l/2.0))/sqrt(1.0 + cos(b)*cos(l/2.0) ) ;         
		    y=R2D*(sqrt(2.0)*sin(b))/sqrt(1.0 + cos(b)*cos(l/2.0) );

		    i=(int)floor(((x+(params.mdim/2.))/params.mres));
		    ii=(int)floor(((y+(params.mdim/2.))/params.mres));

		    if (params.inmap(i,ii)) {
			    A[ii][i]+=1;
			}
		}
		break;
	}
	
		

	long nelement =  naxes[0] * naxes[1];
	std::cout<< "creating Counts Map...................................." << std::endl;	
	fits_create_img(mapFits, bitpix, naxis, naxes, &status);
	std::cout<< "writinig Counts Map...................................." << std::endl;		
	fits_write_img(mapFits, bitpix, 1, nelement, A, &status);	
	std::cout<< "writing header........................................" << std::endl<< std::endl;	

		
	
	params.write_fits_header(mapFits, status);
	
	
	fits_delete_file(evtFits, &status);
	fits_close_file(mapFits, &status);	
	return status;
}
Exemplo n.º 23
0
int main(int argc, char *argv[])
{
  fitsfile *infptr = 0, *outfptr = 0;  /* FITS file pointers */
  int status = 0;   /* CFITSIO status value MUST be initialized to zero! */
  int icol = 0, incols = 0, outcols = 0, intype = 0, outtype = 0, check = 1;
  long inrep = 0, outrep = 0, width = 0, inrows = 0, outrows = 0, ii = 0, jj = 0;
  unsigned char *buffer = 0;

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

  if (printhelp || argc != 3) {
    fprintf(stderr, "Usage:  %s infile1[ext][filter] outfile[ext]\n", argv[0]);
    fprintf(stderr, "\n");
    fprintf(stderr, "Merge 2 tables by copying all the rows from the 1st table\n");
    fprintf(stderr, "into the 2nd table.  The  2 tables must have identical\n");
    fprintf(stderr, "structure, with the same number of columns with the same\n");
    fprintf(stderr, "datatypes.  This program modifies the output file in place,\n");
    fprintf(stderr, "rather than creating a whole new output file.\n");
    fprintf(stderr, "\n");
    fprintf(stderr, "Examples: \n");
    fprintf(stderr, "\n");
    fprintf(stderr, "1. %s intab.fit+1 outtab.fit+2\n", argv[0]);
    fprintf(stderr, "\n");
    fprintf(stderr, "    merge the table in the 1st extension of intab.fit with\n");
    fprintf(stderr, "    the table in the 2nd extension of outtab.fit.\n");
    fprintf(stderr, "\n");
    fprintf(stderr, "2. %s 'intab.fit+1[PI > 45]' outab.fits+2\n", argv[0]);
    fprintf(stderr, "\n");
    fprintf(stderr, "    Same as the 1st example, except only rows that have a PI\n");
    fprintf(stderr, "    column value > 45 will be merged into the output table.\n");
    fprintf(stderr, "\n");
    return (0);
  }

  /* open both input and output files and perform validity checks */
  if (fits_open_file(&infptr,  argv[1], READONLY,  &status) ||
      fits_open_file(&outfptr, argv[2], READWRITE, &status)) {
    fprintf(stderr, " Couldn't open both files\n");
  }

  else if (fits_get_hdu_type(infptr,  &intype,  &status) ||
           fits_get_hdu_type(outfptr, &outtype, &status)) {
    fprintf(stderr, "couldn't get the type of HDU for the files\n");
  }

  else if (intype == IMAGE_HDU) {
    fprintf(stderr, "The input HDU is an image, not a table\n");
  }

  else if (outtype == IMAGE_HDU) {
    fprintf(stderr, "The output HDU is an image, not a table\n");
  }

  else if (outtype != intype) {
    fprintf(stderr, "Input and output HDUs are not the same type of table.\n");
  }

  else if (fits_get_num_cols(infptr,  &incols,  &status) ||
           fits_get_num_cols(outfptr, &outcols, &status)) {
    fprintf(stderr, "Couldn't get number of columns in the tables\n");
  }

  else if (incols != outcols) {
    fprintf(stderr, "Input and output HDUs don't have same # of columns.\n");
  }

  else if (fits_read_key(infptr, TLONG, "NAXIS1", &width, NULL, &status)) {
    fprintf(stderr, "Couldn't get width of input table\n");
  }

  else if (!(buffer = (unsigned char *) malloc(width))) {
    fprintf(stderr, "memory allocation error\n");
  }

  else if (fits_get_num_rows(infptr,  &inrows,  &status) ||
           fits_get_num_rows(outfptr, &outrows, &status)) {
    fprintf(stderr, "Couldn't get the number of rows in the tables\n");
  }

  else  {
    /* check that the corresponding columns have the same datatypes */
    for (icol = 1; icol <= incols; icol++) {
      fits_get_coltype(infptr,  icol, &intype,  &inrep,  NULL, &status);
      fits_get_coltype(outfptr, icol, &outtype, &outrep, NULL, &status);
      if (intype != outtype || inrep != outrep) {
        fprintf(stderr, "Column %d is not the same in both tables\n", icol);
        check = 0;
      }
    }

    if (check && !status) {
      /* insert 'inrows' empty rows at the end of the output table */
      fits_insert_rows(outfptr, outrows, inrows, &status);

      for (ii = 1, jj = outrows +1; ii <= inrows; ii++, jj++) {
        /* read row from input and write it to the output table */
        fits_read_tblbytes(infptr,  ii, 1, width, buffer, &status);
        fits_write_tblbytes(outfptr, jj, 1, width, buffer, &status);
        if (status) {
          break;  /* jump out of loop if error occurred */
        }
      }

      /* all done; now free memory and close files */
      fits_close_file(outfptr, &status);
      fits_close_file(infptr,  &status);
    }
  }

  if (buffer) {
    free(buffer);
  }

  if (status) {
    fits_report_error(stderr, status);  /* print any error message */
  }
  return (status);
}
Exemplo n.º 24
0
//int main ( int argc, char *argv[] )
int read_value ( char *name, int subint, double *value, int nphase, int nchan, int npol)
{  
//double *read_arrival_time( char *input, long *nrows )
    //int subint = 1;
	//double profile[8*1024];
    fitsfile *fptr;       // pointer to the FITS file, defined in fitsio.h 
    int status;
    int colnum;
    long int nrows;

    status = 0;

    //if ( fits_open_file(&fptr, argv[1], READONLY, &status) )          // open the file
    if ( fits_open_file(&fptr, name, READONLY, &status) )          // open the file
    {
        printf( "error while openning file\n" );
    }

    if ( fits_get_num_rows(fptr, &nrows, &status) )           // get the row number
    {
        printf( "error while getting the row number\n" );
    }
    //printf ("%ld\n", nrows);
    
    //if ( fits_get_colnum(fptr, CASEINSEN, "TSUBINT", &colnum, &status) )           // get the row number
    if ( fits_get_colnum(fptr, CASEINSEN, "DATA", &colnum, &status) )           // get the row number
    {
        printf( "error while getting the colnum number\n" );
		//fits_get_colnum(fptr, CASEINSEN, "DATA", &colnum, &status);
	}
    //printf ("%d\n", colnum);

	///////////////////////////////////////////////////////////////////////////

	int nbin;
    int frow;
    int felem;
    int nelem;
    int null;
    int anynull;
    //double *profile;     // the array to store the profile   

	nbin = nphase;
    //profile = ( double *)malloc( (nchan*npol*nbin) * sizeof( double ) );               // allocate space for column value
    frow = subint;
    felem = 1;
    nelem = nbin*nchan*npol;
    //nelem = 1024;
    null = 0;
    anynull = 0;

    fits_read_col(fptr, TDOUBLE, colnum, frow, felem, nelem, &null, value, &anynull, &status);           // read the column

	//int i;
    //for (i = 0; i < (nchan*npol*nbin); i++)                             // print the results
    //    printf("%d %lf \n", i, profile[i]);

    if ( fits_close_file(fptr, &status) )
    {
        printf( " error while closing the file " );
    }

    return 0;
}
Exemplo n.º 25
0
void processFile(char *fname,tmplStruct *tmpl,FILE *fout,int logit)
{
  pheader *header;
  ptime_observation *obs;
  toaStruct toa;
  fitsfile *fp;
  int i;
  float baselineFrac = 0.1;
  int baselineType = 1;
  int toaAlgorithm=1;
  double dPhi;
  double *offs_sub;
  double *datFreq;
  int nSub = 1;
  FILE *fout_log;
  char logFname[128];
  long double period;

  sprintf(logFname,"log.ptime.%s",fname);
  fout_log = fopen(logFname,"w");
  offs_sub = (double *)malloc(sizeof(double)*nSub);
  obs = (ptime_observation *)malloc(sizeof(ptime_observation));
  header = (pheader *)malloc(sizeof(pheader));
  fp = openFitsFile(fname);
  loadPrimaryHeader(fp,header);

  datFreq= (double *)malloc(sizeof(double)*header->nchan);
  allocateObsMemory(obs,header);
  readData(obs,header,fp);
  // Now get an array of subintegration times
  readSubintOffs(obs,offs_sub,fp);
  // Get an array of frequencies
  readDatFreq(obs,datFreq,fp,header->nchan);

  printf("offs_sub = %g\n",offs_sub[0]);
  // Calculate the period
  {
    FILE *pred_out;
    int status=0;
    long nrows,row;
    char nval[128]="UNKNOWN";
    int anynul=0;
    long double mjd0;
    long double frequency;
    char **line;
    T2Predictor pred;
    int ret;

    line = (char **)malloc(sizeof(char *));
    line[0] = (char *)malloc(sizeof(char)*1024);     


    if (!(pred_out = fopen("ptime.pred","w"))){
      printf("Unable to open file >%s<\n","ptime.pred");
    }
    fits_movnam_hdu(fp,BINARY_TBL,(char *)"T2PREDICT",1,&status);
    if (status)
      {
	printf("No predictor table in PSRFITS file\n");
	status=0;
      }
    fits_get_num_rows(fp,&nrows,&status);
    printf("NROWS = %d\n",nrows);
    for (row = 1; row <= nrows ; row++){
      fits_read_col_str(fp,1,row,1,1,nval,line,&anynul,&status);
      printf("Have read %s\n",line[0]);
      fprintf(pred_out,"%s\n",line[0]);
    }
    free(line[0]);
    free(line);

    fclose(pred_out);

    T2Predictor_Init(&pred);  // prepare the predictor                                                                                     
    if (ret=T2Predictor_Read(&pred,(char *)"ptime.pred"))
      {
	printf("Error: unable to read predictor\n");
	exit(1);
      }
    mjd0 = header->imjd + (header->smjd + header->stt_offs)/86400.0L;
    frequency = datFreq[0];  //(freq in MHz) WHAT SHOULD THIS BE SET TO!!
    period = 1.0/T2Predictor_GetFrequency(&pred,mjd0,frequency);
    if (period==-1){
      printf("Error: period returned from predictor = -1. This cannot be correct.\n");
      exit(1);
    }
    T2Predictor_Destroy(&pred);
    printf("Period = %.15Lf %.15Lf %.15Lf\n",period,mjd0,frequency);
  }

  closeFitsFile(fp);
  // Must remove a baseline
  removeBaseline(obs,header,baselineType,baselineFrac);
  printf("Here\n");
  // Now get the shift
  if (toaAlgorithm == 1)
    getTOA_alg1(obs,header,tmpl,&toa,fout_log);
  strcpy(toa.fname,fname);



  // Calculate the arrival time
  calcArrivalTime(obs,header,tmpl,&toa,offs_sub,datFreq,period,fout,fout_log);
  free(header);
  free(obs);
  free(offs_sub);
  free(datFreq);
  fclose(fout_log);
}
Exemplo n.º 26
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);
}