Index: trunk/BNC/RTCM3/rtcm3.cpp
===================================================================
--- trunk/BNC/RTCM3/rtcm3.cpp	(revision 52)
+++ trunk/BNC/RTCM3/rtcm3.cpp	(revision 52)
@@ -0,0 +1,1095 @@
+/*
+  Converter for RTCM3 data to RINEX.
+  $Id: rtcm3torinex.c,v 1.4 2006/05/08 09:25:11 stoecker Exp $
+
+  Program written bei
+  Dirk Stoecker
+  Euronik GmbH
+  http://www.euronik.eu/
+
+  for
+
+  Federal Agency for Cartography and Geodesy (BKG)
+  Richard-Strauss-Allee 11
+  D-60598 Frankfurt
+  http://igs.bkg.bund.de/index_ntrip.htm
+
+  Contact Dirk Stoecker [stoecker@euronik.eu] or [euref-ip@bkg.bund.de]
+  with your comments, suggestions, improvements, patches.
+
+  Copyright (C) 2005-2006 by German Federal Agency for Cartography and Geodesy
+
+  This program 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, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+  or read http://www.gnu.org/licenses/gpl.txt
+*/
+
+#include <ctype.h>
+#include <errno.h>
+#include <getopt.h>
+#include <math.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <signal.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <time.h>
+#include <unistd.h>
+
+/* The string, which is send as agent in HTTP request */
+#define AGENTSTRING "NTRIP NtripRTCM3ToRINEX"
+
+#define MAXDATASIZE 1000 /* max number of bytes we can get at once */
+
+/* CVS revision and version */
+static char revisionstr[] = "$Revision: 1.4 $";
+static char datestr[]     = "$Date: 2006/05/08 09:25:11 $";
+static int stop = 0;
+
+/* unimportant, only for approx. time needed */
+#define LEAPSECONDS 14
+
+struct converttimeinfo {
+  int second;    /* seconds of GPS time [0..59] */
+  int minute;    /* minutes of GPS time [0..59] */
+  int hour;      /* hour of GPS time [0..24] */
+  int day;       /* day of GPS time [1..28..30(31)*/
+  int month;     /* month of GPS time [1..12]*/
+  int year;      /* year of GPS time [1980..] */
+};
+
+#define PRN_GPS_START             1
+#define PRN_GPS_END               32
+#define PRN_GLONASS_START         38
+#define PRN_GLONASS_END           61
+
+#define GNSSENTRY_C1DATA     0
+#define GNSSENTRY_C2DATA     1
+#define GNSSENTRY_P1DATA     2
+#define GNSSENTRY_P2DATA     3
+#define GNSSENTRY_L1CDATA    4
+#define GNSSENTRY_L1PDATA    5
+#define GNSSENTRY_L2CDATA    6
+#define GNSSENTRY_L2PDATA    7
+#define GNSSENTRY_D1CDATA    8
+#define GNSSENTRY_D1PDATA    9
+#define GNSSENTRY_D2CDATA    10
+#define GNSSENTRY_D2PDATA    11
+#define GNSSENTRY_S1CDATA    12
+#define GNSSENTRY_S1PDATA    13
+#define GNSSENTRY_S2CDATA    14
+#define GNSSENTRY_S2PDATA    15
+#define GNSSENTRY_NUMBER     16 /* number of types!!! */
+
+/* Data flags. These flags are used in the dataflags field of gpsdata structure
+   and are used the determine, which data fields are filled with valid data. */
+#define GNSSDF_C1DATA         (1<<GNSSENTRY_C1DATA)
+#define GNSSDF_C2DATA         (1<<GNSSENTRY_C2DATA)
+#define GNSSDF_P1DATA         (1<<GNSSENTRY_P1DATA)
+#define GNSSDF_P2DATA         (1<<GNSSENTRY_P2DATA)
+#define GNSSDF_L1CDATA        (1<<GNSSENTRY_L1CDATA)
+#define GNSSDF_L1PDATA        (1<<GNSSENTRY_L1PDATA)
+#define GNSSDF_L2CDATA        (1<<GNSSENTRY_L2CDATA)
+#define GNSSDF_L2PDATA        (1<<GNSSENTRY_L2PDATA)
+#define GNSSDF_D1CDATA        (1<<GNSSENTRY_D1CDATA)
+#define GNSSDF_D1PDATA        (1<<GNSSENTRY_D1PDATA)
+#define GNSSDF_D2CDATA        (1<<GNSSENTRY_D2CDATA)
+#define GNSSDF_D2PDATA        (1<<GNSSENTRY_D2PDATA)
+#define GNSSDF_S1CDATA        (1<<GNSSENTRY_S1CDATA)
+#define GNSSDF_S1PDATA        (1<<GNSSENTRY_S1PDATA)
+#define GNSSDF_S2CDATA        (1<<GNSSENTRY_S2CDATA)
+#define GNSSDF_S2PDATA        (1<<GNSSENTRY_S2PDATA)
+
+#define RINEXENTRY_C1DATA     0
+#define RINEXENTRY_C2DATA     1
+#define RINEXENTRY_P1DATA     2
+#define RINEXENTRY_P2DATA     3
+#define RINEXENTRY_L1DATA     4
+#define RINEXENTRY_L2DATA     5
+#define RINEXENTRY_D1DATA     6
+#define RINEXENTRY_D2DATA     7
+#define RINEXENTRY_S1DATA     8
+#define RINEXENTRY_S2DATA     9
+#define RINEXENTRY_NUMBER     10
+
+/* Additional flags for the data field, which tell us more. */
+#define GNSSDF_LOCKLOSSL1     (1<<29)  /* lost lock on L1 */
+#define GNSSDF_LOCKLOSSL2     (1<<30)  /* lost lock on L2 */
+
+struct gnssdata {
+  int    flags;              /* GPSF_xxx */
+  int    week;               /* week number of GPS date */
+  int    numsats;
+  double timeofweek;         /* milliseconds in GPS week */
+  double measdata[24][GNSSENTRY_NUMBER];  /* data fields */ 
+  int    dataflags[24];      /* GPSDF_xxx */
+  int    satellites[24];     /* SV - IDs */
+  int    snrL1[24];          /* Important: all the 5 SV-specific fields must */
+  int    snrL2[24];          /* have the same SV-order */
+};
+
+struct RTCM3ParserData {
+  unsigned char Message[2048]; /* input-buffer */
+  int    MessageSize;   /* current buffer size */
+  int    NeedBytes;     /* bytes wanted for next run */
+  int    SkipBytes;     /* bytes to skip in next round */
+  int    GPSWeek;
+  int    GPSTOW;        /* in seconds */
+  struct gnssdata Data;
+  int    size;
+  int    lastlockl1[64];
+  int    lastlockl2[64];
+  int    datapos[RINEXENTRY_NUMBER];
+  int    dataflag[RINEXENTRY_NUMBER];
+  int    numdatatypes;
+  int    validwarning;
+  int    init;
+  const char * headerfile;
+};
+
+struct Args
+{
+  const char *server;
+  int         port;
+  const char *user;
+  const char *password;
+  const char *data;
+  const char *headerfile;
+};
+
+/* option parsing */
+#ifdef NO_LONG_OPTS
+#define LONG_OPT(a)
+#else
+#define LONG_OPT(a) a
+static struct option opts[] = {
+{ "data",       required_argument, 0, 'd'},
+{ "server",     required_argument, 0, 's'},
+{ "password",   required_argument, 0, 'p'},
+{ "port",       required_argument, 0, 'r'},
+{ "header",     required_argument, 0, 'f'},
+{ "user",       required_argument, 0, 'u'},
+{ "help",       no_argument,       0, 'h'},
+{0,0,0,0}};
+#endif
+#define ARGOPT "d:hp:r:s:u:f:"
+
+static int getargs(int argc, char **argv, struct Args *args)
+{
+  int res = 1;
+  int getoptr;
+  int help = 0;
+  char *t;
+
+  args->server = "www.euref-ip.net";
+  args->port = 80;
+  args->user = "";
+  args->password = "";
+  args->data = 0;
+  args->headerfile = 0;
+  help = 0;
+
+  do
+  {
+#ifdef NO_LONG_OPTS
+    switch((getoptr = getopt(argc, argv, ARGOPT)))
+#else
+    switch((getoptr = getopt_long(argc, argv, ARGOPT, opts, 0)))
+#endif
+    {
+    case 's': args->server = optarg; break;
+    case 'u': args->user = optarg; break;
+    case 'p': args->password = optarg; break;
+    case 'd': args->data = optarg; break;
+    case 'f': args->headerfile = optarg; break;
+    case 'h': help=1; break;
+    case 'r': 
+      args->port = strtoul(optarg, &t, 10);
+      if((t && *t) || args->port < 1 || args->port > 65535)
+        res = 0;
+      break;
+    case -1: break;
+    }
+  } while(getoptr != -1 || !res);
+
+  datestr[0] = datestr[7];
+  datestr[1] = datestr[8];
+  datestr[2] = datestr[9];
+  datestr[3] = datestr[10];
+  datestr[5] = datestr[12];
+  datestr[6] = datestr[13];
+  datestr[8] = datestr[15];
+  datestr[9] = datestr[16];
+  datestr[4] = datestr[7] = '-';
+  datestr[10] = 0;
+
+  if(!res || help)
+  {
+    fprintf(stderr, "Version %s (%s) GPL\nUsage: %s -s server -u user ...\n"
+    " -d " LONG_OPT("--data       ") "the requested data set\n"
+    " -f " LONG_OPT("--headerfile ") "file for RINEX header information\n"
+    " -s " LONG_OPT("--server     ") "the server name or address\n"
+    " -p " LONG_OPT("--password   ") "the login password\n"
+    " -r " LONG_OPT("--port       ") "the server port number (default 80)\n"
+    " -u " LONG_OPT("--user       ") "the user name\n"
+    , revisionstr, datestr, argv[0]);
+    exit(1);
+  }
+  return res;
+}
+
+static const char encodingTable [64] = {
+  'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
+  'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
+  'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
+  'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'
+};
+
+/* does not buffer overrun, but breaks directly after an error */
+/* returns the number of required bytes */
+static int encode(char *buf, int size, const char *user, const char *pwd)
+{
+  unsigned char inbuf[3];
+  char *out = buf;
+  int i, sep = 0, fill = 0, bytes = 0;
+
+  while(*user || *pwd)
+  {
+    i = 0;
+    while(i < 3 && *user) inbuf[i++] = *(user++);
+    if(i < 3 && !sep)    {inbuf[i++] = ':'; ++sep; }
+    while(i < 3 && *pwd)  inbuf[i++] = *(pwd++);
+    while(i < 3)         {inbuf[i++] = 0; ++fill; }
+    if(out-buf < size-1)
+      *(out++) = encodingTable[(inbuf [0] & 0xFC) >> 2];
+    if(out-buf < size-1)
+      *(out++) = encodingTable[((inbuf [0] & 0x03) << 4)
+               | ((inbuf [1] & 0xF0) >> 4)];
+    if(out-buf < size-1)
+    {
+      if(fill == 2)
+        *(out++) = '=';
+      else
+        *(out++) = encodingTable[((inbuf [1] & 0x0F) << 2)
+                 | ((inbuf [2] & 0xC0) >> 6)];
+    }
+    if(out-buf < size-1)
+    {
+      if(fill >= 1)
+        *(out++) = '=';
+      else
+        *(out++) = encodingTable[inbuf [2] & 0x3F];
+    }
+    bytes += 4;
+  }
+  if(out-buf < size)
+    *out = 0;
+  return bytes;
+}
+
+static uint32_t CRC24(long size, const unsigned char *buf)
+{
+  uint32_t crc = 0;
+  int i;
+
+  while(size--)
+  {
+    crc ^= (*buf++) << (16);
+    for(i = 0; i < 8; i++)
+    {
+      crc <<= 1;
+      if(crc & 0x1000000)
+        crc ^= 0x01864cfb;
+    }
+  }
+  return crc;
+}
+
+static int GetMessage(struct RTCM3ParserData *handle)
+{
+  unsigned char *m, *e;
+  int i;
+
+  m = handle->Message+handle->SkipBytes;
+  e = handle->Message+handle->MessageSize;
+  handle->NeedBytes = handle->SkipBytes = 0;
+  while(e-m >= 3)
+  {
+    if(m[0] == 0xD3)
+    {
+      handle->size = ((m[1]&3)<<8)|m[2];
+      if(e-m >= handle->size+6)
+      {
+        if((uint32_t)((m[3+handle->size]<<16)|(m[3+handle->size+1]<<8)
+        |(m[3+handle->size+2])) == CRC24(handle->size+3, m))
+        {
+          handle->SkipBytes = handle->size;
+          break;
+        }
+        else
+          ++m;
+      }
+      else
+      {
+        handle->NeedBytes = handle->size+6;
+        break;
+      }
+    }
+    else
+      ++m;
+  }
+  if(e-m < 3)
+    handle->NeedBytes = 3;
+  
+  /* copy buffer to front */
+  i = m - handle->Message;
+  if(i && m < e)
+    memmove(handle->Message, m, handle->MessageSize-i);
+  handle->MessageSize -= i;
+
+  return !handle->NeedBytes;
+}
+
+#define LOADBITS(a) \
+{ \
+  while((a) > numbits) \
+  { \
+    if(!size--) break; \
+    bitfield = (bitfield<<8)|*(data++); \
+    numbits += 8; \
+  } \
+}
+
+/* extract bits from data stream
+   b = variable to store result, a = number of bits */
+#define GETBITS(b, a) \
+{ \
+  LOADBITS(a) \
+  b = (bitfield<<(64-numbits))>>(64-(a)); \
+  numbits -= (a); \
+}
+
+/* extract bits from data stream
+   b = variable to store result, a = number of bits */
+#define GETBITSSIGN(b, a) \
+{ \
+  LOADBITS(a) \
+  b = ((int64_t)(bitfield<<(64-numbits)))>>(64-(a)); \
+  numbits -= (a); \
+}
+
+#define SKIPBITS(b) { LOADBITS(b) numbits -= (b); }
+
+static int RTCM3Parser(struct RTCM3ParserData *handle)
+{
+  int ret=0;
+
+  while(!ret && GetMessage(handle))
+  {
+    /* using 64 bit integer types, as it is much easier than handling
+    the long datatypes in 32 bit */
+    uint64_t numbits = 0, bitfield = 0;
+    int size = handle->size, type;
+    unsigned char *data = handle->Message+3;
+
+    GETBITS(type,12)
+    switch(type)
+    {
+    case 1001: case 1002: case 1003: case 1004:
+      if(handle->GPSWeek)
+      {
+        int lastlockl1[64];
+        int lastlockl2[64];
+        struct gnssdata *gnss;
+        int i, num, wasamb=0;
+
+        for(i = 0; i < 64; ++i)
+          lastlockl1[i] = lastlockl2[i] = 0;
+
+        gnss = &handle->Data;
+        memset(gnss, 0, sizeof(*gnss));
+
+        SKIPBITS(12) /* id */
+        GETBITS(i,30)
+        if(i/1000 < (int)handle->GPSTOW - 86400)
+          ++handle->GPSWeek;
+        handle->GPSTOW = i/1000;
+        gnss->timeofweek = i;
+        gnss->week = handle->GPSWeek;
+
+        SKIPBITS(1) /* sync */
+        GETBITS(i,5)
+        gnss->numsats = i;
+        SKIPBITS(4) /* smind, smint */
+
+        for(num = 0; num < gnss->numsats; ++num)
+        {
+          int sv, code, l1range, c,l,s,ce,le,se,amb=0;
+
+          GETBITS(sv, 6);
+          gnss->satellites[num] = (sv < 40 ? sv : sv+80);
+          /* L1 */
+          GETBITS(code, 1);
+          if(code)
+          {
+            c = GNSSDF_P1DATA;  ce = GNSSENTRY_P1DATA;
+            l = GNSSDF_L1PDATA; le = GNSSENTRY_L1PDATA;
+            s = GNSSDF_S1PDATA; se = GNSSENTRY_S1PDATA;
+          }
+          else
+          {
+            c = GNSSDF_C1DATA;  ce = GNSSENTRY_C1DATA;
+            l = GNSSDF_L1CDATA; le = GNSSENTRY_L1CDATA;
+            s = GNSSDF_S1CDATA; se = GNSSENTRY_S1CDATA;
+          }
+          GETBITS(l1range, 24);
+          if(l1range != 0x80000)
+          {
+            gnss->dataflags[num] |= c;
+            gnss->measdata[num][ce] = l1range*0.02;
+          }
+          GETBITSSIGN(i, 20);
+          if(i != 0x80000)
+          {
+            gnss->dataflags[num] |= l;
+            gnss->measdata[num][le] = l1range*0.02+i*0.0005;
+          }
+          GETBITS(i, 7);
+          lastlockl1[sv] = i;
+          if(handle->lastlockl1[sv] > i)
+            gnss->dataflags[num] |= GNSSDF_LOCKLOSSL1;
+          if(type == 1002 || type == 1004)
+          {
+            GETBITS(amb,8);
+            if(amb && (gnss->dataflags[num] & c))
+            {
+              gnss->measdata[num][ce] += amb*299792.458;
+              gnss->measdata[num][le] += amb*299792.458;
+              ++wasamb;
+            }
+            GETBITS(i, 8);
+            if(i)
+            {
+              gnss->dataflags[num] |= s;
+              gnss->measdata[num][se] = i*0.25;
+              i /= 4*4;
+              if(i > 9) i = 9;
+              else if(i < 1) i = 1;
+              gnss->snrL1[num] = i;
+            }
+          }
+          if(type == 1003 || type == 1004)
+          {
+            /* L2 */
+            GETBITS(code,2);
+            if(code)
+            {
+              c = GNSSDF_P2DATA;  ce = GNSSENTRY_P2DATA;
+              l = GNSSDF_L2PDATA; le = GNSSENTRY_L2PDATA;
+              s = GNSSDF_S2PDATA; se = GNSSENTRY_S2PDATA;
+            }
+            else
+            {
+              c = GNSSDF_C2DATA;  ce = GNSSENTRY_C2DATA;
+              l = GNSSDF_L2CDATA; le = GNSSENTRY_L2CDATA;
+              s = GNSSDF_S2CDATA; se = GNSSENTRY_S2CDATA;
+            }
+            GETBITSSIGN(i,14);
+            if(i != 0x2000)
+            {
+              gnss->dataflags[num] |= c;
+              gnss->measdata[num][ce] = l1range*0.02+i*0.02
+              +amb*299792.458;
+            }
+            GETBITSSIGN(i,20);
+            if(i != 0x80000)
+            {
+              gnss->dataflags[num] |= l;
+              gnss->measdata[num][le] = l1range*0.02+i*0.0005
+              +amb*299792.458;
+            }
+            GETBITS(i,7);
+            lastlockl2[sv] = i;
+            if(handle->lastlockl2[sv] > i)
+              gnss->dataflags[num] |= GNSSDF_LOCKLOSSL2;
+            if(type == 1004)
+            {
+              GETBITS(i, 8);
+              if(i)
+              {
+                gnss->dataflags[num] |= s;
+                gnss->measdata[num][se] = i*0.25;
+                i /= 4*4;
+                if(i > 9) i = 9;
+                else if(i < 1) i = 1;
+                gnss->snrL2[num] = i;
+              }
+            }
+          }
+        }
+        for(i = 0; i < 64; ++i)
+        {
+          handle->lastlockl1[i] = lastlockl1[i];
+          handle->lastlockl2[i] = lastlockl2[i];
+        }
+        if(wasamb) /* not RINEX compatible without */
+          ret = 1;
+        else
+          ret = 2;
+      }
+      break;
+    }
+  }
+  return ret;
+}
+
+static int longyear(int year, int month)
+{
+  if(!(year % 4) && (!(year % 400) || (year % 100)))
+  {
+    if(!month || month == 2)
+      return 1;
+  }
+  return 0;
+}
+
+static void converttime(struct converttimeinfo *c, int week, int tow)
+{
+  /* static variables */
+  static const int months[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
+
+  int i, k, doy, j; /* temporary variables */
+  j = week*(7*24*60*60) + tow + 5*24*60*60;
+  for(i = 1980; j >= (k = (365+longyear(i,0))*24*60*60); ++i)
+    j -= k;
+  c->year = i;
+  doy = 1+ (j / (24*60*60));
+  j %= (24*60*60);
+  c->hour = j / (60*60);
+  j %= (60*60);
+  c->minute = j / 60;
+  c->second = j % 60;
+  j = 0;
+  for(i = 1; j + (k = months[i] + longyear(c->year,i)) < doy; ++i)
+    j += k;
+  c->month = i;
+  c->day = doy - j;
+}
+
+struct Header
+{
+  const char *version;
+  const char *pgm;
+  const char *marker;
+  const char *observer;
+  const char *receiver;
+  const char *antenna;
+  const char *position;
+  const char *antennaposition;
+  const char *wavelength;
+  const char *typesofobs; /* should not be modified outside */
+  const char *timeoffirstobs; /* should not be modified outside */
+};
+
+#define MAXHEADERLINES 50
+#define MAXHEADERBUFFERSIZE 4096
+struct HeaderData
+{
+  union
+  {
+    struct Header named;
+    const char *unnamed[MAXHEADERLINES];
+  } data;
+  int  numheaders;
+};
+
+static void HandleHeader(struct RTCM3ParserData *Parser)
+{
+  struct HeaderData hdata;
+  char thebuffer[MAXHEADERBUFFERSIZE];
+  char *buffer = thebuffer;
+  int buffersize = sizeof(thebuffer);
+  int i;
+
+  hdata.data.named.version =
+  "     2.11           OBSERVATION DATA    M (Mixed)"
+  "           RINEX VERSION / TYPE";
+
+  {
+    const char *str;
+    time_t t;
+    struct tm * t2;
+
+    str = getenv("USER");
+    if(!str) str = "";
+    t = time(&t);
+    t2 = gmtime(&t);
+    hdata.data.named.pgm = buffer;
+    i = 1+snprintf(buffer, buffersize,
+    "RTCM3TORINEX %-7.7s%-20.20s%04d-%02d-%02d %02d:%02d    "
+    "PGM / RUN BY / DATE",
+    revisionstr, str, 1900+t2->tm_year, t2->tm_mon+1, t2->tm_mday, t2->tm_hour,
+    t2->tm_min);
+    buffer += i; buffersize -= i;
+
+    hdata.data.named.observer = buffer;
+    i = 1+snprintf(buffer, buffersize,
+    "%-20.20s                                        "
+    "OBSERVER / AGENCY", str);
+    buffer += i; buffersize -= i;
+  }
+
+  hdata.data.named.marker =
+  "RTCM3TORINEX                                                "
+  "MARKER NAME";
+
+  hdata.data.named.receiver =
+  "                                                            "
+  "REC # / TYPE / VERS";
+
+  hdata.data.named.antenna =
+  "                                                            "
+  "ANT # / TYPE";
+
+  hdata.data.named.position =
+  "         .0000         .0000         .0000                  "
+  "APPROX POSITION XYZ";
+
+  hdata.data.named.antennaposition =
+  "         .0000         .0000         .0000                  "
+  "ANTENNA: DELTA H/E/N";
+  
+  hdata.data.named.wavelength =
+  "     1     1                                                "
+  "WAVELENGTH FACT L1/2";
+
+  {
+#define CHECKFLAGS(a, b) \
+    if(flags & GNSSDF_##a##DATA \
+    && !data[RINEXENTRY_##b##DATA]) \
+    { \
+      Parser->dataflag[Parser->numdatatypes] = GNSSDF_##a##DATA; \
+      Parser->datapos[Parser->numdatatypes++] = data[RINEXENTRY_##b##DATA] \
+      = GNSSENTRY_##a##DATA; \
+      snprintf(tbuffer+tbufferpos, sizeof(tbuffer)-tbufferpos, "    "#b); \
+      tbufferpos += 6; \
+    }
+
+    int flags = 0;
+    int data[RINEXENTRY_NUMBER];
+    char tbuffer[6*RINEXENTRY_NUMBER+1];
+    int tbufferpos = 0;
+    for(i = 0; i < RINEXENTRY_NUMBER; ++i)
+      data[i] = 0;
+    for(i = 0; i < Parser->Data.numsats; ++i)
+      flags |= Parser->Data.dataflags[i];
+
+    CHECKFLAGS(C1,C1)
+    CHECKFLAGS(C2,C2)
+    CHECKFLAGS(P1,P1)
+    CHECKFLAGS(P2,P2)
+    CHECKFLAGS(L1C,L1)
+    CHECKFLAGS(L1P,L1)
+    CHECKFLAGS(L2C,L2)
+    CHECKFLAGS(L2P,L2)
+    CHECKFLAGS(D1C,D1)
+    CHECKFLAGS(D1P,D1)
+    CHECKFLAGS(D2C,D2)
+    CHECKFLAGS(D2P,D2)
+    CHECKFLAGS(S1C,S1)
+    CHECKFLAGS(S1P,S1)
+    CHECKFLAGS(S2C,S2)
+    CHECKFLAGS(S2P,S2)
+
+    hdata.data.named.typesofobs = buffer;
+    i = 1+snprintf(buffer, buffersize,
+    "%6i%-54.54s# / TYPES OF OBSERV", Parser->numdatatypes, tbuffer);
+    if(Parser->numdatatypes>9)
+    {
+      i += snprintf(buffer+i-1, buffersize,
+      "\n      %-54.54s# / TYPES OF OBSERV", tbuffer+9*6);
+    }
+    buffer += i; buffersize -= i;
+  }
+
+  {
+    struct converttimeinfo cti;
+    converttime(&cti, Parser->Data.week,
+    floor(Parser->Data.timeofweek/1000.0));
+    hdata.data.named.timeoffirstobs = buffer;
+      i = 1+snprintf(buffer, buffersize,
+    "  %4d    %2d    %2d    %2d    %2d   %10.7f     GPS         "
+    "TIME OF FIRST OBS", cti.year%100, cti.month, cti.day, cti.hour,
+    cti.minute, cti.second + fmod(Parser->Data.timeofweek/1000.0,1.0));
+
+    buffer += i; buffersize -= i;
+  }
+
+  hdata.numheaders = 11;
+
+  if(Parser->headerfile)
+  {
+    FILE *fh;
+    if((fh = fopen(Parser->headerfile, "r")))
+    {
+      int siz;
+      char *lastblockstart;
+      if((siz = fread(buffer, 1, buffersize-1, fh)) > 0)
+      {
+        buffer[siz] = '\n';
+        if(siz == buffersize)
+        {
+          fprintf(stderr, "Header file is too large. Only %d bytes read.",
+          siz);
+        }
+        /* scan the file line by line and enter the entries in the list */
+        /* warn for "# / TYPES OF OBSERV" and "TIME OF FIRST OBS" */
+        /* overwrites entries, except for comments */
+        lastblockstart = buffer;
+        for(i = 0; i < siz; ++i)
+        {
+          if(buffer[i] == '\n')
+          { /* we found a line */
+            char *end;
+            while(buffer[i+1] == '\r')
+              ++i; /* skip \r in case there are any */
+            end = buffer+i;
+            while(*end == '\t' || *end == ' ' || *end == '\r' || *end == '\n')
+              *(end--) = 0;
+            if(end-lastblockstart < 60+5) /* short line */
+              fprintf(stderr, "Short Header line '%s' ignored.\n", lastblockstart);
+            else
+            {
+              int pos;
+              if(!strcmp("COMMENT", lastblockstart+60))
+                pos = hdata.numheaders;
+              else
+              {
+                for(pos = 0; pos < hdata.numheaders; ++pos)
+                {
+                  if(!strcmp(hdata.data.unnamed[pos]+60, lastblockstart+60))
+                    break;
+                }
+                if(!strcmp("# / TYPES OF OBSERV", lastblockstart+60)
+                || !strcmp("TIME OF FIRST OBS", lastblockstart+60))
+                {
+                  fprintf(stderr, "Overwriting header '%s' is dangerous.\n",
+                  lastblockstart+60);
+                }
+              }
+              if(pos >= MAXHEADERLINES)
+              {
+                fprintf(stderr,
+                "Maximum number of header lines of %d reached.\n",
+                MAXHEADERLINES);
+              }
+              else if(!strcmp("END OF HEADER", lastblockstart+60))
+              {
+                fprintf(stderr, "End of header ignored.\n");
+              }
+              else
+              {
+                hdata.data.unnamed[pos] = lastblockstart;
+                if(pos == hdata.numheaders)
+                  ++hdata.numheaders;
+              }
+            }
+            lastblockstart = buffer+i+1;
+          }
+        }
+      }
+      else
+      {
+        fprintf(stderr, "Could not read data from headerfile '%s'.\n",
+        Parser->headerfile);
+      }
+      fclose(fh);
+    }
+    else
+    {
+      fprintf(stderr, "Could not open header datafile '%s'.\n",
+      Parser->headerfile);
+    }
+  }
+
+  for(i = 0; i < hdata.numheaders; ++i)
+    printf("%s\n", hdata.data.unnamed[i]);
+  printf("                                                            "
+  "END OF HEADER\n");
+}
+
+/* let the output complete a block if necessary */
+static void signalhandler(int sig)
+{
+  if(!stop)
+  {
+    fprintf(stderr, "Stop signal number %d received. "
+    "Trying to terminate gentle.\n", sig);
+    stop = 1;
+    alarm(1);
+  }
+}
+
+/* for some reason we had to abort hard (maybe waiting for data */
+#ifdef __GNUC__
+static __attribute__ ((noreturn)) void signalhandler_alarm(
+int sig __attribute__((__unused__)))
+#else /* __GNUC__ */
+static void signalhandler_alarm(int sig)
+#endif /* __GNUC__ */
+{
+  fprintf(stderr, "Programm forcefully terminated.\n");
+  exit(1);
+}
+
+static void HandleByte(struct RTCM3ParserData *Parser, unsigned int byte)
+{
+  Parser->Message[Parser->MessageSize++] = byte;
+  if(Parser->MessageSize >= Parser->NeedBytes)
+  {
+    int r;
+    while((r = RTCM3Parser(Parser)))
+    {
+      int i, j, o;
+      struct converttimeinfo cti;
+
+      if(!Parser->init)
+      {
+        HandleHeader(Parser);
+        Parser->init = 1;
+      }
+      if(r == 2 && !Parser->validwarning)
+      {
+        printf("No valid RINEX! All values are modulo 299792.458!"
+        "           COMMENT\n");
+        Parser->validwarning = 1;
+      }
+
+      converttime(&cti, Parser->Data.week,
+      floor(Parser->Data.timeofweek/1000.0));
+      printf(" %02d %2d %2d %2d %2d %10.7f  0%3d",
+      cti.year%100, cti.month, cti.day, cti.hour, cti.minute, cti.second
+      + fmod(Parser->Data.timeofweek/1000.0,1.0), Parser->Data.numsats);
+      for(i = 0; i < 12 && i < Parser->Data.numsats; ++i)
+      {
+        if(Parser->Data.satellites[i] <= PRN_GPS_END)
+          printf("G%02d", Parser->Data.satellites[i]);
+        else if(Parser->Data.satellites[i] >= PRN_GLONASS_START
+        && Parser->Data.satellites[i] <= PRN_GLONASS_END)
+          printf("R%02d", Parser->Data.satellites[i] - (PRN_GLONASS_START-1));
+        else
+          printf("%3d", Parser->Data.satellites[i]);
+      }
+      printf("\n");
+      o = 12;
+      j = Parser->Data.numsats - 12;
+      while(j > 0)
+      {
+        printf("                                ");
+        for(i = o; i < o+12 && i < Parser->Data.numsats; ++i)
+        {
+          if(Parser->Data.satellites[i] <= PRN_GPS_END)
+            printf("G%02d", Parser->Data.satellites[i]);
+          else if(Parser->Data.satellites[i] >= PRN_GLONASS_START
+          && Parser->Data.satellites[i] <= PRN_GLONASS_END)
+            printf("R%02d", Parser->Data.satellites[i] - (PRN_GLONASS_START-1));
+          else
+            printf("%3d", Parser->Data.satellites[i]);
+        }
+        printf("\n");
+        j -= 12;
+        o += 12;
+      }
+      for(i = 0; i < Parser->Data.numsats; ++i)
+      {
+        for(j = 0; j < Parser->numdatatypes; ++j)
+        {
+          if(!(Parser->Data.dataflags[i] & Parser->dataflag[j])
+          || isnan(Parser->Data.measdata[i][Parser->datapos[j]])
+          || isinf(Parser->Data.measdata[i][Parser->datapos[j]]))
+          { /* no or illegal data */
+            printf("                ");
+          }
+          else
+          {
+            char lli = ' ';
+            char snr = ' ';
+            if(Parser->dataflag[j] & (GNSSDF_L1CDATA|GNSSDF_L1PDATA))
+            {
+              if(Parser->Data.dataflags[i] & GNSSDF_LOCKLOSSL1)
+                lli = '1';
+              snr = '0'+Parser->Data.snrL1[i];
+            }
+            if(Parser->dataflag[j] & (GNSSDF_L2CDATA|GNSSDF_L2PDATA))
+            {
+              if(Parser->Data.dataflags[i] & GNSSDF_LOCKLOSSL2)
+                lli = '1';
+              snr = '0'+Parser->Data.snrL2[i];
+            }
+            printf("%14.3f%c%c",
+            Parser->Data.measdata[i][Parser->datapos[j]],lli,snr);
+          }
+          if(j%5 == 4 || j == Parser->numdatatypes-1)
+            printf("\n");
+        }
+      }
+    }
+  }
+}
+
+int main(int argc, char **argv)
+{
+  struct Args args;
+  struct RTCM3ParserData Parser;
+
+  setbuf(stdout, 0);
+  setbuf(stdin, 0);
+  setbuf(stderr, 0);
+
+  {
+    char *a;
+    int i=0;
+    for(a = revisionstr+11; *a && *a != ' '; ++a)
+      revisionstr[i++] = *a;
+    revisionstr[i] = 0;
+  }
+
+  signal(SIGINT, signalhandler);
+  signal(SIGALRM,signalhandler_alarm);
+  signal(SIGQUIT,signalhandler);
+  signal(SIGTERM,signalhandler);
+  signal(SIGPIPE,signalhandler);
+  memset(&Parser, 0, sizeof(Parser));
+  {
+    time_t tim;
+    tim = time(0) - ((10*365+2+5)*24*60*60+LEAPSECONDS);
+    Parser.GPSWeek = tim/(7*24*60*60);
+    Parser.GPSTOW = tim%(7*24*60*60);
+  }
+
+  if(getargs(argc, argv, &args))
+  {
+    int i, sockfd, numbytes;  
+    char buf[MAXDATASIZE];
+    struct hostent *he;
+    struct sockaddr_in their_addr; /* connector's address information */
+
+    Parser.headerfile = args.headerfile;
+
+    if(!(he=gethostbyname(args.server)))
+    {
+      perror("gethostbyname");
+      exit(1);
+    }
+    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+    {
+      perror("socket");
+      exit(1);
+    }
+    their_addr.sin_family = AF_INET;    /* host byte order */
+    their_addr.sin_port = htons(args.port);  /* short, network byte order */
+    their_addr.sin_addr = *((struct in_addr *)he->h_addr);
+    memset(&(their_addr.sin_zero), '\0', 8);
+    if(connect(sockfd, (struct sockaddr *)&their_addr,
+    sizeof(struct sockaddr)) == -1)
+    {
+      perror("connect");
+      exit(1);
+    }
+
+    if(!args.data)
+    {
+      i = snprintf(buf, MAXDATASIZE,
+      "GET / HTTP/1.0\r\n"
+      "User-Agent: %s/%s\r\n"
+#ifdef UNUSED
+      "Accept: */*\r\n"
+      "Connection: close\r\n"
+#endif
+      "\r\n"
+      , AGENTSTRING, revisionstr);
+    }
+    else
+    {
+      i=snprintf(buf, MAXDATASIZE-40, /* leave some space for login */
+      "GET /%s HTTP/1.0\r\n"
+      "User-Agent: %s/%s\r\n"
+#ifdef UNUSED
+      "Accept: */*\r\n"
+      "Connection: close\r\n"
+#endif
+      "Authorization: Basic "
+      , args.data, AGENTSTRING, revisionstr);
+      if(i > MAXDATASIZE-40 && i < 0) /* second check for old glibc */
+      {
+        fprintf(stderr, "Requested data too long\n");
+        exit(1);
+      }
+      i += encode(buf+i, MAXDATASIZE-i-5, args.user, args.password);
+      if(i > MAXDATASIZE-5)
+      {
+        fprintf(stderr, "Username and/or password too long\n");
+        exit(1);
+      }
+      snprintf(buf+i, 5, "\r\n\r\n");
+      i += 5;
+    }
+    if(send(sockfd, buf, (size_t)i, 0) != i)
+    {
+      perror("send");
+      exit(1);
+    }
+    if(args.data)
+    {
+      int k = 0;
+      while(!stop && (numbytes=recv(sockfd, buf, MAXDATASIZE-1, 0)) != -1)
+      {
+        if(!k)
+        {
+          if(numbytes < 12 || strncmp("ICY 200 OK\r\n", buf, 12))
+          {
+            fprintf(stderr, "Could not get the requested data: ");
+            for(k = 0; k < numbytes && buf[k] != '\n' && buf[k] != '\r'; ++k)
+            {
+              fprintf(stderr, "%c", isprint(buf[k]) ? buf[k] : '.');
+            }
+            fprintf(stderr, "\n");
+            exit(1);
+          }
+          ++k;
+        }
+        else
+        {
+          int z;
+          for(z = 0; z < numbytes && !stop; ++z)
+            HandleByte(&Parser, buf[z]);
+        }
+      }
+    }
+    else
+    {
+      while((numbytes=recv(sockfd, buf, MAXDATASIZE-1, 0)) > 0)
+      {
+        fwrite(buf, (size_t)numbytes, 1, stdout);
+      }
+    }
+
+    close(sockfd);
+  }
+  return 0;
+}
Index: trunk/BNC/RTIGS/rtacp.h
===================================================================
--- trunk/BNC/RTIGS/rtacp.h	(revision 52)
+++ trunk/BNC/RTIGS/rtacp.h	(revision 52)
@@ -0,0 +1,65 @@
+/***************************************************************************
+                          rtacp.h  -  description
+                             -------------------
+    begin                : Mon Mar 27 2000
+    copyright            : (C) 2000 by Ken MacLeod
+    email                : macleod@geod.nrcan.gc.ca
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program 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.                                   *
+ *                                                                         *
+ ***************************************************************************/
+/* $Header: rtacp.h,v 3.1 99/06/08 15:59:45 lahaye Released $ */
+#ifndef _RTACP
+#define _RTACP
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include <time.h>
+#include "rtstruct.h"
+#ifndef _RTAP
+//#include "GTT.h"
+#endif
+
+#define gps_start_second 0
+#define gps_end_second   1572480000
+
+#define DATA_RATE       1	/* data rate used in decimate */
+#define NUM_PTS         14	/* number of code points used in on either side */
+#define L_NUM_PTS       4	/* maximum number of phase points on either side for polynomial fit */
+#define L_ORDER         3      /* order of polynomial fit to phase */
+#define L2_L1_ORDER     3      /* order of polynomial fit to L2-L1 series */
+#define NSEC            30	/* decimation epoch */
+#define MIN_ELEV        10.0
+#define MAXGAP          600     /* gap in stats_l2_l1 function for reinitialization */
+					/* A B and C precise model values */
+
+#define PM_A   ( (154.0*154.0) + (120.0*120.0) ) / ( (154.0*154.0) - (120.0*120.0) )
+#define PM_B   ( 2.0 * (120.0*120.0) ) / ( (154.0*154.0) - (120.0*120.0) )
+#define PM_C   ( 2.0 * (154.0*154.0) ) / ( (154.0*154.0) - (120.0*120.0) )
+
+
+#define L1F            		(154.0 * 10.23e6)	/* L1 frequency */
+#define L2F            		(120.0 * 10.23e6)	/* L2 frequency */
+#define PCR            		(10.23e6)          	/* P chipping rate */
+#define CACR           		(1.023e6)		/* CA chipping rate */
+
+#define DEBUG          	 	1
+
+#define SYS_GPS_OFFSET  	315964800            	/* used for METS */
+
+#define CORH_MAX_TIME_DIFF	30	/* max time diff in seconds between local corrections */
+#define CORH_NUM                10	/* number of previous values used to compute RRC */
+#define RRC_ORDER		3
+
+
+
+
+#endif
Index: trunk/BNC/RTIGS/rtigs.cpp
===================================================================
--- trunk/BNC/RTIGS/rtigs.cpp	(revision 52)
+++ trunk/BNC/RTIGS/rtigs.cpp	(revision 52)
@@ -0,0 +1,717 @@
+
+#include "rtigs.h"
+
+#define MAXSTREAM 2048
+
+int main() {
+
+  unsigned char  data_stream[MAXSTREAM];
+  unsigned short numbytes;
+  RTIGSS_T       rtigs_sta;
+  RTIGSO_T       rtigs_obs;
+  RTIGSM_T       rtigs_met;
+  RTIGSE_T       rtigs_eph;
+  short          PRN;
+  short          retval;
+  unsigned short statID;
+  unsigned short messType;
+  CGPS_Transform GPSTrans;
+
+  memset(data_stream , 0, sizeof(data_stream));
+
+  // use something like recvfrom 
+
+  messType = GPSTrans.GetRTIGSHdrRecType(data_stream);
+  numbytes = GPSTrans.GetRTIGSHdrRecBytes(data_stream);
+  statID   = GPSTrans.GetRTIGSHdrStaID(data_stream);
+
+  switch (messType) {
+  case 100:
+    GPSTrans.Decode_RTIGS_Sta(data_stream, numbytes , rtigs_sta);
+    break;
+  case 200:
+    retval = GPSTrans.Decode_RTIGS_Obs(data_stream, numbytes , rtigs_obs);
+    if (retval >= 1) {
+      GPSTrans.print_CMEAS();
+    }
+    break;
+  case 300:
+    retval = GPSTrans.Decode_RTIGS_Eph(data_stream, numbytes , rtigs_eph, PRN);
+    break;
+  case 400:
+    retval = GPSTrans.Decode_RTIGS_Met(data_stream, numbytes , &rtigs_met); 
+    break;
+  }
+
+  return 0;
+}
+
+// Constructor
+////////////////////////////////////////////////////////////////////////////
+CGPS_Transform::CGPS_Transform() {
+
+  // Decoded Obs Array of 12 CMeas Observation Records
+  memset((void *)&DecObs, 0, sizeof(ARR_OBS_T     ));
+
+  // Keplarian Broadcast Eph
+  memset((void *)&TNAV_Eph,0, sizeof(ARR_TNAV_T   ));
+
+  NumObsRead = -1;
+  CAFlag = -1;
+  ASFlag = -1;
+  P2Flag = -1;
+  P1Flag = -1;
+  InitEndianFlag();
+
+  memset (PhaseArcStartTime, 0, sizeof(PhaseArcStartTime));
+}
+
+// Destructor
+////////////////////////////////////////////////////////////////////////////
+CGPS_Transform::~CGPS_Transform() {
+}
+
+// 
+////////////////////////////////////////////////////////////////////////////
+unsigned short CGPS_Transform::GetRTIGSHdrRecType(unsigned char *RTIGS_Str)
+{
+        unsigned short recordID;
+        memcpy ((void *)&recordID,RTIGS_Str, sizeof(recordID));
+        if (f_IsLittleEndian)
+        {
+                SwitchBytes( (char *)&recordID, sizeof(recordID) );
+        }
+        return recordID;
+}
+
+// 
+////////////////////////////////////////////////////////////////////////////
+unsigned short CGPS_Transform::GetRTIGSHdrRecBytes(unsigned char *RTIGS_Str)
+{
+        unsigned short bytes;
+        memcpy ((void *)&bytes,&RTIGS_Str[8], sizeof(bytes));
+        if (f_IsLittleEndian)
+        {
+                SwitchBytes( (char *)&bytes, sizeof(bytes) );
+        }
+        return bytes;
+
+}
+
+// 
+////////////////////////////////////////////////////////////////////////////
+unsigned short CGPS_Transform::GetRTIGSHdrStaID(unsigned char *RTIGS_Str)
+{
+        unsigned short StaID = 0;
+        memcpy ((void *)&StaID, &RTIGS_Str[2], sizeof(StaID));
+        if (f_IsLittleEndian)
+        {
+                SwitchBytes( (char *)&StaID, sizeof(StaID) );
+        }
+        return StaID;
+}
+
+
+// 
+////////////////////////////////////////////////////////////////////////////
+void CGPS_Transform::InitEndianFlag() {
+  short one = 1;
+  char *cp = (char *)&one;
+  if (*cp== 0) {
+    f_IsLittleEndian = false;
+  }
+  else {
+    f_IsLittleEndian = true;
+  }
+}
+
+// 
+////////////////////////////////////////////////////////////////////////////
+void CGPS_Transform::SwitchBytes( char *Start, int Size ) {
+  char Tmp;
+  char *End = Start + Size - 1;
+  for( Tmp = *Start; Start < End; Tmp = *Start ){
+    *Start++ = *End;
+    *End-- = Tmp;
+  }
+}
+
+// 
+////////////////////////////////////////////////////////////////////////////
+unsigned long  CGPS_Transform::JPL_xtractLongVal (unsigned startBitNbr, unsigned xtractNbrBits, const char *msg)
+{
+  unsigned long    retValue=0, i=0;
+
+  unsigned short posBit     = xtractNbrBits - 1;
+
+  for(i=0; i<xtractNbrBits; i++, startBitNbr++)
+    {
+    unsigned short numShift   = 7 - (startBitNbr % 8);
+    unsigned short byteNbr    = startBitNbr / 8;
+    retValue     |= (((msg[byteNbr] >> numShift) & 0x0001) << posBit--);
+
+    }
+
+  return retValue;
+}
+
+// 
+////////////////////////////////////////////////////////////////////////////
+inline void   CGPS_Transform::SwitchIGS_Sta_HdrBytes( RTIGSS_T *StaHdr)
+{
+  SwitchBytes( (char *)&StaHdr->GPSTime, sizeof(unsigned long) );
+  SwitchBytes( (char *)&StaHdr->num_bytes, sizeof(unsigned short) );
+  SwitchBytes( (char *)&StaHdr->rec_id, sizeof(unsigned short) );
+  SwitchBytes( (char *)&StaHdr->sta_id, sizeof(unsigned short) );
+}
+
+// 
+////////////////////////////////////////////////////////////////////////////
+inline void  CGPS_Transform::SwitchIGS_Obs_HdrBytes( RTIGSO_T *ObsHdr)
+{
+  SwitchBytes( (char *)&ObsHdr->GPSTime, sizeof(unsigned long) );
+  SwitchBytes( (char *)&ObsHdr->num_bytes, sizeof(unsigned short) );
+  SwitchBytes( (char *)&ObsHdr->rec_id, sizeof(unsigned short) );       
+  SwitchBytes( (char *)&ObsHdr->sta_id, sizeof(unsigned short) );
+}
+
+// 
+////////////////////////////////////////////////////////////////////////////
+inline void  CGPS_Transform::SwitchIGS_Eph_HdrBytes( RTIGSE_T *EphHdr)
+
+{
+  SwitchBytes( (char *)&EphHdr->CollectedGPSTime, sizeof(unsigned long) );
+  SwitchBytes( (char *)&EphHdr->num_bytes, sizeof(unsigned short) );
+  SwitchBytes( (char *)&EphHdr->rec_id, sizeof(unsigned short) );
+  SwitchBytes( (char *)&EphHdr->sta_id, sizeof(unsigned short) );
+}
+
+// 
+////////////////////////////////////////////////////////////////////////////
+inline short  CGPS_Transform::SwitchIGS_Met_RecBytes( RTIGSM_T *MetHdr)
+{
+short retval = 1;
+short i, num_items;
+  num_items = (short)MetHdr->numobs;
+  SwitchBytes( (char *)&MetHdr->GPSTime, sizeof(unsigned long) );
+  SwitchBytes( (char *)&MetHdr->num_bytes, sizeof(unsigned short) );
+  SwitchBytes( (char *)&MetHdr->rec_id, sizeof(unsigned short) );
+  SwitchBytes( (char *)&MetHdr->sta_id, sizeof(unsigned short) );
+
+    /*switch met data bytes*/       
+  for (i=0; i < num_items; i++)
+  {
+    if (&MetHdr->mets[i] != NULL)
+    {
+      SwitchBytes( (char *)&MetHdr->mets[i], sizeof(long) );
+    }
+    else
+    {
+      retval = -1;
+    }
+
+  }
+return retval;
+}
+// 
+////////////////////////////////////////////////////////////////////////////
+
+short CGPS_Transform::Save_TNAV_T_To_Container(TNAV_T *rtcurrent_eph, short &prn)
+{
+short retval = 1;//, i;
+long PRN;
+
+  PRN = rtcurrent_eph->Satellite;
+
+  if (f_IsLittleEndian)
+  {       
+    SwitchBytes( (char *)&PRN, sizeof(PRN));
+  }
+
+  if ((PRN > 0) && (PRN <= 32))
+  {
+    memcpy( (void *)&TNAV_Eph.Eph[(PRN-1)]  ,rtcurrent_eph,sizeof(TNAV_T));
+    prn = (short)PRN;
+  }
+  else
+  {
+    retval = -1;
+  }
+return retval;
+}
+
+//
+////////////////////////////////////////////////////////////////////////////
+short CGPS_Transform::CA_Extract(char * CAStr, double &CA_Rng)
+{
+
+
+unsigned long CARng2, CARng1;
+short retval = 0;
+double dtemp;
+
+
+  CGPS_Transform::CAFlag = JPL_xtractLongVal(0, 1,  CAStr);       
+  CGPS_Transform::ASFlag = JPL_xtractLongVal(1, 1,  CAStr);       
+  CGPS_Transform::P2Flag = JPL_xtractLongVal(2, 1,  CAStr);       
+  CGPS_Transform::P1Flag = JPL_xtractLongVal(3, 1,  CAStr);
+
+  if (CAFlag)
+  {
+      //Read most significant bits  
+    CARng2 = JPL_xtractLongVal(4, 4,  CAStr);   
+      //Read an int's worth of data
+    CARng1 = JPL_xtractLongVal (8,32,CAStr);
+//  if (f_IsLittleEndian == false)
+//  {
+      //KML June 8/2004
+      //Added this code to deal with Big Endian architectures     
+//    SwitchBytes( (char *) &CARng2, sizeof(CARng2) );
+//    SwitchBytes( (char *) &CARng1, sizeof(CARng1) );
+//  }
+
+    dtemp = 0.0;
+    dtemp = CARng2;
+
+    CA_Rng = dtemp*pow ((double)2,32);
+    CA_Rng +=       CARng1;
+
+    CA_Rng /= 1000;   //CA in metres
+  }
+  else
+  {
+    retval = -1;
+  }
+return retval;
+}
+
+// 
+////////////////////////////////////////////////////////////////////////////
+short CGPS_Transform::P1_P2_Block_Extract(char * P1P2Str, double CA, double &Rng , double &Phase, double &RngF2Delta,short decode_F1orF2Flag )
+{
+short retval =0;
+short PhaseOverFlowFlag;
+long SignFlag,temp;
+
+double RngDelta, PhaseDelta;
+
+  if (decode_F1orF2Flag == 1)
+  {
+    PhaseOverFlowFlag = CGPS_Transform::P1Flag;
+  }
+  else if (decode_F1orF2Flag == 2)
+  {
+    PhaseOverFlowFlag = CGPS_Transform::P2Flag;
+  }
+    //*****************************
+    // Decode Pseudo Range
+    //*****************************
+  SignFlag = JPL_xtractLongVal (0,1,P1P2Str);
+  temp = JPL_xtractLongVal (1,17,P1P2Str);
+
+//KML June 8/2004
+//      if (f_IsLittleEndian == false)
+//      {
+  //Added this code to deal with Big Endian architectures
+//  SwitchBytes( (char *) &temp, sizeof(temp) );
+//      }
+
+
+  RngDelta = temp;
+  RngDelta /= 1000.0;
+
+
+  if (SignFlag)
+  {
+    RngDelta *= -1;       
+  }
+
+
+  if (decode_F1orF2Flag == 2)
+  {
+    RngF2Delta = RngDelta;
+  }
+
+  Rng = CA +  RngDelta;
+
+    //***************************
+    // Decode Phase
+    //***************************
+
+  SignFlag = JPL_xtractLongVal (18,1, P1P2Str);
+  temp = JPL_xtractLongVal (19,21, P1P2Str);
+//      if (f_IsLittleEndian == false)
+//      {
+
+  //KML June 8th 2004
+  //Added this code to deal with Big Endian architectures
+//  SwitchBytes( (char *) &temp, sizeof(temp) );
+//      }
+
+  PhaseDelta =    temp;
+
+  PhaseDelta =    PhaseDelta * 2 / 100000;
+
+
+
+
+    //Phase overflow add to phase
+  if(PhaseOverFlowFlag)
+  {
+    PhaseDelta += MAXL1L2;
+  }
+
+  if (SignFlag)
+  {
+    PhaseDelta *= -1;       
+  }
+
+  if (decode_F1orF2Flag == 1)
+  {
+    // frequency 1
+    Phase = (CA - (ScaleFactor2*RngF2Delta)+ PhaseDelta) / L1;
+  }
+  else if (decode_F1orF2Flag == 2)
+  {
+    // frequency 2      
+    Phase = (CA - (ScaleFactor1*RngF2Delta)+ PhaseDelta) / L2;
+  }
+  else
+  {
+    retval =-1;
+  }
+return retval;
+}
+
+// 
+////////////////////////////////////////////////////////////////////////////
+short CGPS_Transform::Decode_RTIGS_Sta(unsigned char *RTIGS_Str,  unsigned short RTIGS_Bytes, RTIGSS_T &rtigs_sta)
+{
+short retval = 1;
+  memcpy ((void *)&rtigs_sta.rec_id, &RTIGS_Str[0], (sizeof(RTIGSS_T) - sizeof(rtigs_sta.data)));
+  if (f_IsLittleEndian)
+  {
+    SwitchIGS_Sta_HdrBytes( &rtigs_sta);
+  }
+  if (rtigs_sta.rec_id == 100)
+  {
+    if (rtigs_sta.sta_rec_type ==0 )
+    {
+      rtigs_sta.data = NULL;      
+    }
+    else
+    {
+      retval = -2;    //no other type supported at this time
+    }
+  }
+
+
+  else
+  {
+
+
+    retval = -1;
+
+  }
+
+return retval ;
+}
+
+// 
+////////////////////////////////////////////////////////////////////////////
+short CGPS_Transform::Decode_RTIGS_Soc_Obs(unsigned char *SocStr,  short &StrPos, short CMeasIndex, short SocBytes, unsigned long GPSTime)
+{
+short retval =1;
+double CA,  RngF2Delta,  PhaseL1,PhaseL2, P1, P2;
+//static unsigned short PhaseArcStartTime[MAXSV]; moved to class header
+JPL_COMP_OBS_T GPSObs;
+//printf("String pos %hd Total Bytes %hd\n", StrPos,SocBytes);
+
+  if ((StrPos <= SocBytes) && ((CMeasIndex >= 0 ) &&  (CMeasIndex < MAXSV )))
+  {
+    
+    memcpy((void *)&GPSObs.prn, (void *)&SocStr[StrPos], 1);
+
+    if ((GPSObs.prn > 0 ) && (GPSObs.prn <= 32))
+    {
+      StrPos+=1;
+
+      memcpy((void *)&GPSObs.epoch_sequence, (void *)&SocStr[StrPos],2);
+
+      if (f_IsLittleEndian == false)
+      {
+  //KML June 8/2003
+  //Added this code to deal with Big Endian architectures
+  SwitchBytes( (char *) &GPSObs.epoch_sequence, sizeof(GPSObs.epoch_sequence) );
+      }
+
+    //******************************
+    // Read and decode CA
+    //******************************
+      StrPos+=2;
+      memcpy((void *)&GPSObs.ca_range, (void *)&SocStr[StrPos],5);
+      CA_Extract(GPSObs.ca_range, CA);
+
+      if (CGPS_Transform::CAFlag)       //Defined in the Class by CA_Extract
+      {
+    //************************************
+    // Read CA SNR
+    //************************************
+  StrPos+=5;
+  memcpy((void *)&GPSObs.CA_snr, (void *)&SocStr[StrPos],1);
+    //************************************
+    // Read and decode P2 L2
+    //************************************
+  StrPos+=1;
+  memcpy((void *)&GPSObs.L2_range_phase, (void *)&SocStr[StrPos],5);
+
+  P1_P2_Block_Extract(GPSObs.L2_range_phase,  CA, P2 , PhaseL2, RngF2Delta, 2 );
+
+
+  StrPos+=5;
+  memcpy((void *)&GPSObs.L2_snr, (void *)&SocStr[StrPos],1);
+      //************************************
+      // Read and decode P1 L1
+      //************************************
+  StrPos+=1;
+
+
+  memcpy((void *)&GPSObs.L1_range_phase, (void *)&SocStr[StrPos],5);
+
+  P1_P2_Block_Extract(GPSObs.L1_range_phase, CA, P1, PhaseL1, RngF2Delta, 1);
+
+  StrPos+=5;
+  memcpy((void *)&GPSObs.L1_snr, (void *)&SocStr[StrPos],1);
+  StrPos+=1;
+
+  DecObs.Obs[CMeasIndex].GPSTime = GPSTime;    /* broadcast time sec.*/
+  DecObs.Obs[CMeasIndex].chn = CMeasIndex + 1; /* Channel not real*/
+  DecObs.Obs[CMeasIndex].sat_prn = GPSObs.prn; /* satellite ID*/
+  DecObs.Obs[CMeasIndex].ntrvl = 1;      /* number of seconds Changed from 0 to 1 Nov. 25/2003*/
+  DecObs.Obs[CMeasIndex].flag[0] = 4;    /*observation quality flags*/   //KML Changed Nov. 25/2000 to 4 to indicate Benchmark
+
+  if (PhaseArcStartTime[(short)(GPSObs.prn-1)] !=  GPSObs.epoch_sequence)
+  {
+    PhaseArcStartTime[(short)(GPSObs.prn-1)] =  GPSObs.epoch_sequence;
+    DecObs.Obs[CMeasIndex].flag[0] |= 0x20;
+  }
+
+  DecObs.Obs[CMeasIndex].l1_pseudo_range = CA;      /* frequency-1 CA pseudorange */
+  DecObs.Obs[CMeasIndex].l1_phase = PhaseL1;      /* frequency-1 CA carrier phase   */
+      //****************************************************
+      // Changed SNR Ashtech to DBHz Nov 15/2002
+      //****************************************************
+  DecObs.Obs[CMeasIndex].l1_sn  =  GPSObs.CA_snr;
+
+  DecObs.Obs[CMeasIndex].p1_pseudo_range = P1;  /* frequency-1 P1 carrier phase   */
+  DecObs.Obs[CMeasIndex].p1_phase  =  PhaseL1;    /* frequency-1 P1 pseudorange */
+
+  DecObs.Obs[CMeasIndex].p1_sn = GPSObs.L1_snr;
+
+  DecObs.Obs[CMeasIndex].l2_pseudo_range = P2;    /* frequency-2 pseudorange (XCorr) */
+  DecObs.Obs[CMeasIndex].l2_phase = PhaseL2;  /* frequency-2 carrier phase (XCorr)  */
+
+  DecObs.Obs[CMeasIndex].l2_sn = GPSObs.L2_snr;
+  DecObs.Obs[CMeasIndex].p2_pseudo_range  = P2;       /* frequency-2 pseudorange     */
+  DecObs.Obs[CMeasIndex].p2_phase = PhaseL2;      /* frequency-2 carrier phase   */
+      }
+      else
+      {
+      //skip this obs
+  DecObs.Obs[CMeasIndex].sat_prn = 0;
+      }
+    }
+    else
+    {
+      retval = -2;
+
+    }
+  }
+  else
+  {
+    retval = -1;
+  }
+return retval;
+}
+
+// 
+////////////////////////////////////////////////////////////////////////////
+short CGPS_Transform::RTIGSO_Str_To_CMEAS(unsigned char *RTIGSO_Str, short RTIGS_Bytes, RTIGSO_T &rtigs_obs)
+{
+short retval =1,i, StrPos;//, HdrRetval;
+//short  NumObs= 0;
+short decoded_cnt = 0;
+short  IGSObsMinusPtr;
+
+
+  //************************************
+  // Zero out CMEAS_T container
+  //************************************
+memset((void *)&DecObs.Obs[0], 0 , sizeof(ARR_OBS_T) );
+
+    //***********************************************
+    // Decode Header store in class container
+    //***********************************************
+
+
+  StrPos = IGSObsMinusPtr = sizeof(RTIGSO_T) - sizeof (rtigs_obs.data);
+
+  memcpy ((void *)&rtigs_obs.rec_id, RTIGSO_Str, IGSObsMinusPtr);
+
+  if (f_IsLittleEndian)
+  {
+    SwitchIGS_Obs_HdrBytes( &rtigs_obs);
+  }
+
+
+//      printf("RecNumber : %hd Station ID %hd Num Obs %hd NumBytes %hd\n",rtigs_obs.rec_id, rtigs_obs.sta_id, rtigs_obs.num_obs, rtigs_obs.num_bytes);
+  if((rtigs_obs.rec_id == 200) && (rtigs_obs.num_obs <= MAXCHANNELS_FOR_SOCKETS_TYPE1))
+  {
+    for (i = 0 ; i < rtigs_obs.num_obs;i++)
+    {
+    //*********************************************
+    // the following function decodes the soc
+    // structure and writes the obs to the
+    // class's CMEAS container
+    //*********************************************
+
+      if (Decode_RTIGS_Soc_Obs( RTIGSO_Str, StrPos, decoded_cnt, RTIGS_Bytes, rtigs_obs.GPSTime) < 0)
+      {
+    retval = -2;
+      }
+      else
+      {
+  decoded_cnt ++;
+      }
+    }//end of for
+    retval = NumObsRead = decoded_cnt; //NumObsRead class member
+  }
+  else
+  {
+    retval = -1;
+  }
+//ObsSeqNum++;
+return retval;
+}
+
+
+// 
+////////////////////////////////////////////////////////////////////////////
+short CGPS_Transform::Decode_RTIGS_Obs(unsigned char *RTIGSO_Str,  unsigned short RTIGS_Bytes,RTIGSO_T &rtigs_obs)
+{
+  short retval = 1;//, i;
+
+
+  if ((retval = RTIGSO_Str_To_CMEAS(RTIGSO_Str, RTIGS_Bytes, rtigs_obs)) < 0)
+  {
+    retval = -1;
+  }
+
+return retval;
+}
+
+// 
+////////////////////////////////////////////////////////////////////////////
+short  CGPS_Transform::Decode_RTIGS_Met(unsigned char *RTIGS_Str,  unsigned short RTIGS_Bytes, RTIGSM_T *rtigs_met)
+{
+short retval = 1;
+short numbytes = 0;
+numbytes = sizeof(RTIGSM_T) -  sizeof(rtigs_met->mets);
+memcpy ((void *)rtigs_met, RTIGS_Str, numbytes);
+
+    if ((short)rtigs_met->numobs <= 3)
+  {
+    if (rtigs_met->mets != NULL)
+    {
+      memcpy ((void *)&rtigs_met->mets[0], &RTIGS_Str[numbytes], ((short)rtigs_met->numobs * sizeof(long)) );
+      if (f_IsLittleEndian)
+      {
+  SwitchIGS_Met_RecBytes( rtigs_met);
+      }
+      if (rtigs_met->rec_id != 400)
+      {
+  retval = -1;
+      }
+    }
+    else
+    {
+      retval = -2;
+      delete [] rtigs_met->mets;
+    }
+  }
+  else
+  {
+    printf("failed number of Obs\n");
+  }
+
+return retval;
+}
+
+// 
+////////////////////////////////////////////////////////////////////////////
+short CGPS_Transform::Decode_RTIGS_Eph(unsigned char *RTIGS_Str,  unsigned short RTIGS_Bytes, RTIGSE_T &rtigs_eph, short &PRN)
+{
+  short retval = 1;//, i;
+  short  index = 0;
+  short prn;
+  const short SubFrameSize = 24;
+  TNAV_T trans_eph;
+  index = sizeof(RTIGSE_T ) - sizeof (rtigs_eph.data);
+
+  memcpy ((void *)&rtigs_eph.rec_id, &RTIGS_Str[0], index);       //copy header into struct from string
+  if (f_IsLittleEndian)
+  {
+    SwitchIGS_Eph_HdrBytes( &rtigs_eph);
+  }
+
+  if (rtigs_eph.rec_id == 300)
+  {
+    //*********************************************
+    // the following method saves the eph
+    // in the class's TNAV_T container
+    //*********************************************
+    trans_eph.GPSCollectedTime =    rtigs_eph.CollectedGPSTime;
+    trans_eph. Satellite = (long)rtigs_eph.prn;
+    //********************************************
+    // Container class is in network byte order
+    //********************************************
+    if (f_IsLittleEndian)
+    {
+      SwitchBytes( (char *)&trans_eph.GPSCollectedTime, sizeof(trans_eph.GPSCollectedTime) );
+      SwitchBytes( (char *)&trans_eph. Satellite, sizeof(trans_eph. Satellite) );
+    }
+
+    memcpy((void *)&trans_eph.SubFrame1, (const void *)&RTIGS_Str[index], SubFrameSize);
+    memcpy((void *)&trans_eph.SubFrame2, (const void *)&RTIGS_Str[(index + SubFrameSize)], SubFrameSize);
+    memcpy((void *)&trans_eph.SubFrame3, (const void *)&RTIGS_Str[(index + (SubFrameSize * 2)) ], SubFrameSize);
+    if (Save_TNAV_T_To_Container(&trans_eph, prn) >= 1)       //function saves eph in container and returns prn
+    {
+  PRN = prn;
+    }
+    else
+    {
+      retval = -1;
+    }
+  }
+  else
+  {
+    retval = -1;
+  }
+
+return retval;
+}
+
+void CGPS_Transform::print_CMEAS()
+{
+short i;
+        printf("\nGPSTime   SV    CA      SNR     P1      SNR     P2      SNR\n");
+        printf("Seconds         (m)     DBHz    (m)     DBHz    (m)     DBHz\n");
+        for (i=0; i < NumObsRead ; i++)
+        {
+                printf("%ld %2hd %10.1lf %4.1f %10.1lf %4.1f %10.1lf %4.1f \n",DecObs.Obs[i].GPSTime, DecObs.Obs[i].sat_prn,
+                                                                                DecObs.Obs[i].l1_pseudo_range,DecObs.Obs[i].l1_sn,
+                                                                                DecObs.Obs[i].p1_pseudo_range, DecObs.Obs[i].p1_sn,
+                                                                                DecObs.Obs[i].l2_pseudo_range,DecObs.Obs[i].l2_sn);
+        }
+}
+
Index: trunk/BNC/RTIGS/rtigs.h
===================================================================
--- trunk/BNC/RTIGS/rtigs.h	(revision 52)
+++ trunk/BNC/RTIGS/rtigs.h	(revision 52)
@@ -0,0 +1,127 @@
+
+#ifndef CGPS_TRANSFORM_H
+#define CGPS_TRANSFORM_H
+
+#include <string.h>
+#include <stdio.h>
+#include <math.h>
+#include <sys/time.h>
+#include <iostream>
+
+using namespace std;
+
+#include "rtacp.h"
+#include "rtstruct.h"
+#include "rtigs_records.h"
+
+#define MAXCHANNELS_FOR_SOCKETS_TYPE1 12
+#define MAXSV        32
+#define ScaleFactor1 4.0914555603263203   //(f1ion + f2ion)
+#define ScaleFactor2 2 * F1ION
+#define MAXL1L2      41.94302
+
+void SwitchBytes( char *Start, int Size );
+
+typedef struct
+{
+    unsigned char prn;       // satellite ID
+    unsigned short epoch_sequence; // like Ashtech seq number of phase epochs
+        // was like this, now modulo 10 hours,
+        // each digit is now 1 sec, not .05 secs like before
+
+    char ca_range[5];    // ca range in millimeters
+        // first 4 bits are status bits, as follows
+        // if bit 7 on, sucessful packing of ca_range
+        // if bit 6 on, Z track mode or AS is on
+        // if bit 5 on, overflow of L2_block phase
+        // if bit 4 on, overflow of L1_block phase
+        // next 36 bits are the observable
+        // 68719.476735 is the max allowable obsev.
+        // if not packed, L2_block and L1_block is
+        // just then packed with 0s
+
+    unsigned char CA_snr;  // receiver snr for ca in dbHz KML the SNR is (DBHz * 4.25) rounded to an int (max is 60.0)
+
+    char L2_range_phase[5];
+        // first 2 bytes and 2 bits is for the range, next 6 bits and 2 bytes are for phase.
+        //
+        // range units are in millimeters, from -131071 to 131071  (2^17 - 1)
+        // 0000 0000 0000 0000 01 would be +1 mm
+        // 1000 0000 0000 0000 01 would be -1 mm
+        // 0100 0000 0000 0000 00 would be 65536 mm
+        // 1100 0000 0000 0000 00 would be -65536 mm
+        // 0111 1111 1111 1111 11 would be 131071 mm
+        // 1111 1111 1111 1111 11 woule be -131071 mm
+        // dynamic range must be <= 131.071 meters
+        //
+        // phase units are in 2/100 millimeters from -4194304 to 4194304
+        // 00 0000 0000 0000 0000 0001 would be +.02 mm
+        // 10 0000 0000 0000 0000 0001 would be -.02 mm
+        // 01 1111 1111 1111 1111 1111 ( 2097151) would be 41943.02 mm
+        // 11 1111 1111 1111 1111 1111 (-2097151) would be -41943.02 mm
+        //   (2^21 - 1)*2 mm
+        // dynamic range must be <= 41.94302 meters
+        //
+        // note if the limits are exceded, a -0 (minus zero) is returned
+        // indicating not a number
+        //
+        // Note however, we extended this dynamic range to 83.88606 meters as
+        // below with the spare bits in the ca_range field. If this limit
+        // is exceeded we return a -0 ( minus zero )
+    unsigned char L2_snr;  // snr for this data type in dbHz KML the SNR is (DBHz * 4.25) rounded to an int (max is 60.0 )
+
+    char L1_range_phase[5]; // same as format for L2_range_phase
+
+    unsigned char L1_snr;  // snr for this data type in dbHz KML the SNR is (DBHz * 4.25) rounded to an int (max is 60.0 )
+
+} JPL_COMP_OBS_T;
+
+typedef struct
+{
+   TNAV_T   Eph[MAXSV];      //32 prns
+} ARR_TNAV_T;
+
+typedef struct {
+   CMEAS_T  Obs[MAXSV];   //32 obs
+} ARR_OBS_T ;
+
+class CGPS_Transform {
+private:
+  ARR_OBS_T     DecObs;
+  ARR_TNAV_T    TNAV_Eph;
+  short         NumObsRead;
+  short         CAFlag;
+  short          ASFlag;
+  short          P2Flag;
+  short          P1Flag;
+  bool           f_IsLittleEndian;
+  unsigned short PhaseArcStartTime[MAXSV];
+public:
+  CGPS_Transform();
+  ~CGPS_Transform();
+  void           InitEndianFlag();
+  short          Decode_Soc_Obs(unsigned char  *SocStr, short &StrIndex, short index, short SocBytes);
+  short          Decode_RTIGS_Soc_Obs(unsigned char *SocStr,  short &StrPos, short CMeasIndex, short SocBytes, unsigned long GPSTime);
+  short          RTIGSO_Str_To_CMEAS(unsigned char *RTIGSO_Str, short RTIGS_Bytes, RTIGSO_T &rtigs_obs); //done needs testing KML
+  void           print_CMEAS();
+  short          Save_TNAV_T_To_Container(TNAV_T *rtcurrent_eph, short &prn);
+  short          CA_Extract(char * CAStr, double &CA_Rng);                 //done
+  short          P1_P2_Block_Extract(char * P1P2Str, double CA, double &Rng , double &Phase, double &RngF2Delta,short decode_F1orF2Flag );//done
+  unsigned long  JPL_xtractLongVal (unsigned startBitNbr, unsigned xtractNbrBits, const char *msg);        //done
+  void           SwitchBytes( char *Start, int Size );
+  inline void    SwitchIGS_Sta_HdrBytes( RTIGSS_T *StaHdr);
+  inline void    SwitchIGS_Obs_HdrBytes( RTIGSO_T *ObsHdr);
+  inline void    SwitchIGS_Eph_HdrBytes( RTIGSE_T *EphHdr);
+  inline short   SwitchIGS_Met_RecBytes( RTIGSM_T *MetHdr);
+  unsigned short GetRTIGSHdrRecType(unsigned char *RTIGS_Str);
+  unsigned short GetRTIGSHdrStaID(unsigned char *RTIGS_Str);
+  unsigned short GetRTIGSHdrRecBytes(unsigned char *RTIGS_Str);
+  unsigned long  GetRTIGSHdrGPSSeconds(unsigned char *RTIGS_Str);
+  short          Decode_RTIGS_Sta(unsigned char *RTIGS_Str,   unsigned short RTIGS_Bytes, RTIGSS_T &rtigs_sta_dec);        // contents of record contain all info
+  short          Decode_RTIGS_Obs(unsigned char *RTIGS_Str,  unsigned  short RTIGS_Bytes, RTIGSO_T &rtigs_obs);    // stores obs in class container
+  short          Decode_RTIGS_Eph(unsigned char *RTIGS_Str,  unsigned  short RTIGS_Bytes, RTIGSE_T &rtigs_eph, short arrPRN[]);    // stores eph in class container
+  short          Decode_RTIGS_Eph(unsigned char *RTIGS_Str,  unsigned  short RTIGS_Bytes, RTIGSE_T &rtigs_eph, short &PRN); //stors in class and returns prn
+  short          Decode_RTIGS_Met(unsigned char *RTIGS_Str,   unsigned short RTIGS_Bytes, RTIGSM_T *rtigs_met);    // contents of record contain all info.
+};
+
+#endif
Index: trunk/BNC/RTIGS/rtigs_records.h
===================================================================
--- trunk/BNC/RTIGS/rtigs_records.h	(revision 52)
+++ trunk/BNC/RTIGS/rtigs_records.h	(revision 52)
@@ -0,0 +1,251 @@
+/***************************************************************************
+                          rtigs_records.h  -  description
+                             -------------------
+    begin                : Wed Aug 27 2003
+    copyright            : (C) 2003 by Ken MacLeod
+    email                : ken.macleod@nrcan.gc.ca.
+ ***************************************************************************/
+
+/***************************************************************************
+ *
+ *   This program 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. 
+ *
+ ***************************************************************************/
+#ifndef _RTIGS_T
+#define _RTIGS_T
+
+/*****************************************************************************
+* RT-IGS record structures
+*
+*	General:
+*
+*		Every record will have a defined number. We propose the following:
+*				1) Station record number 100;
+*				2) Observation record number 200;
+*				3) Ephemeris record number 300;
+*				4) Meteorological record number 400;
+*
+*		Every station will have a unique number. We propose the following:
+*
+*				1-99 reserved for JPL
+*				100-199 reserved for NRCan
+*				200-299 reserved for NGS
+*				300-399 reserved for ESOC
+*				400-499 reserved for GFZ
+*				500-599 reserved for BKG
+*				600-699 reserved for GEOSCIENCE AUS.
+*				700-799 others
+*				etc
+*		The number of bytes in each real time message will include the header as
+*		well as the data content, but NOT the pointer. For example :
+*
+*			1) A station message is output once per hour and is 20 bytes
+*
+*			2) An observation message is output once per second. The header is
+*				12 bytes long and the SOC data is 21 bytes per PRN. So a typical
+*				RTIGSO_T message will be 390 bytes if 8 sats are being tracked
+*
+*			3) An ephemeris message is output when the ephemeris is decoded by the
+*				GPS receiver. The time in the Ephemeris header is the collected time.
+*				One ephemeris can be bundled in a RTIGSE_T.
+*				A RTIGSE_T  message contains one eph.  the  message consists of 12 header
+*				bytes and 72 ephemeris bytes, for a total of 84 bytes.
+*
+*			4) The RTIGSM_T  (met) message should be issues once every 15 minutes.
+*				 A basic met message consists of a 12 byte header and 3 longs (temp,
+*				 press and relative humidity) for a total of 24 bytes.
+*				
+*		All records will be related to a station configuration indicated by the
+*		Issue of Data Station(IODS). The IODS will enable the user to identify
+*		the equipment and software that was used to derive the observation data.
+*
+*		Each record header will contain the GPS Time in seconds which is
+*		continuous from ((6 Jan-1980)).
+*
+*		The data payload of each record will consist of observations. The
+*		structures shown below indicate a pointer to data but in fact the broadcast
+*		messages will not contain the pointed only the data. Users will have to
+*		manage the data and the pointer is shown to illustrate where the data is
+*		located in the message and one possible data management option.
+*		
+*
+* 		All record data in network byte order (Big Endian), ie  IA32 users will
+*		have to swap bytes ;-)
+******************************************************************************
+* Developed by Ken MacLeod Aug. 27/2003
+* Updated and revised Feb. 10/2004 with comments from R. Muellershoen
+*****************************************************************************/
+
+#define MAXSTA	256
+#define MAXSOC 264		/* 12 + (12 * 21) = 264*/
+#define MAXEPH 876			/* 12 + (12 * 72) = 876*/
+#define MAXMETS 6
+
+
+/*****************************************************************************
+* Structure name : RTIGSS_T
+*
+*		Purpose:
+* 		
+*		Encapsulate the station information that is required for real-time users
+*
+*		Users should use this record is to  link data to a specific station
+*		configuration.
+*		The station message should be transmitted by station operator every
+*		hour and upon update.
+*		 If the stations record Issue of Data Station(IODS) and the IODS in the
+*		observation record do not match then the data should be used without
+*		further investigation
+*
+*		
+*
+* 		This record is not intended to replace the IGS Station log but it is
+*		seen as a subset of the IGS log and contains information that enables
+*		real-time users to monitor station changes.
+*
+* 
+*Version: 1.0
+*
+*By Ken MacLeod Aug. 27/2003
+*Changes: Revised Feb. 10/2004 updated the message description info.
+ ****************************************************************************/
+
+typedef struct rtigs_station
+{
+	unsigned short rec_id; 					/*100 indicates station record this message */
+																/* to be issued once per hour*/
+	unsigned short sta_id;					/*unique number assigned to each station. */
+																/* Uniquely linked to an IGS Station log by */
+																/* the station record*/
+	unsigned long GPSTime;				/* time of issue, GPS time is seconds from */
+																/* the beginning of GPS (6 Jan-1980)*/
+	unsigned short num_bytes;			/* total number of bytes in the message,  */
+																/* including the header*/
+	unsigned char IODS;						/* a flag indicating the current station */
+																/* configuration this will change every time */
+																/* the station hardware changes*/														
+	unsigned char sta_rec_type;			/* could be various station data formats: */
+																/*  0 indicates that there is no additional */
+																/*  station data*/
+	char IGS_UniqueID[8];					/* IGS ID eg NRC1 will use IGS 4 character */
+																/* standard but c requires a \0 to terminate */
+																/* the string */
+	unsigned char *data;						/* default station headers Does Not  */
+																/* contain data.  The current message does */
+																/* not contain additional station  */
+																/* information the pointer is shown only */
+																/* to illustrate  options*/
+}RTIGSS_T;
+
+/******************************************************************************
+ * Structure name : RTIGSO_T
+ *
+ * Purpose :  GPS Observations
+ *						Currently the JPL Soc format is used to compress the
+ *						observation data. 
+ *						See JPL's website for a description of the SOC
+ * 						compression routine
+ *Version: 1.0
+ *
+ *By Ken MacLeod Aug. 27/2003
+ *Changes: Revised Feb. 10/2004 Remove station clock and obs time
+ * in milliseconds and add to the message description
+ *****************************************************************************/
+typedef struct rtigs_obs
+{
+	unsigned short rec_id;					/* 200 indicates rt-igs gps observation*/
+	unsigned short sta_id;					/* Unique num. assigned to each station */
+																/* Uniquely linked to an IGS Station log y */
+																/* the station record*/
+	unsigned long GPSTime;				/* observation time of issue, GPS time is */
+																/* seconds from the beginning of GPS */
+																/* (6 Jan-1980)*/
+	unsigned short num_bytes;			/* total number of bytes in the message,  */
+																/* including the header, but not the data */
+																/* pointer*/
+	unsigned char IODS;						/* a flag indicating the current station */
+																/* configuration that derived  the */
+																/* observations this  value will change */
+																/* every time the station configuration */
+																/* changes*/
+	unsigned char num_obs;				/* number of GPS Observations in data block*/
+	unsigned char *data;						/* pointer to soc observation data (4 byte pointer), this pointer */
+																/* is not in the message the data starts */
+																/* here,  the pointer is used to manage the */
+																/* SOC data once the RTIGS0_T message has */
+																/* been decoded */
+} RTIGSO_T;
+/*****************************************************************************
+ * Structure name : RTIGSE_T
+ *
+ * Purpose :  SV Ephemeris in Broadcast format parity removed
+ *
+ *Version: 1.0
+ *
+ *By Ken MacLeod Aug. 27/2003
+ *Changes: Revised Feb. 10/2004
+ *****************************************************************************/
+typedef struct rtigs_ephemeris
+{
+	unsigned short	rec_id;						/* 300 indicates rt-igs eph*/
+	unsigned short	sta_id;						/* unique number assigned */
+																	/* to each station*/
+	unsigned long CollectedGPSTime;					/* time ephemeris received at */
+																	/*station, GPS time is seconds */
+																	/* from the beginning of GPS */
+																	/* (6 Jan-1980)*/
+	unsigned short	num_bytes;				/* total number of bytes in the message, */
+																	/* including the header, but not the size */
+																	/*  of the data pointer*/
+	unsigned char	IODS;							/* a flag indicating the current station */
+																	/* configuration that derived the */
+																	/* observations this will change every */
+																	/* time the sta config changes*/
+	unsigned char prn;								/* PRN*/
+	unsigned char *data;							/* In the RTIGSE_T message the data */
+																	/* starts here,  the pointer is used to */
+																	/* manage the eph data once the RTIGSE_T */
+																	/* message has  been decoded */
+																	/* The RTIGSE_T eph. format consists of */
+																	/* the 3 broadcast sub frames  with the */
+																	/* parity bits removed so 3 */
+																	/* subframes = 72 bytes */
+} RTIGSE_T;
+
+/***********************************************************************
+ * Structure name : RTIGSM_T
+ *
+ * Purpose :  Station Meteorological observations
+ *
+ *Version: 1.0
+ *
+ *By Ken MacLeod Aug. 27/2003
+ *Changes: Changed the met array to an long pointer
+ ***********************************************************************/
+typedef struct rtigs_mets
+{
+	unsigned short		rec_id; 					/* 400 indicates rt-igs met*/
+	unsigned short		sta_id; 					/* unique number assigned to each */
+																	/* station*/
+	unsigned long		GPSTime;				/* time of issue, GPS time is seconds */
+																	/* from the beginning of GPS (6 Jan-1980)*/
+	unsigned short		num_bytes; 			/* total number of bytes in the message,*/
+																	/* including the header but not the pointer*/
+	unsigned char		IODS;						/* a flag indicating the current station */
+																	/* config that derived the observations */
+																	/* this will change every time the station */
+																	/* configuration changes*/
+	unsigned char		numobs;					/* if only temp, press, rel hum then : 3  */
+	long *mets;											/* temp(Deg C),   press (mb),  */
+																	/* rel humid(%),  zenith Wet(metres), */
+																	/* Zenith Dry(metres),  Zenith Total */
+																	/* (metres) and  each scaled by 1000 so */
+																	/* 1000.123 mb = 1000123*/
+																	/*if the zenith observations are not */
+																	/* present only enter 3 for the num of obs.*/
+} RTIGSM_T;
+
+#endif
Index: trunk/BNC/RTIGS/rtstruct.h
===================================================================
--- trunk/BNC/RTIGS/rtstruct.h	(revision 52)
+++ trunk/BNC/RTIGS/rtstruct.h	(revision 52)
@@ -0,0 +1,233 @@
+/***************************************************************************
+                          rtstruct.h  -  description
+                             -------------------
+    begin                : Tue Mar 7 2000
+    copyright            : (C) 2000 by Ken MacLeod
+    email                : macleod@geod.nrcan.gc.ca
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program 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.                                   *
+ *                                                                         *
+ ***************************************************************************/
+/*-------------------------------------------------------------------------*/
+/* Name : rtstruct.h								   */
+
+/* Purpose : structure definitions for the wide area prototype		   */
+
+/* RCS: $Header: rtstruct.h,v 3.10 99/08/18 15:06:33 macleod Released $ */
+
+/* Externals :                                                             */
+/*-------------------------------------------------------------------------*/
+#ifndef _RTSTRUCT
+#define _RTSTRUCT
+
+/**************************************************************************/
+/***									***/
+/***	RTAP Function Prototypes:					***/
+/***									***/
+/***		1) typedef defines the RTAP types for non-RTAP		***/
+/***		   compiles						***/
+/***									***/
+/***		2) To compile within RTAP use -D_RTAP compile option	***/
+/***									***/
+/***    Note: Most function prototypes are commented out until the	***/
+/***	      corresponding functions are changed accordingly		***/
+/***									***/
+/**************************************************************************/
+
+#ifdef _RTAP
+
+#include <rtap/types.h>
+#include <rtap/database.h>
+
+#else
+
+typedef double          rtDouble;
+typedef float           rtFloat;
+typedef char            rtChar;
+typedef unsigned char   rtUInt8;
+typedef unsigned short  rtUInt16;
+typedef unsigned int    rtUInt32;
+typedef int             rtInt32;
+typedef short           rtInt16;
+typedef char            rtInt8;
+typedef int             rtInt;
+typedef struct timeval	rtTime;
+
+typedef rtUInt32        rtDbQuality;
+typedef rtUInt8         rtLogical;
+typedef rtUInt8         rtBytes4[4];
+typedef rtUInt8         rtBytes8[8];
+typedef rtUInt8         rtBytes12[12];
+typedef rtUInt8         rtBytes16[16];
+typedef rtUInt8         rtBytes20[20];
+typedef rtUInt8         rtBytes32[32];
+typedef rtUInt8         rtBytes48[48];
+typedef rtUInt8         rtBytes64[64];
+typedef rtUInt8         rtBytes80[80];
+typedef rtUInt8         rtBytes128[128];
+typedef rtUInt8         rtBytes256[256];
+
+#endif
+
+/* Now define our constants */
+/* Our CONS_T structure member names are now lower case to prevent conflict */
+
+#define  MAX_STA     	     (24)		/* maximum stations  	   */
+#define  PI   (3.141592653589793)		/* value of PI		   */
+#define  DTR  (0.017453292519943)		/* deg to rad conversion con. */
+#define  C	   (299792458.00)		/* speed of light in vaccuum  */
+#define  F1	    (1575.42E+06)		/* GPS L1 frequency	   */
+#define  F1_SQUARE	(F1 * F1)		/* GPS L1 frequency squared   */
+#define  L1              (C / F1)		/* GPS L1 wavelength          */
+#define  F2	    (1227.60E+06)		/* GPS L2 frequency	   */
+#define  F2_SQUARE	(F2 * F2)		/* GPS L2 frequency squared   */
+#define  L2              (C / F2)		/* GPS L2 wavelength          */
+#define  F3             (F1 - F2)		/* GPS widelane frequency     */
+#define  L3              (C / F3)		/* GPS widelane wavelength    */
+#define  F1ION (F2_SQUARE / (F1_SQUARE - F2_SQUARE)) /* L1 iono scale factor */
+#define  F2ION (F1_SQUARE / (F1_SQUARE - F2_SQUARE)) /* L2 iono scale factor */
+#define  IonoH	       (350000.0)		/* Ionospheric height in metres */
+
+				/*******************************
+				* Content: Broadcast Orbit
+				*          Representation
+				********************************/
+typedef struct broadcast{
+double	satellite;						/* satellite number 	*/
+double	gps_week;					/* gps week number from 81/01/06*/
+double 	user_range_acc;		/* user range accuracy in meters  */
+double	sat_health;				/* satellite health (all bits)   */
+double	fit_interval;				/* ephemeris fit interval   */
+double	l2code;						/* Codes on L2 indicator  */
+double	l2pflag;						/* Data flag for L2 P code */
+double	issue_of_clock;		/* issue of clock 	  */
+double	issue_of_eph;			/* issue of ephemeris 		   */
+double	transmit_time;			/* time of transmission	   */
+double	clock_ref_time;			/* reference time of the clock	   */
+double	eph_ref_time;			/* reference time of the ephem   */
+double	a0;								/* satellite clock coefficient	   */
+double	a1;								/* satellite clock coefficient	   */
+double	a2;								/* satellite clock coefficient	   */
+double 	ref_mean_anmly;		/* mean anomoly at reference time */
+double	mean_mot_diff;			/* mean motion difference   */
+double	orbit_ecc;					/* orbit eccentricity		   */
+double	orbit_semimaj;			/* square root of orbit semimajor axis */
+double	arg_of_perigee;		/* argument of perigee	   */
+double	orbit_incl;					/* orbit inclination		   */
+double	incl_rate;					/* orbit inclination rate   */
+double	right_asc;					/* right ascension	   */
+double	right_asc_rate;			/* rate of right ascension   */
+double	lat_cos_corr;			/* ampl of cos harm corr to arg of lat */
+double	lat_sin_corr;				/* ampl of sin harm corr to arg of lat */
+double	orbit_cos_corr;			/* ampl of cos harm corr to orbit	   */
+double	orbit_sin_corr;			/* ampl of sin harm corr to orbit	   */
+double	incl_cos_corr;			/* ampl of cos harm corr to the incl   */
+double	incl_sin_corr;			/* ampl of sin harm corr to the incl   */
+double	group_delay;			/* estimated group delay differential  */
+}BEPH_T;
+
+
+
+					/******************************
+					* Content:Receiver independent 
+					* GPS observation data structure
+					* contains all possible obs
+					*******************************/
+typedef struct complete_measurement{
+unsigned long		GPSTime;			/* broadcast time sec.*/
+unsigned char	  chn;							/* Channel*/
+unsigned char   sat_prn;				/* satellite ID*/
+unsigned short	ntrvl;			/* number of seconds */
+unsigned char		flag[4];								/*observation quality flags*/
+float				l1_sn;				/* signal-to-noise CA frequency 1 */
+
+double		l1_pseudo_range;	/* frequency-1 CA pseudorange */
+double		l1_phase;		/* frequency-1 CA carrier phase   */
+											/*KML for this struct SNR will be DBHz */
+double		p1_pseudo_range;	/* frequency-1 P1 pseudorange */
+double		p1_phase;		/* frequency-1 P1 carrier phase   */
+float				p1_sn;			/* signal-to-noise P1 frequency 1 */
+float 			l2_sn;			/* signal-to-noise frequency 2 */
+
+                      /*KML for this struct SNR will be DBHz */
+double		l2_pseudo_range;	/* frequency-2 pseudorange (XCorr) */
+double		l2_phase;		/* frequency-2 carrier phase (XCorr)  */
+										/*KML for this struct SNR will be DBHz */
+double		p2_pseudo_range;	/* frequency-2 pseudorange     */
+double		p2_phase;		/* frequency-2 carrier phase   */
+}CMEAS_T;
+
+
+
+
+					/*******************************
+					* Content:Turbo Rogue Receiver 
+					* Raw Turbo Broadcast Message
+					*******************************/ 
+typedef struct rawtbeph{
+char		block_type;		/* Turbo record type */
+char		block_length;		/* Turbo record in bytes */
+char		Satellite;                      /* Sat. PRN */
+char		Dummy;
+long		GPSEpochTime;
+long		GPSCollectedTime;
+unsigned long	SubFrame1[6];      /* SubFrame1 hexbits */
+unsigned long	SubFrame2[6];      /* SubFrame2 hexbits */
+unsigned long	SubFrame3[6];		 /* SubFrame3 hexbits */
+}RNAV_T;
+
+					/********************************
+					* Content: Turbo Rogue Receiver 
+					* Raw TurboRogue GPS observation 
+					********************************/
+typedef struct rawtbobserv{
+char		BlockType; 
+char		BlockSize;
+char		Satellite;
+char		Channel;
+long		GPSTimeTag;
+char		SampleInterval;
+char		Flags;
+unsigned short	SNR[3];
+double		CAfaz;
+double		CAtau;
+float		faz1;
+float		tau1;
+float		faz2;
+float		tau2;
+}TBIN_T;
+
+				/*******************************
+				* Content:Turbo Rogue Receiver
+				* Turbo Broadcast Message 
+				*******************************/
+typedef struct reducedbeph{
+long		Satellite;
+long		GPSCollectedTime;
+unsigned long	SubFrame1[6];      /* SubFrame1 hexbits */
+unsigned long	SubFrame2[6];      /* SubFrame2 hexbits */
+unsigned long	SubFrame3[6];		 /* SubFrame3 hexbits */
+}TNAV_T;
+
+
+					/*************************************
+					* Content: Meteorological Observations
+					* Summarized  met data
+					*************************************/
+typedef struct scaledmet{
+long		GPSTime;					/*GPS Time */
+long		Temp;							/*scaled temperature */
+long		TempStdDev;			  /*scaled temp. std dev */
+long		Pressure;					/*scaled pressure */
+long		PressureStdDev	;	/*scaled press. std dev */
+long		RelHum;					  /*scaled percentage */
+long		RelHumStdDev;		  /*scaled prec. std dev */
+}METS_T;
+
+#endif
Index: trunk/BNC/bnc.bck
===================================================================
--- trunk/BNC/bnc.bck	(revision 39)
+++ trunk/BNC/bnc.bck	(revision 52)
@@ -2,10 +2,14 @@
 fileName="bnc`date +%y%m%d`"
 
-tar -cvf ${fileName}.tar bnc.bck    \
-                         *.cpp      \
-                         *.h        \
-                         *.pro      \
-                         RTCM/*.cpp \
-                         RTCM/*.h
+tar -cvf ${fileName}.tar bnc.bck     \
+                         *.cpp       \
+                         *.h         \
+                         *.pro       \
+                         RTCM/*.cpp  \
+                         RTCM/*.h    \
+                         RTCM3/*.cpp \
+                         RTCM3/*.h   \
+                         RTIGS/*.cpp \
+                         RTIGS/*.h
 
 gzip      ${fileName}.tar
