File: util.c

package info (click to toggle)
gpsbabel 1.3.2-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 15,956 kB
  • ctags: 9,083
  • sloc: ansic: 87,514; xml: 13,640; pascal: 6,981; sh: 3,770; makefile: 811; perl: 754; tcl: 74; objc: 7
file content (1572 lines) | stat: -rw-r--r-- 30,345 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
/*
    Misc utilities.

    Copyright (C) 2002-2005 Robert Lipe, robertlipe@usa.net

    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 USA

 */

#include "defs.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <stdarg.h>
#include <time.h>

#if defined WORDS_BIGENDIAN
# define i_am_little_endian 0
#else
# define i_am_little_endian 1
#endif

#ifdef DEBUG_MEM
#define DEBUG_FILENAME "/tmp/gpsbabel.debug"

static FILE *debug_mem_file = NULL;
void 
debug_mem_open() 
{
	debug_mem_file = xfopen( DEBUG_FILENAME, "a", "debug" );
}

void
debug_mem_output(char *format, ...) 
{
	va_list args;
	va_start( args, format );
	if ( debug_mem_file ) {
		vfprintf( debug_mem_file, format, args );
		fflush( debug_mem_file );
	}
	va_end( args );
}

void
debug_mem_close()
{
	if ( debug_mem_file ) {
		fclose(debug_mem_file);
	}
	debug_mem_file = NULL;
}
#endif

void *
#ifdef DEBUG_MEM
XMALLOC(size_t size, DEBUG_PARAMS)
#else
xmalloc(size_t size)
#endif
{
	void *obj = malloc(size);

#ifdef DEBUG_MEM
	debug_mem_output( "malloc, %x, %d, %s, %d\n", 
			obj, size, file, line );
#endif
	if (!obj) {
		fatal("gpsbabel: Unable to allocate %ld bytes of memory.\n", (unsigned long) size);
	}

	return obj;
}

void *
#ifdef DEBUG_MEM
XCALLOC(size_t nmemb, size_t size, DEBUG_PARAMS)
#else
xcalloc(size_t nmemb, size_t size)
#endif
{
	void *obj = calloc(nmemb, size);
#ifdef DEBUG_MEM
	debug_mem_output( "calloc, %x, %d, %d, %s, %d\n", 
			obj, nmemb, size, file, line );
#endif

	if (!obj) {
		fatal("gpsbabel: Unable to allocate %ld bytes of memory.\n", (unsigned long) size);
	}

	return obj;
}

void
#ifdef DEBUG_MEM
XFREE( void *mem, DEBUG_PARAMS )
#else
xfree( void *mem )
#endif
{
	free(mem);
#ifdef DEBUG_MEM
	debug_mem_output( "free, %x, %s, %d\n", 
			mem, file, line );
#endif
}

char *
#ifdef DEBUG_MEM
XSTRDUP(const char *s, DEBUG_PARAMS )
#else
xstrdup(const char *s)
#endif
{
	char *o = s ? strdup(s) : strdup("");
#ifdef DEBUG_MEM
	debug_mem_output( "strdup, %x, %x, %s, %d\n", 
			o, s, file, line );
#endif

	if (!o) {
		fatal("gpsbabel: Unable to allocate %ld bytes of memory.\n", (unsigned long) strlen(s));
	}

	return o;
}

/*
 * Duplicate at most sz bytes in str.
 */
char *
#ifdef DEBUG_MEM
XSTRNDUP(const char *str, size_t sz, DEBUG_PARAMS )
#else
xstrndup(const char *str, size_t sz)
#endif
{
	size_t newlen = 0;
	char *cin = (char *)str;
	char *newstr;

	while ((newlen < sz) && (*cin != '\0')) {
		newlen++;
		cin++;
	}
	
	newstr = (char *) xmalloc(newlen + 1);
	memcpy(newstr, str, newlen);    
	newstr[newlen] = 0;

	return newstr;
}

/*
 * Lazily trim whitespace (though not from allocated version) 
 * while copying.
 */
char *
#ifdef DEBUG_MEM
XSTRNDUPT(const char *str, size_t sz, DEBUG_PARAMS )
#else
xstrndupt(const char *str, size_t sz)
#endif
{
	size_t newlen = 0;
	char *cin = (char *)str;
	char *newstr;

	while ((newlen < sz) && (*cin != '\0')) {
		newlen++;
		cin++;
	}
	
	newstr = (char *) xmalloc(newlen + 1);
	memcpy(newstr, str, newlen);    
	newstr[newlen] = 0;
	rtrim(newstr);

	return newstr;
}

void *
#ifdef DEBUG_MEM
XREALLOC(void *p, size_t s, DEBUG_PARAMS )
#else
xrealloc(void *p, size_t s)
#endif
{
	char *o = (char *) realloc(p,s);
#ifdef DEBUG_MEM
	debug_mem_output( "realloc, %x, %x, %x, %s, %d\n", 
			o, p, s, file, line );
#endif

	if (!o) {
		fatal("gpsbabel: Unable to realloc %ld bytes of memory.\n", (unsigned long) s);
	}

	return o;
}

/*
* For an allocated string, realloc it and append 's'
*/
char *
#ifdef DEBUG_MEM
XSTRAPPEND(char *src, const char *newd, DEBUG_PARAMS)
#else
xstrappend(char *src, const char *newd)
#endif
{
	size_t newsz;

	if (!src) {
		return xxstrdup(newd, file, line);
	}
	if (!newd) {
		return xxstrdup(src, file, line);
	}

	newsz = strlen(src) + strlen(newd) + 1;
	src = xxrealloc(src, newsz, file, line);
	strcat(src, newd);

	return src;
}

/*
 * Wrapper for open that honours - for stdin, stdout, unifies error text.
 */
FILE *
xfopen(const char *fname, const char *type, const char *errtxt)
{
	FILE *f;
	int am_writing = strchr(type, 'w') != NULL;

	if (fname == NULL) {
		fatal("%s must have a filename specified for %s.\n",
				errtxt, am_writing ? "write" : "read");
	}

	if (0 == strcmp(fname, "-"))
		return am_writing ? stdout : stdin;
	f = fopen(fname, type);
	if (NULL == f) {
		fatal("%s cannot open '%s' for %s.  Error was '%s'.\n",
				errtxt, fname, 
				am_writing ? "write" : "read", 
				strerror(errno));
	}
	return f;
}

void
xfprintf(const char *errtxt, FILE *stream, const char *format, ...)
{
	va_list ap;
	va_start(ap, format);
	if (vfprintf(stream, format, ap) < 0) {
		fatal("%s writing output file.  Error was '%s'.\n",
				errtxt, strerror(errno));
	}
	va_end(ap);
}

void
xfputs(const char *errtxt, const char *s, FILE *stream)
{
	if (fputs(s, stream) < 0) {
		fatal("%s Writing output file.  Error was '%s'.\n",
				errtxt, strerror(errno));
	}
}

/*
 * Allocate a string using a format list with optional arguments
 */

int
xvasprintf(char **strp, const char *fmt, va_list args)
{
	/* From http://perfec.to/vsnprintf/pasprintf.c */
/* size of first buffer malloc; start small to exercise grow routines */
#define	FIRSTSIZE	64
	char *buf = NULL;
	int bufsize;
	char *newbuf;
	size_t nextsize = 0;
	int outsize;

	bufsize = 0;
	for (;;) {
		if (bufsize == 0) {
			if ((buf = xmalloc(FIRSTSIZE)) == NULL) {
				*strp = NULL;
				return -1;
			}
			bufsize = 1;
		} else if ((newbuf = xrealloc(buf, nextsize)) != NULL) {
			buf = newbuf;
			bufsize = nextsize;
		} else {
			xfree(buf);
			*strp = NULL;
			return -1;
		}

		outsize = vsnprintf(buf, bufsize, fmt, args);

		if (outsize == -1) {
			/* Clear indication that output was truncated, but no
			 * clear indication of how big buffer needs to be, so
			 * simply double existing buffer size for next time.
			 */
			nextsize = bufsize * 2;

		} else if (outsize == bufsize) {
			/* Output was truncated (since at least the \0 could
			 * not fit), but no indication of how big the buffer
			 * needs to be, so just double existing buffer size
			 * for next time.
			 */
			nextsize = bufsize * 2;

		} else if (outsize > bufsize) {
			/* Output was truncated, but we were told exactly how
			 * big the buffer needs to be next time. Add two chars
			 * to the returned size. One for the \0, and one to
			 * prevent ambiguity in the next case below.
			 */
			nextsize = outsize + 2;

		} else if (outsize == bufsize - 1) {
			/* This is ambiguous. May mean that the output string
			 * exactly fits, but on some systems the output string
			 * may have been trucated. We can't tell.
			 * Just double the buffer size for next time.
			 */
			nextsize = bufsize * 2;

		} else {
			/* Output was not truncated */
			break;
		}
	}
	*strp = buf;
	return 0;
}

int
xasprintf(char **strp, const char *fmt, ...)
{
	va_list args;
	int rval;

	va_start(args, fmt);
	rval = xvasprintf(strp, fmt, args);
	va_end(args);

	return rval;
	
}

/* 
 * Duplicate a pascal string into a normal C string.
 */
char *
pstrdup(char *src)
{
	int len = src[0];
	char *obuf = xmalloc(len + 1);

	memcpy(obuf, src + 1, len);
	obuf[len] = 0;

	return obuf;
}

void 
rtrim(char *s)
{
	char *t = s;

	if (!s || !*s) {
		return;
	}

	while (*s) {
		s++;
	}

	s--;
	while ((s >= t) && isspace (*s)) {
		*s = 0;
		s--;
	}
}

/*
 * Like trim, but trims whitespace from both beginning and end.
 */
char *
lrtrim(char *buff)
{
	char *c;

	c = buff + strlen(buff);
	while ((c >= buff) && ((unsigned char)*c <= ' ')) *c-- = '\0';

	c = buff;
	while ((*c != '\0') && ((unsigned char)*c <= ' ')) c++;

	return c;
}

/*
 *   Like strcmp, but case insensitive.  Like Berkeley's strcasecmp.
 */

int 
case_ignore_strcmp(const char *s1, const char *s2)
{
	for(;toupper(*s1) == toupper(*s2); ++ s1, ++s2) {
		if (*s1 == 0)
			return 0;
	}
	return (toupper(*s1) < toupper(*s2)) ? -1 : +1;

}

int 
case_ignore_strncmp(const char *s1, const char *s2, int n)
{
	int rv = 0;

	while (n && ((rv = toupper(*s1) - toupper(*s2)) == 0)
		&& *s1) {
		s1++;
		s2++;
		n--;
	}
	return rv;
}

/*
 * compare str with match
 * match may contain wildcards "*" and "?"
 *
 * examples:
 *		str_match("ABCDE", "*BC*") ->	1
 *		str_match("ABCDE", "A*C*E") ->	1
 *		str_match("?ABCDE", "\\?A*") ->	1
 *		str_match("", "*A") -> 		0
 */
 
int
str_match(const char *str, const char *match)
{
	char *m, *s;
	
	s = (char *)str;
	m = (char *)match; 
	
	while (*m || *s)
	{
		switch(*m) 
		{
			
			case '\0':
				/* there is something left in s, FAIL */
				return 0;

			case '*':
				/* skip all wildcards */
				while ((*m == '*') || (*m == '?')) m++;
				if (*m == '\0') return 1;
				
				if (*m == '\\')				/* ? escaped ? */
				{
					m++;
					if (*m == '\0') return 0;
				}

				do
				{
					char *mx, *sx;
					
					while (*s && (*s != *m)) s++;
					if (*s == '\0') return 0;
					
					sx = s + 1;
					mx = m + 1;
					
					while (*sx)
					{
						if (*mx == '\\')	/* ? escaped ? */
						{
							mx++;
							if (*mx == '\0') return 0;
							
						}
						if (*sx == *mx)
						{
							sx++;
							mx++;
						}
						else
							break;
					}
					if (*mx == '\0')		/* end of match */
					{
						if (*sx == '\0') return 1;
						s++;
					}
					else if ((*mx == '?') || (*mx == '*'))
					{
						s = sx;
						m = mx;
						break;
					}
					else
						s++;
				} while (*s);
				break;
				
			case '?':
				if (*s == '\0') return 0;	/* no character left */
				m++;
				s++;
				break;
				
			case '\\':
				m++;
				if (*m == '\0') return 0; /* incomplete escape sequence */
				/* pass-through next character */
				
			default:
				if (*m != *s) return 0;
				m++;
				s++;
		}
	}
	return ((*s == '\0') && (*m == '\0'));
}

/*
 * as str_match, but case insensitive 
 */
 
int
case_ignore_str_match(const char *str, const char *match)
{
	char *s1, *s2;
	int res;
	
	s1 = strupper(xstrdup(str));
	s2 = strupper(xstrdup(match));
	res = str_match(s1, s2);
	xfree(s1);
	xfree(s2);
	
	return res;
}

void
printposn(const double c, int is_lat)
{
	char d;
	if (is_lat) {
		if (c < 0) d = 'S'; else d = 'N';
	} else {
		if (c < 0) d = 'W'; else d = 'E';
	}
	printf("%f%c ", fabs(c), d);
}

void
is_fatal(const int condition, const char *fmt, ...)
{
	va_list args;
	char buff[128];

	if (condition == 0) return;

	va_start(args, fmt);
	vsnprintf(buff, sizeof(buff), fmt, args);
	va_end(args);

	fatal("%s\n", buff);
}

/*
 * Read 4 bytes in big-endian.   Return as "int" in native endianness.
 */
signed int
be_read32(const void *p)
{
	unsigned char *i = (unsigned char *) p;
	return i[0] << 24 | i[1] << 16  | i[2] << 8 | i[3];
}

signed int
be_read16(const void *p)
{
	unsigned char *i = (unsigned char *) p;
	return i[0] << 8 | i[1];
}

void
be_write16(void *addr, const unsigned value)
{
	unsigned char *p = addr;
	p[0] = value >> 8;
	p[1] = value;
	
}

void
be_write32(void *pp, const unsigned i)
{
	char *p = (char *)pp;

	p[0] = (i >> 24) & 0xff;
	p[1] = (i >> 16) & 0xff;
	p[2] = (i >> 8) & 0xff;
	p[3] = i & 0xff;
}

signed int
le_read16(const void *addr)
{
	const unsigned char *p = addr;
	return p[0] | (p[1] << 8);
}

signed int
le_read32(const void *addr)
{
	const unsigned char *p = addr;
	return p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
}

/*
 *  Read a little-endian 64-bit value from 'src' and return it in 'dest' 
 *  in host endianness.
 */
void
le_read64(void *dest, const void *src)
{
	char *cdest = dest;
	const char *csrc = src;

	if (i_am_little_endian) {
		memcpy(dest, src, 8);
	} else {
		int i;
		for (i = 0; i < 8; i++) {
			cdest[i] = csrc[7-i];
		}
	}
}

void
le_write16(void *addr, const unsigned value)
{
	unsigned char *p = addr;
	p[0] = value;
	p[1] = value >> 8;
	
}

void 
le_write32(void *addr, const unsigned value)
{
	unsigned char *p = addr;
	p[0] = value;
	p[1] = value >> 8;
	p[2] = value >> 16;
	p[3] = value >> 24;
}

signed int 
si_round( double d )
{
	if ( d < 0 ) {
		return (signed int)(d-0.5);
	}
	else {
		return (signed int)(d+0.5);
	}
}

/*
 *  Return a time_t suitable for adding to a time_t that is in GMT to
 *  make it a local time.
 *  Obsolete: to use mkgmtime instead.
 */
signed int 
get_tz_offset(void)
{
	time_t now = current_time();
	time_t later = mktime(gmtime(&now));

	if (later == -1) {
		return 0;
	} else {
		return (signed int) difftime(now, later);
	}
}

/*
	mkgmtime -- convert tm struct in UTC to time_t

	works just like mktime but without all the mucking
	around with timezones and daylight savings

	obsoletes get_tz_offset()

	Borrowed from lynx GPL source code
	http://lynx.isc.org/release/lynx2-8-5/src/mktime.c

	Written by Philippe De Muyter <phdm@macqel.be>.
*/

time_t
mkgmtime(struct tm *t)
{
	short  month, year;
	time_t result;
	static int      m_to_d[12] =
		{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};

	month = t->tm_mon;
	year = t->tm_year + month / 12 + 1900;
	month %= 12;
	if (month < 0)
	{
		year -= 1;
		month += 12;
	}
	result = (year - 1970) * 365 + m_to_d[month];
	if (month <= 1)
		year -= 1;
	result += (year - 1968) / 4;
	result -= (year - 1900) / 100;
	result += (year - 1600) / 400;
	result += t->tm_mday;
	result -= 1;
	result *= 24;
	result += t->tm_hour;
	result *= 60;
	result += t->tm_min;
	result *= 60;
	result += t->tm_sec;
	return(result);
}

/*
 * mklocaltime: same as mktime, but try to recover the "Summer time flag",
 *              which is evaluated by mktime
 */
time_t
mklocaltime(struct tm *t)
{
	time_t result;
	struct tm check = *t;
	
	check.tm_isdst = 0;
	result = mktime(&check);
	check = *localtime(&result);
	if (check.tm_isdst == 1) {	/* DST is in effect */
		check = *t;
		check.tm_isdst = 1;
		result = mktime(&check);
	}
	return result;
}

/*
 * A wrapper for time(2) that allows us to "freeze" time for testing.
 */
time_t
current_time(void)
{
	if (getenv("GPSBABEL_FREEZE_TIME")) {
		return 0;
	}

	return time(NULL);
}

/*
 * Return the (zero based) month number of the year or -1 for failure.
 */
signed int
month_lookup(const char *m)
{
	static const char *months[] = {
		"JAN", "FEB", "MAR", "APR", "MAY", "JUN", 
		"JUL", "AUG", "SEP", "OCT", "NOV", "DEC", NULL };
	const char **mp;

	for (mp = months; *mp; mp++) {
		if (0 == case_ignore_strcmp(*mp, m))
			return mp - months;
	}
	return -1;
}

/*
 * Return a pointer to a constant string that is suitable for icon lookup
 * based on geocache attributes.   The strings used are those present in 
 * a GPX file from geocaching.com.  Thus we sort of make all the other 
 * formats do lookups based on these strings.
 */
const char *
get_cache_icon(const waypoint *waypointp)
{
	if (global_opts.no_smart_icons)
		return NULL;

	/*
	 * For icons, type overwrites container.  So a multi-micro will 
	 * get the icons for "multi".
 	 */
	switch (waypointp->gc_data.type) {
		case gt_virtual:
			return "Virtual cache";
		case gt_multi:
			return "Multi-Cache";
		case gt_event:
			return "Event Cache";
		case gt_suprise:
			return "Unknown Cache";
		case gt_webcam:
			return "Webcam Cache";
		default:
			break;
	}
	switch (waypointp->gc_data.container) {
		case gc_micro: 
			return "Micro-Cache";
			break;
		default:
			break;
	}
	return NULL;
}

double
endian_read_double(void* ptr, int read_le)
{
  double ret;
  char r[8];
  void *p;
  int i;
  
  if ( i_am_little_endian == read_le ) {
	  p = ptr;
  }
  else {
	  for (i = 0; i < 8; i++)
	  {
		r[i] = ((char*)ptr)[7-i];
	  }
	  p = r;
  }
  
  memcpy(&ret, p, 8);
  return ret;
}

void
endian_write_double(void* ptr, double d, int write_le)
{
  char *r = (char *)(void *)&d;
  int i;
  char *optr = ptr;

  if ( i_am_little_endian == write_le ) {
	  memcpy( ptr, &d, 8);
  }
  else {
	  for (i = 0; i < 8; i++)
	  {
		*optr++ = r[7-i];
	  }
  }
}

double
pdb_read_double( void *ptr ) {return endian_read_double(ptr, 0);}

double 
le_read_double( void *ptr ) {return endian_read_double(ptr,1);}

double 
be_read_double( void *ptr ) {return endian_read_double(ptr,0);}

void
pdb_write_double( void *ptr, double d ) {endian_write_double(ptr,d,0);}

void
le_write_double( void *ptr, double d ) {endian_write_double(ptr,d,1);}

void 
be_write_double( void *ptr, double d ) {endian_write_double(ptr,d,0);}

/* Magellan and PCX formats use this DDMM.mm format */
double ddmm2degrees(double pcx_val) {
	double minutes;
	signed int deg;
	deg = (signed int) (pcx_val / 100.0);
	minutes = (((pcx_val / 100.0) - deg) * 100.0) / 60.0;
	return (double) deg + minutes;
}

double degrees2ddmm(double deg_val) {
	signed int deg;
	deg = (signed int) deg_val;
	return (double) (deg * 100.0) + ((deg_val - deg) * 60.0);
}

/*
 * replace a single occurrence of "search" in  "s" with "replace".
 * Returns an allocated copy if substitution was made, otherwise returns NULL.
 * Doesn't try to make an optimally sized dest buffer.
 */
char *
strsub(const char *s, const char *search, const char *replace)
{
       char *p;
       int len = strlen(s);
       int slen = strlen(search);
       int rlen = strlen(replace);
       char *d;

       p = strstr(s, search);
       if (!slen || !p) {
               return NULL;
       }
       
       d = xmalloc(len + rlen);

       /* Copy first part */
       len = p - s;
       memcpy(d, s, len);
       d[len] = 0;

       /* Copy replacement */
       strcat(d, replace);

       /* Copy last part */
       strcat(d, p + slen);
       return d;
}

/*
 *  As strsub, but do it globally.
 */
char *
gstrsub(const char *s, const char *search, const char *replace)
{
	char *o = xstrdup(s);

	while (strstr(o, search)) {
		char *oo = o;
		o = strsub(o, search, replace);
		xfree(oo);
	}

	return o;
}

/*
 * Like strstr, but starts from back of string.
 */
char *
xstrrstr(const char *s1, const char *s2) 
{
	char *r = NULL, *next = NULL; 

	while (next = strstr(s1, s2), NULL != next) {
		r = next;
		s1 = next + 1;
	}
	return r;
}

/*
 *
 */
char *
strupper(char *src)
{
	char *c;
	
	for (c = src; *c; c++) {
		*c = toupper(*c);
	}
	return src;
}

/*
 *
 */
char *
strlower(char *src)
{
	char *c;
	
	for (c = src; *c; c++) {
		*c = tolower(*c);
	}
	return src;
}

char *
rot13( const char *s )
{
	char *result = xstrdup( s );
	char *cur = result;
	int flip = 1;
	while (cur && *cur ) {
		if ( flip ) {
			if (*cur == '[') flip = 0;
			else if ( *cur >= 'A' && *cur <= 'Z' ) {
				*cur = 'A' + ((*cur-'A')+13)%26;
			}
			else if ( *cur >= 'a' && *cur <= 'z' ) {
				*cur = 'a' + ((*cur-'a')+13)%26;
			}
		}
		else if ( *cur == ']' ) flip = 1;
		cur++;
	}
	return result;
}

/*
 * Convert a human readable date format (i.e. "YYYY/MM/DD") into
 * a format usable for strftime and others 
 */
 
char *
convert_human_date_format(const char *human_datef)
{
	char *result, *cin, *cout;
	char prev;
	int ylen;
	
	result = xcalloc((2*strlen(human_datef)) + 1, 1);
	cout = result;
	prev = '\0';
	ylen = 0;
	
	for (cin = (char *)human_datef; *cin; cin++)
	{
		char okay = 1;
		
		if (toupper(*cin) != 'Y') ylen = 0;
		if (isalpha(*cin)) 
		{
			switch(*cin) 
			{
			case 'y': case 'Y':
				if (prev != 'Y')
				{ 
					strcat(cout, "%y"); 
					cout += 2;
					prev = 'Y'; 
				}
				ylen++;
				if (ylen > 2) *(cout-1) = 'Y';
				break;
			case 'm': case 'M':
				if (prev != 'M')
				{
					strcat(cout, "%m");
					cout += 2;
					prev = 'M';
				}
				break;
			case 'd': case 'D':
				if (prev != 'D')
				{
					strcat(cout, "%d");
					cout += 2;
					prev = 'D';
				}
				break;
			default:
				okay = 0;
			}
		}
		else if (ispunct(*cin))
		{
			*cout++ = *cin;
			prev = '\0';
		}
		else okay = 0;
		
		is_fatal(okay == 0, "Invalid character \"%c\" in date format!", *cin);
	}
	return result;
}

/*
 * Convert a human readable time format (i.e. "HH:mm:ss") into
 * a format usable for strftime and others
 */

char *
convert_human_time_format(const char *human_timef)
{
	char *result, *cin, *cout;
	char prev;
	
	result = xcalloc((2*strlen(human_timef)) + 1, 1);
	cout = result;
	prev = '\0';
	
	for (cin = (char *)human_timef; *cin; cin++)
	{
		int okay = 1;
		
		if (isalpha(*cin))
		{
			switch(*cin)
			{
			case 'S': case 's':
				if (prev != 'S') { 
					strcat(cout, "%S"); 
					cout += 2;
					prev = 'S'; 
				}
				break;
				
			case 'M': case 'm':
				if (prev != 'M') { 
					strcat(cout, "%M"); 
					cout += 2;
					prev = 'M'; 
				}
				break;
				
			case 'h':				/* 12-hour-clock */
				if (prev != 'H') {
					strcat(cout, "%l");	/* 1 .. 12 */
					cout += 2;
					prev = 'H';
				}
				else *(cout-1) = 'I';		/* 01 .. 12 */
				break;
				
			case 'H':				/* 24-hour-clock */
				if (prev != 'H') {
					strcat(cout, "%k");
					cout += 2;
					prev = 'H';
				}
				else *(cout-1) = 'H';
				break;
				
			case 'x':
				if (prev != 'X') {
					strcat(cout, "%P");
					cout += 2;
					prev = 'X';
				}
				else *(cout-1) = 'P';
				break;
				
			case 'X':
				if (prev != 'X') {
					strcat(cout, "%p");
					cout += 2;
					prev = 'X';
				}
				else *(cout-1) = 'p';
				break;
				
			default:
				okay = 0;
			}
		}
		else if (ispunct(*cin) || isspace(*cin))
		{
			*cout++ = *cin;
			prev = '\0';
		}
		else okay = 0;
		
		is_fatal(okay == 0, "Invalid character \"%c\" in time format!", *cin);
	}
	return result;
}


/* 
 * Return a decimal degree pair as
 * DD.DDDDD  DD MM.MMM or DD MM SS.S
 * fmt = ['d', 'm', 's']
 * html = 1 for html output otherwise text
 */
char *
pretty_deg_format(double lat, double lon, char fmt, int html) 
{
	double  latmin, lonmin, latsec, lonsec;
	int     latint, lonint;
	char	latsig, lonsig;
	char	*result;
	latsig = lat < 0 ? 'S':'N';
	lonsig = lon < 0 ? 'W':'E';
	latint = abs((int) lat);
  	lonint = abs((int) lon);
	latmin = 60.0 * (fabs(lat) - latint);
	lonmin = 60.0 * (fabs(lon) - lonint);
	latsec = 60.0 * (latmin - floor(latmin));
	lonsec = 60.0 * (lonmin - floor(lonmin));
	if (fmt == 'd') { /* ddd */
		xasprintf ( &result, "%c%6.5f%s %c%6.5f%s",
			latsig, fabs(lat), html?"&deg;":"", 
			lonsig, fabs(lon), html?"&deg;":"" );
	}
	else if (fmt == 's') { /* dms */
		xasprintf ( &result, "%c%d%s%02d'%04.1f\" %c%d%s%02d'%04.1f\"",
                        latsig, latint, html?"&deg;":" ", (int)latmin, latsec,
			lonsig, lonint, html?"&deg;":" ", (int)lonmin, lonsec);
	}
	else { /* default dmm */
		xasprintf ( &result,  "%c%d%s%06.3f %c%d%s%06.3f",
			latsig, latint, html?"&deg;":" ", latmin, 
			lonsig, lonint, html?"&deg;":" ", lonmin);
	} 
	return result;
}



/* 
 * Get rid of potentially nasty HTML that would influence another record
 * that includes;
 * <body> - to stop backgrounds/background colours from being loaded
 * </body> and </html>- stop processing altogether
 * <style> </style> - stop overriding styles for everything
 */
char *
strip_nastyhtml(const char * in)
{
	char *returnstr, *sp;
	char *lcstr, *lcp;
	
	sp = returnstr = xstrdup(in);
	lcp = lcstr = strlower(xstrdup(in));
	
	while (lcp = strstr(lcstr, "<body>"), NULL != lcp) {
		sp = returnstr + (lcp - lcstr) ; /* becomes <!   > */
		sp++; *sp++ = '!'; *sp++ = ' '; *sp++ = ' '; *sp++ = ' ';
		*lcp = '*';         /* so we wont find it again */
	}
	while (lcp = strstr(lcstr, "<body"), lcp != NULL) {   /* becomes <!--        --> */
		sp = returnstr + (lcp - lcstr) ;
		sp++; *sp++ = '!'; *sp++ = '-';  *sp++ = '-';  
		while ( (*sp) && (*sp != '>') ) {
		  sp++;
		}
		*--sp = '-'; *--sp = '-'; 
		*lcp = '*';         /* so we wont find it again */
	}
	while (lcp = strstr(lcstr, "</body>"), NULL != lcp) {
		sp = returnstr + (lcp - lcstr) ; /* becomes <!---- */
		sp++; *sp++ = '!'; *sp++ = '-'; *sp++ = '-'; *sp++ = '-'; *sp++ = '-'; 
		*lcp = '*';         /* so we wont find it again */
	}
	while (lcp = strstr(lcstr, "</html>"), NULL != lcp) {
		sp = returnstr + (lcp - lcstr) ; /* becomes </---- */
		sp++; *sp++ = '!'; *sp++ = '-'; *sp++ = '-'; *sp++ = '-'; *sp++ = '-'; 
		*lcp = '*';         /* so we wont find it again */
	}
	while (lcp = strstr(lcstr, "<style"), NULL != lcp) {
		sp = returnstr + (lcp - lcstr) ; /* becomes <!--   */
		sp++; *sp++ = '!'; *sp++ = '-'; *sp++ = '-';  *sp++ = ' '; *sp++ = ' '; *sp = ' ';
		*lcp = '*';         /* so we wont find it again */
	}
	while (lcp = strstr(lcstr, "</style>"), NULL != lcp) {
		sp = returnstr + (lcp - lcstr) ; /* becomes    --> */
		*sp++ = ' '; *sp++ = ' '; *sp++ = ' '; *sp++ = ' '; *sp++ = ' '; *sp++ = '-'; *sp++ = '-'; 
		*lcp = '*';         /* so we wont find it again */
	}
	while (lcp = strstr(lcstr, "<image"), NULL != lcp) {
		sp = returnstr + (lcp - lcstr) ; /* becomes <img */
		sp+=3; *sp++ = 'g'; *sp++ = ' '; *sp++ = ' ';
		*lcp = '*';
	}
	xfree (lcstr);
	return (returnstr);
}
	
/*
 *  Without getting into all the complexity of technically legal HTML,
 *  this function tries to strip "ugly" parts of it to make it more 
 *  pleasant for a human reader.   Yes, this falls down in all kinds of
 *  ways such as spaces within the tags, etc.
 */
char * 
strip_html(const utf_string *in)
{
	char *outstring, *out;
	char *instr = in->utfstring;
	char tag[8];
	unsigned short int taglen = 0;
	
	if (!in->is_html)
		return xstrdup(in->utfstring);
	/*
	 * We only shorten, so just dupe the input buf for space.
	 */

	outstring = out = xstrdup(in->utfstring);

	tag[0] = 0;
	while (*instr) {
		if ((*instr == '<') || (*instr == '&')) {
			tag[0] = *instr;
			taglen = 0;
		}
		
		if (! tag[0]) {
			if (*instr == '\n') {
				*out++ = ' ';
				do {
					instr++;
				} while (isspace(*instr));
				continue;
			} else {
				*out++ = *instr;
			}
		}
		else {
			if (taglen < (sizeof(tag)-1)) {
				tag[taglen++] = tolower(*instr);
				tag[taglen] = 0;
			}
		}
		
		if ( ((tag[0] == '<') && (*instr == '>')) ||
		     ((tag[0] == '&') && (*instr == ';')) ) {
			if (! strcmp(tag,"&amp;"))
				*out++ = '&';
			else if (! strcmp (tag, "&lt;"))
				*out++ = '<';
			else if (! strcmp (tag, "&gt;"))
				*out++ = '>';
			else if (! strcmp (tag, "&quot;"))
				*out++ = '"';
			else if (! strcmp (tag, "&nbsp;"))
				*out++ = ' ';
			else if (! strcmp (tag, "&deg;")) {
				*out++ = 'd'; *out++ = 'e'; *out++ = 'g';
			}
			else if ((tag[0]=='<') && (tag[1]=='p'))
				*out++ = '\n';
			else if ((tag[0]=='<') && (tag[1]=='b') && (tag[2]=='r'))
				*out++ = '\n';
			else if ((tag[0]=='<') && (tag[1]=='/') && (tag[2]=='t') && (tag[3]=='r'))
				*out++ = '\n';
			else if ((tag[0]=='<') && (tag[1]=='/') && (tag[2]=='t') && (tag[3]=='d'))
				*out++ = ' ';
			else if ((tag[0]=='<') && (tag[1]=='i') && (tag[2]=='m') && (tag[3]=='g')) {
				*out++ = '['; *out++ = 'I'; *out++ = 'M'; *out++ = 'G'; *out++ = ']';
			}
			
		      tag[0] = 0;
		}
		instr++;
	}
	*out++ = 0;
	return (outstring);
}

typedef struct {
	const char * text;
	const char * entity;
	int  not_html;
} entity_types;

static 
entity_types stdentities[] =  {
	{ "&",	"&amp;", 0 },
	{ "'", 	"&apos;", 1 },
	{ "<",	"&lt;", 0 },
	{ ">",	"&gt;", 0 },
	{ "\"",	"&quot;", 0 },
	{ NULL,	NULL, 0 }
};

static 
char * 
entitize(const char * str, int is_html) 
{
	int elen, ecount, nsecount;
	entity_types *ep;
	const char * cp;
	char * p, * tmp, * xstr;

	int bytes = 0;
	int value = 0;
	ep = stdentities;
	elen = ecount = nsecount = 0;

	/* figure # of entity replacements and additional size. */
	while (ep->text) {
		cp = str;
		while ((cp = strstr(cp, ep->text)) != NULL) {
			elen += strlen(ep->entity) - strlen(ep->text);
			ecount++;
			cp += strlen(ep->text);
		}
		ep++;
	}
	
	/* figure the same for other than standard entities (i.e. anything
	 * that isn't in the range U+0000 to U+007F */
	
#if 0
	for ( cp = str; *cp; cp++ ) {
		if ( *cp & 0x80 ) {
			cet_utf8_to_ucs4( cp, &bytes, &value );
			cp += bytes-1;
			elen += sprintf( tmpsub, "&#x%x;", value ) - bytes;
		        nsecount++;	
		}
	}
#endif

	/* enough space for the whole string plus entity replacements, if any */
	tmp = xcalloc((strlen(str) + elen + 1), 1);
	strcpy(tmp, str);

	/* no entity replacements */
	if (ecount == 0 && nsecount == 0)
		return (tmp);

        if ( ecount != 0 ) {	
		for (ep = stdentities; ep->text; ep++) {
			p = tmp;
			if (is_html && ep->not_html)  {
				continue;
			}
			while ((p = strstr(p, ep->text)) != NULL) {
				elen = strlen(ep->entity);

				xstr = xstrdup(p + strlen(ep->text));

				strcpy(p, ep->entity);
				strcpy(p + elen, xstr);

				xfree(xstr);

				p += elen;
			}  
		}
	}

	if ( nsecount != 0 ) {
		p = tmp;
		while (*p) {
			if ( *p & 0x80 ) {
				cet_utf8_to_ucs4( p, &bytes, &value );
				if ( p[bytes] ) {
					xstr = xstrdup( p + bytes );
				}
				else {
					xstr = NULL;
				}
				sprintf( p, "&#x%x;", value );
				p = p+strlen(p);
				if ( xstr ) {
					strcpy( p, xstr );
					xfree(xstr);
				}
			}
			else {
				p++;
			}
		}
	}	
	return (tmp);
}

/*
 * Public callers for the above to hide the absence of &apos from HTML
 */

char * xml_entitize(const char * str) 
{
	return entitize(str, 0);
}

char * html_entitize(const char * str) 
{
	return entitize(str, 1);
}

/*
 * xml_tag utilities
 */

xml_tag *xml_next( xml_tag *root, xml_tag *cur )
{
	if ( cur->child ) {
		cur = cur->child;
	}
	else if ( cur->sibling ) {
		cur = cur->sibling;
	}
	else {
		cur = cur->parent;
		if ( cur == root ) {
			cur = NULL;
		}
		if ( cur ) {
			cur = cur->sibling;
		}
	}
	return cur;
}

xml_tag *xml_findnext( xml_tag *root, xml_tag *cur, char *tagname ) 
{
	xml_tag *result = cur;
	do {
		result = xml_next( root, result );
	} while ( result && case_ignore_strcmp( result->tagname, tagname ));
	return result;
}

xml_tag *xml_findfirst( xml_tag *root, char *tagname )
{
	return xml_findnext( root, root, tagname );
}

char *xml_attribute( xml_tag *tag, char *attrname ) 
{
	char *result = NULL;
	if ( tag->attributes ) {
		char **attr = tag->attributes;
		while ( attr && *attr ) {
			if ( 0 == case_ignore_strcmp( *attr, attrname )) {
				result = attr[1];
				break;
			}
			attr+=2;
		}
	}
	return result;
}