summaryrefslogtreecommitdiffstats
path: root/libtecla-1.4.1/history.c
blob: 5a8d94f205606bf100e43d5306c0c99a29a15510 (plain) (blame)
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
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
/*
 * Copyright (c) 2000, 2001 by Martin C. Shepherd.
 * 
 * All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, and/or sell copies of the Software, and to permit persons
 * to whom the Software is furnished to do so, provided that the above
 * copyright notice(s) and this permission notice appear in all copies of
 * the Software and that both the above copyright notice(s) and this
 * permission notice appear in supporting documentation.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
 * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
 * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
 * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 * 
 * Except as contained in this notice, the name of a copyright holder
 * shall not be used in advertising or otherwise to promote the sale, use
 * or other dealings in this Software without prior written authorization
 * of the copyright holder.
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <errno.h>

#include "history.h"
#include "freelist.h"

/*
 * GlLineNode's record the location and length of historical lines in
 * a buffer array.
 */
typedef struct GlLineNode GlLineNode;
struct GlLineNode {
  long id;             /* The unique identifier of this history line */
  time_t timestamp;    /* The time at which the line was archived */
  unsigned group;      /* The identifier of the history group to which the */
                       /*  the line belongs. */
  GlLineNode *next;    /* The next youngest line in the list */
  GlLineNode *prev;    /* The next oldest line in the list */
  int start;           /* The start index of the line in the buffer */
  int nchar;           /* The total length of the line, including the '\0' */
};

/*
 * The number of GlLineNode elements per freelist block.
 */
#define LINE_NODE_BLK 100

/*
 * Lines are organised in the buffer from oldest to newest. The
 * positions of the lines are recorded in a doubly linked list
 * of GlLineNode objects.
 */
typedef struct {
  FreeList *node_mem;    /* A freelist of GlLineNode objects */ 
  GlLineNode *head;      /* The head of the list of lines */
  GlLineNode *tail;      /* The tail of the list of lines */
} GlLineList;

/*
 * All elements of the history mechanism are recorded in an object of
 * the following type.
 */
struct GlHistory {
  char *buffer;       /* A circular buffer used to record historical input */
                      /*  lines. */
  size_t buflen;      /* The length of the buffer array */
  GlLineList list;    /* A list of the start of lines in buffer[] */
  GlLineNode *recall; /* The last line recalled, or NULL if no recall */
                      /*  session is currently active. */
  GlLineNode *id_node;/* The node at which the last ID search terminated */
  const char *prefix; /* A pointer to the line containing the prefix that */
                      /*  is being searched for. */
  int prefix_len;     /* The length of the prefix */
  unsigned long seq;  /* The next ID to assign to a line node */
  unsigned group;     /* The identifier of the current history group */
  int nline;          /* The number of lines currently in the history list */
  int max_lines;      /* Either -1 or a ceiling on the number of lines */
  int enable;         /* If false, ignore history additions and lookups */
};

static char *_glh_restore_line(GlHistory *glh, char *line, size_t dim);
static int _glh_cant_load_history(GlHistory *glh, const char *filename,
				  int lineno, const char *message, FILE *fp);
static int _glh_write_timestamp(FILE *fp, time_t timestamp);
static int _glh_decode_timestamp(char *string, char **endp, time_t *t);
static void _glh_discard_node(GlHistory *glh, GlLineNode *node);
static GlLineNode *_glh_find_id(GlHistory *glh, GlhLineID id);

/*.......................................................................
 * Create a line history maintenance object.
 *
 * Input:
 *  buflen     size_t    The number of bytes to allocate to the circular
 *                       buffer that is used to record all of the
 *                       most recent lines of user input that will fit.
 *                       If buflen==0, no buffer will be allocated.
 * Output:
 *  return  GlHistory *  The new object, or NULL on error.
 */
GlHistory *_new_GlHistory(size_t buflen)
{
  GlHistory *glh;  /* The object to be returned */
/*
 * Allocate the container.
 */
  glh = (GlHistory *) malloc(sizeof(GlHistory));
  if(!glh) {
    fprintf(stderr, "_new_GlHistory: Insufficient memory.\n");
    return NULL;
  };
/*
 * Before attempting any operation that might fail, initialize the
 * container at least up to the point at which it can safely be passed
 * to _del_GlHistory().
 */
  glh->buffer = NULL;
  glh->buflen = buflen;
  glh->list.node_mem = NULL;
  glh->list.head = NULL;
  glh->list.tail = NULL;
  glh->recall = NULL;
  glh->id_node = NULL;
  glh->prefix = NULL;
  glh->prefix_len = 0;
  glh->seq = 0;
  glh->group = 0;
  glh->nline = 0;
  glh->max_lines = -1;
  glh->enable = 1;
/*
 * Allocate the buffer, if required.
 */
  if(buflen > 0) {
    glh->buffer = (char *) malloc(sizeof(char) * buflen);
    if(!glh->buffer) {
      fprintf(stderr, "_new_GlHistory: Insufficient memory.\n");
      return _del_GlHistory(glh);
    };
  };
/*
 * Allocate the GlLineNode freelist.
 */
  glh->list.node_mem = _new_FreeList("_new_GlHistory", sizeof(GlLineNode),
				     LINE_NODE_BLK);
  if(!glh->list.node_mem)
    return _del_GlHistory(glh);
  return glh;
}

/*.......................................................................
 * Delete a GlHistory object.
 *
 * Input:
 *  glh    GlHistory *  The object to be deleted.
 * Output:
 *  return GlHistory *  The deleted object (always NULL).
 */
GlHistory *_del_GlHistory(GlHistory *glh)
{
  if(glh) {
/*
 * Delete the buffer.
 */
    if(glh->buffer) {
      free(glh->buffer);
      glh->buffer = NULL;
    };
/*
 * Delete the freelist of GlLineNode's.
 */
    glh->list.node_mem = _del_FreeList("_del_GlHistory", glh->list.node_mem, 1);
/*
 * The contents of the list were deleted by deleting the freelist.
 */
    glh->list.head = NULL;
    glh->list.tail = NULL;
/*
 * Delete the container.
 */
    free(glh);
  };
  return NULL;
}

/*.......................................................................
 * Add a new line to the end of the history buffer, wrapping round to the
 * start of the buffer if needed.
 *
 * Input:
 *  glh  GlHistory *  The input-line history maintenance object.
 *  line      char *  The line to be archived.
 *  force      int    Unless this flag is non-zero, empty lines and
 *                    lines which match the previous line in the history
 *                    buffer, aren't archived. This flag requests that
 *                    the line be archived regardless.
 * Output:
 *  return     int    0 - OK.
 *                    1 - Error.
 */
int _glh_add_history(GlHistory *glh, const char *line, int force)
{
  GlLineList *list; /* The line location list */
  int nchar;        /* The number of characters needed to record the line */
  GlLineNode *node; /* The new line location list node */
  int empty;        /* True if the string is empty */
  const char *nlptr;/* A pointer to a newline character in line[] */
  int i;
/*
 * Check the arguments.
 */
  if(!glh || !line)
    return 1;
/*
 * Is history enabled?
 */
  if(!glh->enable || !glh->buffer || glh->max_lines == 0)
    return 0;
/*
 * Get the line location list.
 */
  list = &glh->list;
/*
 * Cancel any ongoing search.
 */
  if(_glh_cancel_search(glh))
    return 1;
/*
 * See how much buffer space will be needed to record the line?
 *
 * If the string contains a terminating newline character, arrange to
 * have the archived line NUL terminated at this point.
 */
  nlptr = strchr(line, '\n');
  if(nlptr)
    nchar = (nlptr - line) + 1;
  else
    nchar = strlen(line) + 1;
/*
 * If the line is too big to fit in the buffer, truncate it.
 */
  if(nchar > glh->buflen)
    nchar = glh->buflen;
/*
 * Is the line empty?
 */
  empty = 1;
  for(i=0; i<nchar-1 && empty; i++)
    empty = isspace((int)(unsigned char) line[i]);
/*
 * If the line is empty, don't add it to the buffer unless explicitly
 * told to.
 */
  if(empty && !force)
    return 0;
/*
 * If the new line is the same as the most recently added line,
 * don't add it again, unless explicitly told to.
 */
  if(!force &&
     list->tail && strlen(glh->buffer + list->tail->start) == nchar-1 &&
     strncmp(line, glh->buffer + list->tail->start, nchar-1)==0)
    return 0;
/*
 * Allocate the list node that will record the line location.
 */
  node = (GlLineNode *) _new_FreeListNode(list->node_mem);
  if(!node)
    return 1;
/*
 * Is the buffer empty?
 */
  if(!list->head) {
/*
 * Place the line at the beginning of the buffer.
 */
    strncpy(glh->buffer, line, nchar);
    glh->buffer[nchar-1] = '\0';
/*
 * Record the location of the line.
 */
    node->start = 0;
/*
 * The buffer has one or more lines in it.
 */
  } else {
/*
 * Place the start of the new line just after the most recently
 * added line.
 */
    int start = list->tail->start + list->tail->nchar;
/*
 * If there is insufficient room between the end of the most
 * recently added line and the end of the buffer, we place the
 * line at the beginning of the buffer. To make as much space
 * as possible for this line, we first delete any old lines
 * at the end of the buffer, then shift the remaining contents
 * of the buffer to the end of the buffer.
 */
    if(start + nchar >= glh->buflen) {
      GlLineNode *last; /* The last line in the buffer */
      GlLineNode *ln;   /* A member of the list of line locations */
      int shift;        /* The shift needed to move the contents of the */
                        /*  buffer to its end. */
/*
 * Delete any old lines between the most recent line and the end of the
 * buffer.
 */
      while(list->head && list->head->start > list->tail->start)
	_glh_discard_node(glh, list->head);
/*
 * Find the line that is nearest the end of the buffer.
 */
      last = NULL;
      for(ln=list->head; ln; ln=ln->next) {
	if(!last || ln->start > last->start)
	  last = ln;
      };
/*
 * How big a shift is needed to move the existing contents of the
 * buffer to the end of the buffer?
 */
      shift = last ? (glh->buflen - (last->start + last->nchar)) : 0;
/*
 * Is any shift needed?
 */
      if(shift > 0) {
/*
 * Move the buffer contents to the end of the buffer.
 */
	memmove(glh->buffer + shift, glh->buffer, glh->buflen - shift);
/*
 * Update the listed locations to reflect the shift.
 */
	for(ln=list->head; ln; ln=ln->next)
	  ln->start += shift;
      };
/*
 * The new line should now be located at the start of the buffer.
 */
      start = 0;
    };
/*
 * Make space for the new line at the beginning of the buffer by
 * deleting the oldest lines. This just involves removing them
 * from the list of used locations. Also enforce the current
 * maximum number of lines.
 */
    while(list->head &&
	  ((list->head->start >= start && list->head->start - start < nchar) ||
	   (glh->max_lines >= 0 && glh->nline>=glh->max_lines))) {
      _glh_discard_node(glh, list->head);
    };
/*
 * Copy the new line into the buffer.
 */
    memcpy(glh->buffer + start, line, nchar);
    glh->buffer[start + nchar - 1] = '\0';
/*
 * Record its location.
 */
    node->start = start;
  };
/*
 * Append the line location node to the end of the list.
 */
  node->id = glh->seq++;
  node->timestamp = time(NULL);
  node->group = glh->group;
  node->nchar = nchar;
  node->next = NULL;
  node->prev = list->tail;
  if(list->tail)
    list->tail->next = node;
  else
    list->head = node;
  list->tail = node;
  glh->nline++;
  return 0;
}

/*.......................................................................
 * Recall the next oldest line that has the search prefix last recorded
 * by _glh_search_prefix().
 *
 * Input:
 *  glh  GlHistory *  The input-line history maintenance object.
 *  line      char *  The input line buffer. On input this should contain
 *                    the current input line, and on output, if anything
 *                    was found, its contents will have been replaced
 *                    with the matching line.
 *  dim     size_t    The allocated dimensions of the line buffer.
 * Output:
 *  return    char *  A pointer to line[0], or NULL if not found.
 */
char *_glh_find_backwards(GlHistory *glh, char *line, size_t dim)
{
  GlLineNode *node; /* The line location node being checked */
  int first;        /* True if this is the start of a new search */
/*
 * Check the arguments.
 */
  if(!glh || !line) {
    fprintf(stderr, "_glh_find_backwards: NULL argument(s).\n");
    return NULL;
  };
/*
 * Is history enabled?
 */
  if(!glh->enable || !glh->buffer || glh->max_lines == 0)
    return NULL;
/*
 * Check the line dimensions.
 */
  if(dim < strlen(line) + 1) {
    fprintf(stderr,
       "_glh_find_backwards: 'dim' inconsistent with strlen(line) contents.\n");
    return NULL;
  };
/*
 * Is this the start of a new search?
 */
  first = glh->recall==NULL;
/*
 * If this is the first search backwards, save the current line
 * for potential recall later, and mark it as the last line
 * recalled.
 */
  if(first) {
    if(_glh_add_history(glh, line, 1))
      return NULL;
    glh->recall = glh->list.tail;
  };
/*
 * If there is no search prefix, the prefix last set by glh_search_prefix()
 * doesn't exist in the history buffer.
 */
  if(!glh->prefix)
    return NULL;
/*
 * From where should we start the search?
 */
  if(glh->recall)
    node = glh->recall->prev;
  else
    node = glh->list.tail;
/*
 * Search backwards through the list for the first match with the
 * prefix string.
 */
  for( ; node &&
      (node->group != glh->group ||
       strncmp(glh->buffer + node->start, glh->prefix, glh->prefix_len) != 0);
      node = node->prev)
    ;
/*
 * Was a matching line found?
 */
  if(node) {
/*
 * Recall the found node as the starting point for subsequent
 * searches.
 */
    glh->recall = node;
/*
 * Copy the matching line into the provided line buffer.
 */
    strncpy(line, glh->buffer + node->start, dim);
    line[dim-1] = '\0';
    return line;
  };
/*
 * No match was found.
 */
  return NULL;
}

/*.......................................................................
 * Recall the next newest line that has the search prefix last recorded
 * by _glh_search_prefix().
 *
 * Input:
 *  glh  GlHistory *  The input-line history maintenance object.
 *  line      char *  The input line buffer. On input this should contain
 *                    the current input line, and on output, if anything
 *                    was found, its contents will have been replaced
 *                    with the matching line.
 *  dim     size_t    The allocated dimensions of the line buffer.
 * Output:
 *  return    char *  The line requested, or NULL if no matching line
 *                    was found.
 */
char *_glh_find_forwards(GlHistory *glh, char *line, size_t dim)
{
  GlLineNode *node; /* The line location node being checked */
/*
 * Check the arguments.
 */
  if(!glh || !line) {
    fprintf(stderr, "_glh_find_forwards: NULL argument(s).\n");
    return NULL;
  };
/*
 * Is history enabled?
 */
  if(!glh->enable || !glh->buffer || glh->max_lines == 0)
    return NULL;
/*
 * Check the line dimensions.
 */
  if(dim < strlen(line) + 1) {
    fprintf(stderr,
       "_glh_find_forwards: 'dim' inconsistent with strlen(line) contents.\n");
    return NULL;
  };
/*
 * From where should we start the search?
 */
  if(glh->recall)
    node = glh->recall->next;
  else
    return NULL;
/*
 * If there is no search prefix, the prefix last set by glh_search_prefix()
 * doesn't exist in the history buffer.
 */
  if(!glh->prefix)
    return NULL;
/*
 * Search forwards through the list for the first match with the
 * prefix string.
 */
  for( ; node &&
      (node->group != glh->group ||
       strncmp(glh->buffer + node->start, glh->prefix, glh->prefix_len) != 0);
      node = node->next)
    ;
/*
 * Was a matching line found?
 */
  if(node) {
/*
 * Did we hit the line that was originally being edited when the
 * current history traversal started?
 */
    if(node == glh->list.tail)
      return _glh_restore_line(glh, line, dim);
/*
 * Copy the matching line into the provided line buffer.
 */
    strncpy(line, glh->buffer + node->start, dim);
    line[dim-1] = '\0';
/*
 * Record the starting point of the next search.
 */
    glh->recall = node;
/*
 * Return the matching line to the user.
 */
    return line;
  };
/*
 * No match was found.
 */
  return NULL;
}

/*.......................................................................
 * If a search is in progress, cancel it.
 *
 * This involves discarding the line that was temporarily saved by
 * _glh_find_backwards() when the search was originally started,
 * and reseting the search iteration pointer to NULL.
 *
 * Input:
 *  glh  GlHistory *  The input-line history maintenance object.
 * Output:
 *  return     int    0 - OK.
 *                    1 - Error.
 */
int _glh_cancel_search(GlHistory *glh)
{
/*
 * Check the arguments.
 */
  if(!glh) {
    fprintf(stderr, "_glh_cancel_search: NULL argument(s).\n");
    return 1;
  };
/*
 * If there wasn't a search in progress, do nothing.
 */
  if(!glh->recall)
    return 0;
/*
 * Delete the node of the preserved line.
 */
  _glh_discard_node(glh, glh->list.tail);
/*
 * Reset the search pointers.
 */
  glh->recall = NULL;
  glh->prefix = "";
  glh->prefix_len = 0;
  return 0;
}

/*.......................................................................
 * Set the prefix of subsequent history searches.
 *
 * Input:
 *  glh  GlHistory *  The input-line history maintenance object.
 *  line      char *  The command line who's prefix is to be used.
 *  prefix_len int    The length of the prefix.
 * Output:
 *  return     int    0 - OK.
 *                    1 - Error.
 */
int _glh_search_prefix(GlHistory *glh, const char *line, int prefix_len)
{
  GlLineNode *node; /* The line location node being checked */
/*
 * Check the arguments.
 */
  if(!glh) {
    fprintf(stderr, "_glh_search_prefix: NULL argument(s).\n");
    return 1;
  };
/*
 * Is history enabled?
 */
  if(!glh->enable || !glh->buffer || glh->max_lines == 0)
    return 0;
/*
 * Record a zero length search prefix?
 */
  if(prefix_len <= 0) {
    glh->prefix_len = 0;
    glh->prefix = "";
    return 0;
  };
/*
 * Record the length of the new search prefix.
 */
  glh->prefix_len = prefix_len;
/*
 * If any history line starts with the specified prefix, record a
 * pointer to it for comparison in subsequent searches. If the prefix
 * doesn't match any of the lines, then simply record NULL to indicate
 * that there is no point in searching. Note that _glh_add_history()
 * clears this pointer by calling _glh_cancel_search(), so there is
 * no danger of it being used after the buffer has been modified.
 */
  for(node = glh->list.tail ; node &&
      (node->group != glh->group ||
       strncmp(glh->buffer + node->start, line, prefix_len) != 0);
      node = node->prev)
    ;
/*
 * If a matching line was found record it for use as the search
 * prefix.
 */
  glh->prefix = node ? glh->buffer + node->start : NULL;
  return 0;
}

/*.......................................................................
 * Recall the oldest recorded line.
 *
 * Input:
 *  glh  GlHistory *  The input-line history maintenance object.
 *  line      char *  The input line buffer. On input this should contain
 *                    the current input line, and on output, its contents
 *                    will have been replaced with the oldest line.
 *  dim     size_t    The allocated dimensions of the line buffer.
 * Output:
 *  return    char *  A pointer to line[0], or NULL if not found.
 */
char *_glh_oldest_line(GlHistory *glh, char *line, size_t dim)
{
  GlLineNode *node; /* The line location node being checked */
  int first;        /* True if this is the start of a new search */
/*
 * Check the arguments.
 */
  if(!glh || !line) {
    fprintf(stderr, "_glh_oldest_line: NULL argument(s).\n");
    return NULL;
  };
/*
 * Is history enabled?
 */
  if(!glh->enable || !glh->buffer || glh->max_lines == 0)
    return NULL;
/*
 * Check the line dimensions.
 */
  if(dim < strlen(line) + 1) {
    fprintf(stderr,
       "_glh_oldest_line: 'dim' inconsistent with strlen(line) contents.\n");
    return NULL;
  };
/*
 * Is this the start of a new search?
 */
  first = glh->recall==NULL;
/*
 * If this is the first search backwards, save the current line
 * for potential recall later, and mark it as the last line
 * recalled.
 */
  if(first) {
    if(_glh_add_history(glh, line, 1))
      return NULL;
    glh->recall = glh->list.tail;
  };
/*
 * Locate the oldest line that belongs to the current group.
 */
  for(node=glh->list.head; node && node->group != glh->group; 
      node = node->next)
    ;
/*
 * No line found?
 */
  if(!node)
    return NULL;
/*
 * Record the above node as the starting point for subsequent
 * searches.
 */
  glh->recall = node;
/*
 * Copy the recalled line into the provided line buffer.
 */
  strncpy(line, glh->buffer + node->start, dim);
  line[dim-1] = '\0';
  return line;
}

/*.......................................................................
 * Recall the line that was being entered when the search started.
 *
 * Input:
 *  glh  GlHistory *  The input-line history maintenance object.
 *  line      char *  The input line buffer. On input this should contain
 *                    the current input line, and on output, its contents
 *                    will have been replaced with the line that was
 *                    being entered when the search was started.
 *  dim     size_t    The allocated dimensions of the line buffer.
 * Output:
 *  return    char *  A pointer to line[0], or NULL if not found.
 */
char *_glh_current_line(GlHistory *glh, char *line, size_t dim)
{
/*
 * Check the arguments.
 */
  if(!glh || !line) {
    fprintf(stderr, "_glh_current_line: NULL argument(s).\n");
    return NULL;
  };
/*
 * Is history enabled?
 */
  if(!glh->enable || !glh->buffer || glh->max_lines == 0)
    return NULL;
/*
 * Check the line dimensions.
 */
  if(dim < strlen(line) + 1) {
    fprintf(stderr,
       "_glh_current_line: 'dim' inconsistent with strlen(line) contents.\n");
    return NULL;
  };
/*
 * Restore the original line.
 */
  return _glh_restore_line(glh, line, dim);
}

/*.......................................................................
 * Remove the line that was originally being edited when the history
 * traversal was started, from its saved position in the history list,
 * and place it in the provided line buffer.
 *
 * Input:
 *  glh  GlHistory *  The input-line history maintenance object.
 *  line      char *  The input line buffer. On input this should contain
 *                    the current input line, and on output, its contents
 *                    will have been replaced with the saved line.
 *  dim     size_t    The allocated dimensions of the line buffer.
 * Output:
 *  return    char *  A pointer to line[0], or NULL if not found.
 */
static char *_glh_restore_line(GlHistory *glh, char *line, size_t dim)
{
  GlLineNode *tail;   /* The tail node to be discarded */
/*
 * If there wasn't a search in progress, do nothing.
 */
  if(!glh->recall)
    return NULL;
/*
 * Get the list node that is to be removed.
 */
  tail = glh->list.tail;
/*
 * If a pointer to the saved line is being used to record the
 * current search prefix, reestablish the search prefix, to
 * have it recorded by another history line if possible.
 */
  if(glh->prefix == glh->buffer + tail->start)
    (void) _glh_search_prefix(glh, glh->buffer + tail->start, glh->prefix_len);
/*
 * Copy the recalled line into the input-line buffer.
 */
  strncpy(line, glh->buffer + tail->start, dim);
  line[dim-1] = '\0';
/*
 * Discard the line-location node.
 */
  _glh_discard_node(glh, tail);
/*
 * Mark the search as ended.
 */
  glh->recall = NULL;
  return line;
}

/*.......................................................................
 * Query the id of a history line offset by a given number of lines from
 * the one that is currently being recalled. If a recall session isn't
 * in progress, or the offset points outside the history list, 0 is
 * returned.
 *
 * Input:
 *  glh    GlHistory *  The input-line history maintenance object.
 *  offset       int    The line offset (0 for the current line, < 0
 *                      for an older line, > 0 for a newer line.
 * Output:
 *  return GlhLineID    The identifier of the line that is currently
 *                      being recalled, or 0 if no recall session is
 *                      currently in progress.
 */
GlhLineID _glh_line_id(GlHistory *glh, int offset)
{
  GlLineNode *node; /* The line location node being checked */
/*
 * Is history enabled?
 */
  if(!glh->enable || !glh->buffer || glh->max_lines == 0)
    return 0;
/*
 * Search forward 'offset' lines to find the required line.
 */
  if(offset >= 0) {
    for(node=glh->recall; node && offset != 0; node=node->next) {
      if(node->group == glh->group)
	offset--;
    };
  } else {
    for(node=glh->recall; node && offset != 0; node=node->prev) {
      if(node->group == glh->group)
	offset++;
    };
  };
  return node ? node->id : 0;
}

/*.......................................................................
 * Recall a line by its history buffer ID. If the line is no longer
 * in the buffer, or the id is zero, NULL is returned.
 *
 * Input:
 *  glh  GlHistory *  The input-line history maintenance object.
 *  id   GlhLineID    The ID of the line to be returned.
 *  line      char *  The input line buffer. On input this should contain
 *                    the current input line, and on output, its contents
 *                    will have been replaced with the saved line.
 *  dim     size_t    The allocated dimensions of the line buffer.
 * Output:
 *  return    char *  A pointer to line[0], or NULL if not found.
 */
char *_glh_recall_line(GlHistory *glh, GlhLineID id, char *line, size_t dim)
{
  GlLineNode *node; /* The line location node being checked */
/*
 * Is history enabled?
 */
  if(!glh->enable || !glh->buffer || glh->max_lines == 0)
    return NULL;
/*
 * If we are starting a new recall session, save the current line
 * for potential recall later.
 */
  if(!glh->recall && _glh_add_history(glh, line, 1))
    return NULL;
/*
 * Search for the specified line.
 */
  node = _glh_find_id(glh, id);
/*
 * Not found?
 */
  if(!node || node->group != glh->group)
    return NULL;
/*
 * Record the node of the matching line as the starting point
 * for subsequent searches.
 */
  glh->recall = node;
/*
 * Copy the recalled line into the provided line buffer.
 */
  strncpy(line, glh->buffer + node->start, dim);
  line[dim-1] = '\0';
  return line;
}

/*.......................................................................
 * Save the current history in a specified file.
 *
 * Input:
 *  glh        GlHistory *  The input-line history maintenance object.
 *  filename  const char *  The name of the new file to record the
 *                          history in.
 *  comment   const char *  Extra information such as timestamps will
 *                          be recorded on a line started with this
 *                          string, the idea being that the file can
 *                          double as a command file. Specify "" if
 *                          you don't care.
 *  max_lines        int    The maximum number of lines to save, or -1
 *                          to save all of the lines in the history
 *                          list.
 * Output:
 *  return           int    0 - OK.
 *                          1 - Error.
 */
int _glh_save_history(GlHistory *glh, const char *filename, const char *comment,
		      int max_lines)
{
  FILE *fp;         /* The output file */
  GlLineNode *node; /* The line being saved */
  GlLineNode *head; /* The head of the list of lines to be saved */
/*
 * Check the arguments.
 */
  if(!glh || !filename || !comment) {
    fprintf(stderr, "_glh_save_history: NULL argument(s).\n");
    return 1;
  };
/*
 * Attempt to open the specified file.
 */
  fp = fopen(filename, "w");
  if(!fp) {
    fprintf(stderr, "_glh_save_history: Can't open %s (%s).\n",
	    filename, strerror(errno));
    return 1;
  };
/*
 * If a ceiling on the number of lines to save was specified, count
 * that number of lines backwards, to find the first line to be saved.
 */
  head = NULL;
  if(max_lines >= 0) {
    for(head=glh->list.tail; head && --max_lines > 0; head=head->prev)
      ;
  };
  if(!head)
    head = glh->list.head;
/*
 * Write the contents of the history buffer to the history file, writing
 * associated data such as timestamps, to a line starting with the
 * specified comment string.
 */
  for(node=head; node; node=node->next) {
/*
 * Write peripheral information associated with the line, as a comment.
 */
    if(fprintf(fp, "%s ", comment) < 0 ||
       _glh_write_timestamp(fp, node->timestamp) ||
       fprintf(fp, " %u\n", node->group) < 0) {
      fprintf(stderr, "Error writing %s (%s).\n", filename, strerror(errno));
      (void) fclose(fp);
      return 1;
    };
/*
 * Write the history line.
 */
    if(fprintf(fp, "%s\n", glh->buffer + node->start) < 0) {
      fprintf(stderr, "Error writing %s (%s).\n", filename, strerror(errno));
      (void) fclose(fp);
      return 1;
    };
  };
/*
 * Close the history file.
 */
  if(fclose(fp) == EOF) {
    fprintf(stderr, "Error writing %s (%s).\n", filename, strerror(errno));
    return 1;
  };
  return 0;
}

/*.......................................................................
 * Restore previous history lines from a given file.
 *
 * Input:
 *  glh        GlHistory *  The input-line history maintenance object.
 *  filename  const char *  The name of the file to read from.
 *  comment   const char *  The same comment string that was passed to
 *                          _glh_save_history() when this file was
 *                          written.
 *  line            char *  A buffer into which lines can be read.
 *  dim            size_t   The allocated dimension of line[].
 * Output:
 *  return           int    0 - OK.
 *                          1 - Error.
 */
int _glh_load_history(GlHistory *glh, const char *filename, const char *comment,
		      char *line, size_t dim)
{
  FILE *fp;            /* The output file */
  size_t comment_len;  /* The length of the comment string */
  time_t timestamp;    /* The timestamp of the history line */
  unsigned group;      /* The identifier of the history group to which */
                       /*  the line belongs. */
  int lineno;          /* The line number being read */
/*
 * Check the arguments.
 */
  if(!glh || !filename || !comment || !line) {
    fprintf(stderr, "_glh_load_history: NULL argument(s).\n");
    return 1;
  };
/*
 * Measure the length of the comment string.
 */
  comment_len = strlen(comment);
/*
 * Clear the history list.
 */
  _glh_clear_history(glh, 1);
/*
 * Attempt to open the specified file. Don't treat it as an error
 * if the file doesn't exist.
 */
  fp = fopen(filename, "r");
  if(!fp)
    return 0;
/*
 * Attempt to read each line and preceding peripheral info, and add these
 * to the history list.
 */
  for(lineno=1; fgets(line, dim, fp) != NULL; lineno++) {
    char *lptr;          /* A pointer into the input line */
/*
 * Check that the line starts with the comment string.
 */
    if(strncmp(line, comment, comment_len) != 0) {
      return _glh_cant_load_history(glh, filename, lineno,
				    "Corrupt history parameter line", fp);
    };
/*
 * Skip spaces and tabs after the comment.
 */
    for(lptr=line+comment_len; *lptr && (*lptr==' ' || *lptr=='\t'); lptr++)
      ;
/*
 * The next word must be a timestamp.
 */
    if(_glh_decode_timestamp(lptr, &lptr, &timestamp)) {
      return _glh_cant_load_history(glh, filename, lineno,
				    "Corrupt timestamp", fp);
    };
/*
 * Skip spaces and tabs.
 */
    while(*lptr==' ' || *lptr=='\t')
      lptr++;
/*
 * The next word must be an unsigned integer group number.
 */
    group = (int) strtoul(lptr, &lptr, 10);
    if(*lptr != ' ' && *lptr != '\n') {
      return _glh_cant_load_history(glh, filename, lineno,
				    "Corrupt group id", fp);
    };
/*
 * Skip spaces and tabs.
 */
    while(*lptr==' ' || *lptr=='\t')
      lptr++;
/*
 * There shouldn't be anything left on the line.
 */
    if(*lptr != '\n') {
      return _glh_cant_load_history(glh, filename, lineno,
				    "Corrupt parameter line", fp);
    };
/*
 * Now read the history line itself.
 */
    lineno++;
    if(fgets(line, dim, fp) == NULL)
      return _glh_cant_load_history(glh, filename, lineno, "Read error", fp);
/*
 * Append the line to the history buffer.
 */
    if(_glh_add_history(glh, line, 1)) {
      return _glh_cant_load_history(glh, filename, lineno,
				    "Insufficient memory to record line", fp);
    };
/*
 * Record the group and timestamp information along with the line.
 */
    if(glh->list.tail) {
      glh->list.tail->timestamp = timestamp;
      glh->list.tail->group = group;
    };
  };
/*
 * Close the file.
 */
  (void) fclose(fp);
  return 0;
}

/*.......................................................................
 * This is a private error return function of _glh_load_history().
 */
static int _glh_cant_load_history(GlHistory *glh, const char *filename,
				  int lineno, const char *message, FILE *fp)
{
  fprintf(stderr, "%s:%d: %s.\n", filename, lineno, message);
  (void) fclose(fp);
  return 1;
}

/*.......................................................................
 * Switch history groups.
 *
 * Input:
 *  glh        GlHistory *  The input-line history maintenance object.
 *  group      unsigned    The new group identifier. This will be recorded
 *                          with subsequent history lines, and subsequent
 *                          history searches will only return lines with
 *                          this group identifier. This allows multiple
 *                          separate history lists to exist within
 *                          a single GlHistory object. Note that the
 *                          default group identifier is 0.
 * Output:
 *  return           int    0 - OK.
 *                          1 - Error.
 */
int _glh_set_group(GlHistory *glh, unsigned group)
{
/*
 * Check the arguments.
 */
  if(!glh) {
    fprintf(stderr, "_glh_set_group: NULL argument(s).\n");
    return 1;
  };
/*
 * Is the group being changed?
 */
  if(group != glh->group) {
/*
 * Cancel any ongoing search.
 */
    if(_glh_cancel_search(glh))
      return 1;
/*
 * Record the new group.
 */
    glh->group = group;
  };
  return 0;
}

/*.......................................................................
 * Query the current history group.
 *
 * Input:
 *  glh        GlHistory *  The input-line history maintenance object.
 * Output:
 *  return      unsigned    The group identifier.    
 */
int _glh_get_group(GlHistory *glh)
{
  return glh ? glh->group : 0;
}

/*.......................................................................
 * Write a timestamp to a given stdio stream, in the format
 * yyyymmddhhmmss
 *
 * Input:
 *  fp             FILE *  The stream to write to.
 *  timestamp    time_t    The timestamp to be written.
 * Output:
 *  return          int    0 - OK.
 *                         1 - Error.
 */
static int _glh_write_timestamp(FILE *fp, time_t timestamp)
{
  struct tm *t;  /* THe broken-down calendar time */
/*
 * Get the calendar components corresponding to the given timestamp.
 */
  if(timestamp < 0 || (t = localtime(&timestamp)) == NULL) {
    if(fprintf(fp, "?") < 0)
      return 1;
    return 0;
  };
/*
 * Write the calendar time as yyyymmddhhmmss.
 */
  if(fprintf(fp, "%04d%02d%02d%02d%02d%02d", t->tm_year + 1900, t->tm_mon + 1,
	     t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec) < 0)
    return 1;
  return 0;
}

/*.......................................................................
 * Read a timestamp from a string.
 *
 * Input:
 *  string    char *  The string to read from.
 * Input/Output:
 *  endp        char ** On output *endp will point to the next unprocessed
 *                      character in string[].
 *  timestamp time_t *  The timestamp will be assigned to *t.
 * Output:
 *  return       int    0 - OK.
 *                      1 - Error.
 */
static int _glh_decode_timestamp(char *string, char **endp, time_t *timestamp)
{
  unsigned year,month,day,hour,min,sec;  /* Calendar time components */
  struct tm t;
/*
 * There are 14 characters in the date format yyyymmddhhmmss.
 */
  enum {TSLEN=14};                    
  char timestr[TSLEN+1];   /* The timestamp part of the string */
/*
 * If the time wasn't available at the time that the line was recorded
 * it will have been written as "?". Check for this before trying
 * to read the timestamp.
 */
  if(string[0] == '\?') {
    *endp = string+1;
    *timestamp = -1;
    return 0;
  };
/*
 * The timestamp is expected to be written in the form yyyymmddhhmmss.
 */
  if(strlen(string) < TSLEN) {
    *endp = string;
    return 1;
  };
/*
 * Copy the timestamp out of the string.
 */
  strncpy(timestr, string, TSLEN);
  timestr[TSLEN] = '\0';
/*
 * Decode the timestamp.
 */
  if(sscanf(timestr, "%4u%2u%2u%2u%2u%2u", &year, &month, &day, &hour, &min,
	    &sec) != 6) {
    *endp = string;
    return 1;
  };
/*
 * Advance the string pointer over the successfully read timestamp.
 */
  *endp = string + TSLEN;
/*
 * Copy the read values into a struct tm.
 */
  t.tm_sec = sec;
  t.tm_min = min;
  t.tm_hour = hour;
  t.tm_mday = day;
  t.tm_wday = 0;
  t.tm_yday = 0;
  t.tm_mon = month - 1;
  t.tm_year = year - 1900;
  t.tm_isdst = -1;
/*
 * Convert the contents of the struct tm to a time_t.
 */
  *timestamp = mktime(&t);
  return 0;
}

/*.......................................................................
 * Display the contents of the history list.
 *
 * Input:
 *  glh    GlHistory *  The input-line history maintenance object.
 *  fp          FILE *  The stdio stream to write to.
 *  fmt   const char *  A format string. This can contain arbitrary
 *                      characters, which are written verbatim, plus
 *                      any of the following format directives:
 *                        %D  -  The date, like 2001-11-20
 *                        %T  -  The time of day, like 23:59:59
 *                        %N  -  The sequential entry number of the
 *                               line in the history buffer.
 *                        %G  -  The history group number of the line.
 *                        %%  -  A literal % character.
 *                        %H  -  The history line.
 *  all_groups   int    If true, display history lines from all
 *                      history groups. Otherwise only display
 *                      those of the current history group.
 *  max_lines    int    If max_lines is < 0, all available lines
 *                      are displayed. Otherwise only the most
 *                      recent max_lines lines will be displayed.
 * Output:
 *  return       int    0 - OK.
 *                      1 - Error.
 */
int _glh_show_history(GlHistory *glh, FILE *fp, const char *fmt,
		      int all_groups, int max_lines)
{
  GlLineNode *node;      /* The line being displayed */
  GlLineNode *oldest;    /* The oldest line to display */
  enum {TSMAX=32};       /* The maximum length of the date and time string */
  char buffer[TSMAX+1];  /* The buffer in which to write the date and time */
  int idlen;             /* The length of displayed ID strings */
  unsigned grpmax;       /* The maximum group number in the buffer */
  int grplen;            /* The number of characters needed to print grpmax */
/*
 * Check the arguments.
 */
  if(!glh || !fp || !fmt) {
    fprintf(stderr, "_glh_show_history: NULL argument(s).\n");
    return 1;
  };
/*
 * Is history enabled?
 */
  if(!glh->enable || !glh->list.head)
    return 0;
/*
 * Work out the length to display ID numbers, choosing the length of
 * the biggest number in the buffer. Smaller numbers will be padded 
 * with leading zeroes if needed.
 */
  sprintf(buffer, "%lu", (unsigned long) glh->list.tail->id);
  idlen = strlen(buffer);
/*
 * Find the largest group number.
 */
  grpmax = 0;
  for(node=glh->list.head; node; node=node->next) {
    if(node->group > grpmax)
      grpmax = node->group;
  };
/*
 * Find out how many characters are needed to display the group number.
 */
  sprintf(buffer, "%u", (unsigned) grpmax);
  grplen = strlen(buffer);
/*
 * Find the node that follows the oldest line to be displayed.
 */
  if(max_lines < 0) {
    oldest = glh->list.head;
  } else if(max_lines==0) {
    return 0;
  } else {
    for(oldest=glh->list.tail; oldest; oldest=oldest->prev) {
      if((all_groups || oldest->group == glh->group) && --max_lines <= 0)
	break;
    };
/*
 * If the number of lines in the buffer doesn't exceed the specified
 * maximum, start from the oldest line in the buffer.
 */
    if(!oldest)
      oldest = glh->list.head;
  };
/*
 * List the history lines in increasing time order.
 */
  for(node=oldest; node; node=node->next) {
/*
 * Only display lines from the current history group, unless
 * told otherwise.
 */
    if(all_groups || node->group == glh->group) {
      const char *fptr;      /* A pointer into the format string */
      struct tm *t = NULL;   /* The broken time version of the timestamp */
/*
 * Work out the calendar representation of the node timestamp.
 */
      if(node->timestamp != (time_t) -1)
	t = localtime(&node->timestamp);
/*
 * Parse the format string.
 */
      fptr = fmt;
      while(*fptr) {
/*
 * Search for the start of the next format directive or the end of the string.
 */
	const char *start = fptr;
	while(*fptr && *fptr != '%')
	  fptr++;
/*
 * Display any literal characters that precede the located directive.
 */
	if(fptr > start && fprintf(fp, "%.*s", (int) (fptr - start), start) < 0)
	  return 1;
/*
 * Did we hit a new directive before the end of the line?
 */
	if(*fptr) {
/*
 * Obey the directive. Ignore unknown directives.
 */
	  switch(*++fptr) {
	  case 'D':          /* Display the date */
	    if(t && strftime(buffer, TSMAX, "%Y-%m-%d", t) != 0 &&
	       fprintf(fp, "%s", buffer) < 0)
	      return 1;
	    break;
	  case 'T':          /* Display the time of day */
	    if(t && strftime(buffer, TSMAX, "%H:%M:%S", t) != 0 &&
	       fprintf(fp, "%s", buffer) < 0)
	      return 1;
	    break;
	  case 'N':          /* Display the sequential entry number */
	    if(fprintf(fp, "%*lu", idlen, (unsigned long) node->id) < 0)
	      return 1;
	    break;
	  case 'G':
	    if(fprintf(fp, "%*u", grplen, (unsigned) node->group) < 0)
	      return 1;
	    break;
	  case 'H':          /* Display the history line */
	    if(fprintf(fp, "%s", glh->buffer + node->start) < 0)
	      return 1;
	    break;
	  case '%':          /* A literal % symbol */
	    if(fputc('%', fp) == EOF)
	      return 1;
	    break;
	  };
/*
 * Skip the directive.
 */
	  if(*fptr)
	    fptr++;
	};
      };
    };
  };
  return 0;
}

/*.......................................................................
 * Change the size of the history buffer.
 *
 * Input:
 *  glh    GlHistory *  The input-line history maintenance object.
 *  bufsize   size_t    The number of bytes in the history buffer, or 0
 *                      to delete the buffer completely.
 * Output:
 *  return       int    0 - OK.
 *                      1 - Insufficient memory (the previous buffer
 *                          will have been retained). No error message
 *                          will be displayed.
 */
int _glh_resize_history(GlHistory *glh, size_t bufsize)
{
  GlLineNode *node;  /* A line location node in the list of lines */
  GlLineNode *prev;  /* The line location node preceding 'node' */
/*
 * Check the arguments.
 */
  if(!glh)
    return bufsize > 0;
/*
 * If the new size doesn't differ from the existing size, do nothing.
 */
  if(glh->buflen == bufsize)
    return 0;
/*
 * Cancel any ongoing search.
 */
  (void) _glh_cancel_search(glh);
/*
 * Create a wholly new buffer?
 */
  if(glh->buflen == 0) {
    glh->buffer = (char *) malloc(bufsize);
    if(!glh->buffer)
      return 1;
    glh->buflen = bufsize;
/*
 * Delete an existing buffer?
 */
  } else if(bufsize == 0) {
    _glh_clear_history(glh, 1);
    free(glh->buffer);
    glh->buffer = NULL;
    glh->buflen = 0;
/*
 * To get here, we must be shrinking or expanding from one
 * finite size to another.
 */
  } else {
/*
 * If we are shrinking the size of the buffer, then we first need
 * to discard the oldest lines that won't fit in the new buffer.
 */
    if(bufsize < glh->buflen) {
      size_t nbytes = 0;    /* The number of bytes used in the new buffer */
      GlLineNode *oldest;   /* The oldest node to be kept */
/*
 * Searching backwards from the youngest line, find the oldest
 * line for which there will be sufficient room in the new buffer.
 */
      for(oldest = glh->list.tail;
	  oldest && (nbytes += oldest->nchar) <= bufsize;
	  oldest = oldest->prev)
	;
/*
 * We will have gone one node too far, unless we reached the oldest line
 * without exceeding the target length.
 */
      if(oldest) {
	nbytes -= oldest->nchar;
	oldest = oldest->next;
      };
/*
 * Discard the nodes that can't be retained.
 */
      while(glh->list.head && glh->list.head != oldest)
	_glh_discard_node(glh, glh->list.head);
/*
 * If we are increasing the size of the buffer, we need to reallocate
 * the buffer before shifting the lines into their new positions.
 */
    } else {
      char *new_buffer = (char *) realloc(glh->buffer, bufsize);
      if(!new_buffer)
	return 1;
      glh->buffer = new_buffer;
      glh->buflen = bufsize;
    };
/*
 * If there are any lines to be preserved, copy the block of lines
 * that precedes the end of the existing buffer to what will be 
 * the end of the new buffer.
 */
    if(glh->list.head) {
      int shift;  /* The number of bytes to shift lines in the buffer */
/*
 * Get the oldest line to be kept.
 */
      GlLineNode *oldest = glh->list.head;
/*
 * Count the number of characters that are used in the lines that
 * precede the end of the current buffer (ie. not including those
 * lines that have been wrapped to the start of the buffer).
 */
      int n = 0;
      for(node=oldest,prev=oldest->prev; node && node->start >= oldest->start;
	  prev=node, node=node->next)
	n += node->nchar;
/*
 * Move these bytes to the end of the resized buffer.
 */
      memmove(glh->buffer + bufsize - n, glh->buffer + oldest->start, n);
/*
 * Adjust the buffer pointers to reflect the new locations of the moved
 * lines.
 */
      shift = bufsize - n - oldest->start;
      for(node=prev; node && node->start >= oldest->start; node=node->prev)
	node->start += shift;
    };
/*
 * Shrink the buffer?
 */
    if(bufsize < glh->buflen) {
      char *new_buffer = (char *) realloc(glh->buffer, bufsize);
      if(new_buffer)
	glh->buffer = new_buffer;
      glh->buflen = bufsize;  /* Mark it as shrunk, regardless of success */
    };
  };
  return 0;
}

/*.......................................................................
 * Set an upper limit to the number of lines that can be recorded in the
 * history list, or remove a previously specified limit.
 *
 * Input:
 *  glh    GlHistory *  The input-line history maintenance object.
 *  max_lines    int    The maximum number of lines to allow, or -1 to
 *                      cancel a previous limit and allow as many lines
 *                      as will fit in the current history buffer size.
 */
void _glh_limit_history(GlHistory *glh, int max_lines)
{
  if(!glh)
    return;
/*
 * Apply a new limit?
 */
  if(max_lines >= 0 && max_lines != glh->max_lines) {
/*
 * Count successively older lines until we reach the start of the
 * list, or until we have seen max_lines lines (at which point 'node'
 * will be line number max_lines+1).
 */
    int nline = 0;
    GlLineNode *node;
    for(node=glh->list.tail; node && ++nline <= max_lines; node=node->prev)
      ;
/*
 * Discard any lines that exceed the limit.
 */
    if(node) {
      GlLineNode *oldest = node->next;  /* The oldest line to be kept */
/*
 * Delete nodes from the head of the list until we reach the node that
 * is to be kept.
 */
      while(glh->list.head && glh->list.head != oldest)
	_glh_discard_node(glh, glh->list.head);
    };
  };
/*
 * Record the new limit.
 */
  glh->max_lines = max_lines;
  return;
}

/*.......................................................................
 * Discard either all history, or the history associated with the current
 * history group.
 *
 * Input:
 *  glh    GlHistory *  The input-line history maintenance object.
 *  all_groups   int    If true, clear all of the history. If false,
 *                      clear only the stored lines associated with the
 *                      currently selected history group.
 */
void _glh_clear_history(GlHistory *glh, int all_groups)
{
/*
 * Check the arguments.
 */
  if(!glh)
    return;
/*
 * Cancel any ongoing search.
 */
  (void) _glh_cancel_search(glh);
/*
 * Delete all history lines regardless of group?
 */
  if(all_groups) {
    _rst_FreeList(glh->list.node_mem);
    glh->list.head = glh->list.tail = NULL;
    glh->nline = 0;
    glh->id_node = NULL;
/*
 * Just delete lines of the current group?
 */
  } else {
    GlLineNode *node;  /* The line node being checked */
    GlLineNode *prev;  /* The line node that precedes 'node' */
    GlLineNode *next;  /* The line node that follows 'node' */
/*
 * Search out and delete the line nodes of the current group.
 */
    for(node=glh->list.head; node; node=next) {
/*
 * Keep a record of the following node before we delete the current
 * node.
 */
      next = node->next;
/*
 * Discard this node?
 */
      if(node->group == glh->group)
	_glh_discard_node(glh, node);
    };
/*
 * If there are any lines left, and we deleted any lines, there will
 * be gaps in the buffer. These need to be removed.
 */
    if(glh->list.head) {
      int epos;   /* The index of the last used element in the buffer */
/*
 * Find the line nearest the end of the buffer.
 */
      GlLineNode *enode;
      for(node=glh->list.head, prev=NULL;
	  node && node->start >= glh->list.head->start;
	  prev=node, node = node->next)
	;
      enode = prev;
/*
 * Move the end line to abutt the end of the buffer, and remove gaps
 * between the lines that precede it.
 */
      epos = glh->buflen;
      for(node=enode; node; node=node->prev) {
	int shift = epos - (node->start + node->nchar);
	if(shift) {
	  memmove(glh->buffer + node->start + shift,
		  glh->buffer + node->start, node->nchar);
	  node->start += shift;
	};
	epos = node->start;
      };
/*
 * Move the first line in the buffer to the start of the buffer, and
 * remove gaps between the lines that follow it.
 */
      epos = 0;
      for(node=enode ? enode->next : NULL; node; node=node->next) {
	int shift = epos - node->start;
	if(shift) {
	  memmove(glh->buffer + node->start + shift,
		  glh->buffer + node->start, node->nchar);
	  node->start += shift;
	};
	epos = node->start + node->nchar;
      };
    };
  };
  return;
}

/*.......................................................................
 * Temporarily enable or disable the history list.
 *
 * Input:
 *  glh    GlHistory *  The input-line history maintenance object.
 *  enable       int    If true, turn on the history mechanism. If
 *                      false, disable it.
 */
void _glh_toggle_history(GlHistory *glh, int enable)
{
  if(glh)
    glh->enable = enable;
}

/*.......................................................................
 * Remove a given line location node from the history list, and return
 * it to the freelist.
 *
 * Input:
 *  glh    GlHistory *  The input-line history maintenance object.
 *  node  GlLineNode *  The node to be removed. This must be currently
 *                      in the list who's head is glh->list.head, or
 *                      be NULL.
 */
static void _glh_discard_node(GlHistory *glh, GlLineNode *node)
{
  if(node) {
/*
 * Make the node that precedes the node being removed point
 * to the one that follows it.
 */
    if(node->prev)
      node->prev->next = node->next;
    else
      glh->list.head = node->next;
/*
 * Make the node that follows the node being removed point
 * to the one that precedes it.
 */
    if(node->next)
      node->next->prev = node->prev;
    else
      glh->list.tail = node->prev;
/*
 * If we are deleting the node that is marked as the start point of the
 * last ID search, remove the cached starting point.
 */
    if(node == glh->id_node)
      glh->id_node = NULL;
/*
 * Return the node to the free list.
 */
    node = (GlLineNode *) _del_FreeListNode(glh->list.node_mem, node);
/*
 * Decrement the count of the number of lines in the buffer.
 */
    glh->nline--;
  };
}

/*.......................................................................
 * Lookup the details of a given history line, given its id.
 *
 * Input:
 *  glh      GlHistory *  The input-line history maintenance object.
 *  id        GlLineID    The sequential number of the line.
 * Input/Output:
 *  line    const char ** A pointer to the history line will be assigned
 *                        to *line.
 *  group     unsigned *  The group membership of the line will be assigned
 *                        to *group.
 *  timestamp   time_t *  The timestamp of the line will be assigned to
 *                        *timestamp.
 * Output:
 *  return         int    0 - The requested line wasn't found.
 *                        1 - The line was found.
 */
int _glh_lookup_history(GlHistory *glh, GlhLineID id, const char **line,
			unsigned *group, time_t *timestamp)
{
  GlLineNode *node; /* The located line location node */
/*
 * Check the arguments.
 */
  if(!glh)
    return 0;
/*
 * Search for the line that has the specified ID.
 */
  node = _glh_find_id(glh, (GlhLineID) id);
/*
 * Not found?
 */
  if(!node)
    return 0;
/*
 * Return the details of the line.
 */
  if(line)
    *line = glh->buffer + node->start;
  if(group)
    *group = node->group;
  if(timestamp)
    *timestamp = node->timestamp;
  return 1;
}

/*.......................................................................
 * Lookup a node in the history list by its ID.
 *
 * Input:
 *  glh      GlHistory *  The input-line history maintenance object.
 *  id       GlhLineID    The ID of the line to be returned.
 * Output:
 *  return  GlLIneNode *  The located node, or NULL if not found.
 */
static GlLineNode *_glh_find_id(GlHistory *glh, GlhLineID id)
{
  GlLineNode *node;  /* The node being checked */
/*
 * Is history enabled?
 */
  if(!glh->enable || !glh->list.head)
    return NULL;
/*
 * If possible, start at the end point of the last ID search.
 * Otherwise start from the head of the list.
 */
  node = glh->id_node;
  if(!node)
    node = glh->list.head;
/*
 * Search forwards from 'node'?
 */
  if(node->id < id) {
    while(node && node->id != id)
      node = node->next;
    glh->id_node = node ? node : glh->list.tail;
/*
 * Search backwards from 'node'?
 */
  } else {
    while(node && node->id != id)
      node = node->prev;
    glh->id_node = node ? node : glh->list.head;
  };
/*
 * Return the located node (this will be NULL if the ID wasn't found).
 */
  return node;
}

/*.......................................................................
 * Query the state of the history list. Note that any of the input/output
 * pointers can be specified as NULL.
 *
 * Input:
 *  glh         GlHistory *  The input-line history maintenance object.
 * Input/Output:
 *  enabled           int *  If history is enabled, *enabled will be
 *                           set to 1. Otherwise it will be assigned 0.
 *  group        unsigned *  The current history group ID will be assigned
 *                           to *group.
 *  max_lines         int *  The currently requested limit on the number
 *                           of history lines in the list, or -1 if
 *                           unlimited.
 */
void _glh_state_of_history(GlHistory *glh, int *enabled, unsigned *group,
			   int *max_lines)
{
  if(glh) {
    if(enabled)
     *enabled = glh->enable;
    if(group)
     *group = glh->group;
    if(max_lines)
     *max_lines = glh->max_lines;
  };
}

/*.......................................................................
 * Get the range of lines in the history buffer.
 *
 * Input:
 *  glh         GlHistory *  The input-line history maintenance object.
 * Input/Output:
 *  oldest  unsigned long *  The sequential entry number of the oldest
 *                           line in the history list will be assigned
 *                           to *oldest, unless there are no lines, in
 *                           which case 0 will be assigned.
 *  newest  unsigned long *  The sequential entry number of the newest
 *                           line in the history list will be assigned
 *                           to *newest, unless there are no lines, in
 *                           which case 0 will be assigned.
 *  nlines            int *  The number of lines currently in the history
 *                           list.
 */
void _glh_range_of_history(GlHistory *glh, unsigned long *oldest,
			   unsigned long *newest, int *nlines)
{
  if(glh) {
    if(oldest)
      *oldest = glh->list.head ? glh->list.head->id : 0;
    if(newest)
      *newest = glh->list.tail ? glh->list.tail->id : 0;
    if(nlines)
      *nlines = glh->nline;
  };
}

/*.......................................................................
 * Return the size of the history buffer and the amount of the
 * buffer that is currently in use.
 *
 * Input:
 *  glh      GlHistory *  The input-line history maintenance object.
 * Input/Output:
 *  buff_size   size_t *  The size of the history buffer (bytes).
 *  buff_used   size_t *  The amount of the history buffer that
 *                        is currently occupied (bytes).
 */
void _glh_size_of_history(GlHistory *glh, size_t *buff_size, size_t *buff_used)
{
  if(glh) {
    if(buff_size)
      *buff_size = glh->buflen;
/*
 * Determine the amount of buffer space that is currently occupied.
 */
    if(buff_used) {
      size_t used = 0;
      GlLineNode *node;
      for(node=glh->list.head; node; node=node->next)
	used += node->nchar;
      *buff_used = used;
    };
  };
}