/******************************************************************
 * DPUSER - The Next Generation
 *
 * File:     libfits/dpheader.cpp
 * Purpose:  Fits header methods implementation
 * Author:   Thomas Ott
 *
 * Revision history
 * ================
 * 22.09.1999: Implementation
 ******************************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include "fits.h"

#ifdef WIN
#pragma warning (disable: 4996) // disable warning for deprecated POSIX name
#endif

#define SIMPLE_T "SIMPLE  =                    T                                                  "
#define FITS_EMPTY "                                                                                "
#define FITS_END "END                                                                             "
#define FITS_COMMENT "COMMENT                                                                         "

#ifndef TRUE
#define TRUE 1
#endif

#ifndef FALSE
#define FALSE 0
#endif

double degrad(double v) {
	return v*M_PI/180.;
}

int
worldpos (double xpix, double ypix, 
double xref, double yref,
double xrefpix, double yrefpix, double xinc, double yinc, double rot,
double cd1_1, double cd1_2, double cd2_1, double cd2_2,
char *type,
double *xpos, double *ypos)

/* Routine to determine accurate position for pixel coordinates */
/* returns 0 if successful otherwise 1 = angle too large for projection; */
/* does: -SIN, -TAN, -ARC, -NCP, -GLS or -SFL, -MER, -AIT projections */
/* anything else is linear */

/* Input: */
{
  double cosr, sinr, dx, dy, dz, tx;
  double sins, coss, dt, l, m, mg, da, dd, cos0, sin0;
  double rat = 0.0;
  double dect = 0.0;
  double mt, a, y0, td, r2;  /* allan: for COE */
  double dec0, ra0, decout, raout;
  double geo1, geo2, geo3;
  double cond2r=1.745329252e-2;
  double twopi = 6.28318530717959;
  double deps = 1.0e-5;
  bool coorflip = FALSE;
  char ctypes[12][5] ={"-CAR","-SIN","-TAN","-TNX","-ARC","-NCP", "-GLS","-SFL", "-MER",
     "-AIT", "-STG", "-COE"};
  int i;

  /* Structure elements */
  int itype;

  itype = 0;  /* no default type */
  for (i=0;i<12;i++) if (!strncmp(type, ctypes[i], 4)) itype = i;

  /* Set local projection parameters */
  rot = rot * M_PI / 180.;
  cosr = cos (rot);
  sinr = sin (rot);

  /* Offset from ref pixel */
  dx = xpix - xrefpix;
  dy = ypix - yrefpix;

  /* Scale and rotate using CD matrix */
  if (cd1_1 != 0.0) {
    tx = dx * cd1_1 + dy * cd2_1;
    dy = dx * cd1_2 + dy * cd2_2;
    dx = tx;
    }

  /* Scale and rotate using CDELTn and CROTA2 */
  else {

    /* Check axis increments - bail out if either 0 */
    if ((xinc==0.0) || (yinc==0.0)) {
      *xpos=0.0;
      *ypos=0.0;
      return 2;
      }

    /* Scale using CDELT */
    dx = dx * xinc;
    dy = dy * yinc;

    /* Take out rotation from CROTA */
    if (rot != 0.0) {
      tx = dx * cosr - dy * sinr;
      dy = dx * sinr + dy * cosr;
      dx = tx;
      }
    }

  /* Flip coordinates if necessary */
  if (coorflip) {
    tx = dx;
    dx = dy;
    dy = tx;
    }

  /* Default, linear result for error or pixel return  */
  *xpos = xref + dx;
  *ypos = yref + dy;
  if (itype <= 0)
    return 0;

  /* Convert to radians  */
  if (coorflip) {
    dec0 = xref * M_PI / 180.;
    ra0 = yref * M_PI / 180.;
    }
  else {
    ra0 = xref * M_PI / 180.;
    dec0 = yref * M_PI / 180.;
    }
  l = dx * M_PI / 180.;
  m = dy * M_PI / 180.;
  sins = l*l + m*m;
  decout = 0.0;
  raout = 0.0;
  cos0 = cos (dec0);
  sin0 = sin (dec0);

  /* Process by case  */
  switch (itype) {

    case 0:   /* -CAR Cartesian (was WCS_PIX pixel and WCS_LIN linear) */
      rat =  ra0 + l;
      dect = dec0 + m;
      break;

    case 1: /* -SIN sin*/ 
      if (sins>1.0) return 1;
      coss = sqrt (1.0 - sins);
      dt = sin0 * coss + cos0 * m;
      if ((dt>1.0) || (dt<-1.0)) return 1;
      dect = asin (dt);
      rat = cos0 * coss - sin0 * m;
      if ((rat==0.0) && (l==0.0)) return 1;
      rat = atan2 (l, rat) + ra0;
      break;

    case 2:   /* -TAN tan */
    case 3:   /* -TNX tan with polynomial correction */
      if (sins>1.0) return 1;
      dect = cos0 - m * sin0;
      if (dect==0.0) return 1;
      rat = ra0 + atan2 (l, dect);
      dect = atan (cos(rat-ra0) * (m * cos0 + sin0) / dect);
      break;

    case 4:   /* -ARC Arc*/
      if (sins>=twopi*twopi/4.0) return 1;
      sins = sqrt(sins);
      coss = cos (sins);
      if (sins!=0.0) sins = sin (sins) / sins;
      else
	sins = 1.0;
      dt = m * cos0 * sins + sin0 * coss;
      if ((dt>1.0) || (dt<-1.0)) return 1;
      dect = asin (dt);
      da = coss - dt * sin0;
      dt = l * sins * cos0;
      if ((da==0.0) && (dt==0.0)) return 1;
      rat = ra0 + atan2 (dt, da);
      break;

    case 5:   /* -NCP North celestial pole*/
      dect = cos0 - m * sin0;
      if (dect==0.0) return 1;
      rat = ra0 + atan2 (l, dect);
      dt = cos (rat-ra0);
      if (dt==0.0) return 1;
      dect = dect / dt;
      if ((dect>1.0) || (dect<-1.0)) return 1;
      dect = acos (dect);
      if (dec0<0.0) dect = -dect;
      break;

    case 6:   /* -GLS global sinusoid */
    case 7:   /* -SFL Samson-Flamsteed */
      dect = dec0 + m;
      if (fabs(dect)>twopi/4.0) return 1;
      coss = cos (dect);
      if (fabs(l)>twopi*coss/2.0) return 1;
      rat = ra0;
      if (coss>deps) rat = rat + l / coss;
      break;

    case 8:   /* -MER mercator*/
      dt = yinc * cosr + xinc * sinr;
      if (dt==0.0) dt = 1.0;
      dy = (yref/2.0 + 45.0) * M_PI / 180.;
      dx = dy + dt / 2.0 * cond2r;
      dy = log (tan (dy));
      dx = log (tan (dx));
      geo2 = dt * M_PI / 180. / (dx - dy);
      geo3 = geo2 * dy;
      geo1 = cos (degrad (yref));
      if (geo1<=0.0) geo1 = 1.0;
      rat = l / geo1 + ra0;
      if (fabs(rat - ra0) > twopi) return 1; /* added 10/13/94 DCW/EWG */
      dt = 0.0;
      if (geo2!=0.0) dt = (m + geo3) / geo2;
      dt = exp (dt);
      dect = 2.0 * atan (dt) - twopi / 4.0;
      break;

    case 9:   /* -AIT Aitoff*/
      dt = yinc*cosr + xinc*sinr;
      if (dt==0.0) dt = 1.0;
      dt = degrad (dt);
      dy = degrad (yref);
      dx = sin(dy+dt)/sqrt((1.0+cos(dy+dt))/2.0) -
	  sin(dy)/sqrt((1.0+cos(dy))/2.0);
      if (dx==0.0) dx = 1.0;
      geo2 = dt / dx;
      dt = xinc*cosr - yinc* sinr;
      if (dt==0.0) dt = 1.0;
      dt = degrad (dt);
      dx = 2.0 * cos(dy) * sin(dt/2.0);
      if (dx==0.0) dx = 1.0;
      geo1 = dt * sqrt((1.0+cos(dy)*cos(dt/2.0))/2.0) / dx;
      geo3 = geo2 * sin(dy) / sqrt((1.0+cos(dy))/2.0);
      rat = ra0;
      dect = dec0;
      if ((l==0.0) && (m==0.0)) break;
      dz = 4.0 - l*l/(4.0*geo1*geo1) - ((m+geo3)/geo2)*((m+geo3)/geo2) ;
      if ((dz>4.0) || (dz<2.0)) return 1;;
      dz = 0.5 * sqrt (dz);
      dd = (m+geo3) * dz / geo2;
      if (fabs(dd)>1.0) return 1;;
      dd = asin (dd);
      if (fabs(cos(dd))<deps) return 1;;
      da = l * dz / (2.0 * geo1 * cos(dd));
      if (fabs(da)>1.0) return 1;;
      da = asin (da);
      rat = ra0 + 2.0 * da;
      dect = dd;
      break;

    case 10:   /* -STG Sterographic*/
      dz = (4.0 - sins) / (4.0 + sins);
      if (fabs(dz)>1.0) return 1;
      dect = dz * sin0 + m * cos0 * (1.0+dz) / 2.0;
      if (fabs(dect)>1.0) return 1;
      dect = asin (dect);
      rat = cos(dect);
      if (fabs(rat)<deps) return 1;
      rat = l * (1.0+dz) / (2.0 * rat);
      if (fabs(rat)>1.0) return 1;
      rat = asin (rat);
      mg = 1.0 + sin(dect) * sin0 + cos(dect) * cos0 * cos(rat);
      if (fabs(mg)<deps) return 1;
      mg = 2.0 * (sin(dect) * cos0 - cos(dect) * sin0 * cos(rat)) / mg;
      if (fabs(mg-m)>deps) rat = twopi/2.0 - rat;
      rat = ra0 + rat;
      break;

    case 11:    /* COE projection code from Andreas Wicenic, ESO */
      td = tan (dec0);
      y0 = 1.0 / td;
      mt = y0 - m;
      if (dec0 < 0.)
	a = atan2 (l,-mt);
      else
	a = atan2 (l, mt);
      rat = ra0 - (a / sin0);
      r2 = (l * l) + (mt * mt);
      dect = asin (1.0 / (sin0 * 2.0) * (1.0 + sin0*sin0 * (1.0 - r2)));
      break;
  }

  /* Return RA in range  */
  raout = rat;
  decout = dect;
  if (raout-ra0>twopi/2.0) raout = raout - twopi;
  if (raout-ra0<-twopi/2.0) raout = raout + twopi;
  if (raout < 0.0) raout += twopi; /* added by DCW 10/12/94 */

  /* Convert units back to degrees  */
  *xpos = raout * 180. / M_PI;
  *ypos = decout * 180. / M_PI;

  return 0;
}  /* End of worldpos */


int worldpos_old(double xpix, double ypix, double xref, double yref,
      double xrefpix, double yrefpix, double xinc, double yinc, double rot,
      char *type, double *xpos, double *ypos, int *status)

/* WDP 1/97: change the name of the routine from 'worldpos' to 'ffwldp' */

/*  worldpos.c -- WCS Algorithms from Classic AIPS.
    Copyright (C) 1994
    Associated Universities, Inc. Washington DC, USA.
   
    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.
   
    This library is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
    License for more details.
   
    You should have received a copy of the GNU Library General Public License
    along with this library; if not, write to the Free Software Foundation,
    Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
   
    Correspondence concerning AIPS should be addressed as follows:
           Internet email: aipsmail@nrao.edu
           Postal address: AIPS Group
                           National Radio Astronomy Observatory
                           520 Edgemont Road
                           Charlottesville, VA 22903-2475 USA

                 -=-=-=-=-=-=-

    These two ANSI C functions, worldpos() and xypix(), perform
    forward and reverse WCS computations for 8 types of projective
    geometries ("-SIN", "-TAN", "-ARC", "-NCP", "-GLS", "-MER", "-AIT"
    and "-STG"):

        worldpos() converts from pixel location to RA,Dec 
        xypix()    converts from RA,Dec         to pixel location   

    where "(RA,Dec)" are more generically (long,lat). These functions
    are based on the WCS implementation of Classic AIPS, an
    implementation which has been in production use for more than ten
    years. See the two memos by Eric Greisen

        ftp://fits.cv.nrao.edu/fits/documents/wcs/aips27.ps.Z
	ftp://fits.cv.nrao.edu/fits/documents/wcs/aips46.ps.Z

    for descriptions of the 8 projective geometries and the
    algorithms.  Footnotes in these two documents describe the
    differences between these algorithms and the 1993-94 WCS draft
    proposal (see URL below). In particular, these algorithms support
    ordinary field rotation, but not skew geometries (CD or PC matrix
    cases). Also, the MER and AIT algorithms work correctly only for
    CRVALi=(0,0). Users should note that GLS projections with yref!=0
    will behave differently in this code than in the draft WCS
    proposal.  The NCP projection is now obsolete (it is a special
    case of SIN).  WCS syntax and semantics for various advanced
    features is discussed in the draft WCS proposal by Greisen and
    Calabretta at:
    
        ftp://fits.cv.nrao.edu/fits/documents/wcs/wcs.all.ps.Z
    
                -=-=-=-

    The original version of this code was Emailed to D.Wells on
    Friday, 23 September by Bill Cotton <bcotton@gorilla.cv.nrao.edu>,
    who described it as a "..more or less.. exact translation from the
    AIPSish..". Changes were made by Don Wells <dwells@nrao.edu>
    during the period October 11-13, 1994:
    1) added GNU license and header comments
    2) added testpos.c program to perform extensive circularity tests
    3) changed float-->double to get more than 7 significant figures
    4) testpos.c circularity test failed on MER and AIT. B.Cotton
       found that "..there were a couple of lines of code [in] the wrong
       place as a result of merging several Fortran routines." 
    5) testpos.c found 0h wraparound in xypix() and worldpos().
    6) E.Greisen recommended removal of various redundant if-statements,
       and addition of a 360d difference test to MER case of worldpos(). 
*/

/*-----------------------------------------------------------------------*/
/* routine to determine accurate position for pixel coordinates          */
/* returns 0 if successful otherwise:                                    */
/* 1 = angle too large for projection;                                   */
/* (WDP 1/97: changed the return value to 501 instead of 1)              */
/* does: -SIN, -TAN, -ARC, -NCP, -GLS, -MER, -AIT projections            */
/* anything else is linear (== -CAR)                                     */
/* Input:                                                                */
/*   f   xpix    x pixel number  (RA or long without rotation)           */
/*   f   ypiy    y pixel number  (dec or lat without rotation)           */
/*   d   xref    x reference coordinate value (deg)                      */
/*   d   yref    y reference coordinate value (deg)                      */
/*   f   xrefpix x reference pixel                                       */
/*   f   yrefpix y reference pixel                                       */
/*   f   xinc    x coordinate increment (deg)                            */
/*   f   yinc    y coordinate increment (deg)                            */
/*   f   rot     rotation (deg)  (from N through E)                      */
/*   c  *type    projection type code e.g. "-SIN";                       */
/* Output:                                                               */
/*   d   *xpos   x (RA) coordinate (deg)                                 */
/*   d   *ypos   y (dec) coordinate (deg)                                */
/*-----------------------------------------------------------------------*/
 {double cosr, sinr, dx, dy, dz, temp, x, y, z;
  double sins, coss, dect, rat, dt, l, m, mg, da, dd, cos0, sin0;
  double dec0, ra0, decout, raout;
  double geo1, geo2, geo3;
  double cond2r=1.745329252e-2;
  double twopi = 6.28318530717959, deps = 1.0e-5;
  int   i, itype;
  char ctypes[9][5] ={"-CAR","-SIN","-TAN","-ARC","-NCP", "-GLS", "-MER",
     "-AIT", "-STG"};

  if (*status > 0)
     return(*status);

/*   Offset from ref pixel  */
  dx = (xpix-xrefpix) * xinc;
  dy = (ypix-yrefpix) * yinc;
/*   Take out rotation  */
  cosr = cos(rot*cond2r);
  sinr = sin(rot*cond2r);
  if (rot!=0.0)
    {temp = dx * cosr - dy * sinr;
     dy = dy * cosr + dx * sinr;
     dx = temp;}
/*  find type  */
/* WDP 1/97: removed support for default type for better error checking */
/*  itype = 0;   default type is linear */
  itype = -1;  /* no default type */
  for (i=0;i<9;i++) if (!strncmp(type, ctypes[i], 4)) itype = i;
/* default, linear result for error return  */
  *xpos = xref + dx;
  *ypos = yref + dy;
/* convert to radians  */
  ra0 = xref * cond2r;
  dec0 = yref * cond2r;
  l = dx * cond2r;
  m = dy * cond2r;
  sins = l*l + m*m;
  cos0 = cos(dec0);
  sin0 = sin(dec0);

/* process by case  */
  switch (itype) {
    case 0:   /* linear -CAR */
      rat =  ra0 + l;
      dect = dec0 + m;
      break;
    case 1:   /* -SIN sin*/ 
      if (sins>1.0) return(*status = 501);
      coss = sqrt (1.0 - sins);
      dt = sin0 * coss + cos0 * m;
      if ((dt>1.0) || (dt<-1.0)) return(*status = 501);
      dect = asin (dt);
      rat = cos0 * coss - sin0 * m;
      if ((rat==0.0) && (l==0.0)) return(*status = 501);
      rat = atan2 (l, rat) + ra0;
      break;
    case 2:   /* -TAN tan */
      x = cos0*cos(ra0) - l*sin(ra0) - m*cos(ra0)*sin0;
      y = cos0*sin(ra0) + l*cos(ra0) - m*sin(ra0)*sin0;
      z = sin0                       + m*         cos0;
      rat  = atan2( y, x );
      dect = atan ( z / sqrt(x*x+y*y) );
      break;
    case 3:   /* -ARC Arc*/
      if (sins>=twopi*twopi/4.0) return(*status = 501);
      sins = sqrt(sins);
      coss = cos (sins);
      if (sins!=0.0) sins = sin (sins) / sins;
      else
	sins = 1.0;
      dt = m * cos0 * sins + sin0 * coss;
      if ((dt>1.0) || (dt<-1.0)) return(*status = 501);
      dect = asin (dt);
      da = coss - dt * sin0;
      dt = l * sins * cos0;
      if ((da==0.0) && (dt==0.0)) return(*status = 501);
      rat = ra0 + atan2 (dt, da);
      break;
    case 4:   /* -NCP North celestial pole*/
      dect = cos0 - m * sin0;
      if (dect==0.0) return(*status = 501);
      rat = ra0 + atan2 (l, dect);
      dt = cos (rat-ra0);
      if (dt==0.0) return(*status = 501);
      dect = dect / dt;
      if ((dect>1.0) || (dect<-1.0)) return(*status = 501);
      dect = acos (dect);
      if (dec0<0.0) dect = -dect;
      break;
    case 5:   /* -GLS global sinusoid */
      dect = dec0 + m;
      if (fabs(dect)>twopi/4.0) return(*status = 501);
      coss = cos (dect);
      if (fabs(l)>twopi*coss/2.0) return(*status = 501);
      rat = ra0;
      if (coss>deps) rat = rat + l / coss;
      break;
    case 6:   /* -MER mercator*/
      dt = yinc * cosr + xinc * sinr;
      if (dt==0.0) dt = 1.0;
      dy = (yref/2.0 + 45.0) * cond2r;
      dx = dy + dt / 2.0 * cond2r;
      dy = log (tan (dy));
      dx = log (tan (dx));
      geo2 = dt * cond2r / (dx - dy);
      geo3 = geo2 * dy;
      geo1 = cos (yref*cond2r);
      if (geo1<=0.0) geo1 = 1.0;
      rat = l / geo1 + ra0;
      if (fabs(rat - ra0) > twopi) return(*status = 501); /* added 10/13/94 DCW/EWG */
      dt = 0.0;
      if (geo2!=0.0) dt = (m + geo3) / geo2;
      dt = exp (dt);
      dect = 2.0 * atan (dt) - twopi / 4.0;
      break;
    case 7:   /* -AIT Aitoff*/
      dt = yinc*cosr + xinc*sinr;
      if (dt==0.0) dt = 1.0;
      dt = dt * cond2r;
      dy = yref * cond2r;
      dx = sin(dy+dt)/sqrt((1.0+cos(dy+dt))/2.0) -
	  sin(dy)/sqrt((1.0+cos(dy))/2.0);
      if (dx==0.0) dx = 1.0;
      geo2 = dt / dx;
      dt = xinc*cosr - yinc* sinr;
      if (dt==0.0) dt = 1.0;
      dt = dt * cond2r;
      dx = 2.0 * cos(dy) * sin(dt/2.0);
      if (dx==0.0) dx = 1.0;
      geo1 = dt * sqrt((1.0+cos(dy)*cos(dt/2.0))/2.0) / dx;
      geo3 = geo2 * sin(dy) / sqrt((1.0+cos(dy))/2.0);
      rat = ra0;
      dect = dec0;
      if ((l==0.0) && (m==0.0)) break;
      dz = 4.0 - l*l/(4.0*geo1*geo1) - ((m+geo3)/geo2)*((m+geo3)/geo2) ;
      if ((dz>4.0) || (dz<2.0)) return(*status = 501);;
      dz = 0.5 * sqrt (dz);
      dd = (m+geo3) * dz / geo2;
      if (fabs(dd)>1.0) return(*status = 501);;
      dd = asin (dd);
      if (fabs(cos(dd))<deps) return(*status = 501);;
      da = l * dz / (2.0 * geo1 * cos(dd));
      if (fabs(da)>1.0) return(*status = 501);;
      da = asin (da);
      rat = ra0 + 2.0 * da;
      dect = dd;
      break;
    case 8:   /* -STG Sterographic*/
      dz = (4.0 - sins) / (4.0 + sins);
      if (fabs(dz)>1.0) return(*status = 501);
      dect = dz * sin0 + m * cos0 * (1.0+dz) / 2.0;
      if (fabs(dect)>1.0) return(*status = 501);
      dect = asin (dect);
      rat = cos(dect);
      if (fabs(rat)<deps) return(*status = 501);
      rat = l * (1.0+dz) / (2.0 * rat);
      if (fabs(rat)>1.0) return(*status = 501);
      rat = asin (rat);
      mg = 1.0 + sin(dect) * sin0 + cos(dect) * cos0 * cos(rat);
      if (fabs(mg)<deps) return(*status = 501);
      mg = 2.0 * (sin(dect) * cos0 - cos(dect) * sin0 * cos(rat)) / mg;
      if (fabs(mg-m)>deps) rat = twopi/2.0 - rat;
      rat = ra0 + rat;
      break;

    default:
      /* fall through to here on error */
      return(*status = 504);
  }

/*  return ra in range  */
  raout = rat;
  decout = dect;
  if (raout-ra0>twopi/2.0) raout = raout - twopi;
  if (raout-ra0<-twopi/2.0) raout = raout + twopi;
  if (raout < 0.0) raout += twopi; /* added by DCW 10/12/94 */

/*  correct units back to degrees  */
  *xpos  = raout  / cond2r;
  *ypos  = decout  / cond2r;
  return(*status);
}  /* End of worldpos */

int pixpos(double xpos, double ypos, double xref, double yref, 
      double xrefpix, double yrefpix, double xinc, double yinc, double rot,
      char *type, double *xpix, double *ypix, int *status)
/* WDP  1/97: changed name of routine from xypix to ffxypx    */
/*-----------------------------------------------------------------------*/
/* routine to determine accurate pixel coordinates for an RA and Dec     */
/* returns 0 if successful otherwise:                                    */
/* 1 = angle too large for projection;                                   */
/* 2 = bad values                                                        */
/* WDP 1/97: changed the return values to 501 and 502 instead of 1 and 2 */
/* does: -SIN, -TAN, -ARC, -NCP, -GLS, -MER, -AIT projections            */
/* anything else is linear                                               */
/* Input:                                                                */
/*   d   xpos    x (RA) coordinate (deg)                                 */
/*   d   ypos    y (dec) coordinate (deg)                                */
/*   d   xref    x reference coordinate value (deg)                      */
/*   d   yref    y reference coordinate value (deg)                      */
/*   f   xrefpix x reference pixel                                       */
/*   f   yrefpix y reference pixel                                       */
/*   f   xinc    x coordinate increment (deg)                            */
/*   f   yinc    y coordinate increment (deg)                            */
/*   f   rot     rotation (deg)  (from N through E)                      */
/*   c  *type    projection type code e.g. "-SIN";                       */
/* Output:                                                               */
/*   f  *xpix    x pixel number  (RA or long without rotation)           */
/*   f  *ypiy    y pixel number  (dec or lat without rotation)           */
/*-----------------------------------------------------------------------*/
 {double dx, dy, dz, r, ra0, dec0, ra, dec, coss, sins, dt, da, dd, sint;
  double l, m, geo1, geo2, geo3, sinr, cosr, cos0, sin0;
  double cond2r=1.745329252e-2, deps=1.0e-5, twopi=6.28318530717959;
  int   i, itype;
  char ctypes[9][5] ={"-CAR","-SIN","-TAN","-ARC","-NCP", "-GLS", "-MER",
     "-AIT", "-STG"};

  /* 0h wrap-around tests added by D.Wells 10/12/94: */
  dt = (xpos - xref);
  if (dt >  180) xpos -= 360;
  if (dt < -180) xpos += 360;
  /* NOTE: changing input argument xpos is OK (call-by-value in C!) */

/* default values - linear */
  dx = xpos - xref;
  dy = ypos - yref;
/*  dz = 0.0; */
/*  Correct for rotation */
  r = rot * cond2r;
  cosr = cos (r);
  sinr = sin (r);
  dz = dx*cosr + dy*sinr;
  dy = dy*cosr - dx*sinr;
  dx = dz;
/*     check axis increments - bail out if either 0 */
  if ((xinc==0.0) || (yinc==0.0)) {*xpix=0.0; *ypix=0.0; return(*status = 502);}
/*     convert to pixels  */
  *xpix = dx / xinc + xrefpix;
  *ypix = dy / yinc + yrefpix;

/*  find type  */
/* WDP 1/97: removed support for default type for better error checking */
/*  itype = 0;   default type is linear */
  itype = -1;  /* no default type */
  for (i=0;i<9;i++) if (!strncmp(type, ctypes[i], 4)) itype = i;
  if (itype==0) return(*status);  /* done if linear */

/* Non linear position */
  ra0 = xref * cond2r;
  dec0 = yref * cond2r;
  ra = xpos * cond2r;
  dec = ypos * cond2r;

/* compute direction cosine */
  coss = cos (dec);
  sins = sin (dec);
  cos0 = cos (dec0);
  sin0 = sin (dec0);
  l = sin(ra-ra0) * coss;
  sint = sins * sin0 + coss * cos0 * cos(ra-ra0);

/* process by case  */
  switch (itype) {
    case 1:   /* -SIN sin*/ 
         if (sint<0.0) return(*status = 501);
         m = sins * cos(dec0) - coss * sin(dec0) * cos(ra-ra0);
      break;
    case 2:   /* -TAN tan */
         if (sint<=0.0) return(*status = 501);
         if( cos0<0.001 ) {
            /* Do a first order expansion around pole */
            m = (coss * cos(ra-ra0)) / (sins * sin0);
            m = (-m + cos0 * (1.0 + m*m)) / sin0;
         } else {
            m = ( sins/sint - sin0 ) / cos0;
         }
	 if( fabs(sin(ra0)) < 0.3 ) {
	    l  = coss*sin(ra)/sint - cos0*sin(ra0) + m*sin(ra0)*sin0;
	    l /= cos(ra0);
	 } else {
	    l  = coss*cos(ra)/sint - cos0*cos(ra0) + m*cos(ra0)*sin0;
	    l /= -sin(ra0);
	 }
      break;
    case 3:   /* -ARC Arc*/
         m = sins * sin(dec0) + coss * cos(dec0) * cos(ra-ra0);
         if (m<-1.0) m = -1.0;
         if (m>1.0) m = 1.0;
         m = acos (m);
         if (m!=0) 
            m = m / sin(m);
         else
            m = 1.0;
         l = l * m;
         m = (sins * cos(dec0) - coss * sin(dec0) * cos(ra-ra0)) * m;
      break;
    case 4:   /* -NCP North celestial pole*/
         if (dec0==0.0) 
	     return(*status = 501);  /* can't stand the equator */
         else
	   m = (cos(dec0) - coss * cos(ra-ra0)) / sin(dec0);
      break;
    case 5:   /* -GLS global sinusoid */
         dt = ra - ra0;
         if (fabs(dec)>twopi/4.0) return(*status = 501);
         if (fabs(dec0)>twopi/4.0) return(*status = 501);
         m = dec - dec0;
         l = dt * coss;
      break;
    case 6:   /* -MER mercator*/
         dt = yinc * cosr + xinc * sinr;
         if (dt==0.0) dt = 1.0;
         dy = (yref/2.0 + 45.0) * cond2r;
         dx = dy + dt / 2.0 * cond2r;
         dy = log (tan (dy));
         dx = log (tan (dx));
         geo2 = dt * cond2r / (dx - dy);
         geo3 = geo2 * dy;
         geo1 = cos (yref*cond2r);
         if (geo1<=0.0) geo1 = 1.0;
         dt = ra - ra0;
         l = geo1 * dt;
         dt = dec / 2.0 + twopi / 8.0;
         dt = tan (dt);
         if (dt<deps) return(*status = 502);
         m = geo2 * log (dt) - geo3;
         break;
    case 7:   /* -AIT Aitoff*/
         da = (ra - ra0) / 2.0;
         if (fabs(da)>twopi/4.0) return(*status = 501);
         dt = yinc*cosr + xinc*sinr;
         if (dt==0.0) dt = 1.0;
         dt = dt * cond2r;
         dy = yref * cond2r;
         dx = sin(dy+dt)/sqrt((1.0+cos(dy+dt))/2.0) -
             sin(dy)/sqrt((1.0+cos(dy))/2.0);
         if (dx==0.0) dx = 1.0;
         geo2 = dt / dx;
         dt = xinc*cosr - yinc* sinr;
         if (dt==0.0) dt = 1.0;
         dt = dt * cond2r;
         dx = 2.0 * cos(dy) * sin(dt/2.0);
         if (dx==0.0) dx = 1.0;
         geo1 = dt * sqrt((1.0+cos(dy)*cos(dt/2.0))/2.0) / dx;
         geo3 = geo2 * sin(dy) / sqrt((1.0+cos(dy))/2.0);
         dt = sqrt ((1.0 + cos(dec) * cos(da))/2.0);
         if (fabs(dt)<deps) return(*status = 503);
         l = 2.0 * geo1 * cos(dec) * sin(da) / dt;
         m = geo2 * sin(dec) / dt - geo3;
      break;
    case 8:   /* -STG Sterographic*/
         da = ra - ra0;
         if (fabs(dec)>twopi/4.0) return(*status = 501);
         dd = 1.0 + sins * sin(dec0) + coss * cos(dec0) * cos(da);
         if (fabs(dd)<deps) return(*status = 501);
         dd = 2.0 / dd;
         l = l * dd;
         m = dd * (sins * cos(dec0) - coss * sin(dec0) * cos(da));
      break;

    default:
      /* fall through to here on error */
      return(*status = 504);

  }  /* end of itype switch */

/*   back to degrees  */
  dx = l / cond2r;
  dy = m / cond2r;
/*  Correct for rotation */
  dz = dx*cosr + dy*sinr;
  dy = dy*cosr - dx*sinr;
  dx = dz;
/*     convert to pixels  */
  *xpix = dx / xinc + xrefpix;
  *ypix = dy / yinc + yrefpix;
  return(*status);
}  /* end xypix */

int
worldpix (double xpos, double ypos,
          double xref, double yref,
          double xrefpix, double yrefpix, double xinc, double yinc, double rot,
          double cd1_1, double cd1_2, double cd2_1, double cd2_2,
          char *type,
          double *xpix, double *ypix)

/*-----------------------------------------------------------------------*/
/* routine to determine accurate pixel coordinates for an RA and Dec     */
/* returns 0 if successful otherwise:                                    */
/*  1 = angle too large for projection;                                  */
/*  2 = bad values                                                       */
/* does: SIN, TAN, ARC, NCP, GLS or SFL, MER, AIT, STG, CAR, COE projections    */
/* anything else is linear                                               */

{
  double dx, dy, ra0, dec0, ra, dec, coss, sins, dt, da, dd, sint;
  double l, m, geo1, geo2, geo3, sinr, cosr, tx, x, a2, a3, a4;
  double rthea,gamby2,a,b,c,phi,an,rap,v,tthea,co1,co2,co3,co4,ansq; /* COE */
  double cond2r=1.745329252e-2, deps=1.0e-5, twopi=6.28318530717959;

  double dc1_1, dc1_2, dc2_1, dc2_2, det;

  bool coorflip = FALSE;
  char ctypes[12][5] ={"-CAR","-SIN","-TAN","-TNX","-ARC","-NCP", "-GLS","-SFL", "-MER",
     "-AIT", "-STG", "-COE"};
  int i;
/* Structure elements */
  int itype;

  /* Set local projection parameters */
  rot = rot * M_PI / 180.;
  cosr = cos (rot);
  sinr = sin (rot);

  /* Projection type */
  itype = 0;  /* no default type */
  for (i=0;i<12;i++) if (!strncmp(type, ctypes[i], 4)) itype = i;

  /* Nonlinear position */
  if (itype > 0) {
    if (coorflip) {
      dec0 = xref * M_PI / 180.;
      ra0 = yref * M_PI / 180.;
      dt = xpos - yref;
      }
    else {
      ra0 = xref * M_PI / 180.;
      dec0 = yref * M_PI / 180.;
      dt = xpos - xref;
      }

    /* 0h wrap-around tests added by D.Wells 10/12/1994: */
    /* Modified to exclude weird reference pixels by D.Mink 2/3/2004 */
    if (xrefpix*xinc > 180.0 || xrefpix*xinc < -180.0) {
    if (dt > 360.0) xpos -= 360.0;
    if (dt < 0.0) xpos += 360.0;
    }
    else {
    if (dt > 180.0) xpos -= 360.0;
    if (dt < -180.0) xpos += 360.0;
    }
    /* NOTE: changing input argument xpos is OK (call-by-value in C!) */

    ra = xpos * M_PI / 180.;
    dec = ypos * M_PI / 180.;

    /* Compute direction cosine */
    coss = cos (dec);
    sins = sin (dec);
    l = sin(ra-ra0) * coss;
    sint = sins * sin(dec0) + coss * cos(dec0) * cos(ra-ra0);
    }
  else {
    l = 0.0;
    sint = 0.0;
    sins = 0.0;
    coss = 0.0;
    ra = 0.0;
    dec = 0.0;
    ra0 = 0.0;
    dec0 = 0.0;
    m = 0.0;
    }

  /* Process by case  */
  switch (itype) {

    case 0:   /* -CAR Cartesian */
      l = ra - ra0;
      m = dec - dec0;
      break;

    case 1:   /* -SIN sin*/
    if (sint<0.0) return 1;
    m = sins * cos(dec0) - coss * sin(dec0) * cos(ra-ra0);
    break;

    case 3:   /* -TNX tan with polynomial correction */
//    case WCS_TPV:   /* -TPV tan with polynomial correction */
//    case WCS_ZPX:   /* -ZPX zpn with polynomial correction */
    case 2:   /* -TAN tan */
    if (sint<=0.0) return 1;
    m = sins * sin(dec0) + coss * cos(dec0) * cos(ra-ra0);
    l = l / m;
    m = (sins * cos(dec0) - coss * sin(dec0) * cos(ra-ra0)) / m;
    break;

    case 4:   /* -ARC Arc*/
    m = sins * sin(dec0) + coss * cos(dec0) * cos(ra-ra0);
    if (m<-1.0) m = -1.0;
    if (m>1.0) m = 1.0;
    m = acos (m);
    if (m!=0)
        m = m / sin(m);
    else
        m = 1.0;
    l = l * m;
    m = (sins * cos(dec0) - coss * sin(dec0) * cos(ra-ra0)) * m;
    break;

    case 5:   /* -NCP North celestial pole*/
    if (dec0==0.0)
        return 1;  /* can't stand the equator */
    else
        m = (cos(dec0) - coss * cos(ra-ra0)) / sin(dec0);
    break;

    case 6:   /* -GLS global sinusoid */
    case 7:   /* -SFL Samson-Flamsteed */
    dt = ra - ra0;
    if (fabs(dec)>twopi/4.0) return 1;
    if (fabs(dec0)>twopi/4.0) return 1;
    m = dec - dec0;
    l = dt * coss;
    break;

    case 8:   /* -MER mercator*/
    dt = yinc * cosr + xinc * sinr;
    if (dt==0.0) dt = 1.0;
    dy = degrad (yref/2.0 + 45.0);
    dx = dy + dt / 2.0 * cond2r;
    dy = log (tan (dy));
    dx = log (tan (dx));
    geo2 = degrad (dt) / (dx - dy);
    geo3 = geo2 * dy;
    geo1 = cos (degrad (yref));
    if (geo1<=0.0) geo1 = 1.0;
    dt = ra - ra0;
    l = geo1 * dt;
    dt = dec / 2.0 + twopi / 8.0;
    dt = tan (dt);
    if (dt<deps) return 2;
    m = geo2 * log (dt) - geo3;
    break;

    case 9:   /* -AIT Aitoff*/
    l = 0.0;
    m = 0.0;
    da = (ra - ra0) / 2.0;
    if (fabs(da)>twopi/4.0) return 1;
    dt = yinc*cosr + xinc*sinr;
    if (dt==0.0) dt = 1.0;
    dt = degrad (dt);
    dy = degrad (yref);
    dx = sin(dy+dt)/sqrt((1.0+cos(dy+dt))/2.0) -
         sin(dy)/sqrt((1.0+cos(dy))/2.0);
    if (dx==0.0) dx = 1.0;
    geo2 = dt / dx;
    dt = xinc*cosr - yinc* sinr;
    if (dt==0.0) dt = 1.0;
    dt = degrad (dt);
    dx = 2.0 * cos(dy) * sin(dt/2.0);
    if (dx==0.0) dx = 1.0;
    geo1 = dt * sqrt((1.0+cos(dy)*cos(dt/2.0))/2.0) / dx;
    geo3 = geo2 * sin(dy) / sqrt((1.0+cos(dy))/2.0);
    dt = sqrt ((1.0 + cos(dec) * cos(da))/2.0);
    if (fabs(dt)<deps) return 3;
    l = 2.0 * geo1 * cos(dec) * sin(da) / dt;
    m = geo2 * sin(dec) / dt - geo3;
    break;

    case 10:   /* -STG Sterographic*/
    da = ra - ra0;
    if (fabs(dec)>twopi/4.0) return 1;
    dd = 1.0 + sins * sin(dec0) + coss * cos(dec0) * cos(da);
    if (fabs(dd)<deps) return 1;
    dd = 2.0 / dd;
    l = l * dd;
    m = dd * (sins * cos(dec0) - coss * sin(dec0) * cos(da));
    break;

    case 11:    /* allan: -COE projection added, AW, ESO*/
    gamby2 = sin (dec0);
    tthea = tan (dec0);
    rthea = 1. / tthea;
    a = -2. * tthea;
    b = tthea * tthea;
    c = tthea / 3.;
    a2 = a * a;
    a3 = a2 * a;
    a4 = a2 * a2;
    co1 = a/2.;
    co2 = -0.125 * a2 + b/2.;
    co3 = -0.25 * a*b + 0.0625 * a3 + c/2.0;
    co4 = -0.125 * b*b - 0.25 * a*c + 0.1875 * b*a2 - (5.0/128.0)*a4;
    phi = ra0 - ra;
    an = phi * gamby2;
    v = dec - dec0;
    rap = rthea * (1.0 + v * (co1+v * (co2+v * (co3+v * co4))));
    ansq = an * an;
    if (cd1_1 != 0.0)
        l = rap * an * (1.0 - ansq/6.0) * (cd1_1 / fabs(cd1_1));
    else
        l = rap * an * (1.0 - ansq/6.0) * (xinc / fabs(xinc));
    m = rthea - (rap * (1.0 - ansq/2.0));
    break;

    }  /* end of itype switch */

  /* Convert back to degrees  */
  if (itype > 0) {
    dx = l * 180. / M_PI;
    dy = m * 180. / M_PI;
    }

  /* For linear or pixel projection */
  else {
    dx = xpos - xref;
    dy = ypos - yref;
    }

  if (coorflip) {
    tx = dx;
    dx = dy;
    dy = tx;
    }

  /* Scale and rotate using CD matrix */
  if (cd1_1 != 0.0) {

// invert cd matrix
    det = cd1_1 * cd2_2 - cd1_2 * cd2_1;
    dc1_1 = cd2_2 / det;
    dc1_2 = -cd1_2 / det;
    dc2_1 = -cd2_1 / det;
    dc2_2 = cd1_1 / det;

    tx = dx * dc1_1 + dy * dc2_1;
    dy = dx * dc1_2 + dy * dc2_2;
    dx = tx;
    }

  /* Scale and rotate using CDELTn and CROTA2 */
  else {

    /* Correct for rotation */
    if (rot!=0.0) {
      tx = dx*cosr + dy*sinr;
      dy = dy*cosr - dx*sinr;
      dx = tx;
      }

    /* Scale using CDELT */
    if (xinc != 0.)
      dx = dx / xinc;
    if (yinc != 0.)
      dy = dy / yinc;
    }

  /* Convert to pixels  */
  *xpix = dx + xrefpix;

  /*
  if (itype == 0) {
    if (*xpix > wcs->nxpix) {
      x = *xpix - (360.0 / xinc);
      if (x > 0.0) *xpix = x;
      }
    else if (*xpix < 0) {
      x = *xpix + (360.0 / xinc);
      if (x <= wcs->nxpix) *xpix = x;
      }
    }
   */
  *ypix = dy + yrefpix;

  return 0;
}  /* end worldpix */


/* Calculate spectral axis value at position pix, taking into account logarithmic axes */
double pixwave(double pix, double crpix, double crval, double cdelt, bool logwave) {
    if (logwave) {
        return crval * exp((pix - crpix) * cdelt / crval); // following Greisen et al, 2006, EQ 4 & 5
    } else {
        return crval + (pix - crpix) * cdelt;
    }
}

/* Calculate pixel position at spectral value val, taking into account logarithmic axes */
int wavepix(double pix, double crpix, double crval, double cdelt, bool logwave) {
    if (logwave) {
        return (int)(crpix + crval / cdelt * log(pix / crval) + 0.5);
    } else {
        return (int)(crpix + (pix - crval) / cdelt + 0.5);
    }
}

/*!
Constructor: Allocates minimum space for a FITS conforming header (2880 bytes).
The first line is set to "SIMPLE = T", the last to "END"
*/

void Fits::InitHeader(void) {
	
	header = (char *)malloc(2881 * sizeof(char));
	HeaderLength = 2880;
/*
	strcpy(header, SIMPLE_T);
	for (i = 0; i < 34; i++) strcat(header, FITS_EMPTY);
	strcat(header, FITS_END);
*/
  memset(header, ' ', 2880);
	header[0] = 'S';
	header[1] = 'I';
	header[2] = 'M';
	header[3] = 'P';
	header[4] = 'L';
	header[5] = 'E';
	header[8] = '=';
	header[29] = 'T';
	header[35*80] = 'E';
	header[35*80+1] = 'N';
	header[35*80+2] = 'D';
	header[2880] = 0;
}

/*!
Copies a FITS header
*/

void Fits::CopyHeader(const Fits & source) {
	free(header);
	header = strdup(source.header);
	HeaderLength = source.HeaderLength;
	if (source.hasRefPix()) {
//		crot = source.crot;
		strncpy(crtype, source.crtype, 9);
	}
}

/*
Utility function to check if key is complete and valid. Trailing whitespace are
ignored and upon success also stripped of the passed char*
This also supports keys which are longer than 8 bytes (e.g. HIERARCH ESO ...)
*/

bool verifyFitsKey(char *key) {
    char work[81];
    strcpy(work, key);
    int l;

// strip off trailing spaces off key
    while ((work[strlen(work) - 1] == ' ') && (strlen(work) > 0)) work[strlen(work) - 1] = 0;

// key must not be empty
    l = strlen(work);
    if (l == 0) return FALSE;

// Key is less or equal 8 characters. Must not contain any whitespace
    if (l <= 8) {
        if (strchr(work, ' ') == NULL) {
            if (l < 8) for (int i = l; i < 8; i++) strcat(work, " ");
            strncpy(key, work, strlen(work) + 1);
            return TRUE;
        }
        return FALSE;
    }

// Key is longer, therefore must start with HIERARCH
    if (strstr(work, "HIERARCH") != work) return FALSE;
    strcat(work, " ");
    strncpy(key, work, strlen(work) + 1);
    return TRUE;
}

/*!
Set an integer key, optionally with a comment
*/

bool Fits::SetIntKey(const char *key, int value, const char *comment) {
    char work[81], sval[81];
    int i, l;

    strcpy(work, key);

// is the name valid?
    if (!verifyFitsKey(work)) return FALSE;

// If the key is COMMENT or HISTORY, we don't delete the key and append as far down as possible
    if ((strlen(key) == 7) && ((strncmp(key, "COMMENT", 7) == 0) || (strncmp(key, "HISTORY", 7) == 0))) {
        snprintf(work, 80, "%s %i", key, value);
        if (strlen(work) < 80) strncat(work, FITS_EMPTY, 80 - strlen(work));
        return InsertLine(work, true);
    }

// Create necessary line
    if (strlen(work) <= 8) sprintf(sval, "= %21i ", value);
    else sprintf(sval, "= %i ", value);
    strncat(work, sval, 80 - strlen(work));
	if (comment) {
        strncat(work, "/ ", 80 - strlen(work));
        strncat(work, comment, 80 - strlen(work));
	}
	if (strlen(work) < 80) strncat(work, FITS_EMPTY, 80 - strlen(work));
	DeleteKey(key);
	return InsertLine(work);
}

/*!
Set several integer keys; The key names are generated from the base and
the numbers 1..n, where n < 10;
*/

bool Fits::SetIntKeys(const char *base, int *values, int n) {
	int i;
	char *key;
	
	if (n > 9) return FALSE;
	key = (char *)malloc(strlen(base) + 2);
	for (i = 1; i < 10; i++) {
		sprintf(key, "%s%i", base, i);
		if (i <= n) {
			if (!SetIntKey(key, values[i - 1])) {
				free(key);
				return FALSE;
			}
		} else DeleteKey(key);
	}
	free(key);
	return TRUE;
}

/*!
Set a floating point key, optionally with a comment
*/

bool Fits::SetFloatKey(const char *key, double value, const char *comment) {
    char work[81], sval[81];
    int i, l;

    strcpy(work, key);

// is the name valid?
    if (!verifyFitsKey(work)) return FALSE;

// If the key is COMMENT or HISTORY, we don't delete the key and append as far down as possible
    if ((strlen(key) == 7) && ((strncmp(key, "COMMENT", 7) == 0) || (strncmp(key, "HISTORY", 7) == 0))) {
        snprintf(work, 80, "%s %.21g", key, value);
        if (strlen(work) < 80) strncat(work, FITS_EMPTY, 80 - strlen(work));
        return InsertLine(work, true);
    }

// Create necessary line
    if (strlen(work) <= 8) sprintf(sval, "= %21.15g ", value);
    else sprintf(sval, "= %.21g ", value);
    strncat(work, sval, 80 - strlen(work));
    if (comment) {
        strncat(work, "/ ", 80 - strlen(work));
        strncat(work, comment, 80 - strlen(work));
    }
    if (strlen(work) < 80) strncat(work, FITS_EMPTY, 80 - strlen(work));
    DeleteKey(key);
    return InsertLine(work);
}

/*!
Set several floating point keys; The key names are generated from the base and
the numbers 1..n, where n < 10;
*/

bool Fits::SetFloatKeys(const char *base, double *values, int n) {
	int i;
	char *key;
	
	if (n > 9) return FALSE;
	key = (char *)malloc(strlen(base) + 2);
	for (i = 1; i < 10; i++) {
		sprintf(key, "%s%i", base, i);
		if (i <= n) {
			if (!SetFloatKey(key, values[i - 1])) {
				free(key);
				return FALSE;
			}
		} else DeleteKey(key);
	}
	free(key);
	return TRUE;
}

/*!
Set a string key, optionally with a comment
*/

bool Fits::SetStringKey(const char *key, const char *value, const char *comment) {
    char work[81], sval[81];
    int i, l;

    strcpy(work, key);

// is the name valid?
    if (!verifyFitsKey(work)) return FALSE;

// Create necessary line

// If the key is COMMENT or HISTORY, we don't delete the key and append as far down as possible
    if ((strlen(key) == 7) && ((strncmp(key, "COMMENT", 7) == 0) || (strncmp(key, "HISTORY", 7) == 0))) {
        snprintf(work, 80, "%s %s", key, value);
        if (strlen(work) < 80) strncat(work, FITS_EMPTY, 80 - strlen(work));
        return InsertLine(work, true);
    }
    if (value[0] == '\'') snprintf(sval, 77, "= %s", value);
    else snprintf(sval, 75, "= '%s'", value);
    if (sval[strlen(sval) - 1] != '\'') {
        if (strlen(sval) < 80) strcat(sval, "'");
        else sval[80] = '\'';
    }
    strncat(work, sval, 80 - strlen(work));
    if ((strlen(work) == 80) && (work[79] != '\'')) work[79] = '\'';
    if (comment) {
        strncat(work, " / ", 80 - strlen(work));
        strncat(work, comment, 80 - strlen(work));
    }
    if (strlen(work) < 80) strncat(work, FITS_EMPTY, 80 - strlen(work));
    DeleteKey(key);
    return InsertLine(work);
}

/*!
Set several string keys; The key names are generated from the base and
the numbers 1..n, where n < 10;
*/

bool Fits::SetStringKeys(const char *base, char **values, int n) {
	int i;
	char *key;
	
	if (n > 9) return FALSE;
	key = (char *)malloc(strlen(base) + 2);
	for (i = 1; i < 10; i++) {
		sprintf(key, "%s%i", base, i);
		if (i <= n) {
			if (!SetStringKey(key, values[i - 1])) {
				free(key);
				return FALSE;
			}
		} else DeleteKey(key);
	}
	free(key);
	return TRUE;
}

/*
Utility function to check if key + line is complete and valid.
This also supports keys which are longer than 8 bytes (e.g. HIERARCH ESO ...)
*/

bool verifyFitsHeaderEntry(const char *key, const char *line, int l) {
	bool rv = FALSE;
	char *pos;
	int i;

	rv = (strncmp(line, key, l) == 0);
	if (rv) {
        if (l > 8) {
            if (strncmp(key, "HIERARCH", 8) != 0) return FALSE;
        }
        pos = strchr((char*)line, '=');
		if (pos == NULL) return FALSE;
		for (i = l; i < pos-line; i++) {
			if (line[i] != ' ') return FALSE;
		}
	}
	return rv;
}

/*!
Get an integer key
*/

bool Fits::GetIntKey(const char *key, int *value) {
	char *pos, *val, *p;
	int l = strlen(key);
	
	for (pos = header; pos < header + HeaderLength; pos += 80) {
        if (verifyFitsHeaderEntry(key, pos, l)) {
			val = strchr(pos, '=');
			if (val == NULL) return FALSE;
			val++;
			*value = strtol(val, &p, 10);
			if (p == val) return FALSE;
			return TRUE;
		}
	}
	return FALSE;
}

/*!
Get several integer keys. The key name is generated from base and the numbers
1...n, where n < 10.
*/

bool Fits::GetIntKeys(const char *base, int *values, int n) {
	int i;
	char *key;
	
	if (n > 9) return FALSE;
	key = (char *)malloc(strlen(base) + 2);
	for (i = 1; i <= n; i++) {
		sprintf(key, "%s%i", base, i);
		if (!GetIntKey(key, &values[i - 1])) values[i - 1] = 0;
	}
	free(key);
	return TRUE;
}

/*!
Get a floating point key.
*/

bool Fits::GetFloatKey(const char *key, double *value) const {
	char *pos, *val, *p;
	int l = strlen(key);
	
	for (pos = header; pos < header + HeaderLength; pos += 80) {
//		if (strncmp(pos, key, l) == 0) {
        if (verifyFitsHeaderEntry(key, pos, l)) {
			val = strchr(pos, '=');
			if (val == NULL) return FALSE;
			val++;
			*value = strtod(val, &p);
			if (p == val) return FALSE;
			return TRUE;
		}
	}
	return FALSE;
}

/*!
Get several floating point keys. The key name is generated from base and the numbers
1...n, where n < 10.
*/

bool Fits::GetFloatKeys(const char *base, double *values, int n) {
	int i;
	char *key;
	
	if (n > 9) return FALSE;
	key = (char *)malloc(strlen(base) + 2);
	for (i = 1; i <= n; i++) {
		sprintf(key, "%s%i", base, i);
		if (!GetFloatKey(key, &values[i - 1])) values[i - 1] = 0.0;
	}
	free(key);
	return TRUE;
}

/*!
Get a string key.
If the FITS key is a number (either floating point or integer),
return the verbose copy of the key.
*/

bool Fits::GetStringKey(const char *key, char *value) const {
    char *pos, *npos, *lpos;
    int i, l = strlen(key);
    bool rv = FALSE;

    strcpy(value, "");
    for (pos = header; pos < header + HeaderLength; pos += 80) {
//        if (strncmp(pos, key, l) == 0) {
                if (verifyFitsHeaderEntry(key, pos, l)) {
            if ((npos = strchr(pos, '\'')) == NULL) {
                rv = FALSE;
            } else {
                rv = TRUE;
            }

            if (rv) {
                npos++;
                if (npos - pos > 70) {
                    rv = FALSE;
                }
                if (rv) {
                    if ((lpos = strchr(npos, '\'')) == NULL) {
                        return FALSE;
                    }
                    lpos--;
                    for (i = 0; i < lpos - npos + 1; i++) {
                        value[i] = npos[i];
                    }
                    value[lpos - npos + 1] = 0;
                }
            }
            if (!rv) {
                rv = TRUE;
                if ((npos = strchr(pos, '=')) == NULL) {
                    return FALSE;
                }
                npos++;
                while ((npos[0] == ' ') && (npos-pos < 80)) {
                    npos++;
                }
                i = 0;
//                while (isdigit(npos[0]) || (npos[0] == '.') || (npos[0] == '+') || (npos[0] == '-') || (tolower(npos[0] == 'e')) || (tolower(npos[0] == 'd'))) {
                while ((!((npos[0] == '/') || (npos[0] == ' '))) && (npos-pos < 80)) {
                    value[i] = npos[0];
                    npos++;
                    i++;
                }
                value[i] = 0;
            }
            return rv;
        }
    }
    return rv;
}

/*!
Get several string keys. The key name is generated from base and the numbers
1...n, where n < 10.
*/

bool Fits::GetStringKeys(const char *base, char **values, int n) {
	int i;
	char *key;
	
	if (n > 9) return FALSE;
	key = (char *)malloc(strlen(base) + 2);
	for (i = 1; i <= n; i++) {
		sprintf(key, "%s%i", base, i);
		if (!GetStringKey(key, values[i - 1])) strcpy(values[i - 1], "");
	}
	free(key);
	return TRUE;
}

/*!
Delete a key.
*/

bool Fits::DeleteKey(const char *key) {
	char *line;
	int i, l = strlen(key);
	bool rv = FALSE;
	
	for (line = header; line < header + HeaderLength; line += 80) {
        if (verifyFitsHeaderEntry(key, line, l)) {
//		if (strncmp(line, key, l) == 0) {
			rv = TRUE;
			for (i = 0; i < 80; i++) line[i] = ' ';
		}
	}
	return rv;
}

/*!
Return key position
*/

int Fits::KeyPosition(const char *key) {
    char *line;
    int i, l = strlen(key);
    int rv = 0;

    for (line = header, i = 1; line < header + HeaderLength; line += 80, i++) {
        if (verifyFitsHeaderEntry(key, line, l)) {
            rv = i;
            break;
        }
    }
    return rv;
}

/*!
Return key position
*/

bool Fits::MoveKey(const char *key, int position) {
    if (position * 80 > (HeaderLength - 80)) return fits_error("trying to move fits key past the end");

    int oldpos;
    if ((oldpos = KeyPosition(key)) == position) return true; // key is already at the correct position
    if (oldpos == 0) return false; // key does not exist

    char line[81];
    strncpy(line, (const char *)(header + (oldpos-1) * 80), 80);

    if (position < oldpos) {
        memmove(header + position * 80, header + (position - 1) * 80, (oldpos - position) * 80);
        memcpy(header + (position - 1) * 80, line, 80);
    } else {
        memmove(header + (oldpos - 1) * 80, header + oldpos * 80, (position - oldpos) * 80);
        memcpy(header + (position - 1) * 80, line, 80);
    }

    return true;
}

/*!
Insert a line in the FITS header. If no space is left, the header is
expanded by 2880 bytes, according to the FITS standard.
If the second argument is set to TRUE, the line will be put just before the END keyword.
*/

bool Fits::InsertLine(const char *line, bool atend) {
	int i;
	char *end, *iend, *pos, endstring[81];

// where is the END key?
	endstring[80] = 0;
	iend = NULL;
	for (end = header + 80; end < header + HeaderLength; end += 80) {
		if (strncmp(end, "END     ", 8) == 0) {
			iend = end;
			break;
		}
	}
	if (iend == NULL) {
		dp_output("The FITS header does not contain the END keyword.\n");
		return FALSE;
	}

// See if there is an empty line
    if (!atend) {
        for (pos = header + 80; pos < iend; pos += 80) {
            if (strncmp(pos, FITS_EMPTY, 80) == 0) {
                for (i = 0; i < 80; i++) pos[i] = line[i];
                return TRUE;
            }
        }
    } else {
        pos = iend;
        while (strncmp(pos - 80, FITS_EMPTY, 80) == 0) {
            pos -= 80;
        }
        if (pos < iend) {
            for (i = 0; i < 80; i++) pos[i] = line[i];
            return TRUE;
        }
    }

// no empty line found; save END key and overwrite
	strncpy(endstring, iend, 80);
	for (i = 0; i < 80; i++) iend[i] = line[i];

// see if there is room for END key
	if (iend != header + HeaderLength - 80) {
		for (i = 80; i < 160; i++) iend[i] = endstring[i - 80];
		return TRUE;
	} else {

// still no empty line found; expand
		header[HeaderLength] = 0;
		HeaderLength += 2880;
		header = (char *)realloc(header, (HeaderLength + 1) * sizeof(char));
		for (i = 0; i < 35; i++) strcat(header, FITS_EMPTY);
		strcat(header, endstring);
	}
	return TRUE;
}

double Fits::getCRPIX(int which) const {
	double rv = 1.0;
	char key[256];

	sprintf(key, "CRPIX%i", which);
	GetFloatKey(key, &rv);

	return rv;
}

double Fits::getCRVAL(int which) const {
	double rv = 1.0;
	char key[256];
	
	sprintf(key, "CRVAL%i", which);
	GetFloatKey(key, &rv);
	
	return rv;
}

// Aug 27, 2020: Replaced by proper handling in readWCSinfo
/*
double Fits::getCDELT(int which) const {
	double rv = 1.0;
	char key[256];
	
	sprintf(key, "CD%i_%i", which, which);
	if (!GetFloatKey(key, &rv)) {
		sprintf(key, "CDELT%i", which);
		GetFloatKey(key, &rv);
	}
	
	return rv;
}
*/

double Fits::getCDELT(int which) const {
    double rv = 1., pc = 1.;

    if (which < 3) {
        wcsinfo info;
        info = readWCSinfo(*this);
        if (which == 1) rv = info.xinc;
        else if (which == 2) rv = info.yinc;
    } else {
        char key[256];

        sprintf(key, "CD%i_%i", which, which);
        if (!GetFloatKey(key, &rv)) {
            sprintf(key, "CDELT%i", which);
            GetFloatKey(key, &rv);
            sprintf(key, "PC%i_%i", which, which);
            GetFloatKey(key, &pc);
            rv *= pc;
        }
    }
    return rv;
}

bool Fits::isAxisLog(int which) {
    char key[9];
    sprintf(key, "CTYPE%i", which);

    char ctype[81];
    bool logwave = false;

    if (GetStringKey(key, ctype)) {
        if (strlen(ctype) == 8) {
            if (!strncmp((char *)(&ctype[4]), "-LOG", 4)) logwave = true;
        }
    }
    return logwave;
}

/*!
Read a FITS header from a file.
The file pointer fd must be at the correct position.
*/

int Fits::ReadFitsHeader() {
    if (nocfitsio == true) {
        char *st;
        int i;
        ssize_t off;
        bool eoh = FALSE;

    // Is the file open?
        if (gz && gfd == NULL) {
            return -1;
        } else if (fd == NULL) {
            return -1;
        }

        free(header);
        header = (char *)malloc(2881 * sizeof(char));
        HeaderLength = 2880;

        header[80] = header[2880] = 0;
        dpread(header, 80);
    /*
     * Since the original (fortran) dpuser puts in some #0's at the
     * very beginning, we have to replace them
     */

        for (i = 0; i < 80; i++) {
            if (header[i] == 0) header[i] = ' ';
        }

        if ((st = strstr(header, "SIMPLE")) == NULL) {
            dp_output("Specified file is not in valid fits format!\n");
            return -1;
        }
        off = st - header;
        dpseek(off - 80, SEEK_CUR);

    // Read in header in chunks of 2880 bytes until we find the keyword END

        while (!eoh) {
            if (dpread(header + HeaderLength - 2880, 2880) != 2880) {
                dp_output("Premature end of fits header!\n");
                return -1;
            }
            for (i = 0; i < HeaderLength; i += 80) {

                if (strncmp(header + i, "END     ", 8) == 0) eoh = TRUE;
            }
            if (!eoh) {
                HeaderLength += 2880;
                header = (char *)realloc(header, (HeaderLength + 1) * sizeof(char));
                header[HeaderLength] = 0;
            }
        }
        if (off) for (i = 0; i < HeaderLength; i++) if (header[i] == 0) header[i] = ' ';
        if (off) off += 12;

        int nrAxis = 0;
        if (GetIntKey("NAXIS", &nrAxis) && (nrAxis == 0)) {
            extensionType = EMPTY;
        }
        return HeaderLength;
    }

    int nkeys = 0;
    char *rv;
    int line;

    fits_hdr2str(fitsio_fd, FALSE, NULL, 0, &rv, &nkeys, &fitsio_status);

    int additionalSpace = 2880 - (nkeys * 80) % 2880;
    if (additionalSpace != 0) rv = (char *)realloc(rv, nkeys * 80 + additionalSpace + 1);
    for (line = 0; line < 36 - nkeys % 36; line++) {
        strcat(rv, FITS_EMPTY);
    }
    free(header);
    header = strdup(rv);
    fits_free_memory(rv, &fitsio_status);

    HeaderLength = strlen(header);
    int nrAxis = 0;
    if (GetIntKey("NAXIS", &nrAxis) && (nrAxis == 0)) {
        extensionType = EMPTY;
    }
//    return HeaderLength + off;

    return HeaderLength;
}

/*!
Read a FITS header extension from a file. The file pointer will
be placed at the end of the extension header.
*/

int Fits::ReadFitsExtensionHeader(int extendNumber, bool trial, bool raw) {
    if (nocfitsio == true) {
        char *st;
        int i, extension;
        bool eoh = FALSE;
        int bpix, n, na[10];
        long long totaloffset, offset;

        if (extendNumber < 1) {
            return -1;
        }

        // Is the file open?
        if (gz && gfd == NULL) {
            return -1;
        } else if (fd == NULL) {
            return -1;
        }

        free(header);
        header = (char *)malloc(2881 * sizeof(char));
        HeaderLength = 2880;

        // move to the beginning of the file and read the header
        dpseek(0L, SEEK_SET);
        header[80] = header[2880] = 0;
        dpread(header, 80);
        dpseek(-80, SEEK_CUR);

        // The primary header must contain the SIMPLE keyword
        if ((st = strstr(header, "SIMPLE")) == NULL) {
            dp_output("Specified file is not in valid fits format!\n");
            return -1;
        }

        // Read in header in chunks of 2880 bytes until we find the keyword END
        while (!eoh) {
            if (dpread(header + HeaderLength - 2880, 2880) != 2880) {
                dp_output("Premature end of fits header!\n");
                return -1;
            }
            for (i = 0; i < HeaderLength; i += 80) {
                if (strncmp(header + i, "END     ", 8) == 0)
                    eoh = TRUE;
            }

            if (!eoh) {
                HeaderLength += 2880;
                header = (char *)realloc(header, (HeaderLength + 1) * sizeof(char));
                header[HeaderLength] = 0;
            }
        }

        // get header information, move to next extension header
        // for our purpose, we need BITPIX, NAXIS, NAXIS1...NAXISn
        if (!GetIntKey("BITPIX", &bpix))
            bpix = 0;
        bpix = abs(bpix) / 8;
        if (!GetIntKey("NAXIS", &n))
            n = 0;
        else
            GetIntKeys("NAXIS", na, n);
        offset = bpix;
        if (n == 0) {
            offset = 0;
        } else {
                for (i = 0; i < n; i++)
                    offset *= na[i];
                if ((offset % 2880) != 0) {
                    offset += 2880 - (offset % 2880);
                }
        }
    //    printf("%i %i %i %i %i %i\n", bpix, n, na[0], na[1], na[2], na[3]);
        totaloffset = offset + HeaderLength;

        // loop to the desired header
        for (extension = 1; extension <= extendNumber; extension++) {
    //        printf("reading extension %i...\nThe offset is: %i\n", extension, offset);

            // move to the beginning of the next header
            dpseek(totaloffset, SEEK_SET);
            if (dptell() != totaloffset) {
                if (!trial) {
                    dp_output("Could not seek file position %i\n", totaloffset);
                    dp_output("File position is %i\n", dptell());
                }
                return -1;
            }

            // read header
            free(header);
            header = (char *)malloc(2881 * sizeof(char));
            HeaderLength = 2880;

            header[80] = header[2880] = 0;
            dpread(header, 80);
            dpseek(totaloffset, SEEK_SET);
    //@        dpseek(-80, SEEK_CUR);

    //        printf("first line is: %s\n", header);
            // The extension header must begin with XTENSION
            if ((st = strstr(header, "XTENSION")) == NULL) {
                if (!trial) {
                    dp_output("Specified file is not in valid fits format!\n");
                }
                return -1;
            }

            // Read in header in chunks of 2880 bytes until we find the keyword END
            eoh = FALSE;
            while (!eoh) {
                if (dpread(header + HeaderLength - 2880, 2880) != 2880) {
                    if (!trial)
                        dp_output("Premature end of fits header!\n");
                    return -1;
                }

                for (i = 0; i < HeaderLength; i += 80) {
                    if (strncmp(header + i, "END     ", 8) == 0)
                        eoh = TRUE;
                }
                if (!eoh) {
                    HeaderLength += 2880;
                    header = (char *)realloc(header, (HeaderLength + 1) * sizeof(char));
                    header[HeaderLength] = 0;
                }
            }

            // get header information, move to next extension header
            // for our purpose, we need BITPIX, NAXIS, NAXIS1...NAXISn
            if (!GetIntKey("BITPIX", &bpix))
                bpix = 0;
            bpix = abs(bpix) / 8;
            if (!GetIntKey("NAXIS", &n))
                n = 0;
            else
                GetIntKeys("NAXIS", na, n);
            offset = bpix;

            // added agudo: copied code from main-header part above in order to
            // detect also empty extensions inbetween
            if (n == 0) {
                offset = 0;
            } else {
                    for (i = 0; i < n; i++)
                        offset *= na[i];
                    if ((offset % 2880) != 0) {
                        offset += 2880 - (offset % 2880);
                    }
            }
    //        for (i = 0; i < n; i++)
    //            offset *= na[i];
    //        offset += 2880 - (offset % 2880);
            // end added agudo


            totaloffset += HeaderLength + offset;
    //        printf("%i %i %i %i %i %i\n", bpix, n, na[0], na[1], na[2], na[3]);
        }
//        return HeaderLength;
    } else {

        fitsio_status = 0;
        fits_movabs_hdu(fitsio_fd, extendNumber+1, NULL, &fitsio_status);
        if (fitsio_status != 0) return 0;
        ReadFitsHeader();
    }
    // replace first line in header by SIMPLE = T
		char exttype[81];
        extensionType = EMPTY;
		
		if (GetStringKey("XTENSION", exttype)) {
			if (strncasecmp("IMAGE", exttype, 5) == 0) extensionType = IMAGE;
			else if (strncasecmp("TABLE", exttype, 5) == 0) extensionType = TABLE;
			else if (strncasecmp("BINTABLE", exttype, 8) == 0) extensionType = BINTABLE;
		}
		
    if (!raw) {
        for (int i = 0; i < 80; i++)
            header[i] = SIMPLE_T[i];
    }
    HeaderLength = strlen(header);

    return HeaderLength;
}

/*!
Write a FITS header to a file.
The file pointer fd must be at the correct position.
*/

bool Fits::WriteFitsHeader(FILE *fd) {
	return (int)fwrite(header, 1, HeaderLength, fd) == HeaderLength;
}

/*!
Return a pointer to the string representing the header.
*/

char * Fits::GetHeader() const {
	return header;
}

/* Stolen from cfitsio wcsutil.c */
/*
       read the values of the celestial coordinate system keywords.
       These values may be used as input to the subroutines that
       calculate celestial coordinates. (ffxypx, ffwldp)

       Modified in Nov 1999 to convert the CD matrix keywords back
       to the old CDELTn form, and to swap the axes if the dec-like
       axis is given first, and to assume default values if any of the
       keywords are not present.
*/
wcsinfo readWCSinfo(const Fits &source) {
	wcsinfo info;

    char ctype[81];
    double cd11, cd21, cd22, cd12;
    double pi =  3.1415926535897932;
    double phia, phib, temp;
    double toler = .0002;  /* tolerance for angles to agree (radians) */
	bool ok;

    if (!source.GetFloatKey("CRVAL1", &info.xrval))
       info.xrval = 0.;

    if (!source.GetFloatKey("CRVAL2", &info.yrval))
       info.yrval = 0.;

    if (!source.GetFloatKey("CRPIX1", &info.xrpix))
        info.xrpix = 0.;

    if (!source.GetFloatKey("CRPIX2", &info.yrpix))
        info.yrpix = 0.;

    /* look for PCi_j keywords */

    ok = source.GetFloatKey("PC1_1", &cd11);
    if (!source.GetFloatKey("PC2_1", &cd21)) cd21 = 0.0;
    if (!source.GetFloatKey("PC1_2", &cd12)) cd12 = 0.0;
    if (ok) ok = source.GetFloatKey("PC2_2", &cd22);

    if (ok) { /* convert to CDi_j */
        double cdelt1 = 1., cdelt2 = 1.;
        source.GetFloatKey("CDELT1", &cdelt1);
        source.GetFloatKey("CDELT2", &cdelt2);
        cd11 *= cdelt1;
        cd12 *= cdelt1;
        cd21 *= cdelt2;
        cd22 *= cdelt2;
    } else {
        /* look for CDi_j keywords */
        ok = source.GetFloatKey("CD1_1", &cd11);
        if (!source.GetFloatKey("CD2_1", &cd21)) cd21 = 0.0;
        if (!source.GetFloatKey("CD1_2", &cd12)) cd12 = 0.0;
        if (ok) ok = source.GetFloatKey("CD2_2", &cd22);
    }

    if (ok) {
        /* there are 2 ways to compute the angle: */
        phia = atan2( cd21, cd11);
        phib = atan2(-cd12, cd22);

        /* ensure that phia <= phib */
        if (phib < phia) {
            temp = phia;
            phia = phib;
            phib = temp;
        }

        /* there is a possible 180 degree ambiguity in the angles */
        /* so add 180 degress to the smaller value if the values  */
        /* differ by more than 90 degrees = pi/2 radians.         */
        /* (Later, we may decide to take the other solution by    */
        /* subtracting 180 degrees from the larger value).        */

        if ((phib - phia) > (pi / 2.))
           phia += pi;

        if (fabs(phia - phib) > toler)
        {
           /* angles don't agree, so looks like there is some skewness */
           /* between the axes.  Return with an error to be safe. */
//               *status = APPROX_WCS_KEY;
        }

        phia = (phia + phib) /2.;  /* use the average of the 2 values */
        info.xinc = cd11 / cos(phia);
        info.yinc = cd22 / cos(phia);
        info.rot = phia * 180. / pi;

        /* common usage is to have a positive yinc value.  If it is */
        /* negative, then subtract 180 degrees from rot and negate  */
        /* both xinc and yinc.  */

        if (info.yinc < 0)
        {
            info.xinc = -(info.xinc);
            info.yinc = -(info.yinc);
            info.rot = info.rot - 180.;
        }
    } else {  /* no CD matrix keywords either */
        if (!source.GetFloatKey("CDELT1", &info.xinc)) info.xinc = 1.;
        if (!source.GetFloatKey("CDELT2", &info.yinc)) info.yinc = 1.;
        if (!source.GetFloatKey("CROTA2", &info.rot)) info.rot=0.;
    }

    /* get the type of projection, if any */
    if (!source.GetStringKey("CTYPE1", ctype))
         info.type[0] = '\0';
    else
    {
        /* copy the projection type string */
        strncpy(info.type, &ctype[4], 4);
        info.type[4] = '\0';

        /* check if RA and DEC are inverted */
        if (!strncmp(ctype, "DEC-", 4) || !strncmp(ctype+1, "LAT", 3))
        {
            /* the latitudinal axis is given first, so swap them */

/*
 this case was removed on 12/9.  Apparently not correct.

            if ((*xinc / *yinc) < 0. )  
                *rot = -90. - (*rot);
            else
*/
            info.rot = 90. - (info.rot);

            /* Empirical tests with ds9 show the y-axis sign must be negated */
            /* and the xinc and yinc values must NOT be swapped. */
            info.yinc = -(info.yinc);

            temp = info.xrval;
            info.xrval = info.yrval;
            info.yrval = temp;
        }   
    }

	
	
	return info;
}

bool Fits::hasRefPix(void) const {
    bool noRefPix = true;
    noRefPix = noRefPix && ((getCRPIX(1) == 1.) && (getCDELT(1) == 1.) && (getCRVAL(1) == 1.));
    if (Naxis(0) >= 2) {
        noRefPix = noRefPix && ((getCRPIX(2) == 1.) && (getCDELT(2) == 1.) && (getCRVAL(2) == 1.));
    }
    if (Naxis(0) == 3) {
        noRefPix = noRefPix && ((getCRPIX(3) == 1.) && (getCDELT(3) == 1.) && (getCRVAL(3) == 1.));
    }
    if (noRefPix) {
        return false;
    } else {
        return true;
    }
}

