File: key.c

package info (click to toggle)
bibtool 2.43-1.2
  • links: PTS
  • area: main
  • in suites: hamm
  • size: 2,964 kB
  • ctags: 1,922
  • sloc: ansic: 18,261; makefile: 654; perl: 261; sh: 214; tcl: 51; awk: 15; sed: 8
file content (2273 lines) | stat: -rw-r--r-- 97,112 bytes parent folder | download | duplicates (2)
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
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
/******************************************************************************
** $Id: key.c,v 2.33 1997/12/06 22:56:00 gerd Exp gerd $
**=============================================================================
** 
** This file is part of BibTool.
** It is distributed under the GNU General Public License.
** See the file COPYING for details.
** 
** (c) 1996-1997 Gerd Neugebauer
** 
** Net: gerd@informatik.uni-koblenz.de
** 
******************************************************************************/

#include <bibtool/general.h>
#include <bibtool/symbols.h>
#include <bibtool/type.h>
#include <bibtool/entry.h>
#include <bibtool/error.h>
#include <bibtool/key.h>
#include <bibtool/rsc.h>
#include <bibtool/names.h>
#include <bibtool/tex_read.h>
#include <bibtool/wordlist.h>
#include <bibtool/expand.h>
#ifdef HAVE_TIME_H
#include <time.h>
#endif
#include "config.h"

/*****************************************************************************/
/* Internal Programs							     */
/*===========================================================================*/

#ifdef __STDC__
#define _ARG(A) A
#else
#define _ARG(A) ()
#endif
 char *get_field _ARG((DB db,Record rec,char *name));/* key.c                */
 char* fmt_expand _ARG((StringBuffer *sb,char *cp,DB db,Record rec));/* key.c*/
 int apply_fmt _ARG((StringBuffer *sb,char *fmt,Record rec,DB db));/* key.c  */
 int foreach_ignored_word _ARG((int (*fct)_ARG((char*))));/* key.c           */
 int mark_key _ARG((DB db,Record rec));		   /* key.c                  */
 int set_field _ARG((DB db,Record rec,char *name,char *value));/* key.c      */
 static KeyNode new_key_node _ARG((int type,char *string));/* key.c          */
 static char * itostr _ARG((int i,char *digits));  /* key.c                  */
 static int add_fmt_tree _ARG((char *s,KeyNode *treep));/* key.c             */
 static int deTeX _ARG((char *line,void (*save_fct)_ARG((char*)),int commap));/* key.c*/
 static int eval__fmt _ARG((StringBuffer *sb,KeyNode kn,Record rec));/* key.c*/
 static int eval_fmt _ARG((StringBuffer *sb,KeyNode kn,Record rec,DB db));/* key.c*/
 static int fmt__parse _ARG((char **sp,KeyNode *knp));/* key.c               */
 static int fmt_c_names _ARG((char *line,int min,int max,int not));/* key.c  */
 static int fmt_c_string _ARG((char * s,int min,int max,int not));/* key.c   */
 static int fmt_c_words _ARG((char *line,int min,int max,int not,int ignore));/* key.c*/
 static int fmt_digits _ARG((StringBuffer *sb,char *s,int mp,int pp,int n,int sel,int trunc));/* key.c*/
 static int fmt_parse _ARG((char **sp,KeyNode *knp));/* key.c                */
 static void Push_Word _ARG((char *s));		   /* key.c                  */
 static void eval__special _ARG((StringBuffer *sb,KeyNode kn,Record rec));/* key.c*/
 static void fmt_names _ARG((StringBuffer *sb,char *line,int maxname,int post,char *trans));/* key.c*/
 static void fmt_string _ARG((StringBuffer *sb,char * s,int n,char *trans,char *sep));/* key.c*/
 static void fmt_title _ARG((StringBuffer *sb,char *line,int len,int in,char *trans,int ignore,char *sep));/* key.c*/
 static void init_key _ARG((int state));	   /* key.c                  */
 static void key_init _ARG((void));		   /* key.c                  */
 static void push_s _ARG((StringBuffer *sb,unsigned char *s,int max,unsigned char *trans));/* key.c*/
 static void push_word _ARG((char * s));	   /* key.c                  */
 void add_format _ARG((char *s));		   /* key.c                  */
 void add_ignored_word _ARG((char *s));		   /* key.c                  */
 void add_sort_format _ARG((char *s));		   /* key.c                  */
 void clear_ignored_words _ARG((void));		   /* key.c                  */
 void def_format_type _ARG((char *s));		   /* key.c                  */
 void free_key_node _ARG((KeyNode kn));		   /* key.c                  */
 void make_key _ARG((DB db,Record rec));	   /* key.c                  */
 void make_sort_key _ARG((DB db,Record rec));	   /* key.c                  */
 void set_base _ARG((char *value));		   /* key.c                  */
 void set_separator _ARG((int n,char *s));	   /* key.c                  */

#ifdef DEBUG
 static void show_fmt _ARG((KeyNode kn,int in));   /* key.c                  */
#endif

/*****************************************************************************/
/* External Programs							     */
/*===========================================================================*/

 static DB tmp_key_db;

/*---------------------------------------------------------------------------*/

#define KEYSTYLE_EMPTY		0x0010
#define KEYSTYLE_SHORT		0x0020
#define KEYSTYLE_LONG		0x0030
#define KEYSTYLE_EXTENDED	0x0040

 static char	*percent_chars = "NntTdDsSwWp";	   /*                        */

#define DetexNone  0
#define DetexLower 1
#define DetexUpper 2

 static StringBuffer *key_sb = (StringBuffer*)NULL;
 static StringBuffer *tmp_sb = (StringBuffer*)NULL;

/*---------------------------------------------------------------------------*/

 static KeyNode key_tree      = (KeyNode)0;
 static KeyNode sort_key_tree = (KeyNode)0;


 static NameNode format[NUMBER_OF_FORMATS];	   /*                        */

/*-----------------------------------------------------------------------------
** Variable*:	formatp
** Type:	int
** Purpose:	Indicator variable which determines the state of
**		|format|. It is set to |FALSE| as soon as |format| is
**		initialized. 
**___________________________________________________			     */
 static int formatp = TRUE;			   /*                        */

#define SkipSpaces(CP)	  while ( is_space(*CP) ) ++(CP)
#define SkipAllowed(CP)	  while ( is_allowed(*CP) ) ++(CP)
#define ParseNumber(CP,N) if (is_digit(*CP)) { N = 0;			\
   while(is_digit(*CP) ){ N = N*10 + (*CP)-'0'; ++CP; }}
#define Expect(CP,C,RET)  SkipSpaces(CP);				\
			  if ( *CP == C ) { ++(CP); }			\
			  else { ErrPrintF("*** BibTool: Missing %c",C);\
				   return RET; }
#define MakeNode(KNP,TYPE,SP,CP) c = *CP; *CP = '\0';			\
			  *KNP = new_key_node(TYPE,symbol(*SP));	\
			  *CP  = c;
#define ParseOrReturn(CP,NODEP)						\
	if ( (ret=fmt_parse(CP,NODEP)) != 0  ) return ret


/*****************************************************************************/
/***				Private word stack			   ***/
/*****************************************************************************/

 static char   **words	  = (char**)0;
 static size_t words_len  = 0;
 static size_t words_used = 0;
#define WordLenInc 16

#define PushWord(S)	if(words_len>words_used) words[words_used++]=S;	\
			else			 Push_Word(S)
#define ResetWords	words_used = 0

/*-----------------------------------------------------------------------------
** Function:	push_word()
** Purpose:	Push a word to the stack. Wrapper function.
** Arguments:
**	s	word to push
** Returns:	nothing
**___________________________________________________			     */
static void push_word(s)			   /*			     */
  register char * s;				   /*			     */
{ PushWord(s);					   /*			     */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	Push_Word()
** Purpose:	Push a word to the stack when no space is left in the
**		allocated array. 
** Arguments:
**	sword to push
** Returns:	nothing
**___________________________________________________			     */
static void Push_Word(s)			   /*			     */
  register char *s;				   /*			     */
{ register char **wp;				   /*			     */
						   /*			     */
  words_len += WordLenInc;			   /*			     */
  if ( words_len == WordLenInc )		   /*			     */
  { wp = (char**)malloc(words_len*sizeof(char*)); }/*			     */
  else						   /*			     */
  { wp = (char**)realloc(words,words_len*sizeof(char*)); }/*		     */
  if ( wp == (char**)0 )			   /*			     */
  { words_len -= WordLenInc;			   /*			     */
    ERROR("Push_Word() failed: Word not pushed."); /*		             */
    return;					   /*			     */
  }						   /*			     */
						   /*			     */
  words = wp;					   /*			     */
  PushWord(s);					   /*			     */
}						   /*------------------------*/


/*****************************************************************************/
/***			Key Separator Section				   ***/
/*****************************************************************************/

#define NoSeps 8

 static char *key_seps[NoSeps] =
 { /* 0 */ "**key*",
   /* 1 */ "-",
   /* 2 */ ".",
   /* 3 */ ".",
   /* 4 */ ":",
   /* 5 */ "-",
   /* 6 */ "*",
   /* 7 */ ".ea"
 };

#define DefaultKey    key_seps[0]
#define InterNameSep  key_seps[1]
#define NamePreSep    key_seps[2]
#define NameNameSep   key_seps[3]
#define NameTitleSep  key_seps[4]
#define TitleTitleSep key_seps[5]
#define KeyNumberSep  key_seps[6]
#define EtAl	      key_seps[7]

/*-----------------------------------------------------------------------------
** Function:	set_separator()
** Purpose:	Modify the key_seps array. This array contains the
**		different separators used during key formatting. The
**		elements of the array have the following meaning:
**		\begin{description}
**		\item[0] The default key which is used when the
**		formatting instruction fails completely.
**		\item[1] The separator which is inserted between
**		different names of a multi-authored publication.
**		\item[2] The separator inserted between the first name
**		and the last name when a name is formatted.
**		\item[3] The separator inserted between the last names
**		when more then one last name is present
**		\item[4] The separator between the name and the title
**		of a publication.
**		\item[5] The separator inserted between words of the
**		title.
**		\item[6] The separator inserted before the number
**		which might be added to disambiguate reference keys.
**		\item[7] The string which is added when a list of
**		names is truncated. (|.ea|)
**		\end{description}
** Arguments:
**	n	Array index to modify.
**	s	New value for the given separator. The new value is
**		stored as a symbol. Thus the memory of |s| need not to
**		be preserved after this function is completed.
**		The characters which are not allowed are silently sypressed.
** Returns:	nothing
**___________________________________________________			     */
void set_separator(n,s)				   /*			     */
  register int	n;				   /*			     */
  register char *s;				   /*			     */
{ register char *t, *tp;			   /*			     */
  						   /*                        */
  if ( n < 0 || n >= NoSeps )			   /*			     */
  { ERROR("Invalid separator specification.");     /*			     */
    return;					   /*			     */
  }						   /*			     */
 						   /*                        */
  t  = new_string(s);				   /*			     */
  for ( tp=t; *s ; s++ )		   	   /*			     */
  { if ( is_allowed(*s) ) *tp++ = *s; }	   	   /*			     */
  *tp = '\0';					   /*			     */
 						   /*                        */
  key_seps[n] = symbol(t);			   /*			     */
  free(t);					   /*                        */

  switch (n)
  { case 1: init_key(1); break;
    case 2: init_key(2); break;
  }
}						   /*------------------------*/


/*****************************************************************************/
/***			   Key Base Section				   ***/
/*****************************************************************************/

 static char * key__base[] = 
 { "0123456789",
   "abcdefghijklmnopqrstuvwxyz",
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 };
#define KEY_BASE_DIGIT 0
#define KEY_BASE_LOWER 1
#define KEY_BASE_UPPER 2
 static int key_base = KEY_BASE_DIGIT;

/*-----------------------------------------------------------------------------
** Function:	set_base()
** Purpose:	Define the key base. This value determines the format
**		of the disambiguation string added to a key if
**		required. The following values are considered:
**		\begin{itemize}
**		\item If the value is |upper| or starts with an upper
**		  case letter then the disambiguation is done with
**		  uppercase letters. 
**		\item If the value is |lower| or starts with a lower
**		  case letter then the disambiguation is done with
**		  lowercase letters. 
**		\item If the value is |digit| or starts with an digit
**		  then the disambiguation is done with arabic numbers. 
**		\end{itemize}
**		The comparison of the keywords is done case
**		insensitive. The special values take precedence before
**		the first character rules.
**		
**		If an invalid value is given to this function then an
**		error is raised and the program is terminated.
** Arguments:
**	value	String representation of the new value.
** Returns:	nothing
**___________________________________________________			     */
void set_base(value)				   /*			     */
  register char *value;				   /*			     */
{						   /*			     */
  if	  ( case_cmp(value,"upper") ) key_base = KEY_BASE_UPPER;/*	     */
  else if ( case_cmp(value,"lower") ) key_base = KEY_BASE_LOWER;/*	     */
  else if ( case_cmp(value,"digit") ) key_base = KEY_BASE_DIGIT;/*	     */
  else if ( is_upper(*value) )	      key_base = KEY_BASE_UPPER;/*	     */
  else if ( is_lower(*value) )	      key_base = KEY_BASE_LOWER;/*	     */
  else if ( is_digit(*value) )	      key_base = KEY_BASE_DIGIT;/*	     */
  else { ERROR("Unknown base ignored."); }	   /*			     */
}						   /*------------------------*/

#define ITOA_LEN 32
/*-----------------------------------------------------------------------------
** Function:	itostr()
** Purpose:	Translate number using the ``digits'' given.
**		A static string is returned containing the result.
**		This is a routine generalizing |itoa()|.
** Examples:
**	itostr(X,"0123456789ABCDEF")	 returns the hexadecimal representation
**	itostr(X,"0123456789")		 returns the decimal representation
**	itostr(X,"01234567")		 returns the octal representation
**	itostr(X,"01")			 returns the binary representation
**
** Arguments:
**	i	Integer to translate
**	digits	String of digits to use
** Returns:	
**___________________________________________________			     */
static char * itostr(i,digits)			   /*			     */
  register int	 i;				   /*			     */
  register char	 *digits;			   /*			     */
{ static char	 buffer[ITOA_LEN];		   /* buffer to store result */
  register char	 *bp;				   /* buffer pointer	     */
  register int	 sign,				   /*			     */
		 base;				   /*			     */
						   /*			     */
  base	  = strlen(digits);			   /* how many digits?	     */
  bp	  = buffer+ITOA_LEN-1;			   /* set pointer to the end.*/
  *(bp--) = '\0';				   /* mark the end.	     */
  if ( i<0 ) { sign = -1; i = -i; }		   /*			     */
  else { sign = 0; if ( i == 0 ) *(bp--) = '0'; }  /*			     */
  while ( i > 0 )				   /*			     */
  { *(bp--) = digits[i%base];			   /*			     */
    i	    = i/base;				   /*			     */
  }						   /*			     */
  if ( sign ) *bp = '-'; else ++bp;		   /*			     */
  return(bp);					   /*			     */
}						   /*------------------------*/


/*****************************************************************************/
/***			       Key Init Section				   ***/
/*****************************************************************************/

/*-----------------------------------------------------------------------------
** Function:	init_key()
** Purpose:	Global initializations for the key module.
**		This function has to be called before some of the
**		functions provided in this module are guaranteed to
**		work properly.
** Arguments:	
**	state	
** Returns:	nothing
**___________________________________________________			     */
static void init_key(state)			   /*                        */
  int  state;					   /*                        */
{ int  i;					   /*			     */
  char *s;					   /*                        */
  						   /*                        */
  if ( formatp )				   /*                        */
  {						   /*                        */
    for (i=0;i<NUMBER_OF_FORMATS;i++)		   /*                        */
    { format[i] = NameNULL; }			   /*                        */
    formatp = FALSE;				   /*                        */
  }						   /*                        */
 						   /*                        */
  if ( state & 1 )				   /*                        */
  { 						   /*                        */
    if ( format[0] == NameNULL )		   /*                        */
    { s = new_string("%*l");			   /*                        */
      format[0] = name_format(s);		   /*                        */
      free(s);				   	   /*                        */
    }						   /*                        */
    NameMid(format[0]) = InterNameSep;	   	   /*                        */
  }						   /*                        */
 						   /*                        */
  if ( state & 2 )				   /*                        */
  { 						   /*                        */
    if ( format[1] == NameNULL )		   /*                        */
    { s = new_string("%*l%*1f");		   /*                        */
      format[1] = name_format(s);		   /*                        */
      free(s);				   	   /*                        */
    }						   /*                        */
    NameMid(format[1]) = InterNameSep;	   	   /*                        */
    if (NextName(format[1]))			   /*                        */
    { NamePre(NextName(format[1])) = NamePreSep;   /*                        */
    }						   /*                        */
  }						   /*                        */
}						   /*------------------------*/


/*-----------------------------------------------------------------------------
** Function:	key_init()
** Purpose:	Perform initializations for key generation.
**		The string buffer is opened.
**		Ignored words are initialized if necessary.
** Arguments:   none
** Returns:	nothing
**___________________________________________________			     */
static void key_init()				   /*			     */
{						   /*                        */
#ifdef INITIALIZE_IGNORED_WORDS
  static char *word_list[] =			   /* default ignored words. */
  { INITIALIZE_IGNORED_WORDS, NULL };		   /* Mark the end with NULL */
  register char**wp;				   /*			     */
#endif
						   /*			     */
  if ( key_sb == (StringBuffer*)0 )		   /* Is it the first time?  */
  {						   /*                        */
    if ( (key_sb=sbopen()) == (StringBuffer*)0 )   /* open string buffer     */
    { OUT_OF_MEMORY("key generation."); }	   /*			     */
#ifdef INITIALIZE_IGNORED_WORDS
    for ( wp=word_list; *wp!=NULL; ++wp )	   /* add ignored words.     */
    { add_ignored_word(*wp); }			   /*			     */
#endif
  }						   /*			     */
}						   /*------------------------*/



/*****************************************************************************/
/***			      Key DeTeX Section				   ***/
/*****************************************************************************/

#define DeTeX_BUFF_LEN 256


/*-----------------------------------------------------------------------------
** Function:	deTeX()
** Purpose:	Expand TeX seqeuences or eliminate them.
**
** Arguments:
**	line
**	save_fct
**	commap
** Returns:	
**___________________________________________________			     */
static int deTeX(line,save_fct,commap)		   /*			     */
  char		*line;				   /*			     */
  int		commap;				   /*			     */
  void		(*save_fct)_ARG((char*));	   /*			     */
{ static char	*buffer;			   /*			     */
  static size_t len   = 0;			   /*			     */
  char		c, *s, *bp;			   /*			     */
  char		last  = ' ';			   /*			     */
  int		wp    = 0;			   /*			     */
  int		brace;				   /*			     */
						   /*			     */
#define SaveWord     wp++; (*save_fct)(bp)
#define SaveChar(C)  *(bp++) = last = C
#define StoreChar(C) *(bp++) = C
						   /*			     */
  brace = 2*strlen(line);			   /*			     */
  if ( brace > len )				   /*			     */
  { if ( len == 0 )				   /*			     */
    { len    = ( brace < DeTeX_BUFF_LEN		   /*			     */
		? DeTeX_BUFF_LEN : brace );	   /*			     */
      buffer = malloc(len);			   /*			     */
    }						   /*			     */
    else					   /*			     */
    { len    = brace;				   /*			     */
      buffer = realloc(buffer,len);		   /*			     */
    }						   /*			     */
    if ( buffer == NULL ) 			   /*                        */
    { OUT_OF_MEMORY("deTeX()"); }   		   /*			     */
  }						   /*			     */
						   /*			     */
  TeX_open_string(line);			   /*			     */
  bp	= buffer;				   /*			     */
  brace = 0;					   /*			     */
  wp    = 0;					   /*                        */
  SaveWord;					   /*			     */
						   /*			     */
  while ( TeX_read(&c,&s) )			   /*			     */
  {						   /*			     */
    if (   is_alpha(c)				   /* Letters and	     */
	|| is_digit(c)				   /* digits and	     */
	|| is_extended(c)			   /* extended chars and     */
	|| ( c == '-' && last != c ) )		   /* nonrepeated hyphens    */
    { SaveChar(c); }				   /*			     */
    else if ( is_wordsep(c) && !is_wordsep(last) ) /* Don't repeat spaces.   */
    { if ( brace == 0 )				   /* Remember the beginning */
      { StoreChar('\0'); SaveWord; last = ' '; }   /*  of the next word.     */
      else					   /*                        */
      { char *t;				   /*                        */
	for (t=InterNameSep; *t; ++t )		   /*                        */
	{ SaveChar(*t);	}			   /*                        */
      }		   				   /*			     */
    }						   /*			     */
    else if ( c == '{'	) { ++brace; }		   /* Count braces.	     */
    else if ( c == '}'	)			   /*                        */
    { if ( --brace<0 ) brace = 0;		   /*                        */
    }						   /*			     */
    else if ( c == ',' && commap )		   /* Commas are counted as  */
    { if ( bp != buffer && *(bp-1) != '\0' )	   /*                        */
      { StoreChar('\0');			   /*  single words upon     */
	SaveWord;				   /*  request, or ignored.  */
      }						   /*                        */
      StoreChar(',');				   /*			     */
      StoreChar('\0');				   /*			     */
      SaveWord;					   /*			     */
      last = ' ';				   /*			     */
    }						   /*			     */
  }						   /*			     */
 						   /*                        */
  if ( bp != buffer && *(bp-1) != '\0' )	   /*                        */
  { StoreChar('\0');				   /*                        */
    SaveWord;					   /*                        */
  }						   /*                        */
      						   /*                        */
  StoreChar('\0');				   /* Mark the end.	     */
						   /*			     */
  if ( bp-buffer >= len )			   /*			     */
  { ERROR_EXIT("deTeX buffer overflow."); }	   /*			     */
						   /*			     */
  TeX_close();					   /*			     */
  return wp-1;					   /*			     */
}						   /*------------------------*/


/*****************************************************************************/
/***		       Title Formatting Section				   ***/
/*****************************************************************************/

#define PushS(SB,S)	push_s(SB,S,0,trans)
#define PushStr(SB,S,M)	push_s(SB,S,M,trans)
#define PushC(SB,C)	(void)sbputchar(trans[C],SB);

/*-----------------------------------------------------------------------------
** Function:	push_s()
** Purpose:	Write a translated string to the key string buffer.
** Arguments:
**	s	String to translate
**	max	Maximum number of characters
**	trans	Translation table
** Returns:	nothing
**___________________________________________________			     */
static void push_s(sb,s,max,trans)		   /*			     */
  StringBuffer *sb;
  register unsigned char *s;			   /*			     */
  register int max;				   /*                        */
  register unsigned char *trans;		   /*			     */
{						   /*                        */
  if ( max <= 0 ) 				   /*                        */
  { while ( *s )				   /*			     */
    { (void)sbputchar(trans[*(s++)],sb); }	   /*                        */
  }						   /*			     */
  else						   /*                        */
  { while ( *s && max-->0 )			   /*			     */
    { (void)sbputchar(trans[*(s++)],sb); }	   /*                        */
  }						   /*                        */
}						   /*------------------------*/

 static WordList ignored_words[32] = 
 { WordNULL, WordNULL, WordNULL, WordNULL,
   WordNULL, WordNULL, WordNULL, WordNULL,
   WordNULL, WordNULL, WordNULL, WordNULL,
   WordNULL, WordNULL, WordNULL, WordNULL,
   WordNULL, WordNULL, WordNULL, WordNULL,
   WordNULL, WordNULL, WordNULL, WordNULL,
   WordNULL, WordNULL, WordNULL, WordNULL,
   WordNULL, WordNULL, WordNULL, WordNULL
 };

/*-----------------------------------------------------------------------------
** Function:	add_ignored_word()
** Purpose:	Add a new word to the list of ignored words for title
**		key generation.
**		The argument has to be saved by the caller! This means
**		that it is assumed that the argument is a symbol.
** Arguments:
**	s	Word to add.
** Returns:	nothing
**___________________________________________________			     */
void add_ignored_word(s)			   /*			     */
  register char *s;				   /*			     */
{ key_init();					   /*                        */
  add_word(s,&ignored_words[(*s)&31]);		   /*			     */
  DebugPrint2("Adding ignored word ",s);	   /*                        */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	clear_ignored_words()
** Purpose:	Delete the list of ignored words. Afterwards no words are
**		recognized as ignored words.
** Arguments:	none
** Returns:	nothing
**___________________________________________________			     */
void clear_ignored_words()			   /*                        */
{ int i;					   /*                        */
  key_init();					   /*                        */
 						   /*                        */
  for (i=0;i<32;i++)				   /*                        */
  { free_words(&ignored_words[i],NULL); }	   /*                        */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	foreach_ignored_word()
** Purpose:	Iterator a given function |fct| is applied to each
**		ignored word in turn. If the function returns 0 then
**		the loop is terminated. The different words are
**		visited in a fixed order which does not necessarily
**		coincide with the natural order of words. Thus don't
**		assume this.
** Arguments:
**	fct	Function to apply.
** Returns:	The return status of the last |fct| call.
**___________________________________________________			     */
int foreach_ignored_word(fct)			   /*                        */
  int (*fct)_ARG((char*));			   /*                        */
{ int i;					   /*                        */
 						   /*                        */
  key_init();					   /*                        */
 						   /*                        */
  for (i=0;i<32;i++)				   /*                        */
  { if ( !foreach_word(ignored_words[i],fct))	   /*                        */
    { return 0; }				   /*                        */
  }						   /*                        */
  return 1;					   /*                        */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	fmt_title()
** Purpose:	Format a string according to rules for titles.
**		\TeX{} sequences are expanded and some words may be ignored.
**		The result is pushed to the local string buffer.
** Arguments:
**	line	String to format.
**	len	Number of words to use
**	in	Number of characters per word to use
**	trans	Translation table
**	ignore	Boolean. Certain words are ignored if it is TRUE
**	sep	String separating the words.
** Returns:	nothing
**___________________________________________________			     */
static void fmt_title(sb,line,len,in,trans,ignore,sep)/*		     */
  StringBuffer *sb;				   /*                        */
  char	 *line;					   /*			     */
  int	 len;					   /*			     */
  int	 in;					   /*			     */
  char	 *trans;				   /* Translation table	     */
  int    ignore;				   /*                        */
  char   *sep;					   /*                        */
{ int	 nw, i, j;				   /*			     */
  char	 *s;					   /*			     */
  int	 first = TRUE;				   /*			     */
						   /*			     */
  if ( len == 0 ) return;			   /*                        */
 						   /*                        */
  if (	 tmp_sb == (StringBuffer*)0		   /*			     */
      && (tmp_sb=sbopen()) == (StringBuffer*)0 )   /*			     */
  { OUT_OF_MEMORY("fmt_title()"); } 		   /*			     */
						   /*			     */
  ResetWords;					   /*                        */
  nw = deTeX(*line=='{'?line+1:line,push_word,FALSE);/*			     */
 						   /*                        */
  for ( i=0; i < nw; ++i )		   	   /*			     */
  {						   /*			     */
    sbrewind(tmp_sb);				   /* Reset the string buffer*/
    for ( s=words[i]; *s; ++s )		   	   /* Translate the current  */
    { (void)sbputchar(trans[*s],tmp_sb); }	   /*  word into the sbuffer */
    s = sbflush(tmp_sb);			   /* Get the translated word*/
						   /*			     */
    if ( ! ignore || 				   /*                        */
	 ! find_word(s,ignored_words[(*s)&31] ) )  /*			     */
    { if ( first ) { first = FALSE; }		   /*			     */
      else { PushS(sb,sep); }		   	   /*			     */
      if ( in <= 0 )				   /*                        */
      { PushS(sb,words[i]); }		   	   /* Push the current word  */
      else					   /*                        */
      { for ( s=words[i], j=in; *s && j-->0; ++s ) /* Push the initial part  */
	{ PushC(sb,*s); }			   /*  of the current word.  */
      }						   /*                        */
      if ( len == 1 ) return;	   		   /*                        */
      if ( len > 0  ) len--;			   /*                        */
    }						   /*			     */
  }						   /*			     */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	fmt_c_words()
** Purpose:	Count a list of words.
**		
**
** Arguments:
**	line	string to analyze
**	min	minimum
**	max	maximum or 0
**	not	negation flag
**	ignore	flag to indicate if certain words should be ignored.
** Returns:	
**___________________________________________________			     */
static int fmt_c_words(line,min,max,not,ignore)	   /*			     */
  char	 *line;					   /*			     */
  int	 min;					   /*			     */
  int	 max;					   /*			     */
  int	 not;					   /*			     */
  int	 ignore;				   /*			     */
{ int	 n, i, nw;				   /*			     */
						   /*			     */
  ResetWords;					   /*                        */
  nw = deTeX(*line=='{'?line+1:line,push_word,FALSE);/*			     */
  n = 0;					   /*                        */
 						   /*                        */
  for ( i=0; i < nw; ++i )		   	   /*			     */
  {						   /*			     */
    if ( !ignore || 				   /*                        */
	 !find_word(words[i],ignored_words[(*words[i])&31]) )/*		     */
    { n++; }					   /*			     */
  }						   /*			     */
 						   /*                        */
  if ( n < min || (max>0 && n> max))		   /*                        */
  { return (not?FALSE:TRUE); }			   /*                        */
 						   /*                        */
  return (not?TRUE:FALSE);			   /*                        */
}						   /*------------------------*/


/*****************************************************************************/
/***		         Name Formatting Section			   ***/
/*****************************************************************************/


/*-----------------------------------------------------------------------------
** Function:	def_format_type()
** Purpose:	
**		
**
** Arguments:
**	s
** Returns:	nothing
**___________________________________________________			     */
void def_format_type(s)				   /*                        */
  char *s;					   /*                        */
{ int  n;					   /*                        */
  char *cp;					   /*                        */
  char c;					   /*                        */
 						   /*                        */
  SkipSpaces(s);				   /*                        */
  n = 0;					   /*                        */
  while ( is_digit(*s) ) { n = n*10 + (*s++) - '0'; }/*                      */
  if ( n >= NUMBER_OF_FORMATS )			   /*                        */
  { WARNING("Format type number is out of range.");/*                        */
    return;					   /*                        */
  }						   /*                        */
  if ( rsc_verbose && n <= 1 )			   /*                        */
  { VerbosePrint3("Name format specifier ",	   /*                        */
		  (n==0?"0":"1"),		   /*                        */
		  " has been changed.\n");	   /*                        */
  }						   /*                        */
 						   /*                        */
  if ( formatp ) { init_key(3); }
 						   /*                        */
  SkipSpaces(s);				   /*                        */
  if ( *s == '=' ) s++;				   /*                        */
  Expect(s,'"',);				   /*                        */
  cp = s;					   /*                        */
  while ( *cp && *cp != '"' ) cp++;		   /*                        */
  c   = *cp;					   /*                        */
  *cp = '\0';					   /*                        */
  format[n] = name_format(s);			   /*                        */
  *cp = c;					   /*                        */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	fmt_names()
** Purpose:	Format a list of names separated by 'and'.
**		'and others' is handled properly.
** Arguments:
**	line	String to format.
**	maxname	Number of names to consider
**	maxlen  Number of characters per name to consider
**	trans	Translation table
** Returns:	nothing
**___________________________________________________			     */
static void fmt_names(sb,line,maxname,post,trans)  /*		             */
  StringBuffer *sb;				   /*                        */
  char	      *line;				   /* Name list string	     */
  int	      maxname;				   /* number of names b4 etal*/
  int         post;				   /* number of relevant char*/
  char	      *trans;				   /* Translation table	     */
{ int	      wp,				   /*			     */
	      i;				   /*			     */
  static char *and   = "&";			   /*                        */
  static char *comma = ",";			   /*                        */
  static int  undef_warning = FALSE;		   /*                        */
  						   /*                        */
  if ( maxname == 0 ) return;			   /*                        */
 						   /*                        */
  if (   post < 0				   /*                        */
      || post >= NUMBER_OF_FORMATS		   /*                        */
      || format[post] == NameNULL )		   /*                        */
  { if (undef_warning)				   /*                        */
    { ErrPrintF("*** BibTool: Format %d is not defined. Ignored.\n",/*       */
		post);				   /*                        */
      undef_warning = TRUE;			   /*                        */
    }						   /*                        */
    return;					   /*                        */
  }						   /*                        */
 						   /*                        */
  ResetWords;					   /*                        */
  wp = deTeX(*line=='{'?line+1:line,push_word,TRUE);/*			     */
  words[wp] = NULL;				   /*                        */
 						   /*                        */
  for ( i=0; i<wp; i++)			   	   /*			     */
  { if ( strcmp(words[i],"and") == 0 )		   /*                        */
    { words[i] = and; }				   /*                        */
    else if ( strcmp(words[i],",") == 0 )	   /*                        */
    { words[i] = comma; }			   /*                        */
  }						   /*                        */
 						   /*                        */
  PushS(sb,pp_list_of_names(words,		   /*                        */
			    format[post],	   /*                        */
			    trans,		   /*                        */
			    maxname,		   /*                        */
			    comma,		   /*                        */
			    and,		   /*                        */
			    NameNameSep,EtAl));	   /*                        */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	fmt_c_names()
** Purpose:	Count a list of names
**		
**
** Arguments:
**	line	string to analyze
**	min	minimum
**	max	maximum or 0
**	not	negation flag
** Returns:	nothing
**___________________________________________________			     */
static int fmt_c_names(line,min,max,not)	   /*		             */
  char	      *line;				   /* Name list string	     */
  int         min;				   /* number of relevant char*/
  int	      max;				   /* number of names b4 etal*/
  int         not;				   /* negation flag          */
{ int	      wp,				   /*			     */
	      i,				   /*                        */
	      n;				   /*			     */
  						   /*                        */
  ResetWords;					   /*                        */
  wp = deTeX(*line=='{'?line+1:line,push_word,TRUE);/*			     */
  words[wp] = NULL;				   /*                        */
 						   /*                        */
  for ( i=0, n=1; i<wp; i++)			   /*			     */
  { if ( strcmp(words[i],"and") == 0 ) { n++; }	   /*                        */
  }						   /*                        */
 						   /*                        */
  if ( n < min || (max>0 && n> max))		   /*                        */
  { return (not?FALSE:TRUE); }			   /*                        */
 						   /*                        */
  return (not?TRUE:FALSE);			   /*                        */
}						   /*------------------------*/


/*****************************************************************************/
/***		         Number Formatting Section			   ***/
/*****************************************************************************/

/*-----------------------------------------------------------------------------
** Function:	fmt_digits()
** Purpose:	Search a sequence of digits and push at most n of them 
**		counting from right to the string buffer.
** Example:	fmt_digits("jun 1958",2) pushes "58" to the string buffer.
** Arguments:
**	sb	String buffer to store the result in
**	s	String to format
**	mp	Boolean indicating wether padding with 0s should be performed
**		(true) or not.
**	pp	Boolean indicating wether no number should be 0 or fail
**	n	Length
**	sel	The number to select.
**	trunc	Boolean indicating wether or not to truncate the number.
** Returns:	nothing
**___________________________________________________			     */
static int fmt_digits(sb,s,mp,pp,n,sel,trunc)	   /*			     */
  StringBuffer  *sb;				   /*                        */
  register char *s;				   /*			     */
  int           mp;				   /*                        */
  int           pp;				   /*                        */
  register int	n;				   /*			     */
  int		sel;				   /*                        */
  int           trunc;				   /*                        */
{ register char *cp;				   /*			     */
						   /*			     */
  if ( n < 0 ) { n = ( mp ? 1 : 0x7fff ); }	   /*                        */
 						   /*                        */
  cp = s;					   /*                        */
  while ( sel-->0 )				   /*                        */
  { s = cp;					   /*                        */
    while( *s && !is_digit(*s) ) { ++s; }   	   /* search first digit     */
    if ( *s == '\0' )				   /*                        */
    { cp = s; sel = 0; }			   /*                        */
    else					   /*                        */
    { for ( cp=s; *cp && is_digit(*cp); ++cp) {}   /* skip over digits	     */
    }						   /*                        */
  }						   /*                        */
 						   /*                        */
  if ( trunc && cp-s > n ) s = cp-n;		   /*			     */
  else if ( mp )				   /*                        */
  { while ( cp-s < n-- )			   /*                        */
    { (void)sbputchar('0',sb); }		   /*                        */
  }						   /*                        */
  if ( !mp && *s == '\0' )			   /*                        */
  { if ( pp ) (void)sbputchar('0',sb);	   	   /*                        */
    else return 1;				   /*                        */
  }						   /*                        */
  else						   /*                        */
  {						   /*                        */
    while ( s != cp )				   /*			     */
    { (void)sbputchar(*s,sb); ++s; }	   	   /*			     */
  }						   /*                        */
  return 0;					   /*                        */
}						   /*------------------------*/


/*****************************************************************************/
/***		         String Formatting Section			   ***/
/*****************************************************************************/

/*-----------------------------------------------------------------------------
** Function:	fmt_string()
** Purpose:	Push characters from s onto the string buffer.
**		At most n characters are transfered.
**		Letters are translated accoring to mode.
** Arguments:
**	s	String to format
**	n	Length
**	trans	Translation table
**	sep	Separator
** Returns:	nothing
**___________________________________________________			     */
static void fmt_string(sb,s,n,trans,sep)	   /*			     */
  StringBuffer *sb;				   /*                        */
  register char * s;				   /*			     */
  register int	n;				   /*			     */
  register char *trans;				   /*			     */
  char          *sep;				   /*                        */
{						   /*			     */
  while ( *s && n>0 )				   /*			     */
  { if ( is_allowed(*s) )			   /*			     */
    { (void)sbputchar(trans[*s],sb); n--; }	   /*			     */
    else if ( is_space(*s) )			   /*			     */
    { (void)sbputs(sep,sb); n--;	   	   /*                        */
      while ( is_space(*s) ) s++;		   /* skip over multiple SPC */
      s--;					   /*                        */
    }   					   /*			     */
    ++s;					   /*			     */
  }						   /*			     */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	fmt_c_string()
** Purpose:	Count the number of characters in a string and compare it
**		against an interval.
**
** Arguments:
**	s	string to analyze
**	min	minimum
**	max	maximum or 0
**	not	negation flag
** Returns:	
**___________________________________________________			     */
static int fmt_c_string(s,min,max,not)		   /*			     */
  register char * s;				   /*			     */
  register int  min;				   /*			     */
  register int  max;				   /*			     */
  register int  not;				   /*			     */
{ int           n = 0;				   /*			     */
 						   /*                        */
  while ( *s )				   	   /*			     */
  { if ( is_allowed(*s) ) { n++; }	   	   /*			     */
    else if ( is_space(*s) )			   /*			     */
    { n += strlen(TitleTitleSep);	   	   /*                        */
      while ( is_space(*s) ) s++;		   /* skip over multiple SPC */
    }   					   /*			     */
    ++s;					   /*			     */
  }						   /*			     */
 						   /*                        */
  if ( n < min || (max>0 && n> max))		   /*                        */
  { return (not?FALSE:TRUE); }			   /*                        */
 						   /*                        */
  return (not?TRUE:FALSE);			   /*                        */
}						   /*------------------------*/

#define IfGetField(S,NAME) if((S=get_field(tmp_key_db,rec,NAME))!=NULL)

#define GetEntryOrReturn(S,NAME)					\
	if((S=get_field(tmp_key_db,rec,NAME))==NULL) return(FALSE)


/*-----------------------------------------------------------------------------
** Function:	make_key()
** Purpose:	Generate a key for a given record.
** Arguments:
**	db	Database containing the record.	
**	rec	Record to consider.
** Returns:	nothing
**___________________________________________________			     */
void make_key(db,rec)				   /*			     */
  DB		  db;				   /*                        */
  register Record rec;				   /*			     */
{ register char	  *kp,				   /*			     */
		  **cpp;			   /*			     */
  int		  n,				   /*			     */
		  pos;				   /*			     */
						   /*			     */
  if ( IsSpecialRecord(RecordType(rec)) ) return;  /*			     */
						   /*			     */
  if ( key_tree == (KeyNode)0 )			   /*			     */
  { *RecordHeap(rec) = sym_empty;		   /* store an empty key     */
    return;					   /*			     */
  }						   /*			     */
 						   /*                        */
  if ( formatp ) { init_key(3); }
						   /*			     */
  if ( rsc_key_preserve && **RecordHeap(rec) != '\0' )/*		     */
  { return; }					   /*			     */
						   /*			     */
  key_init();					   /*			     */
  sbrewind(key_sb);				   /* clear key		     */
						   /*			     */
  if ( eval_fmt(key_sb,key_tree,rec,db) )	   /*                        */
  { sbputs(DefaultKey,key_sb);			   /*                        */
  }			   			   /*			     */
						   /*			     */
  pos		    = sbtell(key_sb);		   /*			     */
  kp		    = sbflush(key_sb);		   /* get collected key	     */
  cpp		    = RecordHeap(rec);		   /* get destination for key*/
  ReleaseSymbol(RecordOldKey(rec));
  RecordOldKey(rec) = *cpp;			   /* save old key	     */
  ReleaseSymbol(*cpp);
  *cpp		    = symbol(kp);		   /* store new key	     */
						   /*			     */
  if ( sym_flag(*cpp)&SYMBOL_KEY )		   /* is key already used?   */
  {						   /* Then disambiguate:     */
    (void)sbseek(key_sb,pos);			   /*			     */
    (void)sbputs(KeyNumberSep,key_sb);		   /* put separator at end   */
    n	= 1;					   /* start with no 1	     */
    pos = sbtell(key_sb);			   /*			     */
    do						   /* last symbol was present*/
    { (void)sbseek(key_sb,pos);			   /*			     */
      (void)sbputs(itostr(n++,key__base[key_base]),/*			     */
		   key_sb);			   /*			     */
      *cpp = symbol(sbflush(key_sb));		   /*	store new key	     */
    } while ( sym_flag(*cpp)&SYMBOL_KEY );	   /*			     */
  }						   /*			     */
  sym_set_flag(*cpp,SYMBOL_KEY);		   /* Mark the symbol as key */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	mark_key()
** Purpose:	Set the key mark for the key symbol of a record.
** Arguments:
**	db	Database containing the record.
**	rec	Record to consider
** Returns:	nothing
**___________________________________________________			     */
int mark_key(db,rec)				   /*			     */
  DB	 db;					   /*                        */
  Record rec;				   	   /*			     */
{						   /*			     */
  if ( IsSpecialRecord(RecordType(rec)) ) return 0;/*			     */
 						   /*                        */
  if ( *RecordHeap(rec) == NULL ) { return 0; }	   /*			     */
  sym_set_flag(*RecordHeap(rec),SYMBOL_KEY);	   /*		             */
  return 0;					   /*                        */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	make_sort_key()
** Purpose:	
**
** Arguments:
**	db	Database containing the record.
**	rec	Record to consider.
** Returns:	nothing
**___________________________________________________			     */
void make_sort_key(db,rec)			   /*			     */
  DB		  db;				   /*                        */
  register Record rec;				   /*			     */
{ register char	  *kp;				   /*			     */
						   /*			     */
  if ( IsSpecialRecord(RecordType(rec)) ) return;  /*			     */
						   /*			     */
  key_init();					   /*			     */
  sbrewind(key_sb);				   /* clear key		     */
						   /*			     */
  if (	 sort_key_tree != (KeyNode)0		   /*			     */
      && eval_fmt(key_sb,sort_key_tree,rec,db) == 0 )/*			     */
  { kp		   = sbflush(key_sb);		   /* get collected key	     */
    RecordSortkey(rec) = symbol(kp);		   /* store new key	     */
  }						   /*			     */
  else						   /* If everything fails    */
  { RecordSortkey(rec) = RecordHeap(rec)[0];	   /* use the reference key  */
  }						   /*			     */
}						   /*------------------------*/


/*****************************************************************************/
/***		      Key Format Parsing and Evaluating			   ***/
/*****************************************************************************/

/*-----------------------------------------------------------------------------
** Function:	new_key_node()
** Purpose:	Allocate a new key node
** Arguments:
**	type	
**	string	
** Returns:	The address of the new node.
**		Upon failure exit() is called.
**___________________________________________________			     */
static KeyNode new_key_node(type,string)	   /*			     */
  int	  type;					   /*			     */
  char	  *string;				   /*			     */
{ KeyNode new;					   /*			     */
  if( (new=(KeyNode)malloc(sizeof(SKeyNode))) == (KeyNode)0 )/*		     */
  { OUT_OF_MEMORY(" new_key_node()"); } 	   /*			     */
						   /*			     */
  NodeType(new)	  = type;			   /*			     */
  NodeSymbol(new) = string;			   /*			     */
  NodeNext(new)	  = (KeyNode)0;			   /*			     */
  NodeThen(new)	  = (KeyNode)0;			   /*			     */
  NodeElse(new)	  = (KeyNode)0;			   /*			     */
  NodePre(new)	  = -1;
  NodePost(new)	  = -1;
  return new;					   /*			     */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	free_key_node()
** Purpose:	A tree rooted at a given |KeyNode| will be freed.
**
** Arguments:
**	kn	KeyNode to be freed.
** Returns:	nothing
**___________________________________________________			     */
void free_key_node(kn)				   /*			     */
  KeyNode kn;					   /*			     */
{ KeyNode next;					   /*                        */
						   /*			     */
  while ( kn != (KeyNode)0 )			   /*                        */
  {						   /*                        */
    free_key_node(NodeThen(kn));
    free_key_node(NodeElse(kn));
    next = NodeNext(kn);
    free(kn);					   /*                        */
    kn = next;					   /*                        */
  }						   /*                        */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	add_fmt_tree()
** Purpose:	Extend the format tree
**
** Arguments:
**	s
**	treep
** Returns:	
**___________________________________________________			     */
static int add_fmt_tree(s,treep)		   /*			     */
  char	  *s;					   /*			     */
  KeyNode *treep;				   /*			     */
{ KeyNode kn, kn_or;				   /*			     */
  int	  special   = 0;			   /*			     */
  unsigned char *s0 = (unsigned char*)s;	   /*			     */
						   /*			     */
  if ( s == (char*)NULL ) return FALSE;		   /*			     */
						   /*			     */
  if ( strcmp(s,"empty") == 0 )			   /*			     */
  { free_key_node(*treep);			   /*			     */
    *treep = (KeyNode)0;			   /*                        */
    return TRUE;				   /*                        */
  }		   				   /*                        */
  else if ( strcmp(s,"short"	) == 0 )	   /*                        */
  { special = KEYSTYLE_SHORT;	  }		   /*                        */
  else if ( strcmp(s,"long"	) == 0 )	   /*                        */
  { special = KEYSTYLE_LONG;	  }		   /*                        */
  else if ( strcmp(s,"new.short")  == 0 ||	   /*                        */
	    strcmp(s,"short.need") == 0 )	   /*                        */
  { special = KEYSTYLE_SHORT;			   /*                        */
    rsc_key_preserve = TRUE;			   /*                        */
  }						   /*                        */
  else if ( strcmp(s,"new.long" ) == 0 ||	   /*                        */
	    strcmp(s,"long.need") == 0 )	   /*                        */
  { special = KEYSTYLE_LONG;			   /*                        */
    rsc_key_preserve = TRUE;			   /*                        */
  }						   /*                        */
						   /*			     */
  if ( special )				   /*			     */
  { free_key_node(*treep);			   /*			     */
    *treep = new_key_node(NodeSPECIAL,(char*)NULL);/*			     */
    NodePre(*treep) = special;			   /*			     */
    return TRUE;				   /*			     */
  }						   /*			     */
						   /*			     */
  if ( fmt_parse(&s,&kn) > 0 )			   /*			     */
  { error(ERR_POINT|ERR_WARN,			   /*			     */
	  "Format Error. Format ignored.",	   /*			     */
	  (char*)0,(char*)0,s0,(unsigned char*)s,0,sym_empty);/*	     */
    return FALSE;				   /*			     */
  }						   /*			     */
  if ( *treep == (KeyNode)0 ) { *treep	= kn; }	   /*			     */
  else if ( NodeType(*treep) == NodeSPECIAL )	   /*			     */
  { free_key_node(*treep);			   /*			     */
    *treep  = kn;				   /*			     */
  }						   /*			     */
  else						   /*			     */
  { kn_or = new_key_node(NodeOR,(char*)NULL);	   /*			     */
    NodeThen(kn_or) = *treep;			   /*			     */
    NodeElse(kn_or) = kn;			   /*			     */
    *treep	    = kn_or;			   /*			     */
  }						   /*			     */
						   /*			     */
#ifdef DEBUG
  show_fmt(*treep,0);			   	   /*			     */
#endif
  return TRUE;					   /*			     */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	add_format()
** Purpose:	Add a key format specification to the current
**		specification.  This specification is used for
**		generating new reference keys. Thus the resource
**		|rsc_make_key| is turned on aswell.
**
**		Several strings are treated special. If a special
**		format is encountered then the effect is that the old
**		key specification is cleared first before the new
**		format is added:
**		\begin{description}
**		\item[empty] The empty format is activated. This means that
**		  the format is cleared and without further action the
**		  default key will be used.
**		\item[long] The long format is activated. This means that
**		  authors names with initials and the first word of
**		  the title are used.
**		\item[short] The short format is activated. This means that
**		  authors last names and the first word of the title
**		  are used. 
**		\item[new.long] This means that the long format will
**		  be used but only if the record does not have a key
**		  already. 
**		\item[new.short] This means that the short format will
**		  be used but only if the record does not have a key
**		  already. 
**		\end{description}
** Arguments:
**	s	Specification string
** Returns:	nothing
**___________________________________________________			     */
void add_format(s)				   /*			     */
  register char *s;				   /*			     */
{						   /*			     */
  if ( s == NULL )				   /*			     */
  { WARNING("Missing key format.");		   /*			     */
    return;					   /*			     */
  }						   /*			     */
  rsc_make_key = TRUE;				   /*			     */
  (void)add_fmt_tree(s,&key_tree);		   /*			     */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	add_sort_format()
** Purpose:	Add a sort key format specification to the current
**		specification.  This specification is used for
**		generating new sort keys.
**
**		Several strings are treated special. If a special
**		format is encountered then the effect is that the old
**		key specification is cleared first before the new
**		format is added:
**		\begin{description}
**		\item[empty] The empty format is activated. This means that
**		  the format is cleared and without further action the
**		  default key will be used.
**		\item[long] The long format is activated. This means that
**		  authors names with initials and the first word of
**		  the title are used.
**		\item[short] The short format is activated. This means that
**		  authors last names and the first word of the title
**		  are used. 
**		\item[new.long] This means that the long format will
**		  be used but only if the record does not have a key
**		  already. 
**		\item[new.short] This means that the short format will
**		  be used but only if the record does not have a key
**		  already. 
**		\end{description}
** Arguments:
**	s	Specification string
** Returns:	nothing
**___________________________________________________			     */
void add_sort_format(s)				   /*			     */
  register char *s;				   /*			     */
{						   /*			     */
  if ( s == NULL )				   /*			     */
  { WARNING("Missing sort key format.");	   /*			     */
    return;					   /*			     */
  }						   /*			     */
  (void)add_fmt_tree(s,&sort_key_tree);		   /*			     */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	fmt_parse()
** Purpose:	Parse the format specification given in the string *sp.
**		Store the resulting KeyNode tree in *knp.
**		*sp is modified to point to the first character not used.
**		The return value is 0 iff no problem has been detected.
** Arguments:
**	sp
**	knp
** Returns:	Error code. 0 = success
**___________________________________________________			     */
static int fmt_parse(sp,knp)			   /*			     */
  char		**sp;				   /*			     */
  KeyNode	*knp;				   /*			     */
{ int		ret;				   /*			     */
  KeyNode	new;				   /*			     */
						   /*			     */
  while ( (ret=fmt__parse(sp,knp)) == 0 )	   /*			     */
  { SkipSpaces(*sp);				   /*			     */
    if ( **sp == '#' )				   /*			     */
    { new  = new_key_node(NodeOR,(char*)NULL);	   /*			     */
      NodeThen(new) = *knp;			   /*			     */
      *knp = new;				   /*			     */
      knp  = &NodeElse(new);			   /*			     */
      (*sp)++;					   /*			     */
    }						   /*			     */
    else return 0;				   /*			     */
  }						   /*			     */
  return ret;					   /* return the error code. */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	fmt__parse()
** Purpose:	
**
** Arguments:
**	sp
**	knp
** Returns:	Error code or 0 upon success
**___________________________________________________			     */
static int fmt__parse(sp,knp)			   /*			     */
  char		**sp;				   /*			     */
  KeyNode	*knp;				   /*			     */
{ register char *cp;				   /*			     */
  char		c;				   /*			     */
  int		ret;				   /*			     */
						   /*			     */
  cp = *sp;					   /*			     */
						   /*			     */
  while ( *cp != '\0' )				   /*			     */
  {						   /*			     */
    switch ( *cp )				   /*			     */
    { case ' ' : case '\t': case '\r':		   /* Skip over spaces.	     */
      case '\n': case '\f': case '\b':		   /*			     */
	cp++; break;				   /*			     */
      case '#':					   /* Two cases evaluated    */
      case '}': return 0;			   /*  somewhere else.	     */
      case '%':					   /* Format specification:  */
	{ int  pre  = -1,			   /*			     */
	       post = -1,			   /* %[-][0-9]*[.[0-9]*[a-Z]*/
	       type = 0;			   /*	([a-Z]*)	     */
	  switch ( *++cp )			   /*			     */
	  { case '+': type = NodePlusMask;  ++cp; break;/*		     */
	    case '-': type = NodeMinusMask; ++cp; break;/*		     */
	  }					   /*			     */
	  ParseNumber(cp,pre);			   /*			     */
	  if ( *cp == '.' || *cp == ',' || *cp == '-' )/*		     */
	  { cp++;				   /*                        */
	    ParseNumber(cp,post);		   /*                        */
	  }	   				   /*			     */
	  if ( *cp == '#' )			   /*                        */
	  { cp++;				   /*                        */
	    type |= NodeCountMask;		   /*                        */
	  }					   /*                        */
	  if ( !is_alpha(*cp) )			   /*			     */
	  { ErrPrintF("*** BibTool: Missing format type before: %s",cp);/*   */
	    *sp = cp; return(1);		   /*			     */
	  }					   /*			     */
	  if ( strchr(percent_chars,*cp) == (char*)0 )/*		     */
	  { ErrPrintF("*** BibTool: Illegal format character: %c",*cp);/*    */
	    *sp = cp; return 1;			   /*			     */
	  }					   /*			     */
	  type |= *(cp++);			   /*			     */
	  Expect(cp,'(',1);			   /*			     */
	  SkipSpaces(cp);			   /*			     */
	  *sp = cp;				   /*			     */
	  SkipAllowed(cp);			   /*			     */
	  MakeNode(knp,type,sp,cp)		   /*			     */
	  NodePre(*knp)	 = pre;			   /*			     */
	  NodePost(*knp) = post;		   /*			     */
	  SkipSpaces(cp);			   /*			     */
	  Expect(cp,')',1);			   /*			     */
	  *sp = cp;				   /*			     */
	  knp = & NodeNext(*knp);		   /*			     */
	}					   /*			     */
	break;					   /*			     */
 						   /*                        */
      case '(':					   /*			     */
	cp = (*sp)+1;				   /*			     */
	SkipSpaces(cp);				   /*			     */
	*sp = cp;				   /*			     */
	SkipAllowed(cp);			   /*			     */
	MakeNode(knp,NodeTEST,sp,cp);		   /*			     */
	Expect(cp,')',1);			   /*			     */
	Expect(cp,'{',1);			   /*			     */
	*sp = cp;				   /*			     */
	ParseOrReturn(sp,&NodeThen(*knp));	   /*			     */
	Expect(*sp,'}',1);			   /*			     */
	Expect(*sp,'{',1);			   /*			     */
	ParseOrReturn(sp,&NodeElse(*knp));	   /*			     */
	Expect(*sp,'}',1);			   /*			     */
	knp = & NodeNext(*knp);			   /*			     */
	cp = *sp;				   /*			     */
	break;					   /*			     */
						   /*			     */
      case '{':					   /*			     */
	cp++;				   	   /*			     */
	SkipSpaces(cp);				   /*			     */
	*sp = cp;				   /*                        */
	ParseOrReturn(sp,knp);			   /*			     */
	Expect(*sp,'}',1);			   /*			     */
	knp = & NodeNext(*knp);			   /*			     */
	cp  = *sp;				   /*			     */
	break;					   /*			     */
					   	   /*                        */
      default:					   /*			     */
	*sp = cp;				   /*			     */
	if ( is_allowed(*cp) )			   /*			     */
	{					   /*			     */
	  while ( is_allowed(*cp) ) { ++cp; }	   /*			     */
	  MakeNode(knp,NodeSTRING,sp,cp);	   /*			     */
	  *sp = cp;				   /*			     */
	  knp = & NodeNext(*knp);		   /*			     */
	}					   /*			     */
	else					   /*			     */
	{ ERROR2("Parse format. Illegal character ignored: ",cp);/*          */
	  ++cp;					   /*			     */
	}					   /*			     */
    }						   /*			     */
  }						   /*			     */
  return -1;					   /* Signal end-of-string.  */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	eval_fmt()
** Purpose:	Evaluate the given KeyNode tree w.r.t. the given Record.
**		
**		
** Arguments:
**	kn	
**	rec	
**	db	
** Returns:	0 upon success.
**___________________________________________________			     */
static int eval_fmt(sb,kn,rec,db)		   /*			     */
  StringBuffer *sb;				   /*                        */
  KeyNode	kn;				   /*			     */
  Record	rec;				   /*			     */
  DB		db;				   /*                        */
{ int		pos = sbtell(sb);		   /*			     */
						   /*			     */
  tmp_key_db = db;				   /*                        */
  if ( eval__fmt(sb,kn,rec) != 0 )		   /*			     */
  { (void)sbseek(sb,pos); return 1; }	   	   /*			     */
						   /*			     */
  return 0;					   /*			     */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	eval__fmt()
** Purpose:	Evaluate the given KeyNode tree w.r.t. the given Record
**		Internal version. trash of conjunctions is not removed.
** Arguments:
**	sb	
**	kn
**	rec
** Returns:	
**___________________________________________________			     */
static int eval__fmt(sb,kn,rec)			   /*			     */
  StringBuffer  *sb;				   /*                        */
  KeyNode	kn;				   /*			     */
  Record	rec;				   /*			     */
{ char	   	*s;				   /*			     */
  int		pos;				   /*			     */
  char		*trans;				   /*                        */
						   /*			     */
  DebugPrint1("eval__fmt()");
  while ( kn != (KeyNode)0 )			   /*			     */
  {						   /*                        */
    switch ( NodeType(kn) )			   /*			     */
    { case NodeSTRING:				   /*			     */
	DebugPrint3("STRING \"",NodeSymbol(kn),"\"");/*		             */
	(void)sbputs(NodeSymbol(kn),sb);	   /*			     */
	break;					   /*			     */
      case NodeTEST:				   /*			     */
#ifdef DEBUG
	DebugPrint3("IF_THEN_ELSE (",NodeSymbol(kn),")");/*		     */
	IfGetField(s,NodeSymbol(kn))		   /*			     */
	  DebugPrint1("Field found. Continuing with THEN part");
	else DebugPrint1("Field NOT found. Continuing with ELSE part");
#endif
	IfGetField(s,NodeSymbol(kn))		   /*			     */
	{ (void)eval__fmt(sb,NodeThen(kn),rec); }  /*			     */
	else					   /*			     */
	{ (void)eval__fmt(sb,NodeElse(kn),rec); }  /*			     */
	break;					   /*			     */
 						   /*                        */
      case NodeOR:				   /*			     */
	DebugPrint1("OR Trying THEN part");   	   /*			     */
	pos = sbtell(sb);			   /*			     */
	if ( eval__fmt(sb,NodeThen(kn),rec) != 0 ) /*			     */
	{ (void)sbseek(sb,pos);		   	   /*			     */
	  DebugPrint1("OR THEN part failed. Trying ELSE part.");/*	     */
	  if ( eval__fmt(sb,NodeElse(kn),rec) != 0 )/*			     */
	  { (void)sbseek(sb,pos);		   /*			     */
	    DebugPrint1("OR ELSE part failed");    /*			     */
	    return 1;				   /*			     */
	  }					   /*			     */
	  DebugPrint1("OR ELSE part succeeded");   /*			     */
	}					   /*			     */
	break;					   /*			     */
 						   /*                        */
      case NodeSPECIAL:				   /*			     */
	eval__special(sb,kn,rec);		   /*			     */
	break;					   /*			     */
      default:					   /*			     */
#ifdef DEBUG
	fprintf(err_file,"+++ BibTool: FORMAT %s%d.%d%s%c(%s)\n",/*	     */
		(NodeType(kn)&NodePlusMask?"+":
		 (NodeType(kn)&NodeMinusMask?"-":"")),/*		     */
		NodePre(kn),			   /*			     */
		NodePost(kn),			   /*			     */
		(NodeType(kn)&NodeCountMask?"#":""),/*			     */
		NodeType(kn)&0xff,		   /*			     */
		NodeSymbol(kn));		   /*			     */
#endif
	IfGetField(s,NodeSymbol(kn))		   /*			     */
	{					   /*			     */
	  DebugPrint1("Field found");	   	   /*			     */
 						   /*                        */
	  if (NodeType(kn)&NodeMinusMask) 	   /*                        */
	  { trans = trans_lower; }		   /*                        */
	  else if (NodeType(kn)&NodePlusMask) 	   /*                        */
	  { trans = trans_upper; }		   /*                        */
	  else					   /*                        */
	  { trans = trans_id; }			   /*                        */
#define UsePostOr(X) (NodePost(kn) > 0 ? NodePost(kn) : (X))
#define UsePreOr(X)  (NodePre(kn) >= 0 ? NodePre(kn)  : (X))
#define HasMinus     (NodeType(kn)&NodeMinusMask)
#define HasPlus      (NodeType(kn)&NodePlusMask)
						   /*			     */
	  switch ( NodeType(kn)	& 0x1ff )	   /*			     */
	  {					   /*                        */
	    case 'p':				   /*			     */
	      fmt_names(sb,s,UsePreOr(2),UsePostOr(0),trans);/*          */
	      break;				   /*			     */
	    case 'n':				   /*			     */
	      if ( formatp ) init_key(3);
	      NameStrip(format[0]) = UsePostOr(-1);/*                        */
	      fmt_names(sb,s,UsePreOr(2),0,trans);/*                     */
	      break;				   /*			     */
	    case 'N':				   /*			     */
	      if ( formatp ) init_key(3);
	      NameStrip(format[1]) = UsePostOr(-1);/*                        */
	      if (NextName(format[1]))		   /*                        */
	      { NamePre(NextName(format[1])) = NamePreSep;/*                 */
	      }					   /*                        */
	      fmt_names(sb,s,UsePreOr(2),1,trans);/*                     */
	      break;				   /*			     */
	    case 'T':				   /*			     */
	      fmt_title(sb,			   /*                        */
			s,			   /*                        */
			UsePreOr(1),		   /*                        */
			UsePostOr(0),		   /*                        */
			trans,			   /*                        */
			TRUE,			   /*                        */
			TitleTitleSep);		   /*                        */
	      break;				   /*			     */
	    case 't':				   /*			     */
	      fmt_title(sb,			   /*                        */
			s,			   /*                        */
			UsePreOr(1),		   /*                        */
			UsePostOr(0),		   /*                        */
			trans,			   /*                        */
			FALSE,			   /*                        */
			TitleTitleSep);		   /*                        */
	      break;				   /*			     */
	    case 'd':				   /*			     */
	      if ( fmt_digits(sb,		   /*                        */
			      s,		   /*                        */
			      HasMinus,		   /*                        */
			      HasPlus,		   /*                        */
			      NodePre(kn),	   /*                        */
			      UsePostOr(1),	   /*                        */
			      TRUE) )		   /*                        */
	      { return 1; }			   /*                        */
	      break;				   /*			     */
	    case 'D':				   /*			     */
	      if ( fmt_digits(sb,		   /*                        */
			      s,		   /*                        */
			      HasMinus,		   /*                        */
			      HasPlus,		   /*                        */
			      NodePre(kn),	   /*                        */
			      UsePostOr(1),	   /*                        */
			      FALSE) )		   /*                        */
	      { return 1; }			   /*                        */
	      break;				   /*			     */
	    case 's':				   /*			     */
	      fmt_string(sb,		   /*                        */
			 s,			   /*                        */
			 UsePreOr(0xffff),	   /*                        */
			 trans,			   /*                        */
			 TitleTitleSep);	   /*		             */
	      break;				   /*			     */
	    case 'W':				   /*			     */
	      fmt_title(sb,			   /*                        */
			s,			   /*                        */
			UsePreOr(1),		   /*                        */
			UsePostOr(0),		   /*                        */
			trans,			   /*                        */
			TRUE,			   /*                        */
			sym_empty);		   /*                        */
	      break;				   /*			     */
	    case 'w':				   /*			     */
	      fmt_title(sb,			   /*                        */
			s,			   /*                        */
			UsePreOr(1),		   /*                        */
			UsePostOr(0),		   /*                        */
			trans,			   /*                        */
			FALSE,			   /*                        */
			sym_empty);		   /*                        */
	      break;				   /*			     */
	    case 'p' | NodeCountMask:		   /*			     */
	    case 'n' | NodeCountMask:		   /*			     */
	    case 'N' | NodeCountMask:		   /*			     */
	      if (fmt_c_names(s,UsePreOr(0),UsePostOr(0),HasMinus))/*        */
	      { return 1; }			   /*	                     */
	      break;				   /*			     */
	    case 'd' | NodeCountMask:		   /*			     */
	    case 's' | NodeCountMask:		   /*			     */
	      if (fmt_c_string(s,UsePreOr(0),UsePostOr(0),HasMinus))/*       */
	      { return 1; }			   /*	                     */
	      break;				   /*			     */
	    case 'T' | NodeCountMask:		   /*			     */
	    case 'W' | NodeCountMask:		   /*			     */
	      if (fmt_c_words(s,UsePreOr(0),UsePostOr(0),HasMinus,TRUE))/*   */
	      { return 1; }			   /*	                     */
	      break;				   /*			     */
	    case 't' | NodeCountMask:		   /*			     */
	    case 'w' | NodeCountMask:		   /*			     */
	      if (fmt_c_words(s,UsePreOr(0),UsePostOr(0),HasMinus,FALSE))/*  */
	      { return 1; }			   /*	                     */
	      break;				   /*			     */
	    default: return 1;			   /*			     */
	  }					   /*			     */
	}					   /*			     */
	else					   /*                        */
	{					   /*                        */
	  DebugPrint1("Field not found");	   /*			     */
	  return 1;				   /*                        */
	}			   		   /*			     */
    }						   /*			     */
    kn = NodeNext(kn);				   /*			     */
  }						   /*			     */
#undef UsePostOr
#undef UsePreOr
#undef HasMinus
#undef HasPlus
  return 0;					   /*			     */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	eval__special()
** Purpose:	
**
** Arguments:
**	kn
**	rec
** Returns:	nothing
**___________________________________________________			     */
static void eval__special(sb,kn,rec)		   /*			     */
  StringBuffer *sb;				   /*                        */
  KeyNode	kn;				   /*			     */
  Record	rec;				   /*			     */
{ char		*s;				   /*			     */
  int		missing	= TRUE,		   	   /*			     */
		fmt;			   	   /*			     */
  static char	*s_author	= NULL;		   /*			     */
  static char	*s_editor	= NULL;		   /*			     */
  static char	*s_title	= NULL;		   /*			     */
  static char	*s_booktitle	= NULL;		   /*			     */
  static char	*s_key		= NULL;		   /*			     */
						   /*			     */
  if ( s_author == NULL )			   /*			     */
  { s_author	= sym_add("author",-1);		   /*			     */
    s_editor	= sym_add("editor",-1);		   /*			     */
    s_title	= sym_add("title",-1);		   /*			     */
    s_booktitle = sym_add("booktitle",-1);	   /*			     */
    s_key	= sym_add("key",-1);		   /*			     */
  }						   /*			     */
						   /*			     */
  if ( formatp ) init_key(3);			   /*                        */
  fmt = ( NodePre(kn)==KEYSTYLE_LONG ? 1 : 0 );    /*                        */
  NameStrip(format[fmt]) = NodePost(kn);	   /*                        */
    					   	   /*			     */
  IfGetField(s,s_author)			   /*			     */
  { fmt_names(sb,s,2,fmt,trans_lower);	   	   /*                        */
    missing = FALSE;				   /*			     */
  }						   /*			     */
  else IfGetField(s,s_editor)			   /*			     */
  { fmt_names(sb,s,2,fmt,trans_lower);	   	   /*                        */
    missing = FALSE;				   /*			     */
  }						   /*			     */
						   /*			     */
  IfGetField(s,s_title)				   /*			     */
  { (void)sbputs(NameTitleSep,sb);		   /*			     */
    fmt_title(sb,s,1,0,trans_lower,TRUE,TitleTitleSep);/*		     */
    missing = FALSE;				   /*			     */
  }						   /*			     */
  else IfGetField(s,s_booktitle)		   /*			     */
  { (void)sbputs(NameTitleSep,sb);		   /*			     */
    fmt_title(sb,s,1,0,trans_lower,TRUE,TitleTitleSep);/*		     */
    missing = FALSE;				   /*			     */
  }						   /*			     */
						   /*			     */
  if ( missing )				   /*			     */
  { sbrewind(sb);				   /*			     */
    IfGetField(s,s_key)				   /*			     */
    { fmt_title(sb,s,1,0,trans_lower,TRUE,TitleTitleSep); }/*	             */
    else { (void)sbputs(DefaultKey,sb); }	   /*			     */
  }						   /*			     */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	apply_fmt()
** Purpose:	Expands an arbitrary format specification for a given record.
**		The format specification is given as a string.
**		The result is stored in a string buffer.
** Arguments:
**	sb	Destination string buffer.
**	fmt	Format specification,
**	rec	Record to consider.
**	db	Datrabase containing |rec|.
** Returns:	|1| iff the format is invalid or the evaluation fails. |0|
**		otherwise.
**___________________________________________________			     */
int apply_fmt(sb,fmt,rec,db)			   /*                        */
  StringBuffer   *sb;				   /*                        */
  char	         *fmt;				   /*                        */
  Record         rec;				   /*                        */
  DB	         db;				   /*                        */
{ static char    *old_fmt = NULL;		   /*                        */
  static KeyNode old_kn   = (KeyNode)0;		   /*                        */
  int		 ret;				   /*                        */
 						   /*                        */
  if (   old_fmt == NULL			   /* This is the first time */
      || strcmp(fmt,old_fmt) != 0 )		   /*   or the format needs  */
  {						   /*   recompilation.       */
    key_init();
    if ( old_fmt != NULL )
    { free(old_fmt);
      free_key_node(old_kn);
      old_kn = (KeyNode)0;
    }

    old_fmt = new_string(fmt);
    if ( !add_fmt_tree(old_fmt,&old_kn) )
    { free(old_fmt);
      old_fmt = NULL;
      return 1;
    }
  }
  return eval_fmt(sb,old_kn,rec,db);		   /*                        */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	fmt_expand()
** Purpose:	Expands a format specification of the % type into a given
**		string buffer.
**		
** Arguments:
**	sb	destination string buffer
**	cp	format
** Returns:	The first character after the % format.
**___________________________________________________			     */
char* fmt_expand(sb,cp,db,rec)			   /*                        */
  StringBuffer *sb;				   /*                        */
  char	       *cp;				   /*                        */
  DB	       db;				   /*                        */
  Record       rec;				   /*                        */
{ char *sp, c, *s;			   	   /*                        */
  char *trans = trans_id;			   /*                        */
  int  pre  = -1,				   /*                        */
       post = -1,				   /*                        */
       type = 0;				   /*                        */

  while ( *cp && *cp != '%' )
  { sbputchar(*cp,sb);
    cp++;
  }
					       	   /*                        */
  if (*cp =='%')				   /*                        */
  { 						   /*                        */
    switch ( *++cp )			   	   /*			     */
    { case '+': trans = trans_upper; ++cp; break;  /*		             */
      case '-': trans = trans_lower; ++cp; break;  /*		             */
    }					   	   /*			     */
    ParseNumber(cp,pre);			   /*			     */
    if ( *cp == '.' || *cp == ',' || *cp == '-' )  /*		             */
    { cp++;				   	   /*                        */
      ParseNumber(cp,post);		   	   /*                        */
    }	   				   	   /*			     */
    if ( *cp == '#' )			   	   /*                        */
    { cp++;				   	   /*                        */
      type |= NodeCountMask;		   	   /*                        */
    }					   	   /*                        */
    if ( !is_alpha(*cp) )			   /*			     */
    { ErrPrintF("*** BibTool: Missing format type before: %s",cp);/*         */
      return cp;		   		   /*			     */
    }					   	   /*			     */
    if ( strchr(percent_chars,*cp) == (char*)0 )   /*		             */
    { ErrPrintF("*** BibTool: Illegal format character: %c",*cp);/*          */
      return cp;			   	   /*			     */
    }					   	   /*			     */
    type |= *(cp++);			   	   /*			     */
    Expect(cp,'(',cp);			   	   /*			     */
    SkipSpaces(cp);			   	   /*			     */
    sp = cp;				   	   /*			     */
    SkipAllowed(cp);			   	   /*			     */
    c = *cp;					   /*                        */
    *cp = '\0';					   /*                        */
    sp = symbol(sp);			   	   /*                        */
    *cp = c;					   /*                        */
    SkipSpaces(cp);			   	   /*			     */
    if ( *cp == ')' ) { cp++; }			   /*                        */
    else					   /*                        */
    { ErrPrintF("*** BibTool: Missing ')' in format before: %s\n",*cp);/*    */
      return cp;				   /*                        */
    }						   /*                        */
 						   /*                        */
    if ( (s=get_field(db,rec,sp)) != NULL )
    {					   	   /*			     */
      DebugPrint1("Field found");	   	   /*			     */
 						   /*                        */
#define UsePostOr(X) (post > 0 ? post : (X))
#define UsePreOr(X)  (pre >= 0 ? pre  : (X))
#define HasMinus     (type&NodeMinusMask)
#define HasPlus      (type&NodePlusMask)
      switch ( type & 0x1ff )	   		   /*			     */
      {					   	   /*                        */
	case 'p':				   /*			     */
	  fmt_names(sb,s,UsePreOr(2),UsePostOr(0),trans);/*                  */
	  break;				   /*			     */
	case 'n':				   /*			     */
	  if ( formatp ) init_key(3);
	  NameStrip(format[0]) = UsePostOr(-1);	   /*                        */
	  fmt_names(sb,s,UsePreOr(2),0,trans);	   /*                        */
	  break;				   /*			     */
	case 'N':				   /*			     */
	  if ( formatp ) init_key(3);
	  NameStrip(format[1]) = UsePostOr(-1);	   /*                        */
	  if (NextName(format[1]))		   /*                        */
	  { NamePre(NextName(format[1])) = NamePreSep;/*                     */
	  }					   /*                        */
	  fmt_names(sb,s,UsePreOr(2),1,trans);	   /*                        */
	  break;				   /*			     */
	case 'T':				   /*			     */
	  fmt_title(sb,				   /*                        */
		    s,				   /*                        */
		    UsePreOr(1),		   /*                        */
		    UsePostOr(0),		   /*                        */
		    trans,			   /*                        */
		    TRUE,			   /*                        */
		    TitleTitleSep);		   /*                        */
	  break;				   /*			     */
	case 't':				   /*			     */
	  fmt_title(sb,				   /*                        */
		    s,				   /*                        */
		    UsePreOr(1),		   /*                        */
		    UsePostOr(0),		   /*                        */
		    trans,			   /*                        */
		    FALSE,			   /*                        */
		    TitleTitleSep);		   /*                        */
	  break;				   /*			     */
	case 'd':				   /*			     */
	  (void)fmt_digits(sb,			   /*                        */
			   s,		   	   /*                        */
			   HasMinus,		   /*                        */
			   HasPlus,		   /*                        */
			   pre,	   	   	   /*                        */
			   UsePostOr(1),	   /*                        */
			   TRUE);		   /*                        */
	  break;				   /*			     */
	case 'D':				   /*			     */
	  (void)fmt_digits(sb,			   /*                        */
			   s,		   	   /*                        */
			   HasMinus,		   /*                        */
			   HasPlus,		   /*                        */
			   pre,	   	   	   /*                        */
			   UsePostOr(1),	   /*                        */
			   FALSE);		   /*                        */
	  break;				   /*			     */
	case 's':				   /*			     */
	  fmt_string(sb,			   /*                        */
		     s,				   /*                        */
		     UsePreOr(0xffff),		   /*                        */
		     trans,			   /*                        */
		     " ");	   		   /*		             */
	  break;				   /*			     */
	case 'W':				   /*			     */
	  fmt_title(sb,				   /*                        */
		    s,				   /*                        */
		    UsePreOr(1),		   /*                        */
		    UsePostOr(0),		   /*                        */
		    trans,			   /*                        */
		    TRUE,			   /*                        */
		    sym_empty);			   /*                        */
	  break;				   /*			     */
	case 'w':				   /*			     */
	  fmt_title(sb,				   /*                        */
		    s,				   /*                        */
		    UsePreOr(1),		   /*                        */
		    UsePostOr(0),		   /*                        */
		    trans,			   /*                        */
		    FALSE,			   /*                        */
		    sym_empty);			   /*                        */
	  break;				   /*			     */
      }					   	   /*			     */
    }						   /*                        */
    else					   /*                        */
    { DebugPrint1("Field not found");	   	   /*			     */
    }						   /*                        */
  }						   /*                        */
#undef UsePostOr
#undef UsePreOr
#undef HasMinus
#undef HasPlus
 						   /*                        */
  return cp;					   /*                        */
}						   /*------------------------*/


#ifdef DEBUG
/*-----------------------------------------------------------------------------
** Function:	show_fmt()
** Purpose:	Print a format tree onto the error stream
** Arguments:
**	kn
**	in
** Returns:	nothing
**___________________________________________________			     */
static void show_fmt(kn,in)			   /*			     */
  register KeyNode kn;				   /*			     */
  register int     in;				   /*                        */
{ register int     i;				   /*			     */
#define NLin ErrC('\n');for(i=in;i>0;i--) ErrC(' ')
#define ErrS(S) (void)fputs(S,err_file)
						   /*			     */
  while ( kn != (KeyNode)0 )			   /*			     */
  { switch ( NodeType(kn) )			   /*			     */
    { case NodeSTRING:				   /*			     */
	ErrPrintF(" \"%s\"",NodeSymbol(kn));	   /*			     */
	NLin;					   /*			     */
	break;					   /*			     */
      case NodeTEST:				   /*			     */
	ErrPrintF(" (%s)",NodeSymbol(kn));	   /*			     */
	NLin; ErrS("{ ");			   /*			     */
	show_fmt(NodeThen(kn),in+2);		   /*			     */
	NLin; ErrS("}");			   /*			     */
	NLin; ErrS("{ ");			   /*			     */
	show_fmt(NodeElse(kn),in+2);		   /*			     */
	NLin;					   /*			     */
	ErrS("}");				   /*			     */
	break;					   /*			     */
      case NodeOR:				   /*			     */
	ErrS("{ ");				   /*			     */
	show_fmt(NodeThen(kn),in+2);		   /*			     */
	ErrS("}");			   	   /*			     */
	NLin; ErrS("#");			   /*			     */
	NLin; ErrS("{ ");			   /*			     */
	show_fmt(NodeElse(kn),in+2);		   /*			     */
	NLin;					   /*			     */
	ErrS("}");				   /*			     */
	break;					   /*			     */
      default:					   /*			     */
	fprintf(err_file,"%%%s",	   	   /*			     */
	       (NodeType(kn)&NodePlusMask?"+":	   /*                        */
		(NodeType(kn)&NodeMinusMask?"-":"")));/*		     */
	if ( NodePre(kn)>=0 )			   /*                        */
	  fprintf(err_file,"%d",NodePre(kn));	   /*			     */
	if ( NodePost(kn)>=0 )			   /*                        */
	  fprintf(err_file,".%d",NodePost(kn));	   /*			     */
	fprintf(err_file,"%s%c(%s) ",	   	   /*			     */
	       (NodeType(kn)&NodeCountMask?"#":""),/*			     */
	       NodeType(kn)&0xff,		   /*			     */
	       NodeSymbol(kn));			   /*			     */
    }						   /*			     */
    kn = NodeNext(kn);				   /*			     */
  }						   /*			     */
}						   /*------------------------*/

#endif


 static char * sym_user = NULL;
 static char * sym_host = NULL;

/*-----------------------------------------------------------------------------
** Function:	get_field()
** Purpose:	Evaluate the record |rec|.
**		If name starts with |@| then check the record name.
**		If name starts with |$| then return the special info. 
**		Else search in Record |rec| for the field name and return its
**		value. |NULL| is returned to indicate failure.
** Arguments:
**	rec	Record to analyze.
**	name	Field name to search for. This has to be a symbol if a
**		normal field is sought. For pseudo fields it can be an
**		arbitrary string.
** Returns:	The address of the value or |NULL|.
**___________________________________________________			     */
char *get_field(db,rec,name)		   	   /*			     */
  DB db;					   /*                        */
  register Record rec;				   /*			     */
  register char	  *name;			   /*			     */
{ 						   /*                        */
#ifdef HAVE_TIME_H
  static struct tm *tp;				   /*                        */
  static time_t the_time = 0;			   /*                        */
  static char buffer[32];			   /*                        */
 						   /*                        */
  if ( the_time == 0 )				   /*                        */
  { the_time = time(NULL);			   /*                        */
    tp = localtime(&the_time);			   /*                        */
  }						   /*                        */
#define ReturnTime(F) if ( the_time > 0 )	\
  { (void)strftime(buffer,32,F,tp);		\
    return symbol(buffer); }			\
  return sym_empty
#else
#define ReturnTime(F) return sym_empty
#endif
				   		   /*                        */
  if ( *name == '@' )				   /*			     */
  { if ( case_cmp(name+1,EntryName(RecordType(rec))) )/*		     */
      return EntryName(RecordType(rec));	   /*		             */
  }						   /*			     */
  else if ( *name == '$' )			   /*			     */
  { ++name;					   /*			     */
    switch (*name)				   /*                        */
    { case 'k': case 'K':			   /*                        */
        if ( case_cmp(name,"key") )		   /*			     */
	{ return (**RecordHeap(rec)		   /*                        */
		  ? *RecordHeap(rec)		   /*                        */
		  : NULL);			   /*                        */
	}					   /*		             */
        break;					   /*                        */
      case 'd': case 'D':			   /*                        */
	if ( case_cmp(name,"default.key") )	   /*			     */
	{ return DefaultKey; }			   /*			     */
	else if ( case_cmp(name,"day") )  	   /*			     */
	{ ReturnTime("%d"); }			   /*			     */
	break;    				   /*                        */
      case 'f': case 'F':			   /*                        */
	if ( case_cmp(name,"fmt.et.al") )	   /*			     */
	{ return EtAl; }			   /*			     */
	else if ( case_cmp(name,"fmt.name.pre") )  /*			     */
	{ return NamePreSep; }			   /*			     */
	else if ( case_cmp(name,"fmt.inter.name") )/*			     */
	{ return InterNameSep; }		   /*			     */
	else if ( case_cmp(name,"fmt.name.name") ) /*			     */
	{ return NameNameSep; }			   /*			     */
	else if ( case_cmp(name,"fmt.name.title") )/*			     */
	{ return NameTitleSep; }		   /*			     */
	else if ( case_cmp(name,"fmt.title.title") )/*			     */
	{ return TitleTitleSep; }		   /*			     */
      case 'h': case 'H':			   /*                        */
	if ( case_cmp(name,"hostname") )	   /*			     */
	{ if ( sym_host==NULL )			   /*                        */
	  { sym_host = getenv("HOSTNAME");	   /*                        */
	    sym_host = symbol(sym_host?sym_host:sym_empty);/*                */
	  }					   /*                        */
	  return sym_host;			   /*                        */
	}	   	   			   /*			     */
        else if ( case_cmp(name,"hour") )  	   /*			     */
	{ ReturnTime("%H"); }			   /*			     */
	break;					   /*                        */
      case 'm': case 'M':			   /*                        */
	if ( case_cmp(name,"month") )	   	   /*			     */
	{ ReturnTime("%m"); }			   /*			     */
	else if ( case_cmp(name,"minute") )  	   /*			     */
	{ ReturnTime("%M"); }			   /*			     */
	else if ( case_cmp(name,"mon") )  	   /*			     */
	{ ReturnTime("%B"); }			   /*			     */
	break;    				   /*                        */
      case 's': case 'S':			   /*                        */
	if ( case_cmp(name,"sortkey") )	   	   /*			     */
	{ return RecordSortkey(rec); }		   /*			     */
	else if ( case_cmp(name,"source") )	   /*			     */
	{ return RecordSource(rec); }		   /*			     */
	else if ( case_cmp(name,"second") )	   /*			     */
	{ ReturnTime("%S"); }			   /*			     */
	break;    				   /*                        */
      case 't': case 'T':			   /*                        */
	if ( case_cmp(name,"type") )		   /*			     */
	{ return EntryName(RecordType(rec)); }	   /*			     */
	else if ( case_cmp(name,"time") )	   /*			     */
	{ ReturnTime("%H:%M:%S"); }		   /*			     */
        break;					   /*                        */
      case 'u': case 'U':			   /*                        */
	if ( case_cmp(name,"user") )		   /*			     */
	{ if ( sym_user==NULL )			   /*                        */
	  { sym_user = getenv("USER");		   /*                        */
	    sym_user = symbol(sym_user?sym_user:sym_empty);/*                */
	  }					   /*                        */
	  return sym_user;			   /*                        */
	}	   	   			   /*			     */
        break;					   /*                        */
      case 'w': case 'W':			   /*                        */
	if ( case_cmp(name,"weekday") )	   	   /*			     */
	{ ReturnTime("%a"); }			   /*			     */
	break;    				   /*                        */
      case 'y': case 'Y':			   /*                        */
	if ( case_cmp(name,"year") )	   	   /*			     */
	{ ReturnTime("%Y"); }			   /*			     */
	break;    				   /*                        */
    }						   /*                        */
  }						   /*			     */
  else						   /*			     */
  { register char **cpp;			   /*			     */
    char *xref;					   /*                        */
    register int n, count;			   /*			     */
						   /*			     */
    for ( count=rsc_xref_limit;count>=0;count-- )  /* Prevent infinite loop  */
    {						   /*                        */
      xref = NULL;				   /*                        */
      for ( cpp=RecordHeap(rec), n=RecordFree(rec);/*			     */
	    n > 0;				   /*			     */
	    n -= 2 )				   /*			     */
      {						   /*                        */
	if ( *cpp == name )			   /*                        */
	{ return ( rsc_key_expand_macros	   /*                        */
		   ? expand_rhs(*(cpp+1),"{","}",db)/*                       */
		   : *(cpp+1) );		   /*			     */
	}					   /*                        */
        if ( *cpp == sym_crossref ) { xref = *++cpp; }/*                     */
	else cpp++;				   /*                        */
        cpp++;			   	   	   /*			     */
      }					   	   /*			     */
       						   /*                        */
      if ( xref == NULL ) { return (char*)0; }	   /* No crossref field found*/
      xref = symbol(expand_rhs(xref,sym_empty,sym_empty,db));/*              */
      if ( (rec = db_find(db,xref)) == RecordNULL )/*                        */
      { ErrPrintF("*** BibTool: Crossref `%s' not found.\n",xref);/*         */
	return (char*)0;			   /*                        */
      }						   /*                        */
      DebugPrint2("Following crossref to ",xref);  /*                        */
    }						   /*			     */
  }						   /*                        */
 						   /*                        */
  return (char*)0;				   /* Nothing found.	     */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	set_field()
** Purpose:	Store the given field or pseudo-field in a record.
**		If the field is present then the old value is
**		overwritten.  Otherwise a new field is added. Fields
**		starting with a |$| or |@| are treated special. They
**		denote pseudo fields. If such a pseudo field is
**		undefined then the assignment simply fails.
**
**		In contrast to the function |push_to_record()| this
**		function does not assume that the arguments are
**		symbols. In addition to |push_to_record()| it also
**		handles pseudo-fields.
** Arguments:
**	rec	Record to receive the value.
**	name	Field name to add.
** Returns:	|0| if the asignment has succeeded.
**___________________________________________________			     */
int set_field(db,rec,name,value)		   /*			     */
  DB db;					   /*                        */
  register Record rec;				   /*			     */
  register char	  *name;			   /*			     */
  char	  	  *value;			   /*			     */
{ 						   /*                        */
  value = symbol(value);			   /*                        */
				   		   /*                        */
  if ( *name == '@' )				   /*			     */
  {
  }						   /*			     */
  else if ( *name == '$' )			   /*			     */
  { ++name;					   /*			     */
    switch (*name)				   /*                        */
    { case 'k': case 'K':			   /*                        */
        if ( case_cmp(name,"key") )		   /*			     */
	{ *RecordHeap(rec) = value;	   	   /*                        */
	  return 0;			   	   /*                        */
	}					   /*		             */
        break;					   /*                        */
      case 'd': case 'D':			   /*                        */
	if ( case_cmp(name,"default.key") )	   /*			     */
	{ DefaultKey = value;		   	   /*                        */
	  return 0;				   /*                        */
	}		   			   /*			     */
	break;    				   /*                        */
      case 'f': case 'F':			   /*                        */
	if ( case_cmp(name,"fmt.et.al") )	   /*			     */
	{ EtAl = value; return 0; }	   	   /*			     */
	else if ( case_cmp(name,"fmt.name.pre") )  /*			     */
	{ NamePreSep = value; return 0; }  	   /*			     */
	else if ( case_cmp(name,"fmt.inter.name") )/*			     */
	{ InterNameSep = value; return 0; }	   /*			     */
	else if ( case_cmp(name,"fmt.name.name") ) /*			     */
	{ NameNameSep = value; return 0; } 	   /*			     */
	else if ( case_cmp(name,"fmt.name.title") )/*			     */
	{ NameTitleSep = value; return 0; }	   /*			     */
	else if ( case_cmp(name,"fmt.title.title") )/*			     */
	{ TitleTitleSep = value; return 0; }	   /*			     */
      case 's': case 'S':			   /*                        */
	if ( case_cmp(name,"sortkey") )	   	   /*			     */
	{ RecordSortkey(rec) = value; return 0; }  /*			     */
	else if ( case_cmp(name,"source") )	   /*			     */
	{ RecordSource(rec) = value; return 0; }   /*		             */
	break;    				   /*                        */
      case 't': case 'T':			   /*                        */
	if ( case_cmp(name,"type") )		   /*			     */
	{ int type;				   /*                        */
	  if ( IsNormalRecord(RecordType(rec)) &&  /*                        */
	       (type=find_entry_type(value)) >= 0 )/*                        */
	  { RecordType(rec) = type; return 0; }    /*                        */
	}					   /*                        */
        break;					   /*                        */
      case 'u': case 'U':			   /*                        */
	if ( case_cmp(name,"user") )		   /*			     */
	{ sym_user = value; return 0; }	   	   /*			     */
        break;					   /*                        */
    }						   /*                        */
  }						   /*			     */
  else						   /*			     */
  {   						   /*			     */
    push_to_record(rec,symbol(name),value);	   /*			     */
    return 0;					   /*                        */
  }						   /*                        */
 						   /*                        */
  return 1;				   	   /* Nothing found.	     */
}						   /*------------------------*/