--- ntp-4.2.0a+stable/ntpd/refclock_ripencc.c	2003-03-30 23:50:48.000000000 +0200
+++ ntp-4.2.0a+stable.patched/ntpd/refclock_ripencc.c	2005-07-07 12:36:09.000000000 +0200
@@ -30,6 +30,9 @@
  *
  * Rewrite of the driver for ntpd-4.x.x by Mark Santcroos <marks@ripe.net>
  *
+ * Big-endian/little-endian support fixing and PPS support revision
+ * by Rodolfo Giometti <giometti@linux.it>
+ *
  */
 
 #ifdef HAVE_CONFIG_H
@@ -56,15 +59,12 @@
  * Definitions
  */
 
-/* we are on little endian */
-#define BYTESWAP
-
 /* 
  * DEBUG statements: uncomment if necessary
  */
-/* #define DEBUG_NCC */ /* general debug statements */
-/* #define DEBUG_PPS */ /* debug pps */
-/* #define DEBUG_RAW */ /* print raw packets */
+#define DEBUG_NCC */ /* general debug statements */
+#define DEBUG_PPS */ /* debug pps */
+#define DEBUG_RAW */ /* print raw packets */
 
 #define TRIMBLE_OUTPUT_FUNC
 #define TSIP_VERNUM "7.12a"
@@ -108,6 +108,10 @@
 
 #define NSAMPLES        3       /* stages of median filter */
 
+#ifndef HAVE_PPSAPI
+typedef int pps_handle_t;	/* represents a PPS source */
+#endif   /* HAVE_PPSAPI */
+
 /* Structures */
 
 /* TSIP packets have the following structure, whether report or command. */
@@ -265,10 +269,11 @@
         l_fp    tstamp;                 /* timestamp of last poll */
         
         struct timespec ts;             /* last timestamp */
+#ifdef HAVE_PPSAPI
         pps_params_t pps_params;        /* pps parameters */
         pps_info_t pps_info;            /* last pps data */
+#endif   /* HAVE_PPSAPI */
         pps_handle_t handle;            /* pps handlebars */
-
 };
 
 
@@ -435,8 +440,10 @@
 /* RIPE NCC functions */
 static	void	ripencc_control	P((int, struct refclockstat *, struct
 				refclockstat *, struct peer *));
+#ifdef HAVE_PPSAPI
 static	int	ripencc_ppsapi	P((struct peer *, int, int));
 static	int	ripencc_get_pps_ts	P((struct ripencc_unit *, l_fp *));
+#endif   /* HAVE_PPSAPI */
 static	int	ripencc_start	P((int, struct peer *));
 static 	void	ripencc_shutdown	P((int, struct peer *));
 static 	void	ripencc_poll	P((int, struct peer *));
@@ -470,7 +477,7 @@
 {
 	register struct ripencc_unit *up;
 	struct refclockproc *pp;
-	char device[40];
+	char device[40], id[40], path[40];
 	int fd;
 	struct termios tio;
 	TSIPPKT spt;
@@ -488,10 +495,12 @@
 		return (0);
 	}
 
+	cfmakeraw(&tio);
+
 	/*
 	 * set flags
 	 */
-	tio.c_cflag |= (PARENB|PARODD);
+	tio.c_cflag |= (CS8|PARENB|PARODD);
 	tio.c_iflag &= ~ICRNL;
 	if (tcsetattr(fd, TCSANOW, &tio) == -1) {
 		msyslog(LOG_ERR, "Palisade(%d) tcsetattr(fd, &tio): %m",unit);
@@ -570,7 +579,11 @@
 
 	/* set i/o options */
 	cmd_0x8E4As (&spt,
+#ifdef HAVE_PPSAPI
 		0x01, 		/* PPS on */
+#else
+		0x00, 		/* PPS off */
+#endif   /* HAVE_PPSAPI */
 		0x01, 		/* Timebase UTC */
 		0x00, 		/* polarity positive */
 		0., 		/* 100 ft. cable XXX make flag */
@@ -600,17 +613,31 @@
 		printf("ripencc_start: success\n");
 #endif /* DEBUG_NCC */
 
+#ifdef HAVE_PPSAPI
+#ifdef PPS_HAVE_FINDSOURCE
+	/* Try to find the source (by using "index = -1" we ask just for a
+	 * generic source) */
+	fd = time_pps_findsource(-1, id, 40, path, 40);
+	if (fd < 0) {
+		msyslog(LOG_ERR, "refclock_ripencc: no available PPS source in the system");
+		return (1);
+	}
+	msyslog(LOG_INFO, "refclock_ripencc: found PPS source #%d \"%s\" on \"%s\"", fd, path, id);
+#endif   /* PPS_HAVE_FINDSOURCE */
+
 	/*
 	 * Start the PPSAPI interface if it is there. Default to use
 	 * the assert edge and do not enable the kernel hardpps.
 	 */
 	if (time_pps_create(fd, &up->handle) < 0) {
-		up->handle = 0;
 		msyslog(LOG_ERR, "refclock_ripencc: time_pps_create failed: %m");
 		return (1);
 	}
 
 	return(ripencc_ppsapi(peer, 0, 0));
+#else
+	return 1;
+#endif   /* HAVE_PPSAPI */
 }
 
 /*
@@ -631,11 +658,14 @@
 #endif /* DEBUG_NCC */
 
 	pp = peer->procptr;
+#ifdef HAVE_PPSAPI
 	ripencc_ppsapi(peer, pp->sloppyclockflag & CLK_FLAG2,
 	    pp->sloppyclockflag & CLK_FLAG3);
+#endif   /* HAVE_PPSAPI */
 }
 
 
+#ifdef HAVE_PPSAPI
 /*
  * Initialize PPSAPI
  */
@@ -686,7 +716,7 @@
 	}
 	peer->precision = PPS_PRECISION;
 
-#if DEBUG_NCC
+#ifdef DEBUG_NCC
 	if (debug) {
 		time_pps_getparams(up->handle, &up->pps_params);
 		printf(
@@ -712,7 +742,7 @@
 	)
 {
 	pps_info_t pps_info;
-	struct timespec timeout, ts;
+	struct timespec ts, timeout;
 	double dtemp;
 	l_fp tstmp;
 
@@ -724,8 +754,6 @@
 	/*
 	 * Convert the timespec nanoseconds field to ntp l_fp units.
 	 */ 
-	if (up->handle == 0)
-		return (0);
 	timeout.tv_sec = 0;
 	timeout.tv_nsec = 0;
 	memcpy(&pps_info, &up->pps_info, sizeof(pps_info_t));
@@ -761,6 +789,7 @@
 	*tsptr = tstmp;
 	return (1);
 }
+#endif   /* HAVE_PPSAPI */
 
 /*
  * ripencc_shutdown - shut down a GPS clock
@@ -774,8 +803,9 @@
 	pp = peer->procptr;
 	up = (struct ripencc_unit *)pp->unitptr;
 
-	if (up->handle != 0)
-		time_pps_destroy(up->handle);
+#ifdef HAVE_PPSAPI
+	time_pps_destroy(up->handle);
+#endif   /* HAVE_PPSAPI */
 
 	io_closeclock(&pp->io);
 
@@ -830,7 +860,7 @@
 		pp = peer->procptr;
 		up = (struct ripencc_unit *)pp->unitptr;
 		if (debug)
-			printf("ripencc_send(%d, %02X)\n", up->unit, cmd);
+			printf("ripencc_send(%d)", up->unit);
 	}
 #endif /* DEBUG_RAW */
 
@@ -891,8 +921,8 @@
 	static TSIPPKT rpt; /* structure for current incoming TSIP report  */ 
 	TSIPPKT spt; /* send packet */
 	int ns_since_pps;			
-	int i;
-	char *cp;
+	int l;
+	char *c;
 	/* Use these variables to hold data until we decide its worth keeping */
 	char    rd_lastcode[BMAX];
 	l_fp    rd_tmp;
@@ -928,12 +958,12 @@
 	}
 #endif /* DEBUG_RAW */
 
-	cp = (char*) &rbufp->recv_space;
-	i=rbufp->recv_length;
+	c = (char*) &rbufp->recv_space;
+	l=rbufp->recv_length;
 
-	while (i--) { /* loop over received chars */
+	while (l--) { /* loop over received chars */
 
-		tsip_input_proc(&rpt, (unsigned char) *cp++);
+		tsip_input_proc(&rpt, (unsigned char) *c++);
 
 		if (rpt.status != TSIP_PARSED_FULL)
 			continue;
@@ -978,19 +1008,20 @@
 						refclock_report(peer, CEVNT_BADREPLY);
 						break;
 				}
+
+#ifdef HAVE_PPSAPI
 				/*
 				 * If the PPSAPI is working, rather use its 
 				 * timestamps.
 				 * assume that the PPS occurs on the second 
 				 * so blow any msec
 				 */
-				if (ripencc_get_pps_ts(up, &rd_tmp) == 1) {
+				if (ripencc_get_pps_ts(up, &rd_tmp) != 0) {
 					pp->lastrec = up->tstamp = rd_tmp;
 					pp->nsec = 0;
 				}
 				else
-					msyslog(LOG_INFO, "%s(): ripencc_get_pps_ts returns failure\n",__FUNCTION__);
-
+				   	msyslog(LOG_INFO, "%s(): ripencc_get_pps_ts returns failure\n",__FUNCTION__);
 
 				if (!up->polled) { 
 					msyslog(LOG_INFO, "%s(): unrequested packet\n",__FUNCTION__);
@@ -1001,11 +1032,13 @@
 				/* we have been polled ! */
 				up->polled = 0;
 				up->pollcnt = 2;
+#endif   /* HAVE_PPSAPI */
 
 				/* poll for next packet */
 				cmd_0x8E0Bq(&spt);
 				ripencc_send(peer,spt);
-				
+
+#ifdef HAVE_PPSAPI
 				if (ns_since_pps < 0) { /* no PPS */
 					msyslog(LOG_INFO, "%s(): ns_since_pps < 0",__FUNCTION__);
 					refclock_report(peer, CEVNT_BADTIME);
@@ -1023,10 +1056,45 @@
 				}
 
 				refclock_receive(peer);
+#endif   /* HAVE_PPSAPI */
 				break;
 			
 			case 0x0B: /* comprehensive time packet */
+				if (up->polled <= 0)
+					return;   /* no poll pending, already received or timeout */
+
+				/* poll timestamp */
+				get_systime(&pp->lastrec);
+
+			        up->polled = 0;  /* Poll reply received */
+			        pp->lencode = 0; /* clear time code */
+
+			        /*
+ 				 * Parse primary utc time packet
+				 * and fill refclock structure 
+				 * from results. 
+				 */
 				parse0x8F0B(&rpt, peer);
+
+				/*
+				 * Process the new sample in the median filter and determine the
+				 * reference clock offset and dispersion. 
+ 				 */
+				if (!refclock_process(pp)) {
+					msyslog(LOG_INFO, "%s(): !refclock_process",__FUNCTION__);
+					refclock_report(peer, CEVNT_BADTIME);
+					break;
+				}
+
+				record_clock_stats(&peer->srcadr, pp->a_lastcode);
+
+#ifdef DEBUG
+				if (debug)
+					printf("palisade_receive: unit %d: %s\n",
+					      up->unit, prettydate(&pp->lastrec));
+#endif
+			        pp->lastref = pp->lastrec;
+				refclock_receive(peer);
 				break;
 
 			default: /* other superpackets */
@@ -1223,7 +1291,7 @@
 
 /* for DOS machines, reverse order of bytes as they come through the
  * serial port. */
-#ifdef BYTESWAP
+#ifndef WORDS_BIGENDIAN
 static short bGetShort (unsigned char *bp)
 {
 	short outval;
@@ -1304,20 +1372,21 @@
 	return outval;
 }
 
-#else /* not BYTESWAP */
+#else /* WORDS_BIGENDIAN */
 
 #define bGetShort(bp) 	(*(short*)(bp))
+#define bGetUShort(bp) 	(*(unsigned short*)(bp))
 #define bGetLong(bp) 	(*(long*)(bp))
 #define bGetULong(bp) 	(*(unsigned long*)(bp))
 #define bGetSingle(bp) 	(*(float*)(bp))
 #define bGetDouble(bp)	(*(double*)(bp))
 
-#endif /* BYTESWAP */
+#endif /* WORDS_BIGENDIAN */
 /*
  * Byte-reversal is necessary for little-endian (Intel-based) machines.
  * TSIP streams are Big-endian (Motorola-based).
  */
-#ifdef BYTESWAP
+#ifndef WORDS_BIGENDIAN
 
 void
 bPutFloat (float *in, unsigned char *out)
@@ -1359,14 +1428,23 @@
    *out = *inptr;
 }
 
-#else	/* not BYTESWAP */
+#else	/* WORDS_BIGENDIAN */
 
-void bPutShort (short a, unsigned char *cmdbuf) {*(short*) cmdbuf = a;}
-void bPutULong (long a, unsigned char *cmdbuf) 	{*(long*) cmdbuf = a;}
-void bPutFloat (float a, unsigned char *cmdbuf) {*(float*) cmdbuf = a;}
-void bPutDouble (double a, unsigned char *cmdbuf){*(double*) cmdbuf = a;}
+#if 0
+static void
+bPutShort (unsigned short *a, unsigned char *cmdbuf) {*(short*) cmdbuf = *a;}
+#endif
 
-#endif /* BYTESWAP */
+static void
+bPutFloat (float *a, unsigned char *cmdbuf) {*(float*) cmdbuf = *a;}
+
+static void
+bPutULong (unsigned long *a, unsigned char *cmdbuf) 	{*(long*) cmdbuf = *a;}
+
+static void
+bPutDouble (double *a, unsigned char *cmdbuf){*(double*) cmdbuf = *a;}
+
+#endif /* WORDS_BIGENDIAN */
 
 /*
  * Parse primary utc time packet
@@ -1473,6 +1551,7 @@
 		for (i = 0; i < month - 1; i++)
 			day += day2tab[i];
 	}
+
 	pp->day = day;
 	pp->hour = hour;
 	pp->minute = minute;
@@ -1500,7 +1579,7 @@
 {
 	register struct refclockproc *pp;	
 
-	unsigned day, month, year;	/* data derived from received timecode */
+	unsigned day, day_year, month, year;	/* data derived from received timecode */
 	unsigned hour, minute, second;
 	unsigned utcoff;
 	unsigned char mode;
@@ -1510,7 +1589,7 @@
 	short lat_deg, lon_deg;
 	float lat_min, lon_min;
 	unsigned char north_south, east_west;
-	char sv[9];
+	signed char sv[9];
 
    	static char logbuf[1024];	/* logging string buffer */
 	unsigned char b;
@@ -1543,7 +1622,7 @@
 		hour = (unsigned int )fmod(tow / 3600., 24.);
 	} 
 
-
+	day_year =
 	day =		(unsigned int) buf[11];
 	month =		(unsigned int) buf[12];
 	year =		bGetShort(&buf[13]);
@@ -1578,6 +1657,18 @@
 	lon_deg = (short)lon;
 	lon_min = (lon - lon_deg) * 60.0;
 
+	if (year % 4) {
+		if (day_year > day1tab[month - 1])
+			return(-1);
+		for (i = 0; i < month - 1; i++)
+			day_year += day1tab[i];
+	} else {
+		if (day_year > day2tab[month - 1])
+			return(-1);
+		for (i = 0; i < month - 1; i++)
+			day_year += day2tab[i];
+        }
+
 	for (i=0; i<8; i++) {
 		sv[i] = buf[i + 66];
 		if (sv[i]) {
@@ -1590,6 +1681,7 @@
 	}
 
 
+
 	sprintf(logbuf, "C1 %02d%02d%04d %02d%02d%02d %d %7.0f %.1f %.0f %.1f %d %02d%09.6f %c %02d%09.6f %c %.0f  %d %d %d %d %d %d %d %d",
 		day, month, year, hour, minute, second, mode, bias, biasunc, rate, rateunc, utcoff,
 		lat_deg, lat_min, north_south, lon_deg, lon_min, east_west, alt,
@@ -1600,6 +1692,13 @@
    		puts(logbuf);
 #endif /* DEBUG_NCC */
 
+	pp->year = year;
+	pp->day = day_year;
+	pp->hour = hour;
+	pp->minute = minute;
+	pp->second = second;
+	pp->nsec = 0;  /* FIXME */
+
 	record_clock_stats(&peer->srcadr, logbuf);
 
 	return (0);
@@ -1752,8 +1851,8 @@
  * -------  BYTE-SWAPPING  -------
  * TSIP is big-endian (Motorola) protocol.  To use on little-endian (Intel)
  * systems, the bytes of all multi-byte types (shorts, floats, doubles, etc.)
- * must be reversed.  This is controlled by the MACRO BYTESWAP; if defined, it
- * assumes little-endian protocol.
+ * must be reversed.  This is controlled by the MACRO WORDS_BIGENDIAN; if
+ * not defined, it assumes little-endian protocol.
  * --------------------------------
  *
  * T_PARSER.C and T_PARSER.H contains primitive functions that interpret
@@ -4124,7 +4223,7 @@
          "N/A",
          "N/A",
          "overdetermined clock"};
-   char
+   signed char
    	sv_id[8];
    unsigned char
    	month,
@@ -4867,4 +4966,3 @@
 #else  /* defined(REFCLOCK) && defined(CLOCK_RIPENCC) */
 int refclock_ripencc_bs;
 #endif /* defined(REFCLOCK) && defined(CLOCK_RIPENCC) */
-

