Index: trunk/psLib/src/astro/psTime.c
===================================================================
--- trunk/psLib/src/astro/psTime.c	(revision 20595)
+++ trunk/psLib/src/astro/psTime.c	(revision 22678)
@@ -9,13 +9,11 @@
  *
  *  @author Ross Harman, MHPCC
+ *  @author Paul Price, IfA
  *
- *  @version $Revision: 1.117 $ $Name: not supported by cvs2svn $
- *  @date $Date: 2008-11-09 00:30:07 $
- *
- *  Copyright 2004-2005 Maui High Performance Computing Center, University of Hawaii
+ *  Copyright 2004-2009 Institute for Astronomy, University of Hawaii
  */
 
 #ifdef HAVE_CONFIG_H
-# include "config.h"
+#include "config.h"
 #endif
 
@@ -39,54 +37,29 @@
 #include "psAssert.h"
 
-#define MAX_STRING_LENGTH 256
-
-/** Sidereal angular conversion from seconds to radians for GMST in seconds (i.e. pi/(180*240)) */
-#define S2R (7.272205216643039903848711535369e-5)
-
-/** Two times pi with double precision accuracy */
-#define TWOPI (2.0*M_PI)
-
-/** Conversion from radians to degrees */
-#define R2DEG = (180.0/M_PI)
-
-/** Maximum length of time string */
-#define MAX_TIME_STRING_LENGTH 256
-
-/** Seconds per minute */
-#define  SEC_PER_MINUTE 60.0
-
-/** Seconds per hour */
-#define  SEC_PER_HOUR (60.0*SEC_PER_MINUTE)
-
-/** Seconds per day */
-#define  SEC_PER_DAY (24.0*SEC_PER_HOUR)
-
-/** Seconds per year */
-#define  SEC_PER_YEAR (365.0*SEC_PER_DAY)
-
-/** Microseconds per day */
-#define NSEC_PER_DAY 86400000000000.0
-
-// Time config file path
-static char *timeConfig = NULL;
-
-/** Time metadata read from config file */
-static psMetadata *timeMetadata = NULL;
-
-// Offset to convert terrestrial time(TT) to international atomic time(TAI)
-#define  TAI_TT_OFFSET_SECONDS        32
-#define  TAI_TT_OFFSET_NANOSECONDS    184000000
-
-// Offset from converting to MJD
-#define  MJD_EPOCH_OFFSET             40587.0
-
-// Offset for converting to JD
-#define  JD_EPOCH_OFFSET              2440587.5
-
-// Offset of year 0000 from epoch
-#define YEAR_0000_SEC                 -62125920000
-
-// Offset of year 9999 from epoch
-#define YEAR_9999_SEC                 253202544000
+
+#define S2R (M_PI / (180.0 * 240.0))    /// Sidereal conversion: GMST in seconds to radians
+#define R2DEG = (180.0/M_PI)            /// Conversion from radians to degrees
+#define MAX_STRING_LENGTH 256           /// Maximum length of string
+#define MAX_TIME_STRING_LENGTH 256      /// Maximum length of time string
+#define SEC_PER_MINUTE 60.0             /// Seconds per minute
+#define SEC_PER_HOUR (60.0*SEC_PER_MINUTE) /// Seconds per hour
+#define SEC_PER_DAY (24.0*SEC_PER_HOUR) /// Seconds per day
+#define SEC_PER_YEAR (365.0*SEC_PER_DAY) /// Seconds per year
+#define NSEC_PER_DAY (SEC_PER_DAY * 1000000000.0) /// Nanoseconds per day
+
+#define MJD_EPOCH_OFFSET 40587.0        // Offset from converting to MJD
+#define JD_EPOCH_OFFSET 2440587.5       // Offset for converting to JD
+#define YEAR_0000_SEC -62125920000      // Offset of year 0000 from epoch
+#define YEAR_9999_SEC 253202544000      // Offset of year 9999 from epoch
+
+// Offset to convert terrestrial time (TT) to international atomic time (TAI)
+#define TAI_TT_OFFSET_SECONDS        32
+#define TAI_TT_OFFSET_NANOSECONDS    184000000
+
+
+// Static global variables
+static char *timeConfig = NULL;         // Time config file path
+static psMetadata *timeMetadata = NULL; // Time metadata read from config file
+
 
 /** Static function prototypes */
@@ -99,25 +72,22 @@
 static psTime* convertTimeUTCUT1(psTime* time);
 
-static bool p_psTimeInit(const char *fileName);
+static bool timeInit(const char *fileName);
 
 /** Removes leading and trailing whitespace and # characters from a string. The cleaned string is a new null
  *  terminated copy of the original input string. */
-static char *cleanString(char *inString,
-                         int sLen)
-{
-    char *ptrB = NULL;
-    char *ptrE = NULL;
-    char *cleaned = NULL;
-
-    ptrB = inString;
+static char *cleanString(char *inString,// Input string
+                         int sLen       // Length of string
+                         )
+{
+    char *ptrB = inString;              // Pointer to start
 
     // Skip over leading # or whitespace
-    while (isspace(*ptrB) || *ptrB=='#') {
+    while (isspace(*ptrB) || *ptrB == '#') {
         ptrB++;
     }
 
     // Skip over trailing whitespace, null terminators, and # characters
-    ptrE = inString + sLen - 1;
-    while(isspace(*ptrE) || *ptrE=='\0' || *ptrE=='#') {
+    char *ptrE = inString + sLen - 1;   // Pointer to end
+    while (isspace(*ptrE) || *ptrE == '\0' || *ptrE == '#') {
         ptrE--;
     }
@@ -127,39 +97,31 @@
 
     // Adds '\0' to end of string and +1 to sLen
-    cleaned = psStringNCopy(ptrB, sLen);
-
-    return cleaned;
+    return psStringNCopy(ptrB, sLen);
 }
 
 /** Returns cleaned token based on delimiter, but not including delimiter. Also changes the pointer location
  * the beginning of the string. Tokens are newly allocated null terminated strings. */
-static char* getToken(char **inString,
-                      char *delimiter,
-                      psParseErrorType *status)
-{
-    char *cleanToken = NULL;
-    int sLen = 0;
-
+static char* getToken(char **inString,  // Input string
+                      char *delimiter,  // Delimiter
+                      psParseErrorType *status // Parsing status, returned
+                      )
+{
     // Skip over leading whitespace
-    while(isspace(**inString)) {
+    while (isspace(**inString)) {
         (*inString)++;
     }
 
-    // Length of token, not including delimiter
-    sLen = strcspn(*inString, delimiter);
-
-    if(sLen) {
-
+    int sLen = strcspn(*inString, delimiter); // Length of token, not including delimiter
+    char *cleanToken = NULL;            // Token, cleaned of delimiters
+    if (sLen) {
         // Create new, cleaned, and null terminated token
         cleanToken = cleanString(*inString, sLen);
 
         // Move to end of token
-        //        (*inString) += (sLen+1);
         (*inString) += sLen;
         if (**inString != '\0' ) {
             (*inString)++;
         }
-
-    } else if(**inString!='\0' && sLen==0) {
+    } else if (**inString != '\0' && sLen == 0) {
         *status = PS_PARSE_ERROR_GENERAL;
     }
@@ -210,5 +172,5 @@
 
     // Check if psTime tables are already loaded
-    if(!p_psTimeInit(p_psTimeConfigFilename(NULL))) {
+    if (!timeInit(p_psTimeConfigFilename(NULL))) {
         *status = PS_LOOKUP_ERROR;
         return NAN;
@@ -225,5 +187,5 @@
 
         // Check if table not a metadata item
-        if(tableMetadataItem == NULL) {
+        if (tableMetadataItem == NULL) {
             psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Failed find '%s' in time metadata."),
                     tableName);
@@ -239,10 +201,10 @@
 
         // Check if index within to/from range
-        if(index >= table->validFrom ) {
-            if(index <= table->validTo) {
+        if (index >= table->validFrom ) {
+            if (index <= table->validTo) {
                 // Attempt to interpolate table
                 result = psLookupTableInterpolate(table, index, column);
                 *status = PS_LOOKUP_SUCCESS;
-                if(!isnan(result)) {
+                if (!isnan(result)) {
                     break;
                 }
@@ -258,5 +220,5 @@
 }
 
-bool p_psTimeInit(const char *fileName)
+static bool timeInit(const char *fileName)
 {
     psS32 numLines = 0;
@@ -270,7 +232,4 @@
     char *tableName = NULL;
     char *tableFormat = NULL;
-    char *fullTableName = NULL;
-    psS32 i = 0;
-    psS32 j = 0;
     psS32 numTables = 0;
     psU32 nFail = 0;
@@ -283,18 +242,21 @@
     char metadataTableNames[4][MAX_STRING_LENGTH] = {"daily", "eopc",  "finals", "tai"};
 
-    // Check if the p_psTimeInit has already been ran
-    if (timeMetadata != NULL) {
+    // Check if the timeInit has already been run
+    if (timeMetadata) {
         return true;
     }
 
+    // All memory allocated below is "persistent"
     // XXX this is not thread safe as the persistence setting is global
-    const bool initialPersistence =
-        p_psMemAllocatePersistent(true); // All memory allocated below is "persistent"
+    const bool initialPersistence = p_psMemAllocatePersistent(true); // Initial setting of persistence
 
     // Read config file
     timeMetadata = psMetadataConfigRead(timeMetadata, &nFail, fileName, true);
-    if(timeMetadata == NULL) {
+    if (!timeMetadata) {
+        psError(PS_ERR_IO, false, "Unable to read time configuration file %s", fileName);
         return false;
-    } else if(nFail != 0) {
+    } else if (nFail != 0) {
+        psError(PS_ERR_IO, false, "Failed to parse %d lines reading time configuration file %s",
+                nFail, fileName);
         return false;
     }
@@ -302,5 +264,5 @@
     // Get number of tables
     metadataItem = psMetadataLookup(timeMetadata, "psLib.time.tables.n");
-    if(metadataItem == NULL) {
+    if (metadataItem == NULL) {
         p_psMemAllocatePersistent(initialPersistence);
         psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Failed find '%s' in time metadata."),
@@ -312,5 +274,5 @@
     // Get lower range of tables
     metadataItem = psMetadataLookup(timeMetadata, "psLib.time.tables.from");
-    if(metadataItem == NULL) {
+    if (metadataItem == NULL) {
         p_psMemAllocatePersistent(initialPersistence);
         psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Failed find '%s' in time metadata."),
@@ -319,5 +281,5 @@
     }
     tablesFrom = psVectorCopy(tablesFrom, metadataItem->data.V, PS_TYPE_F64);
-    if(tablesFrom->n != numTables) {
+    if (tablesFrom->n != numTables) {
         p_psMemAllocatePersistent(initialPersistence);
         psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Incorrect vector size. Size: %ld, Expected %d."), tablesFrom->n, numTables);
@@ -328,5 +290,5 @@
     // Get upper range of tables
     metadataItem = psMetadataLookup(timeMetadata, "psLib.time.tables.to");
-    if(metadataItem == NULL) {
+    if (metadataItem == NULL) {
         p_psMemAllocatePersistent(initialPersistence);
         psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Failed find '%s' in time metadata."),
@@ -336,5 +298,5 @@
     }
     tablesTo = psVectorCopy(tablesTo, metadataItem->data.V, PS_TYPE_F64);
-    if(tablesTo->n != numTables) {
+    if (tablesTo->n != numTables) {
         p_psMemAllocatePersistent(initialPersistence);
         psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Incorrect vector size. Size: %ld, Expected %d."), tablesTo->n, numTables);
@@ -346,5 +308,5 @@
     // Get index columns for the tables
     metadataItem = psMetadataLookup(timeMetadata, "psLib.time.tables.index");
-    if(metadataItem == NULL) {
+    if (metadataItem == NULL) {
         p_psMemAllocatePersistent(initialPersistence);
         psError(PS_ERR_BAD_PARAMETER_VALUE,true,_("Failed find '%s' in time metadata."),
@@ -355,5 +317,5 @@
     }
     tablesIndex = psVectorCopy(tablesIndex, metadataItem->data.V, PS_TYPE_S32);
-    if(tablesIndex->n != numTables) {
+    if (tablesIndex->n != numTables) {
         p_psMemAllocatePersistent(initialPersistence);
         psError(PS_ERR_BAD_PARAMETER_VALUE,true,_("Incorrect vector size. Size: %ld, Expected %d."),tablesIndex->n,numTables);
@@ -366,5 +328,5 @@
     // Get path to time data files
     metadataItem = psMetadataLookup(timeMetadata, "psLib.time.tables.dir");
-    if(metadataItem == NULL) {
+    if (metadataItem == NULL) {
         p_psMemAllocatePersistent(initialPersistence);
         psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Failed find '%s' in time metadata."),
@@ -379,5 +341,5 @@
     // Table file names
     metadataItem = psMetadataLookup(timeMetadata, "psLib.time.tables.files");
-    if(metadataItem == NULL) {
+    if (metadataItem == NULL) {
         p_psMemAllocatePersistent(initialPersistence);
         psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Failed find '%s' in time metadata."),
@@ -394,5 +356,5 @@
     // Get table format strings
     metadataItem = psMetadataLookup(timeMetadata, "psLib.time.tables.format");
-    if(metadataItem == NULL) {
+    if (metadataItem == NULL) {
         p_psMemAllocatePersistent(initialPersistence);
         psError(PS_ERR_BAD_PARAMETER_VALUE,true, _("Failed find '%s' in time metadata."),
@@ -411,20 +373,13 @@
     bool no_problem = true;  // True if we've detected no errors
     namesPtr = tableNames;
-    while((tableName=getToken(&namesPtr, " ", &status)) != NULL) {
-
-        // Form path with table name, adding one to length for last '/' that may not occur
-        // in string in cong file
-        fullTableName = (char*)psAlloc(strlen(tableDir)+strlen(tableName)+1+1);
-
-        // Old strings may come back from psAlloc(), so set initial position to EOL
-        fullTableName[0]='\0';
-        strcat(fullTableName, tableDir);
-        strcat(fullTableName, "/");
-        strcat(fullTableName, tableName);
+    int i;                              // Iterator
+    for (i = 0; (tableName = getToken(&namesPtr, " ", &status)) != NULL; i++) {
+        psString fullTableName = NULL;  // Full path for table
+        psStringAppend(&fullTableName, "%s/%s", tableDir, tableName);
 
         // Get table format
-        tableFormat = getToken(&formatPtr,",",&status);
-        if(tableFormat == NULL) {
-            psError(PS_ERR_BAD_PARAMETER_VALUE,no_problem,_("Failed find '%s' in time metadata."),
+        tableFormat = getToken(&formatPtr, ",", &status);
+        if (!tableFormat) {
+            psError(PS_ERR_BAD_PARAMETER_VALUE, no_problem, _("Failed find '%s' in time metadata."),
                     "psLib.time.tables.format");
             no_problem = false;
@@ -432,10 +387,10 @@
 
         // Create and read table
-        if(i < numTables) {
+        if (i < numTables) {
             table = psLookupTableAlloc(fullTableName, (const char*)tableFormat, tablesIndex->data.S32[i]);
             numLines = psLookupTableRead(table);
         } else {
             psError(PS_ERR_BAD_PARAMETER_VALUE, no_problem,
-                    _("Incorrect number of table files entered. Found: %d. Expected: %d."), i+1, numTables);
+                    _("Incorrect number of table files entered. Found: %d. Expected: %d."), i + 1, numTables);
             no_problem = false;
         }
@@ -443,11 +398,11 @@
         // Place tables into metadata slightly altered names as keys to create consistent naming conventions
         foundTable = false;
-        for(j=0; j<numTables; j++) {
+        for (int j = 0; j < numTables; j++) {
             metadataNamesPtr = strstr(tableName, metadataTableNames[j]);
-            if(metadataNamesPtr != NULL) {
+            if (metadataNamesPtr != NULL) {
                 psMetadataAdd(timeMetadata, PS_LIST_TAIL, strcat(metadataTableNames[j], "Table"),
                               PS_DATA_LOOKUPTABLE, NULL, table);
                 foundTable = true;
-            } else if(foundTable==false && j==numTables-1) {
+            } else if (foundTable == false && j == numTables - 1) {
                 psError(PS_ERR_BAD_PARAMETER_VALUE, no_problem,
                         _("Incorrect number of table files entered. Found: %d. Expected: %d."), j, numTables);
@@ -460,11 +415,12 @@
         psFree(tableFormat);
         psFree(table);
-        i++;
     }
 
     p_psMemAllocatePersistent(initialPersistence);
 
-    if(numTables != i) {
-        psError(PS_ERR_BAD_PARAMETER_VALUE, no_problem, _("Incorrect number of table files entered. Found: %d. Expected: %d."), i, numTables);
+    if (numTables != i) {
+        psError(PS_ERR_BAD_PARAMETER_VALUE, no_problem,
+                _("Incorrect number of table files entered. Found: %d. Expected: %d."),
+                i, numTables);
     }
 
@@ -481,5 +437,5 @@
 bool p_psTimeFinalize(void)
 {
-    if(timeMetadata != NULL) {
+    if (timeMetadata != NULL) {
         psFree(timeMetadata);
         timeMetadata = NULL;
@@ -496,18 +452,21 @@
 psTime* psTimeAlloc(psTimeType type)
 {
-    psTime *outTime = NULL;
-
     // Error checks
-    if(type!=PS_TIME_TAI && type!=PS_TIME_UTC && type!=PS_TIME_UT1 &&
-            type!=PS_TIME_TT) {
-        psError(PS_ERR_BAD_PARAMETER_VALUE, true,
-                _("Specified type, %d, is not supported."),
-                type);
-        return NULL;
+    switch (type) {
+      case PS_TIME_TAI:
+      case PS_TIME_UTC:
+      case PS_TIME_UT1:
+      case PS_TIME_TT:
+        // No action
+        break;
+      default:
+        // Since we can never return NULL from an allocator
+        psAbort("Specified type, %d, is not supported.", type);
     }
 
     // Allocate memory for structure
-    outTime = (psTime*)psAlloc(sizeof(psTime));
+    psTime *outTime = psAlloc(sizeof(psTime));
     psMemSetDeallocator(outTime, (psFreeFunc)timeFree);
+
     // Initialize members
     outTime->sec = 0;
@@ -522,5 +481,5 @@
 bool psMemCheckTime(psPtr ptr)
 {
-    return ( psMemGetDeallocator(ptr) == (psFreeFunc)timeFree );
+    return (psMemGetDeallocator(ptr) == (psFreeFunc)timeFree);
 }
 
@@ -528,17 +487,6 @@
 psTime* psTimeGetNow(psTimeType type)
 {
-    struct timeval now;
-    psTime *time = NULL;
-
-    // Allocate psTime struct
-    time = psTimeAlloc(type);
-
-    // Verify time structure allocated
-    if(time == NULL) {
-        return NULL;
-    }
-
     // Get the system time
-    //    if (gettimeofday(&now, (struct timezone *)0) == -1) {
+    struct timeval now;                 // Current time
     if (gettimeofday(&now, 0) == -1) {
         psError(PS_ERR_OS_CALL_FAILED, true,
@@ -547,10 +495,13 @@
     }
 
+    // Allocate psTime struct
+    psTime *time = psTimeAlloc(type);   // Container for current time
+
     // Convert timeval time to psTime
     time->sec = now.tv_sec;
-    time->nsec = now.tv_usec*1000;
+    time->nsec = now.tv_usec * 1000;
 
     // Add most leapseconds to UTC time to get TAI time if necessary
-    if(type == PS_TIME_TAI) {
+    if (type == PS_TIME_TAI) {
         time->sec += p_psTimeGetTAIDelta(time);
     }
@@ -575,5 +526,5 @@
 
     // Check for underflow in nsec
-    if(deltaNsec > time->nsec) {
+    if (deltaNsec > time->nsec) {
         // Borrow second
         time->nsec += 1e9;
@@ -585,5 +536,5 @@
 
     // Check for overflow in nsec
-    if(time->nsec >= 1e9) {
+    if (time->nsec >= 1e9) {
         time->nsec -= 1e9;
         time->sec++;
@@ -595,5 +546,5 @@
     // Check if leapsecond present in delta
     deltaUTC = p_psTimeGetTAIDelta(time);
-    if(fabs(deltaTAI-deltaUTC) >= 1.0) {
+    if (fabs(deltaTAI-deltaUTC) >= 1.0) {
         time->sec++;
     }
@@ -621,5 +572,5 @@
 
     // Check for overflow in nsec
-    if(time->nsec >= 1e9) {
+    if (time->nsec >= 1e9) {
         time->nsec -= 1e9;
         time->sec++;
@@ -641,5 +592,5 @@
 
     // Check for overflow in nsec
-    if(time->nsec >= 1e9) {
+    if (time->nsec >= 1e9) {
         time->nsec -= 1e9;
         time->sec++;
@@ -658,5 +609,5 @@
 
     // Check for nsec underflow
-    if(TAI_TT_OFFSET_NANOSECONDS > time->nsec) {
+    if (TAI_TT_OFFSET_NANOSECONDS > time->nsec) {
         // Borrow second
         time->sec--;
@@ -666,5 +617,5 @@
 
     // Check for overflow in nsec
-    if(time->nsec >= 1e9) {
+    if (time->nsec >= 1e9) {
         time->nsec -= 1e9;
         time->sec++;
@@ -685,8 +636,8 @@
 
     // Since UTC is within 0.9 sec of UT1 then nsec member is the member affected
-    if((ut1utc < 0) && (abs(ut1utc) > time->nsec)) {
+    if ((ut1utc < 0) && (abs(ut1utc) > time->nsec)) {
         // Borrow from sec
         time->sec--;
-        if(time->leapsecond) {
+        if (time->leapsecond) {
             time->leapsecond = false;
         } else {
@@ -699,8 +650,8 @@
 
     // Check for overflow in nsec
-    if(time->nsec >= 1e9) {
+    if (time->nsec >= 1e9) {
         time->nsec -= 1e9;
         time->sec++;
-        if(time->leapsecond) {
+        if (time->leapsecond) {
             time->leapsecond = false;
             time->sec--;
@@ -724,5 +675,5 @@
 
     // If the input type is UT1 then return time and generate error message
-    if(time->type == PS_TIME_UT1) {
+    if (time->type == PS_TIME_UT1) {
         psError(PS_ERR_BAD_PARAMETER_VALUE,true,"Cannot convert from UT1 time type");
         return NULL;
@@ -735,13 +686,13 @@
 
     // Convert from TAI to UTC, TT, UT1
-    if(time->type == PS_TIME_TAI) {
+    if (time->type == PS_TIME_TAI) {
         // Convert from TAI to UTC
-        if(type == PS_TIME_UTC) {
+        if (type == PS_TIME_UTC) {
             time = convertTimeTAIUTC(time);
             // Convert from TAI to TT
-        } else if(type == PS_TIME_TT) {
+        } else if (type == PS_TIME_TT) {
             time = convertTimeTAITT(time);
             // Convert from TAI to UT1
-        } else if(type == PS_TIME_UT1) {
+        } else if (type == PS_TIME_UT1) {
             // Convert to UTC first
             time = convertTimeTAIUTC(time);
@@ -754,7 +705,7 @@
         }
         // Convert from TT to TAI, UTC, UT1
-    } else if(time->type == PS_TIME_TT) {
+    } else if (time->type == PS_TIME_TT) {
         // Convert from TT to UTC
-        if(type == PS_TIME_UTC) {
+        if (type == PS_TIME_UTC) {
             // Convert to TAI time first
             time = convertTimeTTTAI(time);
@@ -762,8 +713,8 @@
             time = convertTimeTAIUTC(time);
             // Convert from TT to TAI
-        } else if(type == PS_TIME_TAI) {
+        } else if (type == PS_TIME_TAI) {
             time = convertTimeTTTAI(time);
             // Convert from TT to UT1
-        } else if(type == PS_TIME_UT1) {
+        } else if (type == PS_TIME_UT1) {
             // Convert to UTC first
             // Convert to TAI time first
@@ -779,10 +730,10 @@
         }
         // Convert from UTC to TAI, TT, UT1
-    } else if(time->type == PS_TIME_UTC) {
+    } else if (time->type == PS_TIME_UTC) {
         // Convert UTC to TAI
-        if(type == PS_TIME_TAI) {
+        if (type == PS_TIME_TAI) {
             time = convertTimeUTCTAI(time);
             // Convert UTC to TT
-        } else if(type == PS_TIME_TT) {
+        } else if (type == PS_TIME_TT) {
             // Convert to TAI time first
             time = convertTimeUTCTAI(time);
@@ -790,5 +741,5 @@
             time = convertTimeTAITT(time);
             // Convert UTC to UT1
-        } else if(type == PS_TIME_UT1) {
+        } else if (type == PS_TIME_UT1) {
             time = convertTimeUTCUT1(time);
             // Convert UTC to unknown time type
@@ -831,5 +782,5 @@
 
     // Verify input time is not in UT1 seconds
-    if(time->type == PS_TIME_UT1) {
+    if (time->type == PS_TIME_UT1) {
         psError(PS_ERR_BAD_PARAMETER_VALUE,true,_("Specified type, %d, is incorrect."),time->type);
         return NAN;
@@ -864,9 +815,9 @@
     // Calculate Greenwich Mean Sidereal Time (GMST) in radians.
     // Equation set up to minimize multiplications.
-    gmstRad = fracDays*TWOPI
-              + (const1+const2*tu+t*(const3+t*(const4+t*(const5+const6*t))))*S2R;
+    gmstRad = fracDays * 2 * M_PI +
+        (const1 + const2 * tu + t * (const3 + t * (const4 + t * (const5 + const6 * t)))) * S2R;
 
     // Place GMST between 0 and 2*pi
-    gmstRad = fmod(gmstRad, TWOPI);
+    gmstRad = fmod(gmstRad, 2 * M_PI);
 
     // Calculate Local Mean Sidereal Time (LMST) in radians
@@ -899,5 +850,5 @@
 
     // Check for invalid bulletin specified
-    if((bulletin != PS_IERS_A) && (bulletin != PS_IERS_B)) {
+    if ((bulletin != PS_IERS_A) && (bulletin != PS_IERS_B)) {
         psError(PS_ERR_BAD_PARAMETER_VALUE,true,"Invalid bulletin specified %d",bulletin);
         return NAN;
@@ -905,5 +856,5 @@
 
     // Check if psTime tables are already loaded
-    if(!p_psTimeInit(p_psTimeConfigFilename(NULL))) {
+    if (!timeInit(p_psTimeConfigFilename(NULL))) {
         psError(PS_ERR_UNKNOWN, true, "failed to init time tables.");
         return NAN;
@@ -911,5 +862,5 @@
 
     // Set lookup table column based on Bullentin
-    if(bulletin == PS_IERS_A) {
+    if (bulletin == PS_IERS_A) {
         tableColumn = 3;
     } else {
@@ -922,5 +873,5 @@
 
     // Value could not be found through table lookup and interpolation
-    if(status == PS_LOOKUP_PAST_TOP) {
+    if (status == PS_LOOKUP_PAST_TOP) {
 
         // Date too early for tables. Get default time delta value from metadata, and issue warning.
@@ -929,5 +880,5 @@
         // Lookup value from time metadata loaded from pslib.config
         tableMetadataItem = psMetadataLookup(timeMetadata, "psLib.time.before.dut");
-        if(tableMetadataItem == NULL) {
+        if (tableMetadataItem == NULL) {
             psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Failed find '%s' in time metadata."),
                     "psLib.time.before.dut");
@@ -936,5 +887,5 @@
         result = tableMetadataItem->data.F64;
 
-    } else if(status == PS_LOOKUP_PAST_BOTTOM) {
+    } else if (status == PS_LOOKUP_PAST_BOTTOM) {
         /* Date too late for tables. Issue warning and use following formulae for predicting
            ahead of the most recent available table entry.
@@ -949,5 +900,5 @@
         // Lookup values to calculate prediction
         tableMetadataItem = psMetadataLookup(timeMetadata, "psLib.time.predict.dut");
-        if(tableMetadataItem == NULL) {
+        if (tableMetadataItem == NULL) {
             psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Failed find '%s' in time metadata."),
                     "psLib.time.predict.dut");
@@ -958,9 +909,10 @@
 
         // Calculate predication of future UT1-UTC
-        t = 2000.0 + (mjd - 51544.03)/365.2422;
-        dut2ut1 = 0.022*sin(TWOPI*t) - 0.012*cos(TWOPI*t) - 0.006*sin(4.0*M_PI*t) + 0.007*cos(4.0*M_PI*t);
-        result = dut->data.F64[0] + dut->data.F64[1]*(mjd - dut->data.F64[2]) - dut2ut1;
-
-    } else if(status != PS_LOOKUP_SUCCESS) {
+        t = 2000.0 + (mjd - 51544.03) / 365.2422;
+        dut2ut1 = 0.022 * sin(2 * M_PI * t) - 0.012 * cos(2 * M_PI * t) -
+            0.006 * sin(4.0 * M_PI * t) + 0.007 * cos(4.0 * M_PI * t);
+        result = dut->data.F64[0] + dut->data.F64[1] * (mjd - dut->data.F64[2]) - dut2ut1;
+
+    } else if (status != PS_LOOKUP_SUCCESS) {
         psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Failed time table interpolation."));
         return NAN;
@@ -1086,5 +1038,5 @@
     PS_ASSERT_INT_WITHIN_RANGE(time->nsec,0,(psU32)((1e9)-1),NULL);
 
-    if(time->type != PS_TIME_TAI) {
+    if (time->type != PS_TIME_TAI) {
         psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Specified type, %d, is incorrect."), time->type);
         return NULL;
@@ -1092,5 +1044,5 @@
 
     // Check if psTime tables are already loaded
-    if(!p_psTimeInit(p_psTimeConfigFilename(NULL))) {
+    if (!timeInit(p_psTimeConfigFilename(NULL))) {
         psError(PS_ERR_UNKNOWN, true, "failed to init time tables.");
         return NULL;
@@ -1105,5 +1057,5 @@
 
     // Value could not be found through table lookup and interpolation
-    if(xStatus==PS_LOOKUP_PAST_TOP && yStatus==PS_LOOKUP_PAST_TOP) {
+    if (xStatus==PS_LOOKUP_PAST_TOP && yStatus==PS_LOOKUP_PAST_TOP) {
 
         // Date too earlier for tables. Get default polar coodinate values from metadata, and issue warning.
@@ -1117,5 +1069,5 @@
 
         tableMetadataItem = psMetadataLookup(timeMetadata, "psLib.time.before.xp");
-        if(tableMetadataItem == NULL) {
+        if (tableMetadataItem == NULL) {
             psError(PS_ERR_BAD_PARAMETER_VALUE, true,
                     _("Failed find '%s' in time metadata."), "psLib.time.before.xp");
@@ -1125,5 +1077,5 @@
 
         tableMetadataItem = psMetadataLookup(timeMetadata, "psLib.time.before.yp");
-        if(tableMetadataItem == NULL) {
+        if (tableMetadataItem == NULL) {
             psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Failed find '%s' in time metadata."), "psLib.time.before.yp");
             return NULL;
@@ -1131,5 +1083,5 @@
         y = tableMetadataItem->data.F64;
 
-    } else if(xStatus==PS_LOOKUP_PAST_BOTTOM && yStatus==PS_LOOKUP_PAST_BOTTOM) {
+    } else if (xStatus==PS_LOOKUP_PAST_BOTTOM && yStatus==PS_LOOKUP_PAST_BOTTOM) {
 
         /* Date too late for tables. Issue warning and use following formulae for predicting
@@ -1154,5 +1106,5 @@
         // Get predicted MJD
         tableMetadataItem = psMetadataLookup(timeMetadata, "psLib.time.predict.mjd");
-        if(tableMetadataItem == NULL) {
+        if (tableMetadataItem == NULL) {
             psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Failed find '%s' in time metadata."),
                     "psLib.time.predict.mjd");
@@ -1163,5 +1115,5 @@
         // Get xp
         tableMetadataItem = psMetadataLookup(timeMetadata, "psLib.time.predict.xp");
-        if(tableMetadataItem == NULL) {
+        if (tableMetadataItem == NULL) {
             psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Failed find '%s' in time metadata."), "psLib.time.predict.xp");
             return NULL;
@@ -1172,5 +1124,5 @@
         // Get yp
         tableMetadataItem = psMetadataLookup(timeMetadata, "psLib.time.predict.yp");
-        if(tableMetadataItem == NULL) {
+        if (tableMetadataItem == NULL) {
             psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Failed find '%s' in time metadata."), "psLib.time.predict.yp");
             return NULL;
@@ -1180,6 +1132,6 @@
 
         // Calculate "a" and "c" constants
-        a = TWOPI*(mjd - mjdPred)/365.25;
-        c = TWOPI*(mjd - mjdPred)/435.0;
+        a = 2 * M_PI * (mjd - mjdPred) / 365.25;
+        c = 2 * M_PI * (mjd - mjdPred) / 435.0;
 
         // Calculate x and y polar coordinates
@@ -1196,5 +1148,5 @@
             yp->data.F64[4]*sin(c);
 
-    } else if(xStatus!=PS_LOOKUP_SUCCESS || yStatus!=PS_LOOKUP_SUCCESS) {
+    } else if (xStatus!=PS_LOOKUP_SUCCESS || yStatus!=PS_LOOKUP_SUCCESS) {
         psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Failed time table interpolation."));
         return NULL;
@@ -1226,5 +1178,5 @@
 
     // Check if psTime tables are loaded/loadable
-    if (!p_psTimeInit(p_psTimeConfigFilename(NULL))) {
+    if (!timeInit(p_psTimeConfigFilename(NULL))) {
         psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Failed to open file %s."),
                 p_psTimeConfigFilename(NULL));
@@ -1234,5 +1186,5 @@
     // Get table from metadata
     tableMetadataItem = psMetadataLookup(timeMetadata, "taiTable");
-    if(tableMetadataItem == NULL) {
+    if (tableMetadataItem == NULL) {
         psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Failed find '%s' in time metadata."), "taiTable");
         return NAN;
@@ -1242,5 +1194,5 @@
 
     // Determine Julian and modified Julian dates used in table lookup and time delta calculation
-    if(time->sec < 0) {
+    if (time->sec < 0) {
         // psTime earlier than epoch
         jd = time->sec / SEC_PER_DAY - time->nsec / NSEC_PER_DAY + JD_EPOCH_OFFSET;
@@ -1253,5 +1205,5 @@
 
     // Set ceiling of the julian date to the last entry in the lookup table
-    if(table->validTo < jd) {
+    if (table->validTo < jd) {
         jd = table->validTo;
     }
@@ -1261,5 +1213,5 @@
 
     // Check for successful interpolation
-    if(results == NULL) {
+    if (results == NULL) {
         psError(PS_ERR_BAD_PARAMETER_VALUE, true, _("Failed time table interpolation."));
         return NAN;
@@ -1272,5 +1224,5 @@
 
     // If const3 not equal to zero solve for difference else floor of const1
-    if(fabs(const3-0.0) > FLT_EPSILON) {
+    if (fabs(const3-0.0) > FLT_EPSILON) {
         out = const1 + (mjd - const2) * const3;
     } else {
@@ -1306,5 +1258,5 @@
 
     // Verify time is UTC type
-    if(utc->type != PS_TIME_UTC) {
+    if (utc->type != PS_TIME_UTC) {
         psError(PS_ERR_BAD_PARAMETER_VALUE,true,_("Specified type, %d, is incorrect."),utc->type);
         return false;
@@ -1316,5 +1268,5 @@
 
     // Check the absolute difference between the two times for leapsecond
-    if(psTimeLeapSecondDelta(utc,prevUtc) >= 1.0) {
+    if (psTimeLeapSecondDelta(utc,prevUtc) >= 1.0) {
         returnValue = true;
     } else {
@@ -1343,5 +1295,5 @@
 
     // Julian date conversion
-    if(time2->sec < 0) {
+    if (time2->sec < 0) {
         // psTime earlier than epoch
         jd = time2->sec / SEC_PER_DAY - time2->nsec / NSEC_PER_DAY + JD_EPOCH_OFFSET;
@@ -1369,5 +1321,5 @@
 
     // Modified Julian date conversion
-    if(time2->sec < 0) {
+    if (time2->sec < 0) {
         // psTime earlier than epoch
         mjd = time2->sec / SEC_PER_DAY - time2->nsec / NSEC_PER_DAY + MJD_EPOCH_OFFSET;
@@ -1416,5 +1368,5 @@
 
     // Check if time is UTC and leapsecond
-    if(((time->type==PS_TIME_UTC)||(time->type==PS_TIME_UT1)) && (time->leapsecond)) {
+    if (((time->type==PS_TIME_UTC)||(time->type==PS_TIME_UT1)) && (time->leapsecond)) {
         // Modify second to be 60
         tempString[17] = '6';
@@ -1487,5 +1439,5 @@
     days = jd - 2440587.5;
     seconds = days * SEC_PER_DAY;
-    if(seconds < 0.0) {
+    if (seconds < 0.0) {
         outTime->nsec = (seconds - (psS64)seconds) * -1000000000.0;  // psTime earlier than epoch
     } else {
@@ -1513,5 +1465,5 @@
     seconds = days * SEC_PER_DAY;
 
-    if(seconds < 0.0) {
+    if (seconds < 0.0) {
         outTime->nsec = (seconds - (psS64)seconds) * -1000000000.0;  // psTime earlier than epoch
     } else {
@@ -1701,5 +1653,5 @@
 
     // Make month in range 3..14 (treat Jan & Feb as months 13..14 of prev year)
-    if( month <= 2 )
+    if ( month <= 2 )
     {
         temp = (14 - month) / 12;
@@ -1707,5 +1659,5 @@
         year -= temp;
         month += 12 * temp;
-    } else if(month > 14)
+    } else if (month > 14)
     {
         temp = (month - 3) / 12;
@@ -1812,5 +1764,5 @@
 
     // Convert time to TAI if necessary, but without changing input arguments
-    if(time->type == PS_TIME_UTC) {
+    if (time->type == PS_TIME_UTC) {
         tempTime = psTimeAlloc(PS_TIME_UTC);
         tempTime->sec = time->sec;
@@ -1833,5 +1785,5 @@
 
     // Convert result to same time type as input
-    if(time->type == PS_TIME_UTC) {
+    if (time->type == PS_TIME_UTC) {
         outTime = psTimeConvert(outTime, PS_TIME_UTC);
     }
@@ -1858,5 +1810,5 @@
 
     // Verify both times of the same type
-    if(time1->type != time2->type) {
+    if (time1->type != time2->type) {
         psError(PS_ERR_BAD_PARAMETER_VALUE,true,_("Specified type, %d, is incorrect."),time1->type);
         return NAN;
@@ -1864,5 +1816,5 @@
 
     // Convert time to TAI if necessary, but without changing input arguments
-    if(time1->type == PS_TIME_UTC) {
+    if (time1->type == PS_TIME_UTC) {
         tempTime1 = psTimeAlloc(PS_TIME_UTC);
         tempTime1->sec = time1->sec;
@@ -1872,5 +1824,5 @@
         tempTime1 = psMemIncrRefCounter((psTime*)time1);
     }
-    if(time2->type == PS_TIME_UTC) {
+    if (time2->type == PS_TIME_UTC) {
         tempTime2 = psTimeAlloc(PS_TIME_UTC);
         tempTime2->sec = time2->sec;
