コード例 #1
0
ファイル: subImage.c プロジェクト: Caltech-IPAC/Montage
struct WorldCoor *montage_getFileInfo(fitsfile *infptr, char *header[], struct imageParams *params)
{
   struct WorldCoor *wcs;
   int status = 0;
   int i;

   if(fits_get_image_wcs_keys(infptr, header, &status))
      montage_printFitsError(status);

   if(fits_read_key_lng(infptr, "NAXIS", &params->naxis, (char *)NULL, &status))
      montage_printFitsError(status);
   
   if(fits_read_keys_lng(infptr, "NAXIS", 1, params->naxis, params->naxes, &params->nfound, &status))
      montage_printFitsError(status);
   
   if(debug)
   {
      for(i=0; i<params->naxis; ++i)
         printf("naxis%d = %ld\n",  i+1, params->naxes[i]);

      fflush(stdout);
   }

   /****************************************/
   /* Initialize the WCS transform library */
   /* and find the pixel location of the   */
   /* sky coordinate specified             */
   /****************************************/

   wcs = wcsinit(header[0]);

   params->isDSS = 0;
   if(wcs->prjcode == WCS_DSS)
      params->isDSS = 1;

   if(wcs == (struct WorldCoor *)NULL)
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Output wcsinit() failed.\"]\n");
      fflush(stdout);
      exit(1);
   }

   /* Extract the CRPIX and (equivalent) CDELT values */
   /* from the WCS structure                          */

   params->crpix[0] = wcs->xrefpix;
   params->crpix[1] = wcs->yrefpix;

   if(params->isDSS)
   {
      params->cnpix[0] = wcs->x_pixel_offset;
      params->cnpix[1] = wcs->y_pixel_offset;
   }
   return wcs;
}
コード例 #2
0
ファイル: wrappers.c プロジェクト: briehanlombaard/js9
/* init the wcs struct and create a new info record */
int initwcs(char *s, int n){
  struct WorldCoor *wcs;
  if( n > 0 ){
    wcs = wcsninit(s, n);
  } else {
    wcs = wcsinit(s);
  }
  if( wcs ){
    wcsoutinit(wcs, getradecsys(wcs));
  }
  return newinfo(wcs);
}
コード例 #3
0
ファイル: spc_CD.c プロジェクト: spacetelescope/aXe_c_code
/**
 * Function: get_wcs
 * Returns a pointer to a WoldCoor structure filled using the extension
 * hdunum of file filename.
 * Sets things to use linear WCS and J2000 equinox.
 *
 * Parameters:
 * @param filename The name of the FITS file
 * @param hdunum the number of the HDU to access
 *
 * Return:
 * @return a pointer to a WoldCoor structure. NULL if no WCS was found
 */
struct WorldCoor *
get_wcs (char filename[], int hdunum)
{
  char *header;
  struct WorldCoor *wcs;
  
  // Read the FITS or IRAF image file header
  header = get_fits_header (filename, hdunum);
  
  // extract the WCS from the header
  wcs = wcsinit (header);
  
  // release memory
  free (header);

  // return the result
  return wcs;
}
コード例 #4
0
ファイル: mCatMap.c プロジェクト: Caltech-IPAC/Montage
int readTemplate(char *filename)
{
   int      i;

   FILE    *fp;

   char     line[MAXSTR];

   char    *header[2];

   int      sys;
   double   epoch;

   double   x, y;
   double   ix, iy;
   double   xpos, ypos;

   int      offscl;

   header[0] = malloc(32768);
   header[1] = (char *)NULL;


   /********************************************************/
   /* Open the template file, read and parse all the lines */
   /********************************************************/

   fp = fopen(filename, "r");

   if(fp == (FILE *)NULL)
      printError("Template file not found");

   while(1)
   {
      if(fgets(line, MAXSTR, fp) == (char *)NULL)
	 break;

      if(line[strlen(line)-1] == '\n')
         line[strlen(line)-1]  = '\0';

      if(debug >= 2)
      {
	 printf("Template line: [%s]\n", line);
	 fflush(stdout);
      }

      for(i=strlen(line); i<80; ++i)
	 line[i] = ' ';
      
      line[80] = '\0';

      strcat(header[0], line);

      parseLine(line);
   }

   if(debug >= 2)
   {
      printf("\nheader ----------------------------------------\n");
      printf("%s\n", header[0]);
      printf("-----------------------------------------------\n\n");
   }


   /****************************************/
   /* Initialize the WCS transform library */
   /****************************************/

   output.wcs = wcsinit(header[0]);

   if(output.wcs == (struct WorldCoor *)NULL)
   {
      printf("[struct stat=\"ERROR\", msg=\"Output wcsinit() failed.\"]\n");
      exit(0);
   }


   /* Kludge to get around bug in WCS library:   */
   /* 360 degrees sometimes added to pixel coord */

   ix = 0.5;
   iy = 0.5;

   offscl = 0;

   pix2wcs(output.wcs, ix, iy, &xpos, &ypos);
   wcs2pix(output.wcs, xpos, ypos, &x, &y, &offscl);

   xcorrection = x-ix;
   ycorrection = y-iy;


   /*************************************/
   /*  Set up the coordinate transform  */
   /*************************************/

   if(output.wcs->syswcs == WCS_J2000)
   {
      sys   = EQUJ;
      epoch = 2000.;

      if(output.wcs->equinox == 1950.)
	 epoch = 1950;
   }
   else if(output.wcs->syswcs == WCS_B1950)
   {
      sys   = EQUB;
      epoch = 1950.;

      if(output.wcs->equinox == 2000.)
	 epoch = 2000;
   }
   else if(output.wcs->syswcs == WCS_GALACTIC)
   {
      sys   = GAL;
      epoch = 2000.;
   }
   else if(output.wcs->syswcs == WCS_ECLIPTIC)
   {
      sys   = ECLJ;
      epoch = 2000.;

      if(output.wcs->equinox == 1950.)
      {
	 sys   = ECLB;
	 epoch = 1950.;
      }
   }
   else       
   {
      sys   = EQUJ;
      epoch = 2000.;
   }

   output.sys   = sys;
   output.epoch = epoch;

   free(header[0]);

   return 0;
}
コード例 #5
0
ファイル: checkHdr.c プロジェクト: Ionozor/js9
int checkHdr(char *infile, int hdrflag, int hdu)
{
   int       i, len, ncard, morekeys;

   int       status = 0;

   char     *keyword;
   char     *value;

   char      fitskeyword[80];
   char      fitsvalue  [80];
   char      fitscomment[80];
   char      tmpstr     [80];

   char     *end;

   char      line  [1024];
   char      pline [1024];

   char     *ptr1;
   char     *ptr2;

   FILE     *fp;
   fitsfile *infptr;

   static int maxhdr;

   if(!mHeader)
   {
      mHeader = malloc(MAXHDR);
      maxhdr = MAXHDR;
   }

   havePLTRAH  = 0;

   haveSIMPLE  = 0;
   haveBITPIX  = 0;
   haveNAXIS   = 0;
   haveNAXIS1  = 0;
   haveNAXIS2  = 0;
   haveCTYPE1  = 0;
   haveCTYPE2  = 0;
   haveCRPIX1  = 0;
   haveCRPIX2  = 0;
   haveCDELT1  = 0;
   haveCDELT2  = 0;
   haveCD1_1   = 0;
   haveCD1_2   = 0;
   haveCD2_1   = 0;
   haveCD2_2   = 0;
   haveCRVAL1  = 0;
   haveCRVAL2  = 0;
   haveBSCALE  = 0;
   haveBZERO   = 0;
   haveBLANK   = 0;
   haveEPOCH   = 0;
   haveEQUINOX = 0;


   /****************************************/
   /* Initialize the WCS transform library */
   /* and find the pixel location of the   */
   /* sky coordinate specified             */
   /****************************************/

   errorCount = 0;

   if(hdrCheck_outfile)
   {
      fout = fopen(hdrCheck_outfile, "w+");

      if(fout == (FILE *)NULL)
      {
         fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Cannot open output file %s.\"]\n", hdrCheck_outfile);
         fflush(fstatus);
         exit(1);
      }
   }

   strcpy(mHeader, "");

   if(fits_open_file(&infptr, infile, READONLY, &status) == 0)
   {
      if(CHdebug)
      {
         printf("\nFITS file\n");
         fflush(stdout);
      }

      if(hdrflag == HDR)
      {
       fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"FITS file (%s) cannot be used as a header template\"]\n",
                infile);
         fflush(fstatus);
         exit(1);
      }

      if(hdu > 0)
      {
         if(fits_movabs_hdu(infptr, hdu+1, NULL, &status))
            FITSerror(status);
      }

      if(fits_get_hdrspace (infptr, &ncard, &morekeys, &status))
         FITSerror(status);
      
      if(ncard > 1000)
         mHeader = realloc(mHeader, ncard * 80 + 1024);

      if(CHdebug)
      {
         printf("ncard = %d\n", ncard);
         fflush(stdout);
      }

      for (i=1; i<=ncard; i++)
      {
         if(fits_read_keyn (infptr, i, fitskeyword, fitsvalue, fitscomment, &status))
            FITSerror(status);

         if(fitsvalue[0] == '\'')
         {
            strcpy(tmpstr, fitsvalue+1);

            if(tmpstr[strlen(tmpstr)-1] == '\'')
               tmpstr[strlen(tmpstr)-1] =  '\0';
         }
         else
            strcpy(tmpstr, fitsvalue);

         fitsCheck(fitskeyword, tmpstr);

         sprintf(line, "%-8s= %20s", fitskeyword, fitsvalue);

         if(strncmp(line, "COMMENT", 7) != 0)
            strAdd(mHeader, line);
      }

      strAdd(mHeader, "END");

      if(fits_close_file(infptr, &status))
         FITSerror(status);
   }
   else
   {
      if(CHdebug)
      {
         printf("\nTemplate file\n");
         fflush(stdout);
      }

      if(hdrflag == FITS)
      {
         fp = fopen(infile, "r");

         if(fp == (FILE *)NULL)
         {
            fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"File %s not found.\"]\n", infile);
            fflush(fstatus);
            exit(1);
         }

         fclose(fp);

         fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"File (%s) is not a FITS image\"]\n",
                infile);
         fflush(fstatus);
         exit(1);
      }

      fp = fopen(infile, "r");

      if(fp == (FILE *)NULL)
      {
         fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"File %s not found.\"]\n", infile);
         fflush(fstatus);
         exit(1);
      }

      while(1)
      {
         if(fgets(line, 1024, fp) == (char *)NULL)
            break;

         if(line[(int)strlen(line)-1] == '\n')
            line[(int)strlen(line)-1]  = '\0';
         
         if(line[(int)strlen(line)-1] == '\r')
            line[(int)strlen(line)-1]  = '\0';
         
         strcpy(pline, line);

         if((int)strlen(line) > 80)
         {
            fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"FITS header lines cannot be greater than 80 characters.\"]\n");
            fflush(fstatus);
            exit(1);
         }

         len = (int)strlen(pline);

         keyword = pline;

         while(*keyword == ' ' && keyword < pline+len)
            ++keyword;

         end = keyword;

         while(*end != ' ' && *end != '=' && end < pline+len)
            ++end;

         value = end;

         while((*value == '=' || *value == ' ' || *value == '\'')
               && value < pline+len)
            ++value;

         *end = '\0';
         end = value;

         if(*end == '\'')
            ++end;

         while(*end != ' ' && *end != '\'' && end < pline+len)
            ++end;

         *end = '\0';

         fitsCheck(keyword, value);

         strAdd(mHeader, line);
         
         if((int)strlen(mHeader) + 160 > maxhdr)
         {
            maxhdr += MAXHDR;
            mHeader = realloc(mHeader, maxhdr);
         }
      }

      fclose(fp);
   }


   /********************************************************/
   /*                                                      */
   /* Check to see if we have the minimum FITS header info */
   /*                                                      */
   /********************************************************/

   if(!haveBITPIX)
      errorOutput("No BITPIX keyword in FITS header");

   if(!haveNAXIS)
      errorOutput("No NAXIS keyword in FITS header");

   if(!haveNAXIS1)
      errorOutput("No NAXIS1 keyword in FITS header");

   if(!haveNAXIS2)
      errorOutput("No NAXIS2 keyword in FITS header");

   if(havePLTRAH)
   {
      /* If we have this parameter, we'll assume this is a DSS header  */
      /* the WCS checking routine should be able to verify if it isn't */

      free(mHeader);

      maxhdr = 0;
      
      mHeader = (char *)NULL;

      return(0);
   }

   if(!haveCTYPE1)
      errorOutput("No CTYPE1 keyword in FITS header");

   if(!haveCTYPE2)
      errorOutput("No CTYPE2 keyword in FITS header");

   if(!haveCRPIX1)
      errorOutput("No CRPIX1 keyword in FITS header");

   if(!haveCRPIX2)
      errorOutput("No CRPIX2 keyword in FITS header");

   if(!haveCRVAL1)
      errorOutput("No CRVAL1 keyword in FITS header");

   if(!haveCRVAL2)
      errorOutput("No CRVAL2 keyword in FITS header");

   if(!haveCD1_1 
   && !haveCD1_2 
   && !haveCD2_1 
   && !haveCD2_2)
   {
      if(!haveCDELT1)
         errorOutput("No CDELT1 keyword (or incomplete CD matrix) in FITS header");
      else if(!haveCDELT2)
         errorOutput("No CDELT2 keyword (or incomplete CD matrix) in FITS header");
   }

   if(strlen(ctype1) < 8)
      errorOutput("CTYPE1 must be at least 8 characters");

   if(strlen(ctype2) < 8)
      errorOutput("CTYPE2 must be at least 8 characters");

   ptr1 = ctype1;

   while(*ptr1 != '-' && *ptr1 != '\0') ++ptr1;
   while(*ptr1 == '-' && *ptr1 != '\0') ++ptr1;

   ptr2 = ctype2;

   while(*ptr2 != '-' && *ptr2 != '\0') ++ptr2;
   while(*ptr2 == '-' && *ptr2 != '\0') ++ptr2;

   if(strlen(ptr1) == 0
   || strlen(ptr2) == 0)
      errorOutput("Invalid CTYPE1 or CTYPE2 projection information");

   if(strcmp(ptr1, ptr2) != 0)
      errorOutput("CTYPE1, CTYPE2 projection information mismatch");

   if(hdrStringent)
   {
      if(strlen(ptr1) != 3)
         errorOutput("Invalid CTYPE1 projection information");

      if(strlen(ptr2) != 3)
         errorOutput("Invalid CTYPE2 projection information");
   }


   /****************************************/
   /* Initialize the WCS transform library */
   /* and find the pixel location of the   */
   /* sky coordinate specified             */
   /****************************************/

   /*
   if(CHdebug)
   {
      printf("header = \n%s\n", mHeader);
      fflush(stdout);
   }
   */

   hdrCheck_wcs = wcsinit(mHeader);

   checkWCS(hdrCheck_wcs, 0);

   if(errorCount > 0)
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"%d Errors\"]\n", 
         errorCount);
      fflush(fstatus);
      exit(1);
   }

   return(0);
}
コード例 #6
0
ファイル: montageExamine.c プロジェクト: Caltech-IPAC/Montage
struct mExamineReturn * mExamine(char *infile, int areaMode, int hdu, int plane3, int plane4, 
                                 double ra, double dec, double radius, int locinpix, int radinpix, int debug)
{
   int    i, j, offscl, nullcnt;
   int    status, clockwise, nfound;
   int    npix, nnull, first;
   int    ixpix, iypix;
   int    maxi, maxj;

   char  *header;
   char   tmpstr[32768];

   char   proj[32];
   int    csys;
   char   csys_str[64];

   char   ctype1[256];
   char   ctype2[256];

   double equinox;

   long   naxis;
   long   naxes[10];

   double naxis1;
   double naxis2;

   double crval1;
   double crval2;

   double crpix1;
   double crpix2;

   double cdelt1;
   double cdelt2;

   double crota2;

   double lon, lat;
   double lonc, latc;
   double rac, decc;
   double racp, deccp;
   double ra1, dec1, ra2, dec2, ra3, dec3, ra4, dec4;
   double xpix, ypix, rpix, rap;

   double x, y, z;
   double xp, yp, zp;

   double rot, beta, dtr;
   double r;

   double sumflux, sumflux2, sumn, mean, background, oldbackground, rms, dot;
   double sigmaref, sigmamax, sigmamin;
   double val, valx, valy, valra, valdec;
   double min, minx, miny, minra, mindec;
   double max, maxx, maxy, maxra, maxdec;
   double x0, y0, z0;

   double  fluxMin, fluxMax, fluxRef, sigma;

   struct WorldCoor *wcs;

   fitsfile *fptr;
   int       ibegin, iend, jbegin, jend;
   long      fpixel[4], nelements;

   double   *data = (double *)NULL;

   struct apPhoto *ap = (struct apPhoto *)NULL;

   int nflux, maxflux;


   struct mExamineReturn *returnStruct;

   returnStruct = (struct mExamineReturn *)malloc(sizeof(struct mExamineReturn));

   memset((void *)returnStruct, 0, sizeof(returnStruct));


   returnStruct->status = 1;

   strcpy(returnStruct->msg, "");


   nflux   = 0;
   maxflux = MAXFLUX;


   /************************************************/
   /* Make a NaN value to use setting blank pixels */
   /************************************************/

   union
   {
      double d;
     char   c[8];
   }
   value;

   double nan;

   for(i=0; i<8; ++i)
      value.c[i] = (char)255;

   nan = value.d;


   dtr = atan(1.)/45.;


   /* Process basic command-line arguments */

   if(debug)
   {
      printf("DEBUG> areaMode = %d \n", areaMode);
      printf("DEBUG> infile   = %s \n", infile);
      printf("DEBUG> ra       = %-g\n", ra);
      printf("DEBUG> dec      = %-g\n", dec);
      printf("DEBUG> radius   = %-g\n", radius);
      fflush(stdout);
   }

   rpix = 0.;

   if(areaMode == APPHOT)
      ap = (struct apPhoto *)malloc(maxflux * sizeof(struct apPhoto));


   /* Open the FITS file and initialize the WCS transform */

   status = 0;
   if(fits_open_file(&fptr, infile, READONLY, &status))
   {
      if(ap) free(ap);
      sprintf(returnStruct->msg, "Cannot open FITS file %s", infile);
      return returnStruct;
   }

   if(hdu > 0)
   {
      status = 0;
      if(fits_movabs_hdu(fptr, hdu+1, NULL, &status))
      {
         if(ap) free(ap);
         sprintf(returnStruct->msg, "Can't find HDU %d", hdu);
         return returnStruct;
      }
   }

   status = 0;
   if(fits_get_image_wcs_keys(fptr, &header, &status))
   {
      if(ap) free(ap);
      sprintf(returnStruct->msg, "Cannot find WCS keys in FITS file %s", infile);
      return returnStruct;
   }

   status = 0;
   if(fits_read_key_lng(fptr, "NAXIS", &naxis, (char *)NULL, &status))
   {
      if(ap) free(ap);
      sprintf(returnStruct->msg, "Cannot find NAXIS keyword in FITS file %s", infile);
      return returnStruct;
   }

   status = 0;
   if(fits_read_keys_lng(fptr, "NAXIS", 1, naxis, naxes, &nfound, &status))
   {
      if(ap) free(ap);
      sprintf(returnStruct->msg, "Cannot find NAXIS1,2 keywords in FITS file %s", infile);
      return returnStruct;
   }


   wcs = wcsinit(header);

   if(wcs == (struct WorldCoor *)NULL)
   {
      if(ap) free(ap);
      sprintf(returnStruct->msg, "WCS initialization failed.");
      return returnStruct;
   }



   /* A bunch of the parameters we want are in the WCS structure */

   clockwise = 0;

   strcpy(ctype1, wcs->ctype[0]);
   strcpy(ctype2, wcs->ctype[1]);

   naxis1 = wcs->nxpix;
   naxis2 = wcs->nypix;

   crval1 = wcs->xref;
   crval2 = wcs->yref;

   crpix1 = wcs->xrefpix;
   crpix2 = wcs->yrefpix;

   cdelt1 = wcs->xinc;
   cdelt2 = wcs->yinc;

   crota2 = wcs->rot;

   if((cdelt1 < 0 && cdelt2 < 0)
   || (cdelt1 > 0 && cdelt2 > 0)) clockwise = 1;

   strcpy(proj, "");

   if(strlen(ctype1) > 5)
   strcpy (proj, ctype1+5);  


   /* We get the Equinox from the WCS.  If not    */
   /* there we take the command-line value. We    */
   /* then infer Julian/Besselian as best we can. */

   equinox = wcs->equinox;

   csys = EQUJ;
   strcpy(csys_str, "EQUJ");

   if(strncmp(ctype1, "RA--", 4) == 0)
   {
      csys = EQUJ;

      strcpy(csys_str, "EQUJ");

      if(equinox < 1975.)
      {
         csys = EQUB;

         strcpy(csys_str, "EQUB");
      }
   }

   if(strncmp(ctype1, "LON-", 4) == 0)
   {
      csys = GAL;
      strcpy(csys_str, "GAL");
   }

   if(strncmp(ctype1, "GLON", 4) == 0)
   {
      csys = GAL;
      strcpy(csys_str, "GAL");
   }

   if(strncmp(ctype1, "ELON", 4) == 0)
   {
      csys = ECLJ;

      strcpy(csys_str, "ECLJ");

      if(equinox < 1975.)
      {
         csys = ECLB;

         strcpy(csys_str, "ECLB");
      }
   }

   if(debug)
   {
      printf("DEBUG> proj      = [%s]\n", proj);
      printf("DEBUG> csys      = %d\n",   csys);
      printf("DEBUG> clockwise = %d\n",   clockwise);
      printf("DEBUG> ctype1    = [%s]\n", ctype1);
      printf("DEBUG> ctype2    = [%s]\n", ctype2);
      printf("DEBUG> equinox   = %-g\n",  equinox);

      printf("\n");
      fflush(stdout);
   }


   /* To get corners and rotation in EQUJ we need the     */
   /* locations of the center pixel and the one above it. */

   pix2wcs(wcs, wcs->nxpix/2.+0.5, wcs->nypix/2.+0.5, &lonc, &latc);
   convertCoordinates (csys, equinox, lonc, latc, 
                       EQUJ, 2000., &rac, &decc, 0.);

   pix2wcs(wcs, wcs->nxpix/2.+0.5, wcs->nypix/2.+1.5, &lonc, &latc);
   convertCoordinates (csys, equinox, lonc, latc, 
                       EQUJ, 2000., &racp, &deccp, 0.);


   /* Use spherical trig to get the Equatorial rotation angle */

   x = cos(decc*dtr) * cos(rac*dtr);
   y = cos(decc*dtr) * sin(rac*dtr);
   z = sin(decc*dtr);

   xp = cos(deccp*dtr) * cos(racp*dtr);
   yp = cos(deccp*dtr) * sin(racp*dtr);
   zp = sin(deccp*dtr);

   beta = acos(x*xp + y*yp + z*zp) / dtr;

   rot = asin(cos(deccp*dtr) * sin((rac-racp)*dtr)/sin(beta*dtr)) / dtr;


   /* And for the four corners we want them uniformly clockwise */

   if(!clockwise)
   {
      pix2wcs(wcs, -0.5, -0.5, &lon, &lat);
      convertCoordinates (csys, equinox, lon, lat, 
                          EQUJ, 2000., &ra1, &dec1, 0.);


      pix2wcs(wcs, wcs->nxpix+0.5, -0.5, &lon, &lat);
      convertCoordinates (csys, equinox, lon, lat, 
                          EQUJ, 2000., &ra2, &dec2, 0.);


      pix2wcs(wcs, wcs->nxpix+0.5, wcs->nypix+0.5, &lon, &lat);
      convertCoordinates (csys, equinox, lon, lat, 
                          EQUJ, 2000., &ra3, &dec3, 0.);


      pix2wcs(wcs, -0.5, wcs->nypix+0.5, &lon, &lat);
      convertCoordinates (csys, equinox, lon, lat, 
                          EQUJ, 2000., &ra4, &dec4, 0.);
   }
   else
   {
      pix2wcs(wcs, -0.5, -0.5, &lon, &lat);
      convertCoordinates (csys, equinox, lon, lat, 
                          EQUJ, 2000., &ra2, &dec2, 0.);


      pix2wcs(wcs, wcs->nxpix+0.5, -0.5, &lon, &lat);
      convertCoordinates (csys, equinox, lon, lat, 
                          EQUJ, 2000., &ra1, &dec1, 0.);


      pix2wcs(wcs, wcs->nxpix+0.5, wcs->nypix+0.5, &lon, &lat);
      convertCoordinates (csys, equinox, lon, lat, 
                          EQUJ, 2000., &ra4, &dec4, 0.);


      pix2wcs(wcs, -0.5, wcs->nypix+0.5, &lon, &lat);
      convertCoordinates (csys, equinox, lon, lat, 
                          EQUJ, 2000., &ra3, &dec3, 0.);
   }


   // Treat the default region (ALL) as a circle 
   // containing the whole image

   if(areaMode == ALL)
   {
      locinpix = 1;
      radinpix = 1;

      ra  = wcs->nxpix / 2.;
      dec = wcs->nypix / 2.;

      radius = sqrt(wcs->nxpix*wcs->nxpix + wcs->nypix*wcs->nypix)/2.;
   }


   /* Get region statistics */

   ixpix = 1;
   iypix = 1;

   if(radinpix) 
   {
      rpix   = radius;
      radius = rpix * fabs(cdelt2);
   }
   else
      rpix = radius / fabs(cdelt2);

   if(locinpix)
   {
      xpix = ra;
      ypix = dec;

      pix2wcs(wcs, xpix, ypix, &lon, &lat);

      if(wcs->offscl)
      {
         if(ap) free(ap);
         sprintf(returnStruct->msg, "Location off the image.");
         return returnStruct;
      }

      convertCoordinates (csys, equinox, lon, lat,
            EQUJ, 2000., &ra, &dec, 0);
   }
   else
   {
      convertCoordinates (EQUJ, 2000., ra, dec,  
            csys, equinox, &lon, &lat, 0.);

      wcs2pix(wcs, lon, lat, &xpix, &ypix, &offscl);

      if(offscl)
      {
         if(ap) free(ap);
         sprintf(returnStruct->msg, "Location off the image.");
         return returnStruct;
      }
   }



   x0 = cos(ra*dtr) * cos(dec*dtr);
   y0 = sin(ra*dtr) * cos(dec*dtr);
   z0 = sin(dec*dtr);

   ixpix = (int)(xpix+0.5);
   iypix = (int)(ypix+0.5);

   if(debug)
   {
      printf("DEBUG> Region statististics for %-g pixels around (%-g,%-g) [%d,%d] [Equatorial (%-g, %-g)\n",
            rpix, xpix, ypix, ixpix, iypix, ra, dec);
      fflush(stdout);
   }


   // Then read the data

   jbegin = iypix - rpix - 1;
   jend   = iypix + rpix + 1;

   ibegin = ixpix - rpix - 1;
   iend   = ixpix + rpix + 1;

   if(ibegin < 1         ) ibegin = 1;
   if(iend   > wcs->nxpix) iend   = wcs->nxpix;

   nelements = iend - ibegin + 1;

   if(jbegin < 1         ) jbegin = 1;
   if(jend   > wcs->nypix) jend   = wcs->nxpix;

   fpixel[0] = ibegin;
   fpixel[1] = jbegin;
   fpixel[2] = 1;
   fpixel[3] = 1;
   fpixel[2] = plane3;
   fpixel[3] = plane4;


   data = (double *)malloc(nelements * sizeof(double));

   status = 0;

   sumflux  = 0.;
   sumflux2 = 0.;
   npix     = 0;
   nnull    = 0;

   val      = 0.;
   valx     = 0.;
   valy     = 0.;
   valra    = 0.;
   valdec   = 0.;

   max      = 0.;
   maxx     = 0.;
   maxy     = 0.;
   maxra    = 0.;
   maxdec   = 0.;

   min      = 0.;
   minx     = 0.;
   miny     = 0.;
   minra    = 0.;
   mindec   = 0.;

   first = 1;

   if(radius > 0.)
   {
      if(debug)
      {
         printf("\nDEBUG> Location: (%.6f %.6f) -> (%d,%d)\n\n", xpix, ypix, ixpix, iypix);
         printf("DEBUG> Radius: %.6f\n\n", rpix);

         printf("DEBUG> i: %d to %d\n", ibegin, iend);
         printf("DEBUG> j: %d to %d\n", jbegin, jend);
      }

      for (j=jbegin; j<=jend; ++j)
      {
         status = 0;
         if(fits_read_pix(fptr, TDOUBLE, fpixel, nelements, &nan,
                  (void *)data, &nullcnt, &status))
         {
            ++fpixel[1];

            continue;
         }

         for(i=0; i<nelements; ++i)
         {
            if(mNaN(data[i]))
            {
               if(debug)
                  printf("%10s ", "NULL");

               ++nnull;
               continue;
            }

            sumflux  += data[i];
            sumflux2 += data[i]*data[i];
            ++npix;

            x  = ibegin + i;
            y  = j;

            pix2wcs(wcs, x, y, &lon, &lat);

            convertCoordinates(csys, equinox, lon, lat, EQUJ, 2000., &ra, &dec, 0.);

            xp = cos(ra*dtr) * cos(dec*dtr);
            yp = sin(ra*dtr) * cos(dec*dtr);
            zp = sin(dec*dtr);

            dot = xp*x0 + yp*y0 + zp*z0;

            if(dot > 1.)
               dot = 1.;

            r = acos(dot)/dtr / fabs(cdelt2);

            if(debug)
            {
               if(r <= rpix)
                  printf("%10.3f ", data[i]);
               else
                  printf("%10s ", ".");
            }

            if(r > rpix)
               continue;


            if(x == ixpix && y == iypix)
            {
               val = data[i];

               valx = x;
               valy = y;
            }

            if(first)
            {
               first = 0;

               min = data[i];

               minx = x;
               miny = y;

               max = data[i];

               maxx = x;
               maxy = y;

               maxi = i+ibegin;
               maxj = j;
            }

            if(data[i] > max)
            {
               max = data[i];

               maxx = x;
               maxy = y;

               maxi = i+ibegin;
               maxj = j;
            }

            if(data[i] < min)
            {
               min = data[i];

               minx = x;
               miny = y;
            }
         }

         pix2wcs(wcs, valx, valy, &lon, &lat);
         convertCoordinates(csys, equinox, lon, lat, EQUJ, 2000., &valra, &valdec, 0.);

         pix2wcs(wcs, minx, miny, &lon, &lat);
         convertCoordinates(csys, equinox, lon, lat, EQUJ, 2000., &minra, &mindec, 0.);

         pix2wcs(wcs, maxx, maxy, &lon, &lat);
         convertCoordinates(csys, equinox, lon, lat, EQUJ, 2000., &maxra, &maxdec, 0.);

         if(debug)
            printf("\n");

         ++fpixel[1];
      }

      mean     = 0.;
      rms      = 0.;
      sigmaref = 0.;
      sigmamin = 0.;
      sigmamax = 0.;

      if(npix > 0)
      {
         mean = sumflux / npix;
         rms  = sqrt(sumflux2/npix - mean*mean);

         sigmaref = (val - mean) / rms; 
         sigmamin = (min - mean) / rms; 
         sigmamax = (max - mean) / rms; 
      }
   }
   

   /* Finally, print out parameters */

   strcpy(montage_json,  "{");
   strcpy(montage_msgstr,  "");


   if(areaMode == ALL || areaMode == REGION)
   {
      sprintf(tmpstr, "\"proj\":\"%s\",",   proj);                   strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"csys\":\"%s\",",   csys_str);              strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"equinox\":%.1f,",  equinox);               strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"naxis\":%ld,",     naxis);                 strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"naxis1\":%d,",     (int)naxis1);           strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"naxis2\":%d,",     (int)naxis2);           strcat(montage_json, tmpstr);

      if(naxis > 2)
      {
         sprintf(tmpstr, " \"naxis3\":%ld,", naxes[2]);              strcat(montage_json, tmpstr);
      }

      if(naxis > 3)
      {
         sprintf(tmpstr, " \"naxis4\":%ld,", naxes[3]);              strcat(montage_json, tmpstr);
      }

      sprintf(tmpstr, " \"crval1\":%.7f,",   crval1);                strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"crval2\":%.7f,",   crval2);                strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"crpix1\":%-g,",    crpix1);                strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"crpix2\":%-g,",    crpix2);                strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"cdelt1\":%.7f,",   cdelt1);                strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"cdelt2\":%.7f,",   cdelt2);                strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"crota2\":%.4f,",   crota2);                strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"lonc\":%.7f,",     lonc);                  strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"latc\":%.7f,",     latc);                  strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"ximgsize\":%.6f,", fabs(naxis1*cdelt1));   strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"yimgsize\":%.6f,", fabs(naxis1*cdelt2));   strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"rotequ\":%.4f,",   rot);                   strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"rac\":%.7f,",      rac);                   strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"decc\":%.7f,",     decc);                  strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"ra1\":%.7f,",      ra1);                   strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"dec1\":%.7f,",     dec1);                  strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"ra2\":%.7f,",      ra2);                   strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"dec2\":%.7f,",     dec2);                  strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"ra3\":%.7f,",      ra3);                   strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"dec3\":%.7f,",     dec3);                  strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"ra4\":%.7f,",      ra4);                   strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"dec4\":%.7f,",     dec4);                  strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"radius\":%.7f,",   radius);                strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"radpix\":%.2f,",   rpix);                  strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"npixel\":%d,",     npix);                  strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"nnull\":%d,",      nnull);                 strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"aveflux\":%-g,",   mean);                  strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"rmsflux\":%-g,",   rms);                   strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"fluxref\":%-g,",   val);                   strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"sigmaref\":%-g,",  sigmaref);              strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"xref\":%.0f,",     valx);                  strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"yref\":%.0f,",     valy);                  strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"raref\":%.7f,",    valra);                 strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"decref\":%.7f,",   valdec);                strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"fluxmin\":%-g,",   min);                   strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"sigmamin\":%-g,",  sigmamin);              strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"xmin\":%.0f,",     minx);                  strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"ymin\":%.0f,",     miny);                  strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"ramin\":%.7f,",    minra);                 strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"decmin\":%.7f,",   mindec);                strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"fluxmax\":%-g,",   max);                   strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"sigmamax\":%-g,",  sigmamax);              strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"xmax\":%.0f,",     maxx);                  strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"ymax\":%.0f,",     maxy);                  strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"ramax\":%.7f,",    maxra);                 strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"decmax\":%.7f",    maxdec);                strcat(montage_json, tmpstr);
   

      sprintf(tmpstr, "proj=\"%s\",",   proj);                   strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " csys=\"%s\",",   csys_str);              strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " equinox=%.1f,",  equinox);               strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " naxis=%ld,",     naxis);                 strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " naxis1=%d,",     (int)naxis1);           strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " naxis2=%d,",     (int)naxis2);           strcat(montage_msgstr, tmpstr);

      if(naxis > 2)
      {
         sprintf(tmpstr, " naxis3=%ld,", naxes[2]);              strcat(montage_msgstr, tmpstr);
      }

      if(naxis > 3)
      {
         sprintf(tmpstr, " naxis4=%ld,", naxes[3]);              strcat(montage_msgstr, tmpstr);
      }

      sprintf(tmpstr, " crval1=%.7f,",   crval1);                strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " crval2=%.7f,",   crval2);                strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " crpix1=%-g,",    crpix1);                strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " crpix2=%-g,",    crpix2);                strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " cdelt1=%.7f,",   cdelt1);                strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " cdelt2=%.7f,",   cdelt2);                strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " crota2=%.4f,",   crota2);                strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " lonc=%.7f,",     lonc);                  strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " latc=%.7f,",     latc);                  strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " ximgsize=%.6f,", fabs(naxis1*cdelt1));   strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " yimgsize=%.6f,", fabs(naxis1*cdelt2));   strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " rotequ=%.4f,",   rot);                   strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " rac=%.7f,",      rac);                   strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " decc=%.7f,",     decc);                  strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " ra1=%.7f,",      ra1);                   strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " dec1=%.7f,",     dec1);                  strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " ra2=%.7f,",      ra2);                   strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " dec2=%.7f,",     dec2);                  strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " ra3=%.7f,",      ra3);                   strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " dec3=%.7f,",     dec3);                  strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " ra4=%.7f,",      ra4);                   strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " dec4=%.7f,",     dec4);                  strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " radius=%.7f,",   radius);                strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " radpix=%.2f,",   rpix);                  strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " npixel=%d,",     npix);                  strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " nnull=%d,",      nnull);                 strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " aveflux=%-g,",   mean);                  strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " rmsflux=%-g,",   rms);                   strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " fluxref=%-g,",   val);                   strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " sigmaref=%-g,",  sigmaref);              strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " xref=%.0f,",     valx);                  strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " yref=%.0f,",     valy);                  strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " raref=%.7f,",    valra);                 strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " decref=%.7f,",   valdec);                strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " fluxmin=%-g,",   min);                   strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " sigmamin=%-g,",  sigmamin);              strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " xmin=%.0f,",     minx);                  strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " ymin=%.0f,",     miny);                  strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " ramin=%.7f,",    minra);                 strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " decmin=%.7f,",   mindec);                strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " fluxmax=%-g,",   max);                   strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " sigmamax=%-g,",  sigmamax);              strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " xmax=%.0f,",     maxx);                  strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " ymax=%.0f,",     maxy);                  strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " ramax=%.7f,",    maxra);                 strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " decmax=%.7f",    maxdec);                strcat(montage_msgstr, tmpstr);
   }
   
   else if(areaMode == APPHOT)
   {
      // For aperture photometry mode we process the flux vs. radius data
      // to get the integrated source flux. 

      rap = radius;

      jbegin = maxj - rap - 1;
      jend   = maxj + rap + 1;

      ibegin = maxi - rap - 1;
      iend   = maxi + rap + 1;

      nelements = iend - ibegin + 1;

      fpixel[0] = ibegin;
      fpixel[1] = jbegin;
      fpixel[2] = 1;
      fpixel[3] = 1;

      for (j=jbegin; j<=jend; ++j)
      {
         status = 0;
         if(fits_read_pix(fptr, TDOUBLE, fpixel, nelements, &nan,
                          (void *)data, &nullcnt, &status))
         {
            if(ap) free(ap);
            free(data);
            sprintf(returnStruct->msg, "Error reading FITS data.");
            return returnStruct;
         }

         for(i=0; i<nelements; ++i)
         {
            if(mNaN(data[i]))
               continue;

            r = sqrt(((double)i+ibegin-maxi)*((double)i+ibegin-maxi) + ((double)j-maxj)*((double)j-maxj));

            if(r > rap)
               continue;

            ap[nflux].rad  = r;
            ap[nflux].flux = data[i];
            ap[nflux].fit  = 0.;

            ++nflux;
            if(nflux >= maxflux)
            {
               maxflux += MAXFLUX;

               ap = (struct apPhoto *)realloc(ap, maxflux * sizeof(struct apPhoto));
            }
         }

         ++fpixel[1];
      }


      // Sort the data by radius

      qsort(ap, (size_t)nflux, sizeof(struct apPhoto), mExamine_radCompare);


      // Find the peak flux and the minimum flux.

      // The max is constrained to be in the first quarter of the
      // data, just to be careful.

      fluxMax = -1.e99;
      fluxMin =  1.e99;

      for(i=0; i<nflux; ++i)
      {
         if(i < nflux/4 && ap[i].flux > fluxMax)
            fluxMax = ap[i].flux;

         if(ap[i].flux < fluxMin)
            fluxMin = ap[i].flux;
      }


      // Fit the minimum a little more carefully, iterating
      // and excluding points more than 3 sigma above the 
      // minimum.

      background = fluxMin;
      sigma      = fluxMax - fluxMin;

      for(j=0; j<1000; ++j)
      {
         oldbackground = background;

         sumn     = 0.;
         sumflux  = 0.;
         sumflux2 = 0.;

         for(i=0; i<nflux; ++i)
         {
            if(fabs(ap[i].flux - background) > 3.*sigma)
               continue;

            sumn     += 1.;
            sumflux  += ap[i].flux;
            sumflux2 += ap[i].flux * ap[i].flux;
         }

         background = sumflux / sumn;
         sigma      = sqrt(sumflux2/sumn - background*background);

         if(fabs((background - oldbackground) / oldbackground) < 1.e-3)
            break;
      }


      fluxRef = (fluxMax-fluxMin) / exp(1.);

      for(i=0; i<nflux; ++i)
      {
         if(ap[i].flux < fluxRef)
         {
            sigma = ap[i].rad;
            break;
         }
      }

      for(i=0; i<nflux; ++i)
      {
         ap[i].fit = (fluxMax-background) * exp(-(ap[i].rad * ap[i].rad) / (sigma * sigma)) + background;

         if(i == 0)
            ap[i].sum = ap[i].flux - background;
         else
            ap[i].sum = ap[i-1].sum + (ap[i].flux - background);
      }


      if(debug)
      {
         printf("|    rad    |    flux    |     fit     |     sum     |\n");
         fflush(stdout);

         for(i=0; i<nflux; ++i)
         {
            printf("%12.6f %12.6f %12.6f %12.6f  \n", ap[i].rad, ap[i].flux, ap[i].fit, ap[i].sum);
            fflush(stdout);
         }
      }

      sprintf(tmpstr, "\"proj\":\"%s\",",    proj);                 strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"csys\":\"%s\",",    csys_str);            strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"equinox\":%.1f,",   equinox);             strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"naxis\":%ld,",      naxis);               strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"naxis1\":%d,",      (int)naxis1);         strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"naxis2\":%d,",      (int)naxis2);         strcat(montage_json, tmpstr);

      if(naxis > 2)
      {
         sprintf(tmpstr, " \"naxis3\":%ld,",   naxes[2]);           strcat(montage_json, tmpstr);
      }

      if(naxis > 3)
      {
         sprintf(tmpstr, " \"naxis4\":%ld,",   naxes[3]);           strcat(montage_json, tmpstr);
      }

      sprintf(tmpstr, " \"crval1\":%.7f,",    crval1);              strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"crval2\":%.7f,",    crval2);              strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"crpix1\":%-g,",     crpix1);              strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"crpix2\":%-g,",     crpix2);              strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"cdelt1\":%.7f,",    cdelt1);              strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"cdelt2\":%.7f,",    cdelt2);              strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"crota2\":%.4f,",    crota2);              strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"lonc\":%.7f,",      lonc);                strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"latc\":%.7f,",      latc);                strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"ximgsize\":%.6f,",  fabs(naxis1*cdelt1)); strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"yimgsize\":%.6f,",  fabs(naxis1*cdelt2)); strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"rotequ\":%.4f,",    rot);                 strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"rac\":%.7f,",       rac);                 strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"decc\":%.7f,",      decc);                strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"ra1\":%.7f,",       ra1);                 strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"dec1\":%.7f,",      dec1);                strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"ra2\":%.7f,",       ra2);                 strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"dec2\":%.7f,",      dec2);                strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"ra3\":%.7f,",       ra3);                 strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"dec3\":%.7f,",      dec3);                strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"ra4\":%.7f,",       ra4);                 strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"dec4\":%.7f,",      dec4);                strcat(montage_json, tmpstr);
      sprintf(tmpstr, " \"totalflux\":%.7e",  ap[nflux/2].sum);     strcat(montage_json, tmpstr);

      sprintf(tmpstr, "proj=\"%s\",",    proj);                 strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " csys=\"%s\",",    csys_str);            strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " equinox=%.1f,",   equinox);             strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " naxis=%ld,",      naxis);               strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " naxis1=%d,",      (int)naxis1);         strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " naxis2=%d,",      (int)naxis2);         strcat(montage_msgstr, tmpstr);

      if(naxis > 2)
      {
         sprintf(tmpstr, " naxis3=%ld,",   naxes[2]);           strcat(montage_msgstr, tmpstr);
      }

      if(naxis > 3)
      {
         sprintf(tmpstr, " naxis4=%ld,",   naxes[3]);           strcat(montage_msgstr, tmpstr);
      }

      sprintf(tmpstr, " crval1=%.7f,",    crval1);              strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " crval2=%.7f,",    crval2);              strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " crpix1=%-g,",     crpix1);              strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " crpix2=%-g,",     crpix2);              strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " cdelt1=%.7f,",    cdelt1);              strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " cdelt2=%.7f,",    cdelt2);              strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " crota2=%.4f,",    crota2);              strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " lonc=%.7f,",      lonc);                strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " latc=%.7f,",      latc);                strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " ximgsize=%.6f,",  fabs(naxis1*cdelt1)); strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " yimgsize=%.6f,",  fabs(naxis1*cdelt2)); strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " rotequ=%.4f,",    rot);                 strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " rac=%.7f,",       rac);                 strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " decc=%.7f,",      decc);                strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " ra1=%.7f,",       ra1);                 strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " dec1=%.7f,",      dec1);                strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " ra2=%.7f,",       ra2);                 strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " dec2=%.7f,",      dec2);                strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " ra3=%.7f,",       ra3);                 strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " dec3=%.7f,",      dec3);                strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " ra4=%.7f,",       ra4);                 strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " dec4=%.7f,",      dec4);                strcat(montage_msgstr, tmpstr);
      sprintf(tmpstr, " totalflux=%.7e",  ap[nflux/2].sum);     strcat(montage_msgstr, tmpstr);
   }

   strcat(montage_json, "}");

   if(ap) free(ap);
   free(data);

   returnStruct->status = 0;

   strcpy(returnStruct->msg,  montage_msgstr);
   strcpy(returnStruct->json, montage_json);
   strcpy(returnStruct->proj, proj);
   strcpy(returnStruct->csys, csys_str);

   returnStruct->equinox   = equinox;
   returnStruct->naxis     = naxis;
   returnStruct->naxis1    = naxis1;
   returnStruct->naxis2    = naxis2;
   returnStruct->naxis3    = naxes[2];
   returnStruct->naxis4    = naxes[3];
   returnStruct->crval1    = crval1;
   returnStruct->crval2    = crval2;
   returnStruct->crpix1    = crpix1;
   returnStruct->crpix2    = crpix2;
   returnStruct->cdelt1    = cdelt1;
   returnStruct->cdelt2    = cdelt2;
   returnStruct->crota2    = crota2;
   returnStruct->lonc      = lonc;
   returnStruct->latc      = latc;
   returnStruct->ximgsize  = fabs(naxis1*cdelt1);
   returnStruct->yimgsize  = fabs(naxis2*cdelt2);
   returnStruct->rotequ    = rot;
   returnStruct->rac       = rac;
   returnStruct->decc      = decc;
   returnStruct->ra1       = ra1;
   returnStruct->dec1      = dec1;
   returnStruct->ra2       = ra2;
   returnStruct->dec2      = dec2;
   returnStruct->ra3       = ra3;
   returnStruct->dec3      = dec3;
   returnStruct->ra4       = ra4;
   returnStruct->dec4      = dec4;
   returnStruct->radius    = radius;
   returnStruct->radpix    = rpix;
   returnStruct->npixel    = npix;
   returnStruct->nnull     = nnull;
   returnStruct->aveflux   = mean;
   returnStruct->rmsflux   = rms;
   returnStruct->fluxref   = val;
   returnStruct->sigmaref  = sigmaref;
   returnStruct->xref      = valx;
   returnStruct->yref      = valy;
   returnStruct->raref     = valra;
   returnStruct->decref    = valdec;
   returnStruct->fluxmin   = min;
   returnStruct->sigmamin  = sigmamin;
   returnStruct->xmin      = minx;
   returnStruct->ymin      = miny;
   returnStruct->ramin     = minra;
   returnStruct->decmin    = mindec;
   returnStruct->fluxmax   = max;
   returnStruct->sigmamax  = sigmamax;
   returnStruct->xmax      = maxx;
   returnStruct->ymax      = maxy;
   returnStruct->ramax     = maxra;
   returnStruct->decmax    = maxdec;

   if(areaMode == APPHOT)
      returnStruct->totalflux = ap[nflux/2].sum;
   else
      returnStruct->totalflux = 0.;

   return returnStruct;
}
コード例 #7
0
ファイル: get_hhdr.c プロジェクト: Caltech-IPAC/Montage
int get_hhdr (char *fname, struct Hdr_rec *hdr_rec, char *msg)
{
   char      header[80000];
   char      str[132];
   FILE     *fptr;
   int       i, status, csys, nfailed, first_failed, clockwise;
   double    lon, lat, equinox;
   double    ra2000, dec2000;
   double    ra, dec;
   double    x1, y1, z1;
   double    x2, y2, z2;

   double    dtr = 1.745329252e-2;

   struct WorldCoor *wcs;

   struct stat buf;

   nfailed      = 0;
   first_failed = 0;
   status       = 0;

   fptr = fopen(fname, "r");
 
   if(fptr == (FILE *)NULL)
   {
      sprintf (msg, "Cannot open header file %s", fname);

      if(showbad)
      {
	 printf("[struct stat=\"INFO\", msg=\"Cannot open file\", file=\"%s\"]\n",
	    fname);
	 
	 fflush(stdout);
      }
      return (1);
   }

   stat(fname, &buf);

   hdr_rec->size = buf.st_size;

   hdr_rec->hdu = 1;

   strcpy(header, "");

   while(1)
   {
      if(fgets(str, 80, fptr) == (char *)NULL)
         break;
      
      while(str[strlen(str)-1] == '\n'
         || str[strlen(str)-1] == '\r')
            str[strlen(str)-1] =  '\0';

      for(i=strlen(str); i<80; ++i)
	 str[i] = ' ';

      str[80] = '\0';

      strcat(header, str);
   }

   wcs = wcsinit(header);

   if(wcs == (struct WorldCoor *)NULL) 
   {
      if(hdr_rec->hdu == 1)
	 first_failed = 1;

      ++nfailed;

      if(showbad)
      {
	 printf("[struct stat=\"INFO\", msg=\"WCS lib init failure\", file=\"%s\", hdu=%d]\n",
	    fname, hdr_rec->hdu);
	 
	 fflush(stdout);
      }

      ++hdr_rec->hdu;
      
      return(1);
   } 

   if(checkWCS(wcs, 1) == 1)
   {
      if(debug)
      {
	 printf("Bad WCS for file %s\n", fname);
	 fflush(stdout);
      }

      wcs = (struct WorldCoor *)NULL;

      if(hdr_rec->hdu == 1)
	 first_failed = 1;

      ++nfailed;

      if(showbad)
      {
	 printf("[struct stat=\"INFO\", msg=\"Bad WCS\", file=\"%s\", hdu=%d]\n",
	    fname, hdr_rec->hdu);
	 
	 fflush(stdout);
      }

      ++hdr_rec->hdu;

      return(1);
   }

   hdr_rec->ns = (int) wcs->nxpix;
   hdr_rec->nl = (int) wcs->nypix;

   strcpy(hdr_rec->ctype1, wcs->ctype[0]);
   strcpy(hdr_rec->ctype2, wcs->ctype[1]);

   hdr_rec->crpix1  = wcs->xrefpix;
   hdr_rec->crpix2  = wcs->yrefpix;
   hdr_rec->equinox = wcs->equinox;
   hdr_rec->crval1  = wcs->xref;
   hdr_rec->crval2  = wcs->yref;
   hdr_rec->cdelt1  = wcs->xinc;
   hdr_rec->cdelt2  = wcs->yinc;
   hdr_rec->crota2  = wcs->rot;

   if(hdr_rec->cdelt1 > 0.
   && hdr_rec->cdelt2 > 0.
   && (hdr_rec->crota2 < -90. || hdr_rec->crota2 > 90.))
   {
      hdr_rec->cdelt1 = -hdr_rec->cdelt1;
      hdr_rec->cdelt2 = -hdr_rec->cdelt2;

      hdr_rec->crota2 += 180.;

      while(hdr_rec->crota2 >= 360.)
	 hdr_rec->crota2 -= 360.;

      while(hdr_rec->crota2 <= -360.)
	 hdr_rec->crota2 += 360.;
   }


   /* Convert center of image to sky coordinates */

   csys = EQUJ;

   if(strncmp(hdr_rec->ctype1, "RA",   2) == 0)
      csys = EQUJ;
   if(strncmp(hdr_rec->ctype1, "GLON", 4) == 0)
      csys = GAL;
   if(strncmp(hdr_rec->ctype1, "ELON", 4) == 0)
      csys = ECLJ;

   equinox = hdr_rec->equinox;

   pix2wcs (wcs, hdr_rec->ns/2., hdr_rec->nl/2., &lon, &lat);


   /* Convert lon, lat to EQU J2000 */

   convertCoordinates (csys, equinox, lon, lat,
		       EQUJ, 2000., &ra2000, &dec2000, 0.);

   hdr_rec->ra2000  = ra2000;
   hdr_rec->dec2000 = dec2000;

   clockwise = 0;

   if((hdr_rec->cdelt1 < 0 && hdr_rec->cdelt2 < 0)
   || (hdr_rec->cdelt1 > 0 && hdr_rec->cdelt2 > 0)) clockwise = 1;


   if(clockwise)
   {
      pix2wcs(wcs, -0.5, -0.5, &lon, &lat);
      convertCoordinates (csys, equinox, lon, lat,
			  EQUJ, 2000., &ra, &dec, 0.);

      hdr_rec->ra1 = ra;
      hdr_rec->dec1 = dec;


      pix2wcs(wcs, wcs->nxpix+0.5, -0.5, &lon, &lat);
      convertCoordinates (csys, equinox, lon, lat,
			  EQUJ, 2000., &ra, &dec, 0.);

      hdr_rec->ra2 = ra;
      hdr_rec->dec2 = dec;


      pix2wcs(wcs, wcs->nxpix+0.5, wcs->nypix+0.5, &lon, &lat);
      convertCoordinates (csys, equinox, lon, lat,
			  EQUJ, 2000., &ra, &dec, 0.);

      hdr_rec->ra3 = ra;
      hdr_rec->dec3 = dec;


      pix2wcs(wcs, -0.5, wcs->nypix+0.5, &lon, &lat);
      convertCoordinates (csys, equinox, lon, lat,
			  EQUJ, 2000., &ra, &dec, 0.);

      hdr_rec->ra4 = ra;
      hdr_rec->dec4 = dec;
   }
   else
   {
      pix2wcs(wcs, -0.5, -0.5, &lon, &lat);
      convertCoordinates (csys, equinox, lon, lat,
			  EQUJ, 2000., &ra, &dec, 0.);

      hdr_rec->ra1 = ra;
      hdr_rec->dec1 = dec;


      pix2wcs(wcs, wcs->nxpix+0.5, -0.5, &lon, &lat);
      convertCoordinates (csys, equinox, lon, lat,
			  EQUJ, 2000., &ra, &dec, 0.);

      hdr_rec->ra2 = ra;
      hdr_rec->dec2 = dec;


      pix2wcs(wcs, wcs->nxpix+0.5, wcs->nypix+0.5, &lon, &lat);
      convertCoordinates (csys, equinox, lon, lat,
			  EQUJ, 2000., &ra, &dec, 0.);

      hdr_rec->ra3 = ra;
      hdr_rec->dec3 = dec;


      pix2wcs(wcs, -0.5, wcs->nypix+0.5, &lon, &lat);
      convertCoordinates (csys, equinox, lon, lat,
			  EQUJ, 2000., &ra, &dec, 0.);

      hdr_rec->ra4 = ra;
      hdr_rec->dec4 = dec;
   }


   x1 = cos(hdr_rec->ra2000*dtr) * cos(hdr_rec->dec2000*dtr);
   y1 = sin(hdr_rec->ra2000*dtr) * cos(hdr_rec->dec2000*dtr);
   z1 = sin(hdr_rec->dec2000*dtr);

   x2 = cos(ra*dtr) * cos(dec*dtr);
   y2 = sin(ra*dtr) * cos(dec*dtr);
   z2 = sin(dec*dtr);

   hdr_rec->radius = acos(x1*x2 + y1*y2 + z1*z2) / dtr;

   hdr_rec->cntr = cntr;
   print_rec (hdr_rec);

   status = 0;
   fclose(fptr);

   return(nfailed);
}
コード例 #8
0
ファイル: mDAGTbls.c プロジェクト: kbochenina/Montage
int readTemplate(char *filename)
{
   int       j;

   FILE     *fp;

   char      line[MAXSTR];

   char      header[80000];

   int       sys;
   double    epoch;



   /**************************************************/
   /* Open the template file and collect information */
   /**************************************************/

   fp = fopen(filename, "r");

   if(fp == (FILE *)NULL)
      printError("Template file not found.");

   strcpy(header, "");

   for(j=0; j<1000; ++j)
   {
      if(fgets(line, MAXSTR, fp) == (char *)NULL)
         break;

      if(line[strlen(line)-1] == '\n')
         line[strlen(line)-1]  = '\0';
      
      if(line[strlen(line)-1] == '\r')
	 line[strlen(line)-1]  = '\0';

      if(debug)
      {
         printf("Template line: [%s]\n", line);
         fflush(stdout);
      }

      stradd(header, line);
   }


   /****************************************/
   /* Initialize the WCS transform library */
   /****************************************/

   if(debug)
   {
      printf("Output Header to wcsinit():\n%s\n", header);
      fflush(stdout);
   }

   output.wcs = wcsinit(header);

   if(output.wcs == (struct WorldCoor *)NULL)
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Output wcsinit() failed.\"]\n");
      exit(1);
   }


   /*************************************/
   /*  Set up the coordinate transform  */
   /*************************************/

   if(output.wcs->syswcs == WCS_J2000)
   {
      sys   = EQUJ;
      epoch = 2000.;

      if(output.wcs->equinox == 1950.)
         epoch = 1950;
   }
   else if(output.wcs->syswcs == WCS_B1950)
   {
      sys   = EQUB;
      epoch = 1950.;

      if(output.wcs->equinox == 2000.)
         epoch = 2000;
   }
   else if(output.wcs->syswcs == WCS_GALACTIC)
   {
      sys   = GAL;
      epoch = 2000.;
   }
   else if(output.wcs->syswcs == WCS_ECLIPTIC)
   {
      sys   = ECLJ;
      epoch = 2000.;

      if(output.wcs->equinox == 1950.)
      {
         sys   = ECLB;
         epoch = 1950.;
      }
   }
   else       
   {
      sys   = EQUJ;
      epoch = 2000.;
   }

   output.sys   = sys;
   output.epoch = epoch;

   return 0;
}
コード例 #9
0
ファイル: mDAGTbls.c プロジェクト: kbochenina/Montage
int main(int argc, char **argv)
{
   int    c;
   char   header[32768];
   char   temp  [MAXSTR];
   char   fmt   [MAXSTR];
   char   rfmt  [MAXSTR];
   char   pfmt  [MAXSTR];
   char   cfmt  [MAXSTR];
   char   ofile [MAXSTR];
   char   scale [MAXSTR];
   int    i, j;
   int    namelen, nimages, ntotal, stat;
   double xpos, ypos;
   double lon, lat;
   double oxpix, oypix;
   int    oxpixMin, oypixMin;
   int    oxpixMax, oypixMax;
   int    offscl, mode;
   int    ncols;
   FILE  *fraw;
   FILE  *fproj;
   FILE  *fcorr;


   /***************************************/
   /* Process the command-line parameters */
   /***************************************/

   debug   = 0;
   opterr  = 0;

   fstatus = stdout;

   while ((c = getopt(argc, argv, "ds:")) != EOF) 
   {
      switch (c) 
      {
         case 'd':
            debug = 1;
            break;

         case 's':
            if((fstatus = fopen(optarg, "w+")) == (FILE *)NULL)
            {
               printf("[struct stat=\"ERROR\", msg=\"Cannot open status file: %s\"]\n",
                  optarg);
               exit(1);
            }
            break;

         default:
	    printf("[struct stat=\"ERROR\", msg=\"Usage: %s [-d][-s statusfile] images.tbl hdr.template raw.tbl projected.tbl corrected.tbl\"]\n", argv[0]);
            exit(1);
            break;
      }
   }

   if (argc - optind < 5) 
   {
      printf("[struct stat=\"ERROR\", msg=\"Usage: %s [-d][-s statusfile] images.tbl hdr.template raw.tbl projected.tbl corrected.tbl\"]\n", argv[0]);
      exit(1);
   }

   strcpy(origimg_file,  argv[optind]);
   strcpy(template_file, argv[optind + 1]);
   strcpy(rawimg_file,   argv[optind + 2]);
   strcpy(projimg_file,  argv[optind + 3]);
   strcpy(corrimg_file,  argv[optind + 4]);

   checkHdr(template_file, 1, 0);

   if(debug)
   {
      printf("\norigimg_file   = [%s]\n", origimg_file);
      printf("template_file  = [%s]\n\n", template_file);
      printf("rawimg_file    = [%s]\n", rawimg_file);
      printf("projimg_file   = [%s]\n", projimg_file);
      printf("corrimg_file   = [%s]\n", corrimg_file);
      fflush(stdout);
   }


   /*************************************************/ 
   /* Process the output header template to get the */ 
   /* image size, coordinate system and projection  */ 
   /*************************************************/ 

   readTemplate(template_file);

   if(debug)
   {
      printf("\noutput.sys       =  %d\n",  output.sys);
      printf("output.epoch     =  %-g\n", output.epoch);
      printf("output proj      =  %s\n",  output.wcs->ptype);

      fflush(stdout);
   }


   /*********************************************/ 
   /* Open the image header metadata table file */
   /*********************************************/ 

   ncols = topen(origimg_file);

   if(ncols <= 0)
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Invalid image metadata file: %s\"]\n",
         origimg_file);
      exit(1);
   }


   icntr    = tcol("cntr");
   ictype1  = tcol("ctype1");
   ictype2  = tcol("ctype2");
   iequinox = tcol("equinox");
   inl      = tcol("nl");
   ins      = tcol("ns");
   icrval1  = tcol("crval1");
   icrval2  = tcol("crval2");
   icrpix1  = tcol("crpix1");
   icrpix2  = tcol("crpix2");
   icdelt1  = tcol("cdelt1");
   icdelt2  = tcol("cdelt2");
   icrota2  = tcol("crota2");
   iepoch   = tcol("epoch");
   ifname   = tcol("fname");
   iscale   = tcol("scale");

   icd11    = tcol("cd1_1");
   icd12    = tcol("cd1_2");
   icd21    = tcol("cd2_1");
   icd22    = tcol("cd2_2");

   if(ins < 0)
      ins = tcol("naxis1");

   if(inl < 0)
      inl = tcol("naxis2");

   if(ifname < 0)
      ifname = tcol("file");

   if(icd11 >= 0 && icd12 >= 0  && icd21 >= 0  && icd12 >= 0)
      mode = CD;

   else if(icdelt1 >= 0 && icdelt2 >= 0  && icrota2 >= 0)
      mode = CDELT;

   else
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Not enough information to determine coverages (CDELTs or CD matrix)\"]\n");
      exit(1);
   }


   if(icntr   < 0
   || ictype1 < 0
   || ictype2 < 0
   || inl     < 0
   || ins     < 0
   || icrval1 < 0
   || icrval2 < 0
   || icrpix1 < 0
   || icrpix2 < 0
   || ifname  < 0)
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Need columns: cntr ctype1 ctype2 nl ns crval1 crval2 crpix1 crpix2 cdelt1 cdelt2 crota2 fname (equinox optional)\"]\n");
      exit(1);
   }


   /******************************************************/
   /* Scan the table to get the true 'file' column width */
   /******************************************************/

   namelen = 0;

   while(1)
   {
      stat = tread();

      if(stat < 0)
	 break;

      strcpy(input.fname, fileName(tval(ifname)));

      if(strlen(input.fname) > namelen)
	 namelen = strlen(input.fname);
   }

   tseek(0);


   /*************************************/
   /* Write headers to the output files */
   /*************************************/

   if((fraw = (FILE *)fopen(rawimg_file, "w+")) == (FILE *)NULL)
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Invalid output metadata file: %s\"]\n",
         rawimg_file);
      exit(1);
   }

   fprintf(fraw, "\\datatype=fitshdr\n");

   if(iscale >= 0)
   {
      sprintf(fmt, "|%%5s|%%8s|%%8s|%%6s|%%6s|%%10s|%%10s|%%10s|%%10s|%%11s|%%11s|%%8s|%%7s|%%10s|%%%ds|\n", namelen+2);

      fprintf(fraw, fmt,
	 "cntr",
	 "ctype1",
	 "ctype2",
	 "naxis1",
	 "naxis2",
	 "crval1",
	 "crval2",
	 "crpix1",
	 "crpix2",
	 "cdelt1",
	 "cdelt2",
	 "crota2",
	 "equinox",
	 "scale",
	 "file");

      fprintf(fraw, fmt,
	 "int",
	 "char",
	 "char",
	 "int",
	 "int",
	 "double",
	 "double",
	 "double",
	 "double",
	 "double",
	 "double",
	 "double",
	 "int",
	 "double",
	 "char");
   }
   else
   {
      sprintf(fmt, "|%%5s|%%8s|%%8s|%%6s|%%6s|%%10s|%%10s|%%10s|%%10s|%%11s|%%11s|%%8s|%%7s|%%%ds|\n", namelen+2);


      fprintf(fraw, fmt,
	 "cntr",
	 "ctype1",
	 "ctype2",
	 "naxis1",
	 "naxis2",
	 "crval1",
	 "crval2",
	 "crpix1",
	 "crpix2",
	 "cdelt1",
	 "cdelt2",
	 "crota2",
	 "equinox",
	 "file");

      fprintf(fraw, fmt,
	 "int",
	 "char",
	 "char",
	 "int",
	 "int",
	 "double",
	 "double",
	 "double",
	 "double",
	 "double",
	 "double",
	 "double",
	 "int",
	 "char");
   }

   if((fproj = (FILE *)fopen(projimg_file, "w+")) == (FILE *)NULL)
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Invalid output metadata file: %s\"]\n",
         projimg_file);
      exit(1);
   }

   fprintf(fproj, "\\datatype=fitshdr\n");

   sprintf(fmt, "|%%5s|%%8s|%%8s|%%6s|%%6s|%%10s|%%10s|%%10s|%%10s|%%11s|%%11s|%%8s|%%7s|%%%ds|\n", namelen+2);

   fprintf(fproj, fmt,
      "cntr",
      "ctype1",
      "ctype2",
      "naxis1",
      "naxis2",
      "crval1",
      "crval2",
      "crpix1",
      "crpix2",
      "cdelt1",
      "cdelt2",
      "crota2",
      "equinox",
      "file");

   fprintf(fproj, fmt,
      "int",
      "char",
      "char",
      "int",
      "int",
      "double",
      "double",
      "double",
      "double",
      "double",
      "double",
      "double",
      "int",
      "char");


   if((fcorr = (FILE *)fopen(corrimg_file, "w+")) == (FILE *)NULL)
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Invalid output metadata file: %s\"]\n",
         corrimg_file);
      exit(1);
   }

   fprintf(fcorr, "\\datatype=fitshdr\n");

   fprintf(fcorr, fmt,
      "cntr",
      "ctype1",
      "ctype2",
      "naxis1",
      "naxis2",
      "crval1",
      "crval2",
      "crpix1",
      "crpix2",
      "cdelt1",
      "cdelt2",
      "crota2",
      "equinox",
      "file");

   fprintf(fcorr, fmt,
      "int",
      "char",
      "char",
      "int",
      "int",
      "double",
      "double",
      "double",
      "double",
      "double",
      "double",
      "double",
      "int",
      "char");


   /************************************************/
   /* Read the metadata and process each image WCS */
   /************************************************/

   namelen = 0;
   nimages = 0;
   ntotal  = 0;

   if(iscale >= 0)
      sprintf(rfmt, " %%5d %%8s %%8s %%6d %%6d %%10.6f %%10.6f %%10.2f %%10.2f %%11.8f %%11.8f %%8.5f %%7.0f %%10s %%%ds\n", namelen+2);
   else
      sprintf(rfmt, " %%5d %%8s %%8s %%6d %%6d %%10.6f %%10.6f %%10.2f %%10.2f %%11.8f %%11.8f %%8.5f %%7.0f %%%ds\n", namelen+2);

   sprintf(pfmt, " %%5d %%8s %%8s %%6d %%6d %%10.6f %%10.6f %%10.2f %%10.2f %%11.8f %%11.8f %%8.5f %%7.0f p%%%ds\n", namelen+2);

   sprintf(cfmt, " %%5d %%8s %%8s %%6d %%6d %%10.6f %%10.6f %%10.2f %%10.2f %%11.8f %%11.8f %%8.5f %%7.0f c%%%ds\n", namelen+2);

   while(1)
   {
      stat = tread();

      if(stat < 0)
	 break;
      
      ++ntotal;

      strcpy(input.ctype1, tval(ictype1));
      strcpy(input.ctype2, tval(ictype2));

      input.cntr      = atoi(tval(icntr));
      input.naxis1    = atoi(tval(ins));
      input.naxis2    = atoi(tval(inl));
      input.crpix1    = atof(tval(icrpix1));
      input.crpix2    = atof(tval(icrpix2));
      input.crval1    = atof(tval(icrval1));
      input.crval2    = atof(tval(icrval2));

      if(mode == CDELT)
      {
	 input.cdelt1    = atof(tval(icdelt1));
	 input.cdelt2    = atof(tval(icdelt2));
	 input.crota2    = atof(tval(icrota2));
      }
      else
      {
	 input.cd11      = atof(tval(icd11));
	 input.cd12      = atof(tval(icd12));
	 input.cd21      = atof(tval(icd21));
	 input.cd22      = atof(tval(icd22));
      }

      input.epoch     = 2000;

      strcpy(header, "");
      sprintf(temp, "SIMPLE  = T"                    ); stradd(header, temp);
      sprintf(temp, "BITPIX  = -64"                  ); stradd(header, temp);
      sprintf(temp, "NAXIS   = 2"                    ); stradd(header, temp);
      sprintf(temp, "NAXIS1  = %d",     input.naxis1 ); stradd(header, temp);
      sprintf(temp, "NAXIS2  = %d",     input.naxis2 ); stradd(header, temp);
      sprintf(temp, "CTYPE1  = '%s'",   input.ctype1 ); stradd(header, temp);
      sprintf(temp, "CTYPE2  = '%s'",   input.ctype2 ); stradd(header, temp);
      sprintf(temp, "CRVAL1  = %11.6f", input.crval1 ); stradd(header, temp);
      sprintf(temp, "CRVAL2  = %11.6f", input.crval2 ); stradd(header, temp);
      sprintf(temp, "CRPIX1  = %11.6f", input.crpix1 ); stradd(header, temp);
      sprintf(temp, "CRPIX2  = %11.6f", input.crpix2 ); stradd(header, temp);

      if(mode == CDELT)
      {
      sprintf(temp, "CDELT1  = %11.6f", input.cdelt1 ); stradd(header, temp);
      sprintf(temp, "CDELT2  = %11.6f", input.cdelt2 ); stradd(header, temp);
      sprintf(temp, "CROTA2  = %11.6f", input.crota2 ); stradd(header, temp);
      }
      else
      {
      sprintf(temp, "CD1_1   = %11.6f", input.cd11   ); stradd(header, temp);
      sprintf(temp, "CD1_2   = %11.6f", input.cd12   ); stradd(header, temp);
      sprintf(temp, "CD2_1   = %11.6f", input.cd21   ); stradd(header, temp);
      sprintf(temp, "CD2_2   = %11.6f", input.cd22   ); stradd(header, temp);
      }

      sprintf(temp, "EQUINOX = %d",     input.equinox); stradd(header, temp);
      sprintf(temp, "END"                            ); stradd(header, temp);
      
      if(iequinox >= 0)
	 input.equinox = atoi(tval(iequinox));

      strcpy(input.fname, fileName(tval(ifname)));

      if(iscale >= 0)
	 strcpy(scale, tval(iscale));

      if(strlen(input.fname) > namelen)
	 namelen = strlen(input.fname);

      if(debug)
      {
	 printf("Image header to wcsinit():\n%s\n", header);
	 fflush(stdout);
      }

      input.wcs = wcsinit(header);

      checkWCS(input.wcs, 0);
			     
      if(input.wcs == (struct WorldCoor *)NULL)
      {
	 fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Bad WCS for image %d\"]\n", 
	    nimages);
	 exit(1);
      }


      /***************************************************/
      /* Check the boundaries of the input image against */
      /* the output region of interest                   */
      /***************************************************/

      oxpixMin =  100000000;
      oxpixMax = -100000000;
      oypixMin =  100000000;
      oypixMax = -100000000;

      /* Check input left and right */

      for (j=0; j<input.naxis2+1; ++j)
      {
	 pix2wcs(input.wcs, 0.5, j+0.5, &xpos, &ypos);

	 convertCoordinates(input.sys, input.epoch, xpos, ypos,
			    output.sys, output.epoch, &lon, &lat, 0.0);
	 
	 wcs2pix(output.wcs, lon, lat, &oxpix, &oypix, &offscl);

	 if(!offscl)
	 {
	    if(oxpix < oxpixMin) oxpixMin = oxpix;
	    if(oxpix > oxpixMax) oxpixMax = oxpix;
	    if(oypix < oypixMin) oypixMin = oypix;
	    if(oypix > oypixMax) oypixMax = oypix;
	 }

	 pix2wcs(input.wcs, input.naxis1+0.5, j+0.5, &xpos, &ypos);

	 convertCoordinates(input.sys, input.epoch, xpos, ypos,
			    output.sys, output.epoch, &lon, &lat, 0.0);
	 
	 wcs2pix(output.wcs, lon, lat, &oxpix, &oypix, &offscl);

	 if(!offscl)
	 {
	    if(oxpix < oxpixMin) oxpixMin = oxpix;
	    if(oxpix > oxpixMax) oxpixMax = oxpix;
	    if(oypix < oypixMin) oypixMin = oypix;
	    if(oypix > oypixMax) oypixMax = oypix;
	 }
      }


      /* Check input top and bottom */

      for (i=0; i<input.naxis1+1; ++i)
      {
	 pix2wcs(input.wcs, i+0.5, 0.5, &xpos, &ypos);

	 convertCoordinates(input.sys, input.epoch, xpos, ypos,
			    output.sys, output.epoch, &lon, &lat, 0.0);
	 
	 wcs2pix(output.wcs, lon, lat, &oxpix, &oypix, &offscl);

	 if(!offscl)
	 {
	    if(oxpix < oxpixMin) oxpixMin = oxpix;
	    if(oxpix > oxpixMax) oxpixMax = oxpix;
	    if(oypix < oypixMin) oypixMin = oypix;
	    if(oypix > oypixMax) oypixMax = oypix;
	 }

	 pix2wcs(input.wcs, i+0.5, input.naxis2+0.5, &xpos, &ypos);

	 convertCoordinates(input.sys, input.epoch, xpos, ypos,
			    output.sys, output.epoch, &lon, &lat, 0.0);
	 
	 wcs2pix(output.wcs, lon, lat, &oxpix, &oypix, &offscl);

	 if(!offscl)
	 {
	    if(oxpix < oxpixMin) oxpixMin = oxpix;
	    if(oxpix > oxpixMax) oxpixMax = oxpix;
	    if(oypix < oypixMin) oypixMin = oypix;
	    if(oypix > oypixMax) oypixMax = oypix;
	 }
      }


      /***************************************************/
      /* Check the boundaries of the region of interest  */
      /* against the input image                         */
      /***************************************************/

      /* Check ouput left and right */

      for (j=0; j<output.wcs->nypix+1; ++j)
      {
	 pix2wcs(output.wcs, 0.5, j+0.5, &xpos, &ypos);

	 convertCoordinates(output.sys, output.epoch, xpos, ypos,
			     input.sys,  input.epoch, &lon, &lat, 0.0);
	 
	 wcs2pix(input.wcs, lon, lat, &oxpix, &oypix, &offscl);

	 if(!offscl)
	 {
	    if(0.5   < oxpixMin) oxpixMin = 0.5;
	    if(0.5   > oxpixMax) oxpixMax = 0.5;

	    if(j+0.5 < oypixMin) oypixMin = j+0.5;
	    if(j+0.5 > oypixMax) oypixMax = j+0.5;
	 }

	 pix2wcs(output.wcs, output.wcs->nxpix+0.5, j+0.5, &xpos, &ypos);

	 convertCoordinates(output.sys, output.epoch, xpos, ypos,
			     input.sys,  input.epoch, &lon, &lat, 0.0);
	 
	 wcs2pix(input.wcs, lon, lat, &oxpix, &oypix, &offscl);

	 if(!offscl)
	 {
	    if(output.wcs->nxpix+0.5 < oxpixMin) oxpixMin = output.wcs->nxpix+0.5;
	    if(output.wcs->nxpix+0.5 > oxpixMax) oxpixMax = output.wcs->nxpix+0.5;

	    if(j+0.5 < oypixMin) oypixMin = j+0.5;
	    if(j+0.5 > oypixMax) oypixMax = j+0.5;
	 }
      }


      /* Check input top and bottom */

      for (i=0; i<output.wcs->nxpix+1; ++i)
      {
	 pix2wcs(output.wcs, i+0.5, 0.5, &xpos, &ypos);

	 convertCoordinates(output.sys, output.epoch, xpos, ypos,
			     input.sys,  input.epoch, &lon, &lat, 0.0);
	 
	 wcs2pix(input.wcs, lon, lat, &oxpix, &oypix, &offscl);

	 if(!offscl)
	 {
	    if(i+0.5 < oxpixMin) oxpixMin = i+0.5;
	    if(i+0.5 > oxpixMax) oxpixMax = i+0.5;

	    if(0.5   < oypixMin) oypixMin = 0.5  ;
	    if(0.5   > oypixMax) oypixMax = 0.5  ;
	 }

	 pix2wcs(output.wcs, i+0.5, output.wcs->nypix+0.5, &xpos, &ypos);

	 convertCoordinates(output.sys, output.epoch, xpos, ypos,
			     input.sys,  input.epoch, &lon, &lat, 0.0);
	 
	 wcs2pix(input.wcs, lon, lat, &oxpix, &oypix, &offscl);

	 if(!offscl)
	 {
	    if(i+0.5 < oxpixMin) oxpixMin = i+0.5;
	    if(i+0.5 > oxpixMax) oxpixMax = i+0.5;

	    if(output.wcs->nypix+0.5 < oypixMin) oypixMin = output.wcs->nypix+0.5;
	    if(output.wcs->nypix+0.5 > oypixMax) oypixMax = output.wcs->nypix+0.5;
	 }
      }

      if(oxpixMax < oxpixMin) continue;
      if(oypixMax < oypixMin) continue;


      /* Remove any possible compression extension */

      strcpy(ofile, input.fname);

      if(strlen(ofile) > 3 && strcmp(ofile+strlen(ofile)-3, ".gz") == 0)
	 ofile[strlen(ofile)-3] = '\0';

      else if(strlen(ofile) > 2 && strcmp(ofile+strlen(ofile)-2, ".Z") == 0)
	 ofile[strlen(ofile)-2] = '\0';

      else if(strlen(ofile) > 2 && strcmp(ofile+strlen(ofile)-2, ".z") == 0)
	 ofile[strlen(ofile)-2] = '\0';

      else if(strlen(ofile) > 4 && strcmp(ofile+strlen(ofile)-4, ".zip") == 0)
	 ofile[strlen(ofile)-4] = '\0';

      else if(strlen(ofile) > 2 && strcmp(ofile+strlen(ofile)-2, "-z") == 0)
	 ofile[strlen(ofile)-2] = '\0';

      else if(strlen(ofile) > 3 && strcmp(ofile+strlen(ofile)-3, "-gz") == 0)
	 ofile[strlen(ofile)-3] = '\0';


      /* Make sure the extension is ".fits" */

      if(strlen(ofile) > 5 && strcmp(ofile+strlen(ofile)-5, ".fits") == 0)
	 ofile[strlen(ofile)-5] = '\0';

      else if(strlen(ofile) > 5 && strcmp(ofile+strlen(ofile)-5, ".FITS") == 0)
	 ofile[strlen(ofile)-5] = '\0';

      else if(strlen(ofile) > 4 && strcmp(ofile+strlen(ofile)-4, ".fit") == 0)
	 ofile[strlen(ofile)-4] = '\0';

      else if(strlen(ofile) > 4 && strcmp(ofile+strlen(ofile)-4, ".FIT") == 0)
	 ofile[strlen(ofile)-4] = '\0';

      else if(strlen(ofile) > 4 && strcmp(ofile+strlen(ofile)-4, ".fts") == 0)
	 ofile[strlen(ofile)-4] = '\0';

      else if(strlen(ofile) > 4 && strcmp(ofile+strlen(ofile)-4, ".FTS") == 0)
	 ofile[strlen(ofile)-4] = '\0';

      strcat(ofile, ".fits");

      if(iscale >= 0)
      {
	 fprintf(fraw, rfmt,
	   nimages+1,
	   output.wcs->ctype[0],
	   output.wcs->ctype[1],
	   oxpixMax - oxpixMin + 1,
	   oypixMax - oypixMin + 1,
	   output.wcs->crval[0],
	   output.wcs->crval[1],
	   output.wcs->crpix[0] - oxpixMin,
	   output.wcs->crpix[1] - oypixMin,
	   output.wcs->cdelt[0],
	   output.wcs->cdelt[1],
	   output.wcs->rot,
	   output.epoch,
	   scale,
	   ofile);
      }
      else
      {
	 fprintf(fraw, rfmt,
	   nimages+1,
	   output.wcs->ctype[0],
	   output.wcs->ctype[1],
	   oxpixMax - oxpixMin + 1,
	   oypixMax - oypixMin + 1,
	   output.wcs->crval[0],
	   output.wcs->crval[1],
	   output.wcs->crpix[0] - oxpixMin,
	   output.wcs->crpix[1] - oypixMin,
	   output.wcs->cdelt[0],
	   output.wcs->cdelt[1],
	   output.wcs->rot,
	   output.epoch,
	   ofile);
      }

      fprintf(fproj, pfmt,
	nimages+1,
	output.wcs->ctype[0],
	output.wcs->ctype[1],
	oxpixMax - oxpixMin + 1,
	oypixMax - oypixMin + 1,
	output.wcs->crval[0],
	output.wcs->crval[1],
	output.wcs->crpix[0] - oxpixMin,
	output.wcs->crpix[1] - oypixMin,
	output.wcs->cdelt[0],
	output.wcs->cdelt[1],
	output.wcs->rot,
	output.epoch,
	ofile);

      fprintf(fcorr, cfmt,
	nimages+1,
	output.wcs->ctype[0],
	output.wcs->ctype[1],
	oxpixMax - oxpixMin + 1,
	oypixMax - oypixMin + 1,
	output.wcs->crval[0],
	output.wcs->crval[1],
	output.wcs->crpix[0] - oxpixMin,
	output.wcs->crpix[1] - oypixMin,
	output.wcs->cdelt[0],
	output.wcs->cdelt[1],
	output.wcs->rot,
	output.epoch,
	ofile);

      ++nimages;
   }


   fclose(fraw);
   fclose(fproj);
   fclose(fcorr);

   fprintf(fstatus, "[struct stat=\"OK\", count=\"%d\", total=\"%d\"]\n", 
      nimages, ntotal);
   fflush(stdout);

   exit(0);
}
コード例 #10
0
ファイル: reduce_match.c プロジェクト: eterps/pwrake
int readFits(char *filename, struct FitsFile *input)
{
    int       status=0;

    char      errstr[MAXSTR];

    int       sys;
    double    epoch;

    char  *input_header;

    int hdu=0;

    double offset=0;


    /*****************************************/
    /* Open the FITS file and get the header */
    /* for WCS setup                         */
    /*****************************************/

    if(fits_open_file(&input->fptr, filename, READONLY, &status))
    {
        sprintf(errstr, "Image file %s missing or invalid FITS", filename);
        printError(errstr);
    }

    if(hdu > 0)
    {
        if(fits_movabs_hdu(input->fptr, hdu+1, NULL, &status))
            printFitsError(status);
    }

    if(fits_get_image_wcs_keys(input->fptr, &input_header, &status))
        printFitsError(status);


    /************************/
    /* Open the weight file */
    /************************/

    /*
    if(haveWeights)
    {
       if(fits_open_file(&weight.fptr, weightfile, READONLY, &status))
       {
     sprintf(errstr, "Weight file %s missing or invalid FITS", weightfile);
     printError(errstr);
       }

       if(hdu > 0)
       {
     if(fits_movabs_hdu(weight.fptr, hdu+1, NULL, &status))
        printFitsError(status);
       }
    }
    */


    /****************************************/
    /* Initialize the WCS transform library */
    /****************************************/

    if(debug >= 3)
    {
        printf("Input header to wcsinit() [input.wcs]:\n%s\n", input_header);
        fflush(stdout);
    }

    input->wcs = wcsinit(input_header);

    if(input->wcs == (struct WorldCoor *)NULL)
    {
        fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Input wcsinit() failed.\"]\n");
        exit(1);
    }

    input->wcs->nxpix += 2 * offset;
    input->wcs->nypix += 2 * offset;

    input->wcs->xrefpix += offset;
    input->wcs->yrefpix += offset;

    input->naxes[0] = input->wcs->nxpix;
    input->naxes[1] = input->wcs->nypix;


    /***************************************************/
    /*  Determine whether these pixels are 'clockwise' */
    /* or 'counterclockwise'                           */
    /***************************************************/

    input->clockwise = 0;

    if((input->wcs->xinc < 0 && input->wcs->yinc < 0)
            || (input->wcs->xinc > 0 && input->wcs->yinc > 0)) input->clockwise = 1;

    if(debug >= 3)
    {
        if(input->clockwise)
            printf("Input pixels are clockwise.\n");
        else
            printf("Input pixels are counterclockwise.\n");
    }


    /*************************************/
    /*  Set up the coordinate transform  */
    /*************************************/

    if (input->wcs->syswcs == WCS_J2000)
    {
        sys   = EQUJ;
        epoch = 2000.;

        if(input->wcs->equinox == 1950.)
            epoch = 1950;
    }
    else if(input->wcs->syswcs == WCS_B1950)
    {
        sys   = EQUB;
        epoch = 1950.;

        if(input->wcs->equinox == 2000.)
            epoch = 2000;
    }
    else if(input->wcs->syswcs == WCS_GALACTIC)
    {
        sys   = GAL;
        epoch = 2000.;
    }
    else if(input->wcs->syswcs == WCS_ECLIPTIC)
    {
        sys   = ECLJ;
        epoch = 2000.;

        if(input->wcs->equinox == 1950.)
        {
            sys   = ECLB;
            epoch = 1950.;
        }
    }
    else
    {
        sys   = EQUJ;
        epoch = 2000.;
    }

    input->sys   = sys;
    input->epoch = epoch;

    return 0;
}