#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
/*--------------------------------------------------------------------------------
 *
 *  File: xCC.c
 *  Author: Arnold Rots, USRA
 *  Date:   1 April 1997
 *
 *  xCC is a function that calculates the RXTE clock corrections for a given MET,
 *  based on the coefficients in tdc.dat.
 *  It is assumed that this file exists in the directory $TIMING_DIR.
 *
 *  int xCC (double t, double *tZero, double *tc)
 *    Input parameter:
 *      double t     time in MET seconds
 *    Output parameters:
 *      double *tZero   value of TIMEZERO for time t; correction in seconds
 *      double *tc      fine clock correction for time t; correction in microseconds
 *    Returns:
 *      0               ok
 *      non-zero        error
 *
 *  If one has a FITS file to which tZero has been applied already, only *tc
 *  needs to be added to the times.
 *  The sense of the corrections is always such that they should be added to the
 *  time stamps in order to get corrected times.
 *
 *-------------------------------------------------------------------------------*/
int xCC (double t, double *tZero, double *tc)
{

  FILE *tdc ;

  char inf[1025] ;
  double subday, m0, m1, m2, end, t0 ;
  double modt, corr = -999999 ;
  int error = 0 ;

/*  sprintf (inf, "%s/tdc.dat", getenv("TIMING_DIR")) ; */
  if ( !( tdc = fopen (inf, "r") ) ) {
    error = -1 ;
    corr = 0 ;
  }

  while ( !error && ( fscanf (tdc, "%lg %lg %lg %lg", &m0, &m1, &m2, &end) ) ) {
    if ( end < 0.0 ) {
      if ( m0 < 0.0 ) {
	error = 2 ;
	break ;
      }
      else {
	subday = m0 ;
	modt = t / 86400.0 - subday ;
	t0 = m1 ;
      }
    }
    else {
      if ( modt < end ) {
	corr = m0 + m1 * modt + m2 * modt * modt ;
	break ;
      }
    }
  }

  if ( error || ( corr == -999999 ) ) {
/*     printf ("Corrections for this time:\n Not Available\n") ; */
    corr = 0 ;
    error-- ;
  }
/*  If one were to calculate corrections for PCA or HEXTE specifically, the following
 *  should be added to *tc
 */
/*  else {
    printf ("TimeZero: %f seconds\n", t0) ;
    printf ("PCA: %d microseconds; HEXTE %d microseconds\n",
	    (long) corr - 16, (long) corr) ;
  }
*/
  fclose (tdc) ;

  *tZero = t0 ;
  *tc = corr ;

  return error ;
}
