/*                                                                              *
 *   This file is part of the ESO UVES Pipeline                                 *
 *   Copyright (C) 2004,2005 European Southern Observatory                      *
 *                                                                              *
 *   This library is free software; you can redistribute it and/or modify       *
 *   it under the terms of the GNU General Public License as published by       *
 *   the Free Software Foundation; either version 2 of the License, or          *
 *   (at your option) any later version.                                        *
 *                                                                              *
 *   This program 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 General Public License for more details.                               *
 *                                                                              *
 *   You should have received a copy of the GNU General Public License          *
 *   along with this program; if not, write to the Free Software                *
 *   Foundation, 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA       *
 *                                                                              */

/*
 * $Author: amodigli $
 * $Date: 2012-12-15 19:02:40 $
 * $Revision: 1.5 $
 * $Name: not supported by cvs2svn $
 */

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

/*----------------------------------------------------------------------------*/
/**
 * @defgroup xsh_baryvel    Velocity correction
 *
 * Compute barycentric, heliocentric velocity corrections
 *
 * The code in this source file is a 1-to-1 translation of MIDAS COMPUT/BARYCOR
 * as defined in /prim/general/src/compxy.for (only the necessary parts were
 * translated). The code is not meant to be particularly readable/maintainable. 
 * To understand the computation the best starting point is probably
 * P. Stumpff, A&A Suppl. Ser. 41, pp. 1-8 (1980)
 *
 */
/*----------------------------------------------------------------------------*/
/**@{*/

/*-----------------------------------------------------------------------------
                                Includes
 -----------------------------------------------------------------------------*/

#include <xsh_baryvel.h>

#include <xsh_pfits.h>
#include <xsh_utils.h>
#include <xsh_error.h>
#include <xsh_msg.h>

#include <cpl.h>

#include <math.h>

/*-----------------------------------------------------------------------------
                                Local functions
 -----------------------------------------------------------------------------*/
static void deg2dms(double in_val, 
         double *degs,
         double *minutes,
         double *seconds);

static void deg2hms(double in_val, 
         double *hour,
         double *min,
         double *sec);

static void compxy(double inputr[19], char inputc[4],
        double outputr[4],
        double utr, double mod_juldat);

static void barvel(double DJE, double DEQ,
        double DVELH[4], double DVELB[4]);


/*----------------------------------------------------------------------------*/
/**
   @brief    Compute velocity correction
   @param    raw_header input FITS header
   @param    bary_corr  (output) baryocentric correction
   @param    helio_corr (output) heliocentric correction
*/
/*----------------------------------------------------------------------------*/
void
xsh_baryvel(const cpl_propertylist *raw_header,
         double *bary_corr,
         double *helio_corr)
{

    double outputr[4];

//inputc(1:3) = "+++"
    char inputc[] = "X+++";       /* 0th index not used */

//define/local rneg/r/1/1 1.0
    double rneg = 1.0;

//   write/keyw inputr/r/1/18 0.0 all
    double inputr[19];                  /* Do not use the zeroth element */


/*
  qc_ra       = m$value({p1},O_POS(1))
  qc_dec      = m$value({p1},O_POS(2))
  qc_geolat   = m$value({p1},{h_geolat})
  qc_geolon   = m$value({p1},{h_geolon})
  qc_obs_time = m$value({p1},O_TIME(7))  !using an image as input it take the
                                         !date from the descriptor O_TIME(1,2,3)
                                         !and the UT from O_TIME(5)
*/
    double qc_ra;
    double qc_dec;
    double qc_geolat;
    double qc_geolon;

    double utr;
    double mod_juldat;

    double ra_hour, ra_min, ra_sec;
    double dec_deg, dec_min, dec_sec;
    double lat_deg, lat_min, lat_sec;
    double lon_deg, lon_min, lon_sec;

    if(cpl_propertylist_has(raw_header,"RA")) {
       check_msg( qc_ra       = xsh_pfits_get_ra(raw_header),  /* in degrees */
                  "Error getting object right ascension");
    } else {
       xsh_msg_warning("RA FITS keyword not present in header, barycor not computed");
       return;
    }

    if(cpl_propertylist_has(raw_header,"DEC")) {
       check_msg( qc_dec      = xsh_pfits_get_dec(raw_header),
                  "Error getting object declination");
    } else {
       xsh_msg_warning("DEC FITS keyword not present in header, barycor not computed");
       return;
    }
    check_msg( qc_geolat   = xsh_pfits_get_geolat(raw_header),
       "Error getting telescope latitude");
    check_msg( qc_geolon   = xsh_pfits_get_geolon(raw_header),
       "Error getting telescope longitude");

    /* double qc_obs_time = xsh_pfits_get_exptime(raw_header);   Not used! */

    check_msg( utr         = xsh_pfits_get_utc(raw_header),
       "Error reading UTC");
    check_msg( mod_juldat  = xsh_pfits_get_mjdobs(raw_header),
       "Error julian date");

    deg2hms(qc_ra,     &ra_hour, &ra_min, &ra_sec);
    deg2dms(qc_dec,    &dec_deg, &dec_min, &dec_sec);
    deg2dms(qc_geolat, &lat_deg, &lat_min, &lat_sec);
    deg2dms(qc_geolon, &lon_deg, &lon_min, &lon_sec);

//   inputr(1) = m$value({p1},o_time(1))
//   inputr(2) = m$value({p1},o_time(2))
//   inputr(3) = m$value({p1},o_time(3))
//   inputr(4) = m$value({p1},o_time(5))                  !UT in real hours
//    inputr[1] = year;        not needed, pass mjd instead
//    inputr[2] = month;
//    inputr[3] = day;
//    inputr[4] = ut_hour;     not needed, pass ut instead
//    inputr[5] = ut_min;
//    inputr[6] = ut_sec;

//   write/keyw inputr/r/7/3 {p4}
    inputr[7] = lon_deg;
    inputr[8] = lon_min;
    inputr[9] = lon_sec;

  //rneg = (inputr(7)*3600.)+(inputr(8)*60.)+inputr(9)
    rneg = (inputr[7]*3600.)+(inputr[8]*60.)+inputr[9];
    //inputc(1:1) = p4(1:1)
    inputc[1] = (lon_deg >= 0) ? '+' : '-';
    //if rneg .lt. 0.0 inputc(1:1) = "-"
    if (rneg < 0) inputc[1] = '-';

//   write/keyw inputr/r/10/3 {p5},0,0
    inputr[10] = lat_deg;
    inputr[11] = lat_min;
    inputr[12] = lat_sec;

//  rneg = (inputr(10)*3600.)+(inputr(11)*60.)+inputr(12)
    rneg = (inputr[10]*3600.)+(inputr[11]*60.)+inputr[12];
//  inputc(2:2) = p5(1:1)
    inputc[2] = (lat_deg >= 0) ? '+' : '-';
//   if rneg .lt. 0.0 inputc(2:2) = "-"
    if (rneg < 0) inputc[2] = '-';

//   write/keyw inputr/r/13/3 {p2},0,0
    inputr[13] = ra_hour;
    inputr[14] = ra_min;
    inputr[15] = ra_sec;

//   write/keyw inputr/r/16/3 {p3},0,0
    inputr[16] = dec_deg;
    inputr[17] = dec_min;
    inputr[18] = dec_sec;

//  inputc(3:3) = p3(1:1)
    inputc[3] = (dec_deg >= 0) ? '+' : '-';
//  rneg = (inputr(16)*3600.)+(inputr(17)*60.)+inputr(18)
    rneg = (inputr[16]*3600.)+(inputr[17]*60.)+inputr[18];
//   if rneg .lt. 0.0 inputc(3:3) = "-"
    if (rneg < 0) inputc[3] = '-';
    

//C  INPUTR/R/1/3    date: year,month,day
//C  INPUTR/R/4/3    universal time: hour,min,sec
//C  INPUTR/R/7/3    EAST longitude of observatory: degree,min,sec  !! NOTE
//C  INPUTR/R/10/3   latitude of observatory: degree,min,sec
//C  INPUTR/R/13/3   right ascension: hour,min,sec
//C  INPUTR/R/16/3   declination: degree,min,sec

    //write/keyw action BA                         !indicate barycorr stuff
    //run MID_EXE:COMPXY                           !compute the corrections

    compxy(inputr, inputc, outputr, utr, mod_juldat);

//   set/format f14.6,g24.12
//   xsh_msg_debug("        Barycentric correction time:      {outputd(1)} day");
//   xsh_msg_debug("        Heliocentric correction time:     {outputd(2)} day");
//   xsh_msg_debug(" ");
   xsh_msg_debug("        Total barycentric RV correction:  %f km/s", outputr[1]);
   xsh_msg_debug("        Total heliocentric RV correction: %f km/s", outputr[2]);
   xsh_msg_debug("          (incl. diurnal RV correction of %f km/s)", outputr[3]);
//   xsh_msg_debug(" ");
//   xsh_msg_debug("Descriptor O_TIME of image {p1} used for date and UT.");

   *bary_corr = outputr[1];
   *helio_corr = outputr[2];

  cleanup:
   return;
}


/*----------------------------------------------------------------------------*/
/**
   @brief    Compute velocity correction
   @param    inputr     input parameters
   @param    inputc     input parameters
   @param    outputr    output parameters
   @param    utr        observation time (seconds)
   @param    mod_juldat observation modified julian date

  INPUTR/R/1/3    date: year,month,day
  INPUTR/R/4/3    universal time: hour,min,sec
  INPUTR/R/7/3    EAST longitude of observatory: degree,min,sec  !! NOTE
  INPUTR/R/10/3   latitude of observatory: degree,min,sec
  INPUTR/R/13/3   right ascension: hour,min,sec
  INPUTR/R/16/3   declination: degree,min,sec
  OUTPUTD/D/1/1   barycentric correction to time (days)
  OUTPUTD/D/2/1   heliocentric correction to time (days)
  OUTPUTR/R/1/1   barycentric correction to radial velocity (km/s)
  OUTPUTR/R/2/1   heliocentric correction to radial velocity (km/s)
  OUTPUTR/R/3/1   diurnal rotation of the earth

*/
/*----------------------------------------------------------------------------*/
static void
compxy(double inputr[19], char inputc[4],
       double outputr[4],
       double utr, double mod_juldat)
{

//      INTEGER   IAV,STAT,KUN(1),KNUL,N
//      INTEGER   MADRID
//
//      DOUBLE PRECISION   UTR,STR,T0,DL,THETA0,PE,ST0HG,STG,GAST,R1
    double STR;

//    double utr     Not used. Use FITS header value instead
    double t0, dl, theta0, pe, st0hg, stg;
//      DOUBLE PRECISION   JD,JD0H,JD00,ZERO
    double jd, jd0h;
//      DOUBLE PRECISION   DCORB(3),DCORH(3),DVELB(3),DVELH(3)
    double dvelb[4], dvelh[4];
//      DOUBLE PRECISION   ALP,BCT,BEOV,BERV,DEL,EDV
    double alp, del, beov, berv, EDV;
//      DOUBLE PRECISION   HAR,HCT,HEOV,HERV,PHI,PI
    double HAR, phi, heov, herv;
//      DOUBLE PRECISION   EQX0,EQX1
//      DOUBLE PRECISION   A0R,A1R,D0R,D1R
//      DOUBLE PRECISION   DSMALL,DTEMP(3)
//
//      REAL   DATE0(3),DATE1(3),DATE00(3),A0(3),A1(3),D0(3),D1(3)
//      REAL   DATE(3),UT(3),OLONG(3),ST(3)
//    double ut[4];
//      REAL   OLAT(3),ALPHA(3),DELTA(3)
//      REAL   RBUF(20)
    double *rbuf;
//
//      CHARACTER   ACTIO*2,SIGNS*3,INPSGN*3
    char inpsgn[4];
//
//      COMMON      /VMR/MADRID(1)
// 
//      DATA    PI  /3.1415926535897928D0/
//      DATA    DSMALL  /1.D-38/


    double *olong, *olat, *alpha, *delta;

//1000  SIGNS = '+++'
    char signs[] = "+++";

//      CALL STKRDR('INPUTR',1,20,IAV,RBUF,KUN,KNUL,STAT)
    rbuf = inputr;
//      CALL STKRDC('INPUTC',1,1,3,IAV,INPSGN,KUN,KNUL,STAT)
    inpsgn[1] = inputc[1];
    inpsgn[2] = inputc[2];
    inpsgn[3] = inputc[3];


//      EQUIVALENCE (RBUF(1),DATE(1)),(RBUF(7),OLONG(1))
//    double *date  = rbuf + 1 - 1;  Not used, use the explicitly passed MJD instead
    olong = rbuf + 7 - 1;
//      EQUIVALENCE (RBUF(10),OLAT(1)),(RBUF(13),ALPHA(1))
    olat  = rbuf + 10 - 1;
    alpha = rbuf + 13 - 1;
//      EQUIVALENCE (RBUF(16),DELTA(1))
    delta = rbuf + 16 - 1;



//      DO 1100 N=1,3
//         UT(N) = RBUF(N+3)
//1100  CONTINUE
//    for (n = 1; n <= 3; n++)
//    {
//        ut[n] = rbuf[n+3];
//    }

// ... convert UT to real hours, calculate Julian date

//  UTR = UT(1)+UT(2)/60.D0+UT(3)/3600.D0
//    utr = ut[1]+ut[2]/60.  +ut[3]/3600.;   

    /* We know this one already but convert seconds -> hours */
    utr /= 3600;

//      CALL JULDAT(DATE,UTR,JD)
    jd = mod_juldat + 2400000.5;
  
// ... likewise convert longitude and latitude of observatory to real hours
// ... and degrees, respectively; take care of signs
// ... NOTE: east longitude is assumed for input !!

//      IF ((OLONG(1).LT.0.0) .OR. (OLONG(2).LT.0.0) .OR.
//     +    (OLONG(3).LT.0.0) .OR. (INPSGN(1:1).EQ.'-')) THEN  
      if (olong[1] < 0 || olong[2] < 0 ||
          olong[3] < 0 || inpsgn[1] == '-') {
//       SIGNS(1:1) = '-'
          signs[1] = '-';
//       OLONG(1) = ABS(OLONG(1))
//       OLONG(2) = ABS(OLONG(2))
//       OLONG(3) = ABS(OLONG(3))
          olong[1] = fabs(olong[1]);
          olong[2] = fabs(olong[2]);
          olong[3] = fabs(olong[3]);
//      ENDIF
      }

//    DL = OLONG(1)+OLONG(2)/60.D0+OLONG(3)/3600.D0
      dl = olong[1]+olong[2]/60.  +olong[3]/3600.;

//    IF (SIGNS(1:1).EQ.'-') DL = -DL              ! negative longitude
      if (signs[1]   == '-') dl = -dl;

//    DL = -DL*24.D0/360.D0                ! convert back to west longitude
      dl = -dl*24.  /360.;

//    IF ((OLAT(1).LT.0.0) .OR. (OLAT(2).LT.0.0) .OR.
//   +    (OLAT(3).LT.0.0) .OR. (INPSGN(2:2).EQ.'-')) THEN  
      if (olat[1] < 0 || olat[2] < 0 ||
      olat[3] < 0 || inpsgn[2] == '-') {
//        SIGNS(2:2) = '-'
      signs[2] = '-';
 
//         OLAT(1) = ABS(OLAT(1))
//         OLAT(2) = ABS(OLAT(2))
//         OLAT(3) = ABS(OLAT(3))
      olat[1] = fabs(olat[1]);
      olat[2] = fabs(olat[2]);
      olat[3] = fabs(olat[3]);
//    ENDIF
      }

//    PHI = OLAT(1)+OLAT(2)/60.D0+OLAT(3)/3600.D0
      phi = olat[1]+olat[2]/60.  +olat[3]/3600.;

//    IF (SIGNS(2:2).EQ.'-') PHI = -PHI                 ! negative latitude
      if (signs[2]   == '-') phi = -phi;

//    PHI = PHI*PI/180.D0
      phi = phi*M_PI/180. ;

// ... convert right ascension and declination to real radians

//    ALP = (ALPHA(1)*3600D0+ALPHA(2)*60D0+ALPHA(3))*PI  /(12.D0*3600.D0)
      alp = (alpha[1]*3600. +alpha[2]*60. +alpha[3])*M_PI/(12.  *3600.  );

//      IF ((DELTA(1).LT.0.0) .OR. (DELTA(2).LT.0.0) .OR.
//     +    (DELTA(3).LT.0.0) .OR. (INPSGN(3:3).EQ.'-')) THEN 
      if (delta[1] < 0 || delta[2] < 0 ||
      delta[3] < 0 || inpsgn[3] == '-') {
//        SIGNS(3:3) = '-'
      signs[3] = '-';
//         DELTA(1) = ABS(DELTA(1))
//         DELTA(2) = ABS(DELTA(2))
//         DELTA(3) = ABS(DELTA(3))
      delta[1] = fabs(delta[1]);
      delta[2] = fabs(delta[2]);
      delta[3] = fabs(delta[3]);
//      ENDIF
      }

//    DEL = (DELTA(1)*3600.D0 + DELTA(2)*60.D0 + DELTA(3))
//     +      * PI/(3600.D0*180.D0)
      del = (delta[1]*3600.0  + delta[2]*60.   + delta[3])
      * M_PI/(3600. *180. );


//    IF (SIGNS(3:3).EQ.'-') DEL = -DEL                 ! negative declination
      if (signs[3]   == '-') del = - del;

// ... calculate earth's orbital velocity in rectangular coordinates X,Y,Z
// ... for both heliocentric and barycentric frames (DVELH, DVELB)
// ... Note that setting the second argument of BARVEL to zero as done below
// ... means that the input coordinates will not be corrected for precession.

//      CALL BARVEL(JD,0.0D0,DVELH,DVELB)
      barvel(jd, 0.0, dvelh, dvelb);

// ... with the rectangular velocity components known, the respective projections
// ... HEOV and BEOV on a given line of sight (ALP,DEL) can be determined:

// ... REFERENCE: THE ASTRONOMICAL ALMANAC 1982 PAGE:B17

//      BEOV=DVELB(1)*DCOS(ALP)*DCOS(DEL)+
//     1     DVELB(2)*DSIN(ALP)*DCOS(DEL)+
//     2     DVELB(3)*DSIN(DEL)
      beov =
      dvelb[1]*cos(alp)*cos(del)+
      dvelb[2]*sin(alp)*cos(del)+
      dvelb[3]*sin(del);
      
//      HEOV=DVELH(1)*DCOS(ALP)*DCOS(DEL)+
//     1     DVELH(2)*DSIN(ALP)*DCOS(DEL)+
//     2     DVELH(3)*DSIN(DEL)
      heov =
      dvelh[1]*cos(alp)*cos(del)+
      dvelh[2]*sin(alp)*cos(del)+
      dvelh[3]*sin(del);
      

// ... For determination also of the contribution due to the diurnal rotation of
// ... the earth (EDV), the hour angle (HAR) is needed at which the observation
// ... was made which requires conversion of UT to sidereal time (ST).

// ... Therefore, first compute ST at 0 hours UT (ST0HG)

// ... REFERENCE : MEEUS J.,1980,ASTRONOMICAL FORMULAE FOR CALCULATORS

//      CALL JULDAT(DATE,ZERO,JD0H)
      jd0h = jd - (utr/24.0);
      
//      T0=(JD0H-2415020.D0)/36525.D0
      t0 = (jd0h-2415020.  )/36525. ;
      
//      THETA0=0.276919398D0+100.0021359D0*T0+0.000001075D0*T0*T0
      theta0 = 0.276919398  +100.0021359  *t0+0.000001075  *t0*t0 ;

//      PE=DINT(THETA0)
      pe = (int) theta0;

//      THETA0=THETA0-PE
      theta0 = theta0 - pe;

//      ST0HG=THETA0*24.D0
      st0hg = theta0*24. ;

// ... now do the conversion UT -> ST (MEAN SIDEREAL TIME)

// ... REFERENCE : THE ASTRONOMICAL ALMANAC 1983, P B7
// ... IN 1983: 1 MEAN SOLAR DAY = 1.00273790931 MEAN SIDEREAL DAYS
// ... ST WITHOUT EQUATION OF EQUINOXES CORRECTION => ACCURACY +/- 1 SEC
//
//      STG=ST0HG+UTR*1.00273790931D0
      stg = st0hg+utr*1.00273790931 ;
      
//      IF (STG.LT.DL) STG=STG+24.D0
      if (stg < dl) stg = stg +24. ;

//      STR=STG-DL
      STR = stg-dl;

//      IF (STR.GE.24.D0) STR=STR-24.D0
      if (STR >= 24. ) STR = STR-24. ;

//      STR = STR*PI/12.D0                                 ! ST in radians
      STR = STR*M_PI/12. ;

//      HAR=STR-ALP                                     ! hour angle of observation
      HAR = STR-alp;
      
//      EDV=-0.4654D0*DSIN(HAR)*DCOS(DEL)*DCOS(PHI)
      EDV = -0.4654  * sin(HAR)* cos(del)* cos(phi);

// ... the total correction (in km/s) is the sum of orbital and diurnal components

//    HERV=HEOV+EDV
      herv=heov+EDV;
//    BERV=BEOV+EDV
      berv=beov+EDV;

      /* The following is not needed. Do not translate */

#if 0
// ... Calculation of the barycentric and heliocentric correction times
// ... (BCT and HCT) requires knowledge of the earth's position in its
// ... orbit. Subroutine BARCOR returns the rectangular barycentric (DCORB)
// ... and heliocentric (DCORH) coordinates.

//      CALL BARCOR(DCORH,DCORB)

// ... from this, the correction times (in days) can be determined:
// ... (REFERENCE: THE ASTRONOMICAL ALMANAC 1982 PAGE:B16)

//      BCT=+0.0057756D0*(DCORB(1)*DCOS(ALP)*DCOS(DEL)+
//     1                DCORB(2)*DSIN(ALP)*DCOS(DEL)+
//     2                DCORB(3)*          DSIN(DEL))
//      HCT=+0.0057756D0*(DCORH(1)*DCOS(ALP)*DCOS(DEL)+
//     1                DCORH(2)*DSIN(ALP)*DCOS(DEL)+
//     2                DCORH(3)*          DSIN(DEL))

//... write results to keywords

//      CALL STKWRD('OUTPUTD',BCT,1,1,KUN,STAT)    ! barycentric correction time
//      CALL STKWRD('OUTPUTD',HCT,2,1,KUN,STAT)    ! heliocentric correction time
#endif


//      RBUF(1) = BERV                             ! barocentric RV correction
//      RBUF(2) = HERV                             ! heliocentric RV correction
// ... (note that EDV is already contained in both BERV and HERV)
//      RBUF(3) = EDV                              ! diurnal RV correction
      rbuf[1] = berv;
      rbuf[2] = herv;
      rbuf[3] = EDV;

//      CALL STKWRR('OUTPUTR',RBUF,1,3,KUN,STAT)
      outputr[1] = rbuf[1];
      outputr[2] = rbuf[2];
      outputr[3] = rbuf[3];
//      GOTO 9000
      return;
}

/* @cond Convert FORTRAN indexing -> C indexing */
#define DCFEL(x,y)  dcfel[y][x]
#define DCFEPS(x,y) dcfeps[y][x]
#define CCSEL(x,y)  ccsel[y][x]
#define DCARGS(x,y) dcargs[y][x]
#define CCAMPS(x,y) ccamps[y][x]
#define CCSEC(x,y)  ccsec[y][x]
#define DCARGM(x,y) dcargm[y][x]
#define CCAMPM(x,y) ccampm[y][x]
#define DCEPS(x)    dceps[x]
#define FORBEL(x)   forbel[x]
#define SORBEL(x)   sorbel[x]
#define SN(x)       sn[x]
#define SINLP(x)    sinlp[x]
#define COSLP(x)    coslp[x]
#define CCPAMV(x)   ccpamv[x]
/* @endcond */
/*----------------------------------------------------------------------------*/
/**
   @brief    compute rectangular heliocentric and barycentric components of
             the earth's orbital velocity
   @param    DJE        Julian date
   @param    DEQ        ???
   @param    DVELH      (output) heliocentric velocity
   @param    DVELB      (output) barycentric velocity

   REFERENCE : STUMPFF P. ASTRON. ASTOPHYS. SUPPL. 41,1,1980
               MODIFICATION : D. GILLET 1983-9-15

*/
/*----------------------------------------------------------------------------*/

//      SUBROUTINE BARVEL(DJE,DEQ,DVELH,DVELB)

static 
void barvel(double DJE, double DEQ,
        double DVELH[4], double DVELB[4])
{
//      DOUBLE PRECISION   DJE,DEQ,DVELH(3),DVELB(3),SN(4)
    double sn[5];
//      DOUBLE PRECISION   DT,DTL,DCT0,DCJUL,DTSQ,DLOCAL,DC2PI,CC2PI
    double DT,DTL,DTSQ,DLOCAL;
//      DOUBLE PRECISION   DRD,DRLD,DCSLD,DC1
    double DRD,DRLD;
//      DOUBLE PRECISION   DXBD,DYBD,DZBD,DZHD,DXHD,DYHD
    double DXBD,DYBD,DZBD,DZHD,DXHD,DYHD;
//      DOUBLE PRECISION   DYAHD,DZAHD,DYABD,DZABD
    double DYAHD,DZAHD,DYABD,DZABD;
//      DOUBLE PRECISION   DML,DEPS,PHI,PHID,PSID,DPARAM,PARAM
    double DML,DEPS,PHI,PHID,PSID,DPARAM,PARAM;
//      DOUBLE PRECISION   CCFDI,CCKM,CCMLD,PLON,POMG,PECC
    double PLON,POMG,PECC;
//      DOUBLE PRECISION   PERTL,PERTLD,PERTRD,PERTP,PERTR,PERTPD
    double PERTL,PERTLD,PERTRD,PERTP,PERTR,PERTPD;
//      DOUBLE PRECISION   SINA,CCSGD,DC1MME,TL
    double SINA,TL;
//      DOUBLE PRECISION   CCSEC3,COSA,ESQ
    double COSA,ESQ;
//      DOUBLE PRECISION   DCFEL(3,8),DCEPS(3),CCSEL(3,17),DCARGS(2,15)
//      DOUBLE PRECISION   CCAMPS(5,15),CCSEC(3,4),DCARGM(2,3)
//      DOUBLE PRECISION   CCAMPM(4,3),CCPAMV(4)
//      DOUBLE PRECISION   A,B,E,F,G,SINF,COSF,T,TSQ,TWOE,TWOG
    double A,B,F,SINF,COSF,T,TSQ,TWOE,TWOG;
//C
//      DOUBLE PRECISION   DPREMA(3,3),DPSI,D1PDRO,DSINLS
    double DPSI,D1PDRO,DSINLS;
//      DOUBLE PRECISION   DCOSLS,DSINEP,DCOSEP
    double DCOSLS,DSINEP,DCOSEP;
//      DOUBLE PRECISION   FORBEL(7),SORBEL(17),SINLP(4),COSLP(4)
    double forbel[8], sorbel[18], sinlp[5], coslp[5];
//      DOUBLE PRECISION   SINLM,COSLM,SIGMA
    double SINLM,COSLM,SIGMA;
//C
//      INTEGER     IDEQ,K,N
//  int IDEQ;
    int K,N;
//C
//      COMMON /BARXYZ/    DPREMA,DPSI,D1PDRO,DSINLS,DCOSLS,
//     +                   DSINEP,DCOSEP,FORBEL,SORBEL,SINLP,
//     +                   COSLP,SINLM,COSLM,SIGMA,IDEQ

//      EQUIVALENCE (SORBEL(1),E),(FORBEL(1),G)
    double *E = sorbel + 1 - 1;
    double *G = forbel + 1 - 1;
//C
//      DATA DC2PI/6.2831853071796D0/,CC2PI/6.283185/,
    double DC2PI = 6.2831853071796E0;
    double CC2PI = 6.283185;             /* ??? */

//     *DC1/1.0D0/,DCT0/2415020.0D0/,DCJUL/36525.0D0/
    double DC1 = 1.0;
    double DCT0 = 2415020.0E0;
    double DCJUL = 36525.0E0;
//C
//      DATA DCFEL/ 1.7400353D+00, 6.2833195099091D+02, 5.2796D-06,
//     *            6.2565836D+00, 6.2830194572674D+02,-2.6180D-06,
//     *            4.7199666D+00, 8.3997091449254D+03,-1.9780D-05,
//     *            1.9636505D-01, 8.4334662911720D+03,-5.6044D-05,
//     *            4.1547339D+00, 5.2993466764997D+01, 5.8845D-06,
//     *            4.6524223D+00, 2.1354275911213D+01, 5.6797D-06,
//     *            4.2620486D+00, 7.5025342197656D+00, 5.5317D-06,
//     *            1.4740694D+00, 3.8377331909193D+00, 5.6093D-06/

    double dcfel[][4] = { {0, 0, 0, 0},
              {0, 1.7400353E+00, 6.2833195099091E+02, 5.2796E-06},
              {0, 6.2565836E+00, 6.2830194572674E+02,-2.6180E-06},
              {0, 4.7199666E+00, 8.3997091449254E+03,-1.9780E-05},
              {0, 1.9636505E-01, 8.4334662911720E+03,-5.6044E-05},
              {0, 4.1547339E+00, 5.2993466764997E+01, 5.8845E-06},
              {0, 4.6524223E+00, 2.1354275911213E+01, 5.6797E-06},
              {0, 4.2620486E+00, 7.5025342197656E+00, 5.5317E-06},
              {0, 1.4740694E+00, 3.8377331909193E+00, 5.6093E-06} };
    
//C
//      DATA DCEPS/ 4.093198D-01,-2.271110D-04,-2.860401D-08/
    double dceps[4] = {0, 4.093198E-01,-2.271110E-04,-2.860401E-08};

//C
//      DATA CCSEL/ 1.675104D-02,-4.179579D-05,-1.260516D-07,
//     *            2.220221D-01, 2.809917D-02, 1.852532D-05,
//     *            1.589963D+00, 3.418075D-02, 1.430200D-05,
//     *            2.994089D+00, 2.590824D-02, 4.155840D-06,
//     *            8.155457D-01, 2.486352D-02, 6.836840D-06,
//     *            1.735614D+00, 1.763719D-02, 6.370440D-06,
//     *            1.968564D+00, 1.524020D-02,-2.517152D-06,
//     *            1.282417D+00, 8.703393D-03, 2.289292D-05,
//     *            2.280820D+00, 1.918010D-02, 4.484520D-06,
//     *            4.833473D-02, 1.641773D-04,-4.654200D-07,
//     *            5.589232D-02,-3.455092D-04,-7.388560D-07,
//     *            4.634443D-02,-2.658234D-05, 7.757000D-08,
//     *            8.997041D-03, 6.329728D-06,-1.939256D-09,
//     *            2.284178D-02,-9.941590D-05, 6.787400D-08,
//     *            4.350267D-02,-6.839749D-05,-2.714956D-07,
//     *            1.348204D-02, 1.091504D-05, 6.903760D-07,
//     *            3.106570D-02,-1.665665D-04,-1.590188D-07/

    double ccsel[][4] = { {0, 0, 0, 0},
              {0, 1.675104E-02, -4.179579E-05, -1.260516E-07},
              {0, 2.220221E-01,  2.809917E-02,  1.852532E-05},
              {0, 1.589963E+00,  3.418075E-02,  1.430200E-05},
              {0, 2.994089E+00,  2.590824E-02,  4.155840E-06},
              {0, 8.155457E-01,  2.486352E-02,  6.836840E-06},
              {0, 1.735614E+00,  1.763719E-02,  6.370440E-06},
              {0, 1.968564E+00,  1.524020E-02, -2.517152E-06},
              {0, 1.282417E+00,  8.703393E-03,  2.289292E-05},
              {0, 2.280820E+00,  1.918010E-02,  4.484520E-06},
              {0, 4.833473E-02,  1.641773E-04, -4.654200E-07},
              {0, 5.589232E-02, -3.455092E-04, -7.388560E-07},
              {0, 4.634443E-02, -2.658234E-05,  7.757000E-08},
              {0, 8.997041E-03,  6.329728E-06, -1.939256E-09},
              {0, 2.284178E-02, -9.941590E-05,  6.787400E-08},
              {0, 4.350267E-02, -6.839749E-05, -2.714956E-07},
              {0, 1.348204E-02,  1.091504E-05,  6.903760E-07},
              {0, 3.106570E-02, -1.665665E-04, -1.590188E-07} };



//      DATA DCARGS/ 5.0974222D+00,-7.8604195454652D+02,
//     *             3.9584962D+00,-5.7533848094674D+02,
//     *             1.6338070D+00,-1.1506769618935D+03,
//     *             2.5487111D+00,-3.9302097727326D+02,
//     *             4.9255514D+00,-5.8849265665348D+02,
//     *             1.3363463D+00,-5.5076098609303D+02,
//     *             1.6072053D+00,-5.2237501616674D+02,
//     *             1.3629480D+00,-1.1790629318198D+03,
//     *             5.5657014D+00,-1.0977134971135D+03,
//     *             5.0708205D+00,-1.5774000881978D+02,
//     *             3.9318944D+00, 5.2963464780000D+01,
//     *             4.8989497D+00, 3.9809289073258D+01,
//     *             1.3097446D+00, 7.7540959633708D+01,
//     *             3.5147141D+00, 7.9618578146517D+01,
//     *             3.5413158D+00,-5.4868336758022D+02/

    double dcargs[][3] = { {0, 0, 0},
               {0, 5.0974222E+00, -7.8604195454652E+02},
               {0, 3.9584962E+00, -5.7533848094674E+02},
               {0, 1.6338070E+00, -1.1506769618935E+03},
               {0, 2.5487111E+00, -3.9302097727326E+02},
               {0, 4.9255514E+00, -5.8849265665348E+02},
               {0, 1.3363463E+00, -5.5076098609303E+02},
               {0, 1.6072053E+00, -5.2237501616674E+02},
               {0, 1.3629480E+00, -1.1790629318198E+03},
               {0, 5.5657014E+00, -1.0977134971135E+03},
               {0, 5.0708205E+00, -1.5774000881978E+02},
               {0, 3.9318944E+00,  5.2963464780000E+01},
               {0, 4.8989497E+00,  3.9809289073258E+01},
               {0, 1.3097446E+00,  7.7540959633708E+01},
               {0, 3.5147141E+00,  7.9618578146517E+01},
               {0, 3.5413158E+00, -5.4868336758022E+02} };

//      DATA CCAMPS/
//     *-2.279594D-5, 1.407414D-5, 8.273188D-6, 1.340565D-5,-2.490817D-7,
//     *-3.494537D-5, 2.860401D-7, 1.289448D-7, 1.627237D-5,-1.823138D-7,
//     * 6.593466D-7, 1.322572D-5, 9.258695D-6,-4.674248D-7,-3.646275D-7,
//     * 1.140767D-5,-2.049792D-5,-4.747930D-6,-2.638763D-6,-1.245408D-7,
//     * 9.516893D-6,-2.748894D-6,-1.319381D-6,-4.549908D-6,-1.864821D-7,
//     * 7.310990D-6,-1.924710D-6,-8.772849D-7,-3.334143D-6,-1.745256D-7,
//     *-2.603449D-6, 7.359472D-6, 3.168357D-6, 1.119056D-6,-1.655307D-7,
//     *-3.228859D-6, 1.308997D-7, 1.013137D-7, 2.403899D-6,-3.736225D-7,
//     * 3.442177D-7, 2.671323D-6, 1.832858D-6,-2.394688D-7,-3.478444D-7,
//     * 8.702406D-6,-8.421214D-6,-1.372341D-6,-1.455234D-6,-4.998479D-8,
//     *-1.488378D-6,-1.251789D-5, 5.226868D-7,-2.049301D-7, 0.0D0,
//     *-8.043059D-6,-2.991300D-6, 1.473654D-7,-3.154542D-7, 0.0D0,
//     * 3.699128D-6,-3.316126D-6, 2.901257D-7, 3.407826D-7, 0.0D0,
//     * 2.550120D-6,-1.241123D-6, 9.901116D-8, 2.210482D-7, 0.0D0,
//     *-6.351059D-7, 2.341650D-6, 1.061492D-6, 2.878231D-7, 0.0D0/

    double ccamps[][6] = 
    {{0, 0, 0, 0, 0, 0},
     {0, -2.279594E-5,  1.407414E-5,  8.273188E-6,  1.340565E-5, -2.490817E-7},
     {0, -3.494537E-5,  2.860401E-7,  1.289448E-7,  1.627237E-5, -1.823138E-7},
     {0,  6.593466E-7,  1.322572E-5,  9.258695E-6, -4.674248E-7, -3.646275E-7},
     {0,  1.140767E-5, -2.049792E-5, -4.747930E-6, -2.638763E-6, -1.245408E-7},
     {0,  9.516893E-6, -2.748894E-6, -1.319381E-6, -4.549908E-6, -1.864821E-7},
     {0,  7.310990E-6, -1.924710E-6, -8.772849E-7, -3.334143E-6, -1.745256E-7},
     {0, -2.603449E-6,  7.359472E-6,  3.168357E-6,  1.119056E-6, -1.655307E-7},
     {0, -3.228859E-6,  1.308997E-7,  1.013137E-7,  2.403899E-6, -3.736225E-7},
     {0,  3.442177E-7,  2.671323E-6,  1.832858E-6, -2.394688E-7, -3.478444E-7},
     {0,  8.702406E-6, -8.421214E-6, -1.372341E-6, -1.455234E-6, -4.998479E-8},
     {0, -1.488378E-6, -1.251789E-5,  5.226868E-7, -2.049301E-7,  0.0E0},
     {0, -8.043059E-6, -2.991300E-6,  1.473654E-7, -3.154542E-7,  0.0E0},
     {0,  3.699128E-6, -3.316126E-6,  2.901257E-7,  3.407826E-7,  0.0E0},
     {0,  2.550120E-6, -1.241123E-6,  9.901116E-8,  2.210482E-7,  0.0E0},
     {0, -6.351059E-7,  2.341650E-6,  1.061492E-6,  2.878231E-7,  0.0E0}};


//      DATA CCSEC3/-7.757020D-08/
    double CCSEC3 = -7.757020E-08;
//C
//      DATA CCSEC/ 1.289600D-06, 5.550147D-01, 2.076942D+00,
//     *            3.102810D-05, 4.035027D+00, 3.525565D-01,
//     *            9.124190D-06, 9.990265D-01, 2.622706D+00,
//     *            9.793240D-07, 5.508259D+00, 1.559103D+01/

    double ccsec[][4] = { {0, 0, 0, 0},
              {0, 1.289600E-06,  5.550147E-01,  2.076942E+00},
              {0, 3.102810E-05,  4.035027E+00,  3.525565E-01},
              {0, 9.124190E-06,  9.990265E-01,  2.622706E+00},
              {0, 9.793240E-07,  5.508259E+00,  1.559103E+01}};

//C
//      DATA DCSLD/ 1.990987D-07/, CCSGD/ 1.990969D-07/
    double DCSLD =  1.990987E-07, CCSGD = 1.990969E-07;
//C
//      DATA CCKM/3.122140D-05/, CCMLD/2.661699D-06/, CCFDI/2.399485D-07/
    double CCKM = 3.122140E-05, CCMLD = 2.661699E-06, CCFDI = 2.399485E-07;
//C
//      DATA DCARGM/ 5.1679830D+00, 8.3286911095275D+03,
//     *             5.4913150D+00,-7.2140632838100D+03,
//     *             5.9598530D+00, 1.5542754389685D+04/

    double dcargm[][3] = {{0, 0, 0},
              {0, 5.1679830E+00,  8.3286911095275E+03},
              {0, 5.4913150E+00, -7.2140632838100E+03},
              {0, 5.9598530E+00,  1.5542754389685E+04}};
//C
//      DATA CCAMPM/
//     *  1.097594D-01, 2.896773D-07, 5.450474D-02, 1.438491D-07,
//     * -2.223581D-02, 5.083103D-08, 1.002548D-02,-2.291823D-08,
//     *  1.148966D-02, 5.658888D-08, 8.249439D-03, 4.063015D-08/

    double ccampm[][5] = {{0, 0, 0, 0, 0},
              {0,  1.097594E-01,  2.896773E-07,  5.450474E-02,  1.438491E-07},
              {0, -2.223581E-02,  5.083103E-08,  1.002548E-02, -2.291823E-08},
              {0,  1.148966E-02,  5.658888E-08,  8.249439E-03,  4.063015E-08} };

//C
//      DATA CCPAMV/8.326827D-11,1.843484D-11,1.988712D-12,1.881276D-12/,
    double ccpamv[] = {0, 8.326827E-11, 1.843484E-11, 1.988712E-12, 1.881276E-12};
//     *     DC1MME/0.99999696D0/
    double DC1MME = 0.99999696E0;
//C

//  IDEQ=DEQ
//  IDEQ=DEQ;

//  DT=(DJE-DCT0)/DCJUL
    DT=(DJE-DCT0)/DCJUL;

//  T=DT
    T=DT;

//  DTSQ=DT*DT
    DTSQ=DT*DT;

//  TSQ=DTSQ
    TSQ=DTSQ;

    DML = 0;  /* Suppress warning */
//      DO 100, K=1,8
    for (K = 1; K <= 8; K++) {

//      DLOCAL=DMOD(DCFEL(1,K)+DT*DCFEL(2,K)+DTSQ*DCFEL(3,K),DC2PI)
    DLOCAL=fmod(DCFEL(1,K)+DT*DCFEL(2,K)+DTSQ*DCFEL(3,K),DC2PI);

//      IF (K.EQ.1)  DML=DLOCAL
    if (K == 1)  DML=DLOCAL;

//      IF (K.NE.1)  FORBEL(K-1)=DLOCAL
    if (K != 1)  FORBEL(K-1)=DLOCAL;
//  100 CONTINUE
    }

//  DEPS=DMOD(DCEPS(1)+DT*DCEPS(2)+DTSQ*DCEPS(3), DC2PI)
    DEPS=fmod(DCEPS(1)+DT*DCEPS(2)+DTSQ*DCEPS(3), DC2PI);

//      DO 200, K=1,17
    for (K = 1; K <= 17; K++) {

//      SORBEL(K)=DMOD(CCSEL(1,K)+T*CCSEL(2,K)+TSQ*CCSEL(3,K),CC2PI)
    SORBEL(K)=fmod(CCSEL(1,K)+T*CCSEL(2,K)+TSQ*CCSEL(3,K),CC2PI);

//  200 CONTINUE
    }

//      DO 300, K=1,4
    for (K = 1; K <= 4; K++) {

//      A=DMOD(CCSEC(2,K)+T*CCSEC(3,K),CC2PI)
    A=fmod(CCSEC(2,K)+T*CCSEC(3,K),CC2PI);
    
//      SN(K)=DSIN(A)
    SN(K)=sin(A);
//  300 CONTINUE
    }

//      PERTL =  CCSEC(1,1)          *SN(1) +CCSEC(1,2)*SN(2)
//     *       +(CCSEC(1,3)+T*CCSEC3)*SN(3) +CCSEC(1,4)*SN(4)

    PERTL =  CCSEC(1,1)          *SN(1) +CCSEC(1,2)*SN(2)
           +(CCSEC(1,3)+T*CCSEC3)*SN(3) +CCSEC(1,4)*SN(4);

//    PERTLD=0.0
//    PERTR =0.0
//    PERTRD=0.0
    PERTLD=0.0;
    PERTR =0.0;
    PERTRD=0.0;

//      DO 400, K=1,15
    for (K = 1; K <= 15; K++) {
//      A=DMOD(DCARGS(1,K)+DT*DCARGS(2,K), DC2PI)
    A=fmod(DCARGS(1,K)+DT*DCARGS(2,K), DC2PI);

//    COSA=DCOS(A)
    COSA=cos(A);

//      SINA=DSIN(A)
    SINA=sin(A);

//      PERTL =PERTL+CCAMPS(1,K)*COSA+CCAMPS(2,K)*SINA
    PERTL =PERTL+CCAMPS(1,K)*COSA+CCAMPS(2,K)*SINA;

//    PERTR =PERTR+CCAMPS(3,K)*COSA+CCAMPS(4,K)*SINA;
    PERTR =PERTR+CCAMPS(3,K)*COSA+CCAMPS(4,K)*SINA;

//         IF (K.GE.11) GO TO 400
    if (K >= 11) break;

//      PERTLD=PERTLD+(CCAMPS(2,K)*COSA-CCAMPS(1,K)*SINA)*CCAMPS(5,K)
    PERTLD=PERTLD+(CCAMPS(2,K)*COSA-CCAMPS(1,K)*SINA)*CCAMPS(5,K);

//      PERTRD=PERTRD+(CCAMPS(4,K)*COSA-CCAMPS(3,K)*SINA)*CCAMPS(5,K)
    PERTRD=PERTRD+(CCAMPS(4,K)*COSA-CCAMPS(3,K)*SINA)*CCAMPS(5,K);

//  400 CONTINUE
    }

//  ESQ=E*E
    ESQ=E[1]*E[1];

//  DPARAM=DC1-ESQ
    DPARAM=DC1-ESQ;

//  PARAM=DPARAM
    PARAM=DPARAM;

//  TWOE=E+E
    TWOE=E[1]+E[1];

//  TWOG=G+G
    TWOG=G[1]+G[1];

//      PHI=TWOE*((1.0-ESQ*0.125D0)*DSIN(G)+E*0.625D0*DSIN(TWOG)
//    *          +ESQ*0.5416667D0*DSIN(G+TWOG) )

    PHI=TWOE*((1.0-ESQ*0.125  )*sin(G[1])+E[1]*0.625  *sin(TWOG)
          +ESQ*0.5416667  *sin(G[1]+TWOG) ) ;
    
    //F=G+PHI
    F=G[1]+PHI;

    //SINF=DSIN(F)
    SINF=sin(F);

    //COSF=DCOS(F)
    COSF=cos(F);

    //DPSI=DPARAM/(DC1+E*COSF)
    DPSI=DPARAM/(DC1+E[1]*COSF);

//  PHID=TWOE*CCSGD*((1.0+ESQ*1.5D0)*COSF+E[1]*(1.25D0-SINF*SINF*0.5D0))
    PHID=TWOE*CCSGD*((1.0+ESQ*1.5  )*COSF+E[1]*(1.25  -SINF*SINF*0.5  ));

//  PSID=CCSGD*E*SINF/SQRT(PARAM)
    PSID=CCSGD*E[1]*SINF/sqrt(PARAM);

//  D1PDRO=(DC1+PERTR)
    D1PDRO=(DC1+PERTR);

//  DRD=D1PDRO*(PSID+DPSI*PERTRD)
    DRD=D1PDRO*(PSID+DPSI*PERTRD);

//  DRLD=D1PDRO*DPSI*(DCSLD+PHID+PERTLD)
    DRLD=D1PDRO*DPSI*(DCSLD+PHID+PERTLD);

//  DTL=DMOD(DML+PHI+PERTL, DC2PI)
    DTL=fmod(DML+PHI+PERTL, DC2PI);

//  DSINLS=DSIN(DTL)
    DSINLS=sin(DTL);

//  DCOSLS=DCOS(DTL)
    DCOSLS=cos(DTL);

//  DXHD = DRD*DCOSLS-DRLD*DSINLS
    DXHD = DRD*DCOSLS-DRLD*DSINLS;

//  DYHD = DRD*DSINLS+DRLD*DCOSLS
    DYHD = DRD*DSINLS+DRLD*DCOSLS;

//  PERTL =0.0
    PERTL =0.0;
//  PERTLD=0.0
    PERTLD=0.0;
//  PERTP =0.0
    PERTP =0.0;
//  PERTPD=0.0
    PERTPD=0.0;

    //DO 500 K=1,3
    for (K = 1; K <= 3; K++) {
      //A=DMOD(DCARGM(1,K)+DT*DCARGM(2,K), DC2PI)
    A=fmod(DCARGM(1,K)+DT*DCARGM(2,K), DC2PI);

      //SINA  =DSIN(A)
    SINA  =sin(A);

      //COSA  =DCOS(A)
    COSA  =cos(A);

      //PERTL =PERTL +CCAMPM(1,K)*SINA
    PERTL =PERTL +CCAMPM(1,K)*SINA;

      //PERTLD=PERTLD+CCAMPM(2,K)*COSA
    PERTLD=PERTLD+CCAMPM(2,K)*COSA;

      //PERTP =PERTP +CCAMPM(3,K)*COSA
    PERTP =PERTP +CCAMPM(3,K)*COSA;

      //PERTPD=PERTPD-CCAMPM(4,K)*SINA
    PERTPD=PERTPD-CCAMPM(4,K)*SINA;

//  500 CONTINUE
    }
    
  //TL=FORBEL(2)+PERTL
    TL=FORBEL(2)+PERTL;

//  SINLM=DSIN(TL)
    SINLM=sin(TL);

//  COSLM=DCOS(TL)
    COSLM=cos(TL);

//  SIGMA=CCKM/(1.0+PERTP)
    SIGMA=CCKM/(1.0+PERTP);

//  A=SIGMA*(CCMLD+PERTLD)
    A=SIGMA*(CCMLD+PERTLD);

//  B=SIGMA*PERTPD
    B=SIGMA*PERTPD;

//  DXHD=DXHD+A*SINLM+B*COSLM
    DXHD=DXHD+A*SINLM+B*COSLM;

//  DYHD=DYHD-A*COSLM+B*SINLM
    DYHD=DYHD-A*COSLM+B*SINLM;

//  DZHD=    -SIGMA*CCFDI*DCOS(FORBEL(3))
    DZHD=    -SIGMA*CCFDI* cos(FORBEL(3));

//  DXBD=DXHD*DC1MME
    DXBD=DXHD*DC1MME;

//  DYBD=DYHD*DC1MME
    DYBD=DYHD*DC1MME;
//  DZBD=DZHD*DC1MME
    DZBD=DZHD*DC1MME;

//      DO 600 K=1,4
    for (K = 1; K <= 4; K++) {

      //PLON=FORBEL(K+3)
    PLON=FORBEL(K+3);

      //POMG=SORBEL(K+1)
    POMG=SORBEL(K+1);

      //PECC=SORBEL(K+9)
    PECC=SORBEL(K+9);

      //TL=DMOD(PLON+2.0*PECC*DSIN(PLON-POMG), CC2PI)
    TL=fmod(PLON+2.0*PECC* sin(PLON-POMG), CC2PI);

      //SINLP(K)=DSIN(TL)
    SINLP(K)= sin(TL);
    
      //COSLP(K)=DCOS(TL)
    COSLP(K)= cos(TL);

      //DXBD=DXBD+CCPAMV(K)*(SINLP(K)+PECC*DSIN(POMG))
    DXBD=DXBD+CCPAMV(K)*(SINLP(K)+PECC*sin(POMG));

      //DYBD=DYBD-CCPAMV(K)*(COSLP(K)+PECC*DCOS(POMG))
    DYBD=DYBD-CCPAMV(K)*(COSLP(K)+PECC*cos(POMG));

      //DZBD=DZBD-CCPAMV(K)*SORBEL(K+13)*DCOS(PLON-SORBEL(K+5))
    DZBD=DZBD-CCPAMV(K)*SORBEL(K+13)*cos(PLON-SORBEL(K+5));

//  600 CONTINUE
    }
    
  //DCOSEP=DCOS(DEPS)
    DCOSEP=cos(DEPS);
  //DSINEP=DSIN(DEPS)
    DSINEP=sin(DEPS);
  //DYAHD=DCOSEP*DYHD-DSINEP*DZHD
    DYAHD=DCOSEP*DYHD-DSINEP*DZHD;
  //DZAHD=DSINEP*DYHD+DCOSEP*DZHD
    DZAHD=DSINEP*DYHD+DCOSEP*DZHD;
  //DYABD=DCOSEP*DYBD-DSINEP*DZBD
    DYABD=DCOSEP*DYBD-DSINEP*DZBD;
  //DZABD=DSINEP*DYBD+DCOSEP*DZBD
    DZABD=DSINEP*DYBD+DCOSEP*DZBD;

  //DVELH(1)=DXHD
    DVELH[1]=DXHD;
  //DVELH(2)=DYAHD
    DVELH[2]=DYAHD;
  //DVELH(3)=DZAHD
    DVELH[3]=DZAHD;

  //DVELB(1)=DXBD
    DVELB[1]=DXBD;
  //DVELB(2)=DYABD
    DVELB[2]=DYABD;
  //DVELB(3)=DZABD
    DVELB[3]=DZABD;
  //DO 800 N=1,3
    for (N = 1; N <= 3; N++) {
      //DVELH(N)=DVELH(N)*1.4959787D8
    DVELH[N]=DVELH[N]*1.4959787E8;
      //DVELB(N)=DVELB(N)*1.4959787D8
    DVELB[N]=DVELB[N]*1.4959787E8;
//    800 CONTINUE
    }
//      RETURN
    return;
}

/*----------------------------------------------------------------------------*/
/**
   @brief    convert degrees -> degrees, minutes, seconds
   @param    in_val     the value to convert
   @param    degs       (output) degrees (integer)
   @param    minutes    (output) minutes (integer)
   @param    seconds    (output) seconds (fractional)
*/
/*----------------------------------------------------------------------------*/

static void
deg2dms(double in_val, 
    double *degs,
    double *minutes,
    double *seconds)
{
    deg2hms(in_val*15, degs, minutes, seconds);
}

/** To get the exact same behaviour as MIDAS this should
    be define'd to 1. (Fixing it does not seem to make a
    difference in the resulting numbers but do it anyway) */
#define MIDAS_BUG 0
/*----------------------------------------------------------------------------*/
/**
   @brief    convert hours -> degrees, minutes, seconds
   @param    in_val     the value to convert
   @param    hours      (output) hours (integer). 360 degrees correspond to 24 h
   @param    minutes    (output) minutes (integer)
   @param    seconds    (output) seconds (fractional)
*/
/*----------------------------------------------------------------------------*/

static void
deg2hms(double in_val, 
    double *hours,
    double *minutes,
    double *seconds)
{
//    define/parameter p1 ? num "Enter value in deg units"
//    define/local in_val/d/1/1 {p1}
//define/local out_val/c/1/80 " " all
//define/local hours/i/1/1 0
//define/local minutes/i/1/1 0
//define/local seconds/d/1/1 0

//define/local tmp/d/1/1 0
    double tmp;
//define/local hold/c/1/80 " " all
//define/local sign/c/1/1 " "

    char sign;

//hold = "{in_val}"
//if m$index(hold,"-") .gt. 0 then
//   in_val = m$abs(in_val)
//   sign = "-"
//else
//   sign = "+"
//endif      
    if (in_val < 0) {
    in_val = fabs(in_val);
    sign = '-';
    }
    else {
    sign = '+';
    }

//set/format i1
//!360 deg corresponds to 24 h=> 15 deg corresponds to 1 h
//  tmp   = in_val / 15
    tmp   = in_val / 15;

//  hours = tmp           !takes the integer part = hours
#if MIDAS_BUG
    *hours= xsh_round_double(tmp);
#else
    *hours= (int) tmp;
#endif

//  tmp   = tmp - hours   !takes the mantissa 
    tmp   = tmp - *hours;
//  tmp   = tmp * 60      !converts the mantissa in minutes
    tmp   = tmp * 60;

//  minutes = tmp         !takes the integer part = minutes
#if MIDAS_BUG
    *minutes= xsh_round_double(tmp);
#else
    *minutes= (int) tmp;
#endif

//  tmp   = tmp - minutes !takes the mantissa
    tmp   = tmp - *minutes;

//  seconds = tmp * 60      !converts the mantissa in seconds = seconds (with decimal)
    *seconds= tmp * 60;

//out_val = "{sign}{hours},{minutes},{seconds}"

    /* Rather than returning it explicitly, just  attach sign to hours */
    if (sign == '-') *hours = -(*hours);

    return;
}

/**@}*/

#if 0   /* Not used / needed.
       We simply get the julian date from the input FITS header */

//      SUBROUTINE JULDAT(INDATE,UTR,JD)
//C++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//C
//C.IDENTIFICATION
//C  FORTRAN subroutine                    JULDAT     version 1.0       870102
//C  original coding:                      D. Gillet        ESO - Garching
//C  variables renamed and restructured:   D. Baade         ST-ECF, Garching
//C
//C.KEYWORDS
//C  geocentric Julian date
//C
//C.PURPOSE
//C  calculate geocentric Julian date for any civil date (time in UT)
//C
//C.ALGORITHM
//C adapted from MEEUS J.,1980, ASTRONOMICAL FORMULAE FOR CALCULATORS
//C
//C.INPUT/OUTPUT
//C the following are passed from and to the calling program:
//C  INDATE(3)    :         civil date as year,month,day OR year.fraction
//C  UT           :         universal time expressed in real hours
//C  JD           :         real geocentric Julian date
//C
//C.REVISIONS
//C made to accept also REAL dates         D. Baade             910408
//C
//C-------------------------------------------------------------------------------
//C

static void 
juldat(double *INDATE,
       double UTR,
       double *JD)
{
//      DOUBLE PRECISION YP,P,C,A,UT
    double UT;

//      DOUBLE PRECISION UTR,JD
//C
//      INTEGER  STAT,IA,IB,IC,ND,DATE(3)
    int DATE[4];
//C
//      REAL    INDATE(3),FRAC
//C

//  UT=UTR / 24.0D0
    UT=UTR / 24.0;

// CHECK FORMAT OF DATE: may be either year,month,date OR year.fraction,0,0 
// (Note that the fraction of the year must NOT include fractions of a day.)
// For all other formats exit and terminate also calling command sequence.
//
//      IF ((INDATE(1)-INT(INDATE(1))).GT.1.0E-6) THEN 
//         IF ((INDATE(2).GT.1.0E-6).OR.(INDATE(3).GT.1.0E-6)) 
//     +       CALL   STETER(1,'Error: Date was entered in wrong format.')

// copy date input buffer copy to other buffer so that calling program 
// does not notice any changes

// FIRST CASE: format was year.fraction

//         DATE(1)=INT(INDATE(1))
//         FRAC=INDATE(1)-DATE(1)
//         DATE(2)=1
//         DATE(3)=1
//      ELSE
//
// SECOND CASE: format was year,month,day
//

//       DATE(1)=NINT(INDATE(1))
    DATE[1]=xsh_round_double(INDATE[1]);

    //FRAC=0
    FRAC = 0;

  //DATE(2)=NINT(INDATE(2))
    DATE[2]=xsh_round_double(INDATE[2]);
  //DATE(3)=NINT(INDATE(3))
    DATE[3]=xsh_round_double(INDATE[3]);

  //IF ((DATE(2).EQ.0).AND.(DATE(3).EQ.0)) THEN
    if ((DATE[2] == 0) &&  (DATE[3] == 0)) {
       //DATE(2)=1
    DATE[2]=1;
       //DATE(3)=1
    DATE[3]=1;
//    ENDIF
    }

//         IF ((DATE(2).LT.1).OR.(DATE(2).GT.12))
//     +   CALL STETER(1,'Error: such a month does not exist')
//         IF ((DATE(3).LT.1).OR.(DATE(3).GT.31))
//     +   CALL STETER(1,'Error: such a day does not exist')
//      ENDIF

// from here on, the normal procedure applies which is based on the 
// format year,month,day:

    //IF (DATE(2) .GT. 2) THEN
    if (DATE[2] > 2) {
      //YP=DATE(1)
    YP=DATE[1];
      //P=DATE[2]
    P=DATE[2];
//    ELSE
    } else {
      //YP=DATE(1)-1
    YP=DATE[1]-1;
      //P=DATE(2)+12.0
    P=DATE(2)+12.0;
//      ENDIF
    }

//  C = DATE(1) + DATE(2)*1.D-2 + DATE(3)*1.D-4 + UT*1.D-6
    C = DATE[1] + DATE[2]*1.E-2 + DATE[3]*1.E-4 + UT*1.E-6;

//  IF (C .GE. 1582.1015D0) THEN
    if (C  >   1582.1015E0) {
      //IA=IDINT(YP/100.D0)
    IA=(int) (YP/100.D0);
      //A=DBLE(IA)
    A=IA;
      //IB=2-IA+IDINT(A/4.D0)
    IB=2-IA+((int)(A/4.D0));
      //ELSE
    } else {
      //IB=0
    IB=0;
      //ENDIF
    }

//      JD = DINT(365.25D0*YP) + DINT(30.6001D0*(P+1.D0)) + DATE(3) + UT
//     *        + DBLE(IB) + 1720994.5D0
    *JD = ((int) (365.25E0*YP)) + ((int)(30.6001D0*(P+1.D0))) + DATE[3] + UT
            + IB + 1720994.5E0;

// finally, take into account fraction of year (if any), respect leap
// year conventions
//
//  IF (FRAC.GT.1.0E-6) THEN
    if (FRAC > 1.0E-6) {
      //ND=365
    ND=365;

      //IF (C.GE.1582.1015D0) THEN
    IF (C >= 1582.1015E0) {
          //IC = MOD(DATE(1),4)
        IC = DATE[1] % 4;
          //IF (IC.EQ.0) THEN
        if (IC == 0) {
          //ND=366
        ND=366;
          //IC = MOD(DATE(1),100)
        IC = DATE[1] % 100;
          //IF (IC.EQ.0) THEN
        if (IC == 0) {
          //IC = MOD(DATE(1),400)
            IC = DATE[1] % 400;
          //IF (IC.NE.0) ND=365
            if (IC != 0) ND=365;
          //ENDIF
        }
        //ENDIF
        }
        //ENDIF
    }

      //IF ( ABS(FRAC*ND-NINT(FRAC*ND)).GT.0.3) THEN
    if (fabs(FRAC*ND-xsh_round_double(FRAC*ND)) > 0.3) {
//            CALL STTPUT
//     +      ('Warning: Fraction of year MAY not correspond to ',STAT)
//            CALL STTPUT('         integer number of days.',STAT)
        xsh_msg_warning("Fraction of year MAY not correspond to "
                 "integer number of days");
//         ENDIF
    }

//      JD = JD+NINT(FRAC*ND)
    *JD = *JD+xsh_round_double(FRAC*ND);
//      ENDIF
    }

//      RETURN
    return;
}
#endif
