summaryrefslogtreecommitdiff
path: root/corelib/ncbistr.c
blob: 2ff3b756857c43ca88a01c1678d679df9b57282e (plain)
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
/*   ncbistr.c
* ===========================================================================
*
*                            PUBLIC DOMAIN NOTICE                          
*               National Center for Biotechnology Information
*                                                                          
*  This software/database is a "United States Government Work" under the   
*  terms of the United States Copyright Act.  It was written as part of    
*  the author's official duties as a United States Government employee and 
*  thus cannot be copyrighted.  This software/database is freely available 
*  to the public for use. The National Library of Medicine and the U.S.    
*  Government have not placed any restriction on its use or reproduction.  
*                                                                          
*  Although all reasonable efforts have been taken to ensure the accuracy  
*  and reliability of the software and data, the NLM and the U.S.          
*  Government do not and cannot warrant the performance or results that    
*  may be obtained by using this software or data. The NLM and the U.S.    
*  Government disclaim all warranties, express or implied, including       
*  warranties of performance, merchantability or fitness for any particular
*  purpose.                                                                
*                                                                          
*  Please cite the author in any work or product based on this material.   
*
* ===========================================================================
*
* File Name:  ncbistr.c
*
* Author:  Gish, Kans, Ostell, Schuler, Brylawski, Vakatov, Lavrentiev
*
* Version Creation Date:   3/4/91
*
* $Revision: 6.12 $
*
* File Description: 
*   	portable string routines
*
* Modifications:  
* --------------------------------------------------------------------------
* $Log: ncbistr.c,v $
* Revision 6.12  2003/09/15 16:21:32  kans
* moved StringDoesHaveText from sqnutils3.c
*
* Revision 6.11  2002/01/16 16:58:38  camacho
* Changed type of buflen parameter in LabelCopy from Int2 to Uint4
*
* Revision 6.10  2001/01/05 22:43:58  shavirin
* Added functions, that transfer Uint8 values to platform-independent
* objects and back.
*
* Revision 6.9  2000/12/04 23:48:02  kans
* trim spaces around string now handles trailing tabs, newlines, etc.
*
* Revision 6.8  2000/11/30 22:46:07  lavr
* Added the following functions for conversions of Int8 and Uint8
* to strings and back; test suite attached at the end of the file.
* Nlm_Int8ToString, Nlm_Uint8ToString, Nlm_StringToInt8, Nlm_StringToUint8
*
* Revision 6.7  2000/08/28 18:36:25  vakatov
* un-const casts in some functions to pass C++ compilation
*
* Revision 6.6  1999/04/15 20:24:06  vakatov
* Dont use "list" name as it can clash with the standard "list<>" template
* on some raw C++ compilers
*
* Revision 6.5  1999/03/11 16:10:00  kans
* StringHasNoText and TrimSpacesAroundString moved from vibforms
*
* Revision 6.4  1998/11/23 00:09:47  kans
* fixed bug in StringTokMT (found by Hugues)
*
* Revision 6.3  1998/10/07 19:09:00  kans
* added Nlm_StringTokMT, multithread-safe version
*
* Revision 6.2  1997/11/26 21:26:25  vakatov
* Fixed errors and warnings issued by C and C++ (GNU and Sun) compilers
*
* Revision 6.1  1997/10/29 02:44:52  vakatov
* Type castings to pass through the C++ compiler
*
* Revision 5.5  1997/07/16 19:49:18  vakatov
* Added Nlm_StringPrintable() function
*
* Revision 5.4  1997/04/11 17:57:25  brandon
* added StrIPCmp, StrNIPCmp
*
 * Revision 5.3  1997/03/04  22:01:12  vakatov
 * Added a set of functions to format(stream2text), unformat(text2stream)
 * and adjust(rule_line) text and test/demo code #TEST_TEXT_FMT for these
 *
 * Revision 5.2  1997/01/03  15:56:28  vakatov
 * Added auxiliary function Nlm_StringNCpy_0() -- that guarantees the
 * resulting string be '\0'-terminated
 *
 * Revision 5.1  1996/12/03  21:48:33  vakatov
 * Adopted for 32-bit MS-Windows DLLs
 *
 * Revision 4.12  1996/05/22  18:04:14  kans
 * changed nulls to '\0' in new string functions
 *
 * Revision 4.11  1996/05/22  14:46:19  brandon
 * Fixed SkipToString, SkipPastString to work with short strings
 *
 * Revision 4.10  1996/05/07  13:22:37  kans
 * more protection for stringsearch
 *
 * Revision 4.9  1996/05/06  15:07:58  kans
 * fixed StringISearch to set d [] based on TO_UPPER, not to crash if nonASCII
 *
 * Revision 4.8  1996/03/14  03:42:44  epstein
 * change String variables to theString to work around SGI4 problem
 *
 * Revision 4.7  1996/01/05  02:29:37  ostell
 * provided return value for TruncateStringCopy()
 *
 * Revision 4.6  1996/01/03  21:04:46  epstein
 * modify StringSubString() API and add other new functions, per Brandon
 *
 * Revision 4.5  1996/01/02  14:17:32  ostell
 * added a number of Brandons functions
 *
 * Revision 4.4  1995/12/28  15:41:56  epstein
 * added Brylawskin to revision history and author list
 *
 * Revision 4.3  1995/12/27  20:53:48  epstein
 * add Brandon's string-management functions
 *
 * Revision 4.2  1995/10/28  15:03:20  ostell
 * added casts to quiet DOS compile warnings
 *
 * Revision 4.1  1995/10/16  13:43:29  epstein
 * fix brain-dmanaged string-compare logic to handle null strings correctly
 *
 * Revision 2.12  1995/07/18  19:56:10  tatiana
 * add Nlm_LabelCopyNext()
 *
 * Revision 2.11  1995/05/30  13:19:37  kans
 * fixed StringSearch algorithm - check until i <= strLen, not just < strLen
 *
* 3/4/91   Kans        Stricter typecasting for GNU C and C++.
* 09-19-91 Schuler     Changed all types expressing sizes to size_t.
* 09-19-91 Schuler     Changed return type for compare functions to int.
* 09-19-91 Schuler     Changed all functions to _cdecl calling convention.
* 09-19-91 Schuler     Where possible, NCBI functions call the actual ANSI
*                       functions after checking for NULL pointers.
* 09-19-91 Schuler     Debug-class error posted on any NULL argument.
* 09-19-91 Schuler     StringSave() calls MemGet() instead of MemNew().
* 09-19-91 Schuler     StringSave(NULL) returns NULL.
* 10-17-91 Schuler     Removed ErrPost() calls on NULL arguments.
* 10-17-91 Schuler     Added Nlm_StringCnt(),Nlm_StringStr(),Nlm_StringTok()
* 11-18-91 Schuler     Added more ANSI-style functions
* 04-15-93 Schuler     Changed _cdecl to LIBCALL
* 05-27-93 Schuler     Added const qualifiers to match ANSI cognates
* 06-14-94 Schuler     Added StrUpper() and StrLower() functions
* 03-08-95 Kans        Added StringSearch and StringISearch
* 12-27-95 Brylawski   Added a variety of functions, including search-and-
*                      replace functions.
*
* ==========================================================================
*/
 
#include <ncbi.h>
#include <ncbiwin.h>

/* ClearDestString clears the destination string if the source is NULL. */
static Nlm_CharPtr NEAR Nlm_ClearDestString (Nlm_CharPtr to, size_t max)
{
  if (to != NULL && max > 0) {
    Nlm_MemSet (to, 0, max);
    *to = '\0';
  }
  return to;
}

NLM_EXTERN size_t LIBCALL  Nlm_StringLen (const char *str)
{
	return str ? StrLen (str) : 0;
}

NLM_EXTERN Nlm_CharPtr LIBCALL  Nlm_StringCpy (char FAR *to, const char FAR *from)
{
	return (to && from) ? StrCpy (to, from) : Nlm_ClearDestString (to, 1);
}

NLM_EXTERN Nlm_CharPtr LIBCALL  Nlm_StringNCpy (char FAR *to, const char FAR *from, size_t max)
{
	return (to && from) ? StrNCpy (to, from, max) : Nlm_ClearDestString (to, max);
}

NLM_EXTERN Nlm_CharPtr LIBCALL  Nlm_StringNCpy_0 (char FAR *to, const char FAR *from, size_t max)
{
  if (to != NULL  &&  max > 0)
    to[0] = '\0';

  if (from != NULL)
    StrNCat(to, from, max - 1);

  return to;
}

NLM_EXTERN Nlm_CharPtr LIBCALL  Nlm_StringCat (char FAR *to, const char FAR *from)
{
	return (to && from) ? StrCat (to, from) : to;
}

NLM_EXTERN Nlm_CharPtr LIBCALL  Nlm_StringNCat (char FAR *to, const char FAR *from, size_t max)
{       
    return (to && from) ? StrNCat (to, from, max) : to;
}

NLM_EXTERN int LIBCALL  Nlm_StringCmp (const char FAR *a, const char FAR *b)
{
	return (a && b) ? StrCmp(a, b) : (a ? 1 : (b ? -1 : 0));
}

NLM_EXTERN int LIBCALL  Nlm_StringNCmp (const char FAR *a, const char FAR *b, size_t max)
{
	return (a && b) ? StrNCmp(a, b, max) : (a ? 1 : (b ? -1 : 0));
}

NLM_EXTERN int LIBCALL  Nlm_StringICmp (const char FAR *a, const char FAR *b)
{
	return (a && b) ? Nlm_StrICmp(a, b) : (a ? 1 : (b ? -1 : 0));
}

NLM_EXTERN int LIBCALL  Nlm_StringNICmp (const char FAR *a, const char FAR *b, size_t max)
{
	return (a && b) ? Nlm_StrNICmp(a, b, max) : (a ? 1 : (b ? -1 : 0));
}

NLM_EXTERN Nlm_CharPtr LIBCALL  Nlm_StringChr (const char FAR *str, int chr)
{
	return (Nlm_CharPtr) (str ? Nlm_StrChr(str,chr) : 0);
}

NLM_EXTERN Nlm_CharPtr LIBCALL  Nlm_StringRChr (const char FAR *str, int chr)
{
	return (Nlm_CharPtr) (str ? Nlm_StrRChr(str,chr) : 0);
}

NLM_EXTERN size_t LIBCALL  Nlm_StringSpn (const char FAR *a, const char FAR *b)
{
	return (a && b) ? Nlm_StrSpn (a, b) : 0;
}

NLM_EXTERN size_t LIBCALL  Nlm_StringCSpn (const char FAR *a, const char FAR *b)
{
	return (a && b) ? Nlm_StrCSpn (a, b) : 0;
}

NLM_EXTERN Nlm_CharPtr LIBCALL  Nlm_StringPBrk (const char FAR *a, const char FAR *b)
{
	return (Nlm_CharPtr) ((a && b) ? Nlm_StrPBrk (a, b) : 0);
}

NLM_EXTERN Nlm_CharPtr LIBCALL  Nlm_StringStr (const char FAR *str1, const char FAR *str2)
{
	return (Nlm_CharPtr) ((str1 && str2) ? Nlm_StrStr(str1,str2) : 0);
}

NLM_EXTERN Nlm_CharPtr LIBCALL  Nlm_StringTok (char FAR *str1, const char FAR *str2)
{
    return str2 ? Nlm_StrTok(str1,str2) : 0;
}

NLM_EXTERN Nlm_CharPtr LIBCALL  Nlm_StringTokMT (char FAR *str1, const char FAR *str2, char FAR **tmp)
{
	char ch;
	char FAR *ptr;
	char FAR *rsult = NULL;

	if (str2 == NULL || tmp == NULL) return NULL;
	if (str1 != NULL) {
  	  *tmp = str1;
    }
    ptr = *tmp;
    if (ptr == NULL) return NULL;
    ch = *ptr;
    while (ch != '\0' && strchr (str2, ch) != NULL) {
      ptr++;
      ch = *ptr;
    }
    if (ch == '\0') {
      *tmp = NULL;
      return NULL;
    }
    rsult = ptr;
    while (ch != '\0' && strchr (str2, ch) == NULL) {
      ptr++;
      ch = *ptr;
    }
    if (ch == '\0') {
      *tmp = NULL;
    } else {
      *ptr = '\0';
      ptr++;
      *tmp = ptr;
    }
    return rsult; 
}

NLM_EXTERN Nlm_CharPtr LIBCALL  Nlm_StringMove (char FAR *to, const char FAR *from)
{
    return (to && from) ? Nlm_StrMove (to, from) : to;
}

NLM_EXTERN Nlm_CharPtr LIBCALL  Nlm_StringSave (const char FAR *from)
{
    return from ? Nlm_StrSave (from) : 0;
}

NLM_EXTERN Nlm_CharPtr LIBCALL  Nlm_StringSaveNoNull (const char FAR *from)
{
    return (from  && *from) ? Nlm_StrSave(from) : 0;
}

NLM_EXTERN size_t LIBCALL  Nlm_StringCnt (const char FAR *str, const char FAR *x_list)
{
    return (str && x_list) ? Nlm_StrCnt(str,x_list) : 0;
}

NLM_EXTERN char * LIBCALL Nlm_StringUpper (char *string)
{
	return (string == NULL) ? 0 : StrUpper(string);
}

NLM_EXTERN char * LIBCALL Nlm_StringLower (char *string)
{
	return (string == NULL) ? 0 : StrLower(string);
}





NLM_EXTERN int LIBCALL  Nlm_StrICmp (const char FAR *a, const char FAR *b)
{
	int diff, done;

    if (a == b)   return 0;

	done = 0;
	while (! done)
	{
		diff = TO_UPPER(*a) - TO_UPPER(*b);
		if (diff)
			return (Nlm_Int2) diff;
		if (*a == '\0')
			done = 1;
		else
		{
			a++; b++;
		}
	}
	return 0;
}

NLM_EXTERN int LIBCALL  Nlm_StrIPCmp (const char FAR *a, const char FAR *b)
{
  int diff, done;
  
  if (a == b)   return 0;
  
  while (*a && !isalnum(*a))
    a++;
  
  while (*b && !isalnum(*b))
    b++;
  
  done = 0;
  while (! done)
    {
      if (!isalnum(*a) && !isalnum(*b))
	{
	  while (*a && !isalnum(*a))
	    a++;
	  
	  while (*b && !isalnum(*b))
	    b++;
	}
      
      diff = TO_UPPER(*a) - TO_UPPER(*b);
      if (diff)
	return (Nlm_Int2) diff;
      if (*a == '\0')
	done = 1;
      else
	{
	  a++; b++;
	}
    }
  return 0;
}

NLM_EXTERN int LIBCALL  Nlm_StrNICmp (const char FAR *a, const char FAR *b, size_t max)
{
	int diff, done;
	
    if (a == b)   return 0;

	done = 0;
	while (! done)
	{
		diff = TO_UPPER(*a) - TO_UPPER(*b);
		if (diff)
			return (Nlm_Int2) diff;
		if (*a == '\0')
			done = 1;
		else
		{
			a++; b++; max--;
			if (! max)
				done = 1;
		}
	}
	return 0;
}

NLM_EXTERN int LIBCALL  Nlm_StrNIPCmp (const char FAR *a, const char FAR *b, size_t max)
{
  int diff, done;
  
  if (a == b)   return 0;
  
  while (*a && !isalnum(*a))
    a++;
  
  while (*b && !isalnum(*b))
    b++;
  
  done = 0;
  while (! done)
    {
      if (!isalnum(*a) && !isalnum(*b))
	{
	  while (*a && !isalnum(*a))
	    {
	      a++; max--;
	      if (!max)
		{
		  done = 1;
		  break;
		}
	    }
	  
	  while (*b && !isalnum(*b))
	    b++;
	}
      
      
      diff = TO_UPPER(*a) - TO_UPPER(*b);
      if (diff)
	return (Nlm_Int2) diff;
      if (*a == '\0')
	done = 1;
      else
	{
	  a++; b++; max--;
	  if (! max)
	    done = 1;
	}
    }
  return 0;
}

NLM_EXTERN Nlm_CharPtr LIBCALL  Nlm_StrSave (const char FAR *from)
{
	size_t len;
	Nlm_CharPtr to;

	len = Nlm_StringLen(from);
	if ((to = (Nlm_CharPtr) Nlm_MemGet(len +1, FALSE)) != NULL) {
    	Nlm_MemCpy (to, from, len +1);
	}
	return to;
}

NLM_EXTERN Nlm_CharPtr LIBCALL  Nlm_StrMove (char FAR *to, const char FAR *from)
{
	while (*from != '\0')
	{
		*to = *from;
		to++; from++;
	}
	*to = '\0';
	return to;
}

NLM_EXTERN Nlm_Boolean LIBCALL Nlm_StringHasNoText (Nlm_CharPtr str)

{
  Nlm_Uchar  ch;	/* to use 8bit characters in multibyte languages */

  if (str != NULL) {
    ch = *str;
    while (ch != '\0') {
      if (ch > ' ') {
        return FALSE;
      }
      str++;
      ch = *str;
    }
  }
  return TRUE;
}

NLM_EXTERN Nlm_Boolean LIBCALL Nlm_StringDoesHaveText (Nlm_CharPtr str)

{
  if (Nlm_StringHasNoText (str)) return FALSE;
  return TRUE;
}

NLM_EXTERN Nlm_CharPtr LIBCALL Nlm_TrimSpacesAroundString (Nlm_CharPtr str)

{
  Nlm_Uchar    ch;	/* to use 8bit characters in multibyte languages */
  Nlm_CharPtr  dst;
  Nlm_CharPtr  ptr;

  if (str != NULL && str [0] != '\0') {
    dst = str;
    ptr = str;
    ch = *ptr;
    while (ch != '\0' && ch <= ' ') {
      ptr++;
      ch = *ptr;
    }
    while (ch != '\0') {
      *dst = ch;
      dst++;
      ptr++;
      ch = *ptr;
    }
    *dst = '\0';
    dst = NULL;
    ptr = str;
    ch = *ptr;
    while (ch != '\0') {
      if (ch > ' ') {
        dst = NULL;
      } else if (dst == NULL) {
        dst = ptr;
      }
      ptr++;
      ch = *ptr;
    }
    if (dst != NULL) {
      *dst = '\0';
    }
  }
  return str;
}

NLM_EXTERN size_t LIBCALL Nlm_StrCnt(const char FAR *s, const char FAR *x_list)
{
	size_t	cmap[1<<CHAR_BIT];
	Nlm_Byte	c;
	size_t	u, cnt;
	const Nlm_Byte *bs = (const Nlm_Byte*)s;
	const Nlm_Byte *blist = (const Nlm_Byte*)x_list;

	if (s == NULL || x_list == NULL)
		return 0;

	for (u = 0; u < DIM(cmap); ++u)
		cmap[u] = 0;
	while (*blist != '\0')
		++cmap[*blist++];

	blist = (Nlm_BytePtr)cmap;

	cnt = 0;
	while ((c = *bs++) != '\0')
		cnt += blist[c];

	return cnt;
}

#ifndef COMP_MSC
NLM_EXTERN char * LIBCALL Nlm_StrUpper (char *string)
{
	register char *p = string;
	ASSERT(string != NULL);
	while (*p)
	{
		if (isalpha(*p))
			*p = (char)toupper(*p);
		++p;
	}
	return string;
}
#endif

#ifndef COMP_MSC
NLM_EXTERN char * LIBCALL Nlm_StrLower (char *string)
{
	register char *p = string;
	ASSERT(string != NULL);
	while (*p)
	{
		if (isalpha(*p))
			*p = (char)tolower(*p);
		++p;
	}
	return string;
}
#endif


/*  -------------------- MeshStringICmp() --------------------------------
 *  MeshStringICmp compares strings where / takes precedence to space.
 */

NLM_EXTERN Nlm_Int2 LIBCALL Nlm_MeshStringICmp (const char FAR *str1, const char FAR *str2)
{
	Nlm_Char  ch1, ch2;

	if (str1 == NULL)
	{
		if (str2 == NULL)
			return (Nlm_Int2)0;
		else
			return (Nlm_Int2)1;
	}
	else if (str2 == NULL)
		return (Nlm_Int2)-1;

	while ((*str1 >= ' ') && (*str2 >= ' ') && (TO_LOWER(*str1) == TO_LOWER(*str2)))
	{
		str1++; str2++;
	}

	ch1 = *str1;
	ch2 = *str2;
	if ((ch1 < ' ') && (ch2 < ' '))
		return (Nlm_Int2)0;
	else if (ch1 < ' ')
		return (Nlm_Int2)-1;
	else if (ch2 < ' ')
		return (Nlm_Int2)1;

	if (ch1 == '/')
	  ch1 = '\31';
	if (ch2 == '/')
	  ch2 = '\31';

	if (TO_LOWER (ch1) > TO_LOWER (ch2))
	  return (Nlm_Int2)1;
	else if (TO_LOWER (ch1) < TO_LOWER (ch2))
	  return (Nlm_Int2)(-1);
	else
	  return (Nlm_Int2)0;
}

/* StringSearch and StringISearch use the Boyer-Moore algorithm, as described
   in Niklaus Wirth, Algorithms and Data Structures, Prentice- Hall, Inc.,
   Englewood Cliffs, NJ., 1986, p. 69.  The original had an error, where
   UNTIL (j < 0) OR (p[j] # s[i]) should be UNTIL (j < 0) OR (p[j] # s[k]). */

static Nlm_CharPtr Nlm_FindSubString (const char FAR *str, const char FAR *sub,
                                      Nlm_Boolean caseCounts)

{
  int      ch;
  int      d [256];
  int      i;
  int      j;
  int      k;
  size_t   strLen;
  size_t   subLen;

  if (sub != NULL && sub [0] != '\0' && str != NULL && str [0] != '\0') {
    strLen = Nlm_StringLen (str);
    subLen = Nlm_StringLen (sub);
    if (subLen <= strLen) {
      for (ch = 0; ch < 256; ch++) {
        d [ch] = subLen;
      }
      for (j = 0; j < (int)(subLen - 1); j++) {
        ch = (int) (caseCounts ? sub [j] : TO_UPPER (sub [j]));
        if (ch >= 0 && ch <= 255) {
          d [ch] = subLen - j - 1;
        }
     }
      i = subLen;
      do {
        j = subLen;
        k = i;
        do {
          k--;
          j--;
        } while (j >= 0 &&
                 (caseCounts ? sub [j] : TO_UPPER (sub [j])) ==
                 (caseCounts ? str [k] : TO_UPPER (str [k])));
        if (j >= 0) {
          ch = (int) (caseCounts ? str [i - 1] : TO_UPPER (str [i - 1]));
          if (ch >= 0 && ch <= 255) {
            i += d [ch];
          } else {
            i++;
          }
        }
      } while (j >= 0 && i <= (int) strLen);
      if (j < 0) {
        i -= subLen;
        return (Nlm_CharPtr) (str + i);
      }
    }
  }
  return NULL;
}

NLM_EXTERN Nlm_CharPtr LIBCALL Nlm_StringSearch (const char FAR *str, const char FAR *sub)

{
  return Nlm_FindSubString (str, sub, TRUE);
}

NLM_EXTERN Nlm_CharPtr LIBCALL Nlm_StringISearch (const char FAR *str, const char FAR *sub)

{
  return Nlm_FindSubString (str, sub, FALSE);
}

NLM_EXTERN Nlm_Uint1Ptr LIBCALL Uint8ToBytes(Nlm_Uint8 value)
{
    Nlm_Uint1Ptr out_bytes;
    Nlm_Int4 i, mask = 0xFF;
    
    out_bytes = MemNew(8);
    
    for(i = 0; i < 8; i++) {
        out_bytes[i] = value & mask;
        value >>= 8;
    }
    
    return out_bytes;
}

NLM_EXTERN Nlm_Uint8 LIBCALL BytesToUint8(Nlm_Uint1Ptr bytes)
{
    Nlm_Uint8 value;
    Nlm_Int4 i;

    value = 0;
    for(i = 7; i >= 0; i--) {
        value += bytes[i];
        if(i) value <<= 8;
    }
    
    return value;
}
static Nlm_Uint8 s_StringToUint8(const char *str, const char **endptr, int *sgn)
{
    int sign = 0;  /* actual sign */
    Nlm_Uint8 limdiv, limoff, result;
    const char *s, *save;
    char c;

    /* assume error */
    *endptr = 0;
    if (!str)
        return 0;

    s = str;
    while (IS_WHITESP(*s))
        s++;
    /* empty string - error */
    if (*s == '\0')
        return 0;

    if (*sgn == 1) {
        if (*s == '-') {
            sign = 1;
            s++;
        } else if (*s == '+') {
            s++;
        }        
    }
    save = s;

    limdiv = UINT8_MAX / 10;
    limoff = UINT8_MAX % 10;
    result = 0;
    
    for (c = *s; c; c = *++s) {
        if (!IS_DIGIT(c)) {
            break;
        }
        c -= '0';
        if (result > limdiv || (result == limdiv && c > limoff)) {
            /* overflow */
            return 0;
        }
        result *= 10;
        result += c;
    }

    /* there was no conversion - error */
    if (save == s)
        return 0;

    *sgn = sign;
    *endptr = s;
    return result;
}


NLM_EXTERN Nlm_Uint8 LIBCALL Nlm_StringToUint8(const char* str, const char** endptr)
{
    int sign = 0; /* no sign allowed */
    return s_StringToUint8(str, endptr, &sign);
}


NLM_EXTERN Nlm_Int8  LIBCALL Nlm_StringToInt8(const char* str, const char** endptr)
{
    int sign = 1; /* sign allowed */
    Nlm_Uint8 result = s_StringToUint8(str, endptr, &sign);
    if (*endptr) {
        /* Check for overflow */
        if (result > (sign
                      ? -((Nlm_Uint8)(INT8_MIN + 1)) + 1
                      : (Nlm_Uint8)(INT8_MAX)))
            *endptr = 0;            
    }
    if (!*endptr)
        return 0;
    return sign ? -result : result;
}


static char *s_Uint8ToString(Nlm_Uint8 value, char *str, size_t str_size)
{
    char buf[32];
    size_t i, j;

    if (!str || str_size < 2)
        return 0;

    for (i = sizeof(buf) - 1; i > 0; i--) {
        buf[i] = (char)(value % 10 + '0');
        value /= 10;
        if (!value)
            break;
    }
    if (!i || (j = sizeof(buf) - i) >= str_size)
        return 0;
    memcpy(str, buf + i, j);
    str[j] = '\0';
    return str;
}


NLM_EXTERN char* LIBCALL Nlm_Uint8ToString(Nlm_Uint8 value, char* str, size_t str_size)
{
    return s_Uint8ToString(value, str, str_size);
}


NLM_EXTERN char* LIBCALL Nlm_Int8ToString (Nlm_Int8  value, char* str, size_t str_size)
{
    Nlm_Uint8 val;
    char *save = str;

    if (value < 0) {
        if (!str || !str_size)
            return 0;
        *str++ = '-';
        str_size--;
        val = -(Nlm_Uint8)(value + 1) + 1;
    } else
        val = value;

    return s_Uint8ToString(val, str, str_size) ? save : 0;
}


/*****************************************************************************
*
*   LabelCopy (to, from, buflen)
*   	Copies the string "from" into "to" for up to "buflen" chars
*   	if "from" is longer than buflen, makes the last character '>'
*   	always puts one '\0' to terminate the string in to
*   	to MUST be one character longer than buflen to leave room for the
*   		last '\0' if from = buflen.
*       returns number of characters transferred to "to"
*
*****************************************************************************/
NLM_EXTERN Nlm_Uint4 LIBCALL Nlm_LabelCopy (Nlm_CharPtr to, Nlm_CharPtr from, Nlm_Uint4 buflen)
{
	Nlm_Uint4 len;

	if ((to == NULL) || (from == NULL) || (buflen < 0)) return 0;
	
	if (buflen == 0)         /* this is a sign of multiple writes */
	{
		*(to-1) = '>';
		return 0;
	}
	
	len = buflen;

	while ((*from != '\0') && (buflen))
	{
		*to = *from;
		from++; to++; buflen--;
	}

	if (*from != '\0')
	{
		*(to - 1) = '>';
	}

	*to = '\0';      /* buffer is bufferlen+1 */
	return (Nlm_Uint4)(len - buflen);
}

NLM_EXTERN void LIBCALL Nlm_LabelCopyNext(Nlm_CharPtr PNTR to, Nlm_CharPtr from, Nlm_Uint4 PNTR buflen)
{
	Nlm_Uint4 diff;

	diff = Nlm_LabelCopy(*to, from, *buflen);
	*buflen -= diff; *to += diff;
	
}

/*****************************************************************************
*
*   LabelCopyExtra (to, from, buflen, prefix, suffix)
*   	Copies the string "from" into "to" for up to "buflen" chars
*   	if all together are longer than buflen, makes the last character '>'
*   	always puts one '\0' to terminate the string in to
*   	to MUST be one character longer than buflen to leave room for the
*   		last '\0' if from = buflen.
*       returns number of characters transferred to "to"
*
*   	if not NULL, puts prefix before from and suffix after from
*   		both contained within buflen
*  
*
*****************************************************************************/
NLM_EXTERN Nlm_Uint4 LIBCALL Nlm_LabelCopyExtra (Nlm_CharPtr to, Nlm_CharPtr from, Nlm_Uint4 buflen, Nlm_CharPtr prefix, Nlm_CharPtr suffix)
{
	Nlm_Int4 len, diff;

	if ((to == NULL) || (buflen < 1) || (from == NULL)) return 0;

	len = buflen;
	diff = Nlm_LabelCopy(to, prefix, buflen);
	buflen -= diff; to += diff;

	diff = Nlm_LabelCopy(to, from, buflen);
	buflen -= diff; to += diff;

	diff = Nlm_LabelCopy(to, suffix, buflen);
	buflen -= diff;

	return (Nlm_Int4)(len-buflen);
}

#define NEWLINE '\n'
#define SPACE ' '

NLM_EXTERN Nlm_CharPtr LIBCALL StrCpyPtr (char FAR *Dest, char FAR *Start, char FAR *Stop)
/* copies the string from Start (inclusive) to Stop (exclusive) to 
string Dest. Start and Stop MUST point to the same string! 
*/
{
  Nlm_CharPtr To = Dest;
  while ( *Start && ( Start < Stop ) )
    *To++ = *Start++;
  *To = NULLB;
  
  return(Dest);
}

NLM_EXTERN Nlm_CharPtr LIBCALL StrDupPtr(char FAR *Start,char FAR *Stop)
/* copies the string from Start (inclusive) to Stop (exclusive) to 
   a new string and returns its pointer. 
   Start and Stop MUST point to the same string! 
*/
{
  Nlm_CharPtr Dest, DestPtr;
  
  DestPtr = Dest = (Nlm_CharPtr)Nlm_MemGet((Stop - Start + 1),MGET_ERRPOST);
  
  while ( *Start && ( Start < Stop ) )
    *DestPtr++ = *Start++;
  *DestPtr = NULLB;
  return(Dest);
}

NLM_EXTERN Nlm_CharPtr LIBCALL SkipSpaces(char FAR *Line)
/* returns the next non-whitespace position in the line. */
{
  while( (*Line != NULLB) && isspace(*Line) )
    Line++;
  return(Line);
}


NLM_EXTERN Nlm_CharPtr LIBCALL SkipToSpace(char FAR *theString)
/* returns a pointer to the leftmost whitespace character in theString, 
   or to the trailing NULL if no whitespace is found. */
{
  while (*theString && ( ! isspace(*theString) ))
    theString++;
  return(theString);
}


NLM_EXTERN Nlm_CharPtr LIBCALL SkipChar(char FAR *theString,char Char)
/* returns a pointer to the next non-Char character in theString. */
{
  while (*theString && ( *theString == Char ) )
    theString++;
  return(theString);
}


NLM_EXTERN Nlm_CharPtr LIBCALL SkipToChar(char FAR *theString,char Char)
/* returns a pointer to leftmost instance of Char in theString, or to
   the trailing NULL if none found. */
{
  while (*theString && ( *theString != Char ) )
    theString++;
  return(theString);
}


NLM_EXTERN Nlm_CharPtr LIBCALL SkipPastChar(char FAR *theString,char Char)
/* returns a pointer to the next character after the leftmost instance
   of Char in theString, or to the trailing NULL if none found. */
{
  while (*theString && ( *theString != Char ) )
    theString++;

  if (*theString)
    return(theString+1);
  else
    return(theString);
}

NLM_EXTERN Nlm_CharPtr LIBCALL SkipToString(char FAR *theString,char FAR *Find)
/* returns a pointer to leftmost instance of Find in theString, or to
   the trailing NULL if none found. */
{
  char *FindPtr,*theStringPtr;
  
  while (*theString)
    {
      FindPtr = Find;
      theStringPtr = theString;
      while (*FindPtr && ( *FindPtr == *theStringPtr))
	{
	  FindPtr++;
	  theStringPtr++;
	}
      
      if (*FindPtr == '\0')
	return(theString);
      else
	theString++;
    }
  
  return(theString);
}


NLM_EXTERN Nlm_CharPtr LIBCALL NoCaseSkipToString(char FAR *theString,char FAR *Find)
/* returns a pointer to leftmost instance of Find in theString, 
   ignoring case, or to the trailing NULL if none found. */
{
  char *FindPtr,*theStringPtr;
  
  while (*theString)
    {
      FindPtr = Find;
      theStringPtr = theString;
      while (*FindPtr && (toupper(*FindPtr) == toupper(*theStringPtr)))
	{
	  FindPtr++;
	  theStringPtr++;
	}
      
      if (*FindPtr == '\0')
	return(theString);
      else
	theString++;
    }
  
  return(theString);
}


NLM_EXTERN Nlm_CharPtr LIBCALL SkipPastString(char FAR *theString,char FAR *Find)
/* returns a pointer to the next character after the leftmost
   instance of Find in theString, or to the trailing NULL if none found. */
{
  Nlm_CharPtr Ptr = SkipToString(theString,Find);

  if (*Ptr == '\0')
    return (Ptr);

  return (Ptr + Nlm_StringLen(Find));
}

NLM_EXTERN Nlm_CharPtr LIBCALL NoCaseSkipPastString(char FAR *theString,char FAR *Find)
/* returns a pointer to the next character after the leftmost
   instance of Find in theString, ignoring case,
   or to the trailing NULL if none found. */
{
  Nlm_CharPtr Ptr = SkipToString(theString,Find);

  if (*Ptr == '\0')
    return (Ptr);

  return (Ptr + Nlm_StringLen(Find));
}

NLM_EXTERN Nlm_CharPtr LIBCALL SkipSet(char FAR *theString,char FAR *CharSet)
/* returns a pointer to the next character in theString that is
   not in CharSet. */
{
  Nlm_CharPtr CharSetPtr;
  while (*theString)
    {
      CharSetPtr = CharSet;
      while ( *CharSetPtr && *theString != *CharSetPtr )
        CharSetPtr++;
      if ( ! *CharSetPtr )
        return (theString);
      theString++;
    }
  return(theString);
}

NLM_EXTERN Nlm_CharPtr LIBCALL SkipToSet(char FAR *theString,char FAR *CharSet)
/* returns a pointer to leftmost instance of any char in string
   CharSet in theString, or to the trailing NULL if none found. */
{
  Nlm_CharPtr CharSetPtr;
  while (*theString)
    {
      CharSetPtr = CharSet;
      while ( *CharSetPtr && (*theString != *CharSetPtr) )
        CharSetPtr++;
      if ( *CharSetPtr )
        return (theString);
      theString++;
    }
  return(theString);
}


NLM_EXTERN Nlm_Boolean LIBCALL StringSub(char FAR *theString, char Find, char Replace)
/* replaces all instances of the character Find in the given theString with
   the character Replace. It returns TRUE if any characters were 
   replaced, else FALSE.   */
{
  Nlm_Boolean Replaced = FALSE;
  while ( *theString != NULLB )
    {
      if ( *theString == Find )
        {
          *theString = Replace;
          Replaced = TRUE;
        }
      theString++;
    }
  return(Replaced);
}

NLM_EXTERN Nlm_Boolean LIBCALL StringSubSet(char FAR *theString,char FAR *FindSet, char Replace)
/* replaces all instances of any character in string FindSet found in
   theString with the character Replace.  It returns TRUE if any
   characters were replaced, else FALSE. */
{
  Nlm_CharPtr FindPtr;
  Nlm_Boolean Replaced = FALSE;

  while ( *theString != NULLB )
    {
      FindPtr = FindSet;
      while ( *FindPtr != NULLB )
        {
          if (*theString == *FindPtr )
            {
              *theString = Replace;
              Replaced = TRUE;
            }
          FindPtr++;
        }
      theString++;
    }
  return(Replaced);
}

NLM_EXTERN Nlm_Boolean LIBCALL StringSubString(char FAR *theString, char FAR *Find, char FAR *Replace, Nlm_Int4 MaxLength)
/* replaces all non-overlapping instances of the string Find in the
   string theString with the string Replace. The strings do not have to be the 
   same size. The new string is truncated at MaxLength characters
   Including the final NULL). If MaxLength is zero, the string's current
   length is presumed to be the maximum.
   It returns TRUE if any strings were replaced, else FALSE.
   */
{
  Nlm_CharPtr FindPtr,ComparePtr,StringPtr,NewString, NewStringPtr;
  Nlm_Int4 SpaceNeeded,Len;
  Nlm_Boolean Replaced = FALSE;

  if (*Find == NULLB)
    return(FALSE);

  Len = Nlm_StringLen(theString);
  SpaceNeeded = MAX( (Nlm_Int4)((Len * Nlm_StringLen(Replace) 
				 * sizeof(Nlm_Char) )
				/ Nlm_StringLen(Find) + 1),Len) + 1;

  NewStringPtr = NewString = (Nlm_CharPtr)
    Nlm_MemGet((size_t)SpaceNeeded, MGET_ERRPOST);

  StringPtr = theString;
  while (*StringPtr != NULLB)
    {
      FindPtr = Find;
      ComparePtr = StringPtr;
      while ( (*FindPtr != NULLB) && (*FindPtr == *ComparePtr) )
	{
	  FindPtr++;
	  ComparePtr++;
	}
      
      /* if we found the entire string, replace it. */
      if (*FindPtr == NULLB)
	{
	  NewStringPtr = StringMove(NewStringPtr,Replace);
	  StringPtr = ComparePtr;
	  Replaced = TRUE;
	}
      else
	/* otherwise, move on to the next character. */
	*NewStringPtr++ = *StringPtr++;
    }
  *NewStringPtr = NULLB;

  if (MaxLength <= 0)
    MaxLength = strlen(theString) + 1;

  /* Truncate the string, if necessary.*/
  if ((Nlm_Int4)strlen(NewString) >= MaxLength - 1)
    {
      NewString[MaxLength-1] = NULLB;
    }
    
  Nlm_StringCpy(theString,NewString);
  Nlm_MemFree(NewString);

  return(Replaced);
}


NLM_EXTERN Nlm_CharPtr LIBCALL StringEnd(char FAR *theString)
/* This returns a pointer to the terminating null of the given theString.
 */
{
  while (*theString != NULLB)
    theString++;
  return(theString);
}



NLM_EXTERN Nlm_Int4 LIBCALL CountChar(char FAR *theString, char Char)
/* returns the number of times a given character appears in the given
   theString. */
{
  Nlm_Int4 CharCount = 0;

  while(*theString)
    if (*theString++ == Char)
      CharCount++;

  return(CharCount);
}

NLM_EXTERN Nlm_Int4 LIBCALL CountStrings(char FAR *theString, char FAR *Find)
/*  This returns the number of non-overlapping instances of Find
    in theString. */
{
  Nlm_Int4 count = 0;
  Nlm_Int4 Len = Nlm_StringLen(Find);
  Nlm_CharPtr Ptr = theString;

  for(;;)
    {
      Ptr = SkipToString(Ptr,Find);
      if (*Ptr == NULLB)
        break;

      count++;
      Ptr += Len;
    }

  return count;
}

NLM_EXTERN Nlm_Int4 LIBCALL CountSet(char FAR *theString, char FAR *Set)
/* returns the number of times any one of a given set of characters 
   appears in the given theString. */
{
  Nlm_Int4 CharCount = 0;
  Nlm_CharPtr SetPtr;

  while(*theString)
    {
      SetPtr = Set;

      while(*SetPtr)
	{
	  if (*theString == *SetPtr)
	    {
	      CharCount++;
	      break;
	    }
	  SetPtr++;
	}

      theString++;
    }

  return(CharCount);
}


NLM_EXTERN Nlm_CharPtr LIBCALL StripSpaces(char FAR *Line)
/* returns a pointer to the next nonwhitespace character in the string
and also removes trailing whitespaces. */
{
  Nlm_CharPtr Ptr;

  Line = SkipSpaces(Line);
  if (*Line != NULLB)
    {
      Ptr = StringEnd(Line) - 1;
      while ( (Ptr > Line) && isspace(*Ptr) )
        Ptr--;
      *(Ptr+1) = NULLB;
    }

  return(Line);
}

NLM_EXTERN void LIBCALL CleanSpaces(char FAR *Line)
/* This in-place deletes all leading and trailing whitespace and replaces
   all instances of one or more whitespace characters with one space,
   or one newline if the whitespace contained a newline.
   */
{
  Nlm_Boolean HasNewLine;
  Nlm_CharPtr LinePtr = SkipSpaces(Line);

  while (*LinePtr )
    {
      while ( *LinePtr &&  ! isspace (*LinePtr) )
        *Line++ = *LinePtr++;

      HasNewLine = FALSE;
      while ( isspace(*LinePtr) )
        {
          if (*LinePtr == NEWLINE)
            HasNewLine = TRUE;
          LinePtr++;
        }

      if (HasNewLine)
        *Line++ = NEWLINE;
      else
        if (*LinePtr)
          *Line++ = SPACE;
    }
  *Line = NULLB;
}


NLM_EXTERN Nlm_Int4 LIBCALL StringDiff(char FAR *This, char FAR *That)
/* This returns the character offset where the strings differ, or -1 if
   the strings are the same. */
{
  Nlm_Int4 Diff = 0;

  while (*This && (*This == *That) )
    {
      Diff++;
      This++;
      That++;
    }

  if (*This || *That)
    return(Diff);
  else
    return (-1);
}

NLM_EXTERN Nlm_Int4 LIBCALL StringDiffNum(char FAR *This, char FAR *That, Nlm_Int4 NumChars)
/* returns the character offset where the strings differ, examining only
   the first NumChars Characters. returns -1 if the two substrings 
   examined are equivalent. */
{
  Nlm_Int4 Diff = 0;

  while ((NumChars > 0) && *This &&  (*This == *That) )
    {
      This++;
      That++;
      NumChars--;
      Diff++;
    }

  if ( NumChars && (*This || *That) )
    return(Diff);
  else 
    return(-1);
}

NLM_EXTERN void LIBCALL TruncateString(char FAR *theString, Nlm_Int4 Length)
/* truncates a string to fit into an array of Length characters, 
   including the trailing NULL. */
{
  if((Nlm_Int4)strlen(theString) >= Length - 1)
    theString [Length-1] = NULLB;
}

NLM_EXTERN Nlm_CharPtr LIBCALL TruncateStringCopy(char FAR *theString, Nlm_Int4 Length)
/* Returns a new string consisting of at most the first length-1 
   characters of theString. */
{
  Nlm_CharPtr NewString = (Nlm_CharPtr)MemNew((size_t)Length);

  StrNCpy(NewString, theString, (size_t)(Length - 1));
  NewString[Length-1] = NULLB;
  return NewString;
}


NLM_EXTERN Nlm_Int4 LIBCALL BreakString(char FAR *theString, Nlm_CharPtr PNTR Words)
/* Breaks up a string at each occurrence of one or more spaces, placing
   each substring obtained into the array Words and returning the 
   number of substrings obtained. 
   */
{
  Nlm_CharPtr Start, Stop, *WordPtr;

  Start = SkipSpaces(theString);
  WordPtr = Words;

  while (*Start)
    {
      Stop = SkipToSpace(Start);
      StrCpyPtr(*WordPtr++,Start,Stop);
      Start = SkipSpaces(Stop);
    }

  return((Nlm_Int4) (WordPtr - Words) );
}

NLM_EXTERN void LIBCALL DeleteChar(char FAR *theString,char Delete)
/* removes all instances of the character Delete from the theString. */
{
  Nlm_CharPtr StringPtr = theString;

  while(*StringPtr)
    {
      if (*StringPtr !=  Delete)
	*theString++ = *StringPtr++;
      else
	StringPtr++;
    }

  *theString = NULLB;
}



NLM_EXTERN Nlm_CharPtr LIBCALL Nlm_StringPrintable(const Nlm_Char PNTR str,
                                                   Nlm_Boolean rn_eol)
{
  size_t str_len = 0;
  const Nlm_Char PNTR s;
  Nlm_CharPtr new_str, new_s;

  if ( !str )
    return NULL;

  if ( rn_eol )
    {
      for (s = str;  *s;  s++)
        if (*s == '\n')
          str_len += 2;
        else if (*s == '\t'  ||  IS_PRINT(*s))
          str_len++;
    }
  else
    {
      for (s = str;  *s;  s++)
        if (*s == '\n'  ||  *s == '\t'  ||  IS_PRINT(*s))
          str_len++;
    }

  new_str = (Nlm_CharPtr)Nlm_MemGet(str_len+1, MGET_ERRPOST);
  if ( !new_str )
    return NULL;

  if ( rn_eol )
    {
      for (s = str, new_s = new_str;  *s;  s++)
        if (*s == '\n')
          {
            *new_s++ = '\r';
            *new_s++ = '\n';
          }
        else if (*s == '\t'  ||  IS_PRINT(*s))
          *new_s++ = *s;
    }
  else
    {
      for (s = str, new_s = new_str;  *s;  s++)
        if (*s == '\n'  ||  *s == '\t'  ||  IS_PRINT(*s))
          *new_s++ = *s;
    }
  *new_s = '\0';

  return new_str;
}
        
  
/*****************************************************************************
 *  Text Formatting Functions
 ****************************************************************************/

#define MAX_NO_DASH 2
#define MIN_LEAD    3
#define MIN_TAIL    1

#define SPACE ' '

/* Act like a regular memcpy but replace all space symbols to #SPACE
 */
static void x_memcpy(Nlm_Char FAR PNTR targ, const Nlm_Char FAR PNTR src,
                     size_t n)
{
  for ( ;  n--;  src++)
    {
      ASSERT ( *src );
      if ( IS_WHITESP(*src) )
        *targ++ = SPACE;
      else
        *targ++ = *src;
    }
}


/* Set of conditions when the decision on the line breaking can be
 * made having only 2 symbols("ch0" and "ch1" -- to the left and to the
 * right of the break, respectively)
 */
static int can_break(Nlm_Char ch0, Nlm_Char ch1)
{
  if (ch1 == '\0'  ||
      IS_WHITESP(ch1)  ||  IS_WHITESP(ch0))
    return 1;

  switch ( ch1 )
    {
    case '(':
    case '[':
    case '{':
      return 1;
    }

  switch ( ch0 )
    {
    case '-':
    case '+':
    case '=':
    case '&':
    case '|':
    case ')':
    case '}':
    case ']':
      if (ch1 != ch0)
        return 1;
      break;
  
    case '\\':
    case '/':
    case '*':
    case ';':
    case ':':
    case ',':
      return 1;

    case '?':
    case '!':
    case '.':
      if (ch1 != '.'  &&  ch1 != '?'  &&  ch1 != '!')
        return 1;
      break;
    }

  return 0;
}


NLM_EXTERN Nlm_CharPtr LIBCALL Nlm_text2stream(const Nlm_Char FAR PNTR str)
{
  int on_space = 0;
  Nlm_CharPtr line, s;

  if ( !str )
    return NULL;

  while (*str  &&  IS_WHITESP( *str ))
    str++;
  if ( !*str )
    return NULL;

  s = line = (Nlm_CharPtr) Nlm_MemNew(Nlm_StringLen(str) + 1);

  for (  ;  *str;  str++)
    {
      if ( IS_WHITESP(*str) )
        {
          if (*str == '\n')
            *s = '\n';
          on_space = 1;
        }
      else
        {
          if ( on_space ) {
            if (*s == '\n'  &&
                s - line > 1  &&  *(s-1) == '-'  &&  IS_ALPHA(*(s-2)))
              {
                *s = '\0';
                s--;  /* eat dash before end-of-line, merge the broken word */
              }
            else
              *s++ = SPACE;

            *s++ = *str;
            on_space = 0;
          }
          else
            *s++ = *str;
        }
    }
  *s = '\0';

  return (Nlm_CharPtr) realloc(line, Nlm_StringLen(line) + 1);
}


NLM_EXTERN size_t Nlm_stream2text(const Nlm_Char FAR PNTR str, size_t max_col,
                                  int PNTR dash)
{
  const Nlm_Char FAR PNTR s;
  const Nlm_Char FAR PNTR sb; /* the nearest breakable position */
  size_t n_lead = 0;
  size_t n_tail = 0;

  size_t len = Nlm_StringLen( str );
  len = max_col < len ? max_col : len;

  *dash = 0;
  if (len == 0  ||  can_break(str[len-1], str[len]))
    return len;

  /* go to the beginning of the last completely fit word */
  for (sb = &str[len-1];
       sb != str  &&  !IS_WHITESP(*sb)  &&  !can_break(*sb, *(sb+1));
       sb--) continue;
  while (sb != str  &&  IS_WHITESP(*sb))
    sb--;

  if (sb == str)
    { /* the first word is longer than "max_col" */
      if (len > MAX_NO_DASH  &&  IS_ALPHA(str[len-1])  &&  IS_ALPHA(str[len]))
        *dash = 1;  /* recommend use dash in the place of last symbol */

      return len;
    }

  /* decide of whether and how to break the last alphabet word */

  /*  count the lead and the tail of the last non-fit word */
  for (s = &str[len];  *s != '\0'  &&  IS_ALPHA(*s);  s++, n_tail++) continue;
  for (s = &str[len-1];  IS_ALPHA(*s);  s--, n_lead++) continue;
  ASSERT ( s > str );

  /* try to "move" symbols from lead in the sake of tail */
  while (n_lead > MIN_LEAD  &&  n_tail < MIN_TAIL)  {
    n_lead--;
    n_tail++;
  }

  if (n_lead < MIN_LEAD  ||  n_tail < MIN_TAIL)
    { /* no luck this time -- move the whole non-fit word to the next line */
      return (sb - str + 1);
    }
  else
    {
      *dash = 1;
      return (s - str + n_lead + 1);
    }
}


NLM_EXTERN Nlm_CharPtr LIBCALL Nlm_rule_line(const Nlm_Char FAR PNTR str,
                                             size_t len,
                                             enumRuleLine method)
{
  size_t str_len;
  size_t n_space;

  /* allocate and initialize the resulting string */
  Nlm_CharPtr s = (Nlm_CharPtr) Nlm_MemNew(len + 1);
  Nlm_MemSet(s, SPACE, len);
  s[len] = '\0';

  /* skip leading and trailing spaces */
  while ( IS_WHITESP(*str) )
    str++;
  if ( !*str )
    return s;
  for (str_len = Nlm_StringLen( str );  IS_WHITESP(str[str_len-1]); str_len--) continue;


  /* truncate the original string if doesn't fit */
  if (len <= str_len) {
    x_memcpy(s, str, len);
    return s;
  }

  n_space = len - str_len;
  switch ( method )
    {
    case RL_Left:
      {
        x_memcpy(s, str, str_len);
        break;
      }
    case RL_Right:
      {
        x_memcpy(s + n_space, str, str_len);
        break;
      }
    case RL_Spread:
      {
        size_t n_gap = 0;

        int prev_space = 0;
        const Nlm_Char FAR PNTR _str = str;
        size_t i = str_len;
        for ( ;  i--;  _str++)
          {
            ASSERT ( *_str );
            if ( IS_WHITESP(*_str) )
              {
                if ( !prev_space ) {
                  n_gap++;
                  prev_space = 1;
                }
                n_space++;
              }
            else
              prev_space = 0;
          }
        ASSERT ( !prev_space );

        if ( n_gap )
          {
            size_t n_div = n_space / n_gap;
            size_t n_mod = n_space % n_gap;

            Nlm_CharPtr _s = s;
            for (_str = str;  *_str; )
              {
                if ( !IS_WHITESP( *_str ) )
                  *_s++ = *_str++;
                else if ( n_space )
                  {
                    size_t n_add = n_div;
                    if (n_mod > 0) {
                      n_add++;
                      n_mod--;
                    }
                    n_space -= n_add;
                    while ( n_add-- )
                      *_s++ = SPACE;

                    for (_str++;  IS_WHITESP(*_str);  _str++) continue;
                  }
                else
                  break;
              }
            ASSERT ( _s == s + len );
            break;
          }  /* else -- use RL_Center */
      }

    case RL_Center:
      {
        x_memcpy(s + n_space/2, str, str_len);
        break;
      }

    default:
      ASSERT ( 0 );
      Nlm_MemFree( s );
      return 0;
    }

  return s;
}


#ifdef TEST_TEXT_FMT
Nlm_Int2 Nlm_Main( void )
{
#define MAX_COL 24
  Nlm_Int4     argc = Nlm_GetArgc();
  Nlm_CharPtr *argv = Nlm_GetArgv();

  Nlm_Char x_str[MAX_COL * 1024];
  FILE *fp = NULL;
  int n_read;

  FILE *logfile = Nlm_FileOpen("stdout", "w");
  ASSERT ( logfile );

  if (argc < 2)  {
    fprintf(logfile, "Usage: %s <file_name>\n", argv[0]);
    return 1;
  }

  fp = Nlm_FileOpen(argv[1], "rb");
  if ( !fp ) {
    fprintf(logfile, "Cannot open file: \"%s\"\n", argv[1]);
    return 2;
  }

  n_read = FileRead(x_str, 1, sizeof(x_str) - 1, fp);
  if (n_read < 2 * MAX_COL) {  
    fprintf(logfile, "Too few bytes read from \"%s\": %d\n", argv[1], n_read);
    return 3;
  }

  ASSERT ( n_read < sizeof(x_str) );
  x_str[n_read] = '\0';

  {{
    size_t max_col = MAX_COL - 1;
    int    inc     = 1;
    enumRuleLine rule_method = RL_Center;

    Nlm_CharPtr str = text2stream( x_str );
    Nlm_CharPtr text_str = str;
    if ( !str ) {  
      fprintf(logfile, "No non-space symbols in \"%s\"\n", argv[1]);
      return 4;
    }
    
    while (*str != '\0')
      {
        Nlm_Char s[MAX_COL + 1];
        int dash = -12345;
        size_t n_print;

        while (*str  &&  IS_WHITESP(*str))
          str++;

        n_print = stream2text(str, max_col, &dash);
        ASSERT ( (max_col > 0  &&  str  &&  *str)  ==  (n_print > 0) );
        ASSERT ( n_print <= max_col );
        ASSERT ( dash != -12345 );

        Nlm_MemCpy(s, str, n_print);
        s[n_print] = '\0';
        ASSERT ( dash == 0  ||  n_print > 1 );
        if ( dash )
          s[--n_print] = '-';

        {{
          Nlm_CharPtr ruled_str = rule_line(s,
                                            (rule_method == RL_Right ||
                                             rule_method == RL_Center ) ?
                                            MAX_COL : max_col,
                                            rule_method);
          fprintf(logfile, "|%s|\n", ruled_str);
          Nlm_MemFree( ruled_str );
        }}
        
        str += n_print;

        if (max_col == 0  ||  max_col == MAX_COL)
          inc = -inc;
        max_col += inc;

        if (max_col == 0)
          if (rule_method == RL_Spread)
            rule_method = RL_Left;
          else
            rule_method++;
      }

    Nlm_MemFree( text_str );
  }}

  Nlm_FileClose( logfile );
  Nlm_FileClose( fp );
  return 0;
}
#endif  /* TEST_TEXT_FMT */


#ifdef TEST_INT8_CONVERSION
Nlm_Int2 Nlm_Main( void )
{
    char buffer[100];
    char *s;
    const char *p;
    Nlm_Int8 i;
    Nlm_Uint8 j;

    s = Nlm_Int8ToString(0, buffer, sizeof(buffer));
    assert(s != 0);
    printf("0 = %s\n", s);
    s = Nlm_Int8ToString(1, buffer, sizeof(buffer));
    assert(s != 0);
    printf("1 = %s\n", s);
    s = Nlm_Int8ToString(1222222, buffer, sizeof(buffer));
    assert(s != 0);
    printf("1222222 = %s\n", s);
    s = Nlm_Int8ToString(-15, buffer, sizeof(buffer));
    assert(s != 0);
    printf("-15 = %s\n", s);
    s = Nlm_Int8ToString(-15555555, buffer, sizeof(buffer));
    assert(s != 0);
    printf("-15555555 = %s\n", s);
    s = Nlm_Int8ToString(INT8_MAX, buffer, sizeof(buffer));
    assert(s != 0);
    printf("INT8_MAX = %s\n", s);
    s = Nlm_Int8ToString(INT8_MIN, buffer, sizeof(buffer));
    assert(s != 0);
    printf("INT8_MIN = %s\n", s);
    s = Nlm_Int8ToString(UINT8_MAX, buffer, sizeof(buffer));
    assert(s != 0);
    printf("UINT8_MAX = %s\n", s);
    s = Nlm_Uint8ToString(UINT8_MAX, buffer, sizeof(buffer));
    assert(s != 0);
    printf("UINT8_MAX = %s\n", s);

    strcpy(buffer, "9223372036854775807");
    i = Nlm_StringToInt8(buffer, &p);
    assert(p == buffer + strlen(buffer));
    s = Nlm_Int8ToString(i, buffer + strlen(buffer) + 1,
                         sizeof(buffer) - strlen(buffer) - 1);
    assert(s != 0);
    assert(strcmp(buffer, s) == 0);
    printf("INT8_MAX input Ok\n");
    i++;
    s = Nlm_Int8ToString(i, buffer, sizeof(buffer));
    assert(s != 0);
    printf("INT8_MAX+1 = %s\n", s);

    strcpy(buffer, "-9223372036854775808");
    i = Nlm_StringToInt8(buffer, &p);
    assert(p == buffer + strlen(buffer));
    s = Nlm_Int8ToString(i, buffer + strlen(buffer) + 1,
                         sizeof(buffer) - strlen(buffer) - 1);
    assert(s != 0);
    assert(strcmp(buffer, s) == 0);
    printf("INT8_MIN input Ok\n");
    i--;
    s = Nlm_Int8ToString(i, buffer, sizeof(buffer));
    assert(s != 0);
    printf("INT8_MIN-1 = %s\n", s);

    strcpy(buffer, "18446744073709551615");
    j = Nlm_StringToUint8(buffer, &p);
    assert(p == buffer + strlen(buffer));
    s = Nlm_Uint8ToString(j, buffer + strlen(buffer) + 1,
                          sizeof(buffer) - strlen(buffer) - 1);
    assert(s != 0);
    assert(strcmp(buffer, s) == 0);
    printf("UINT8_MAX input Ok\n");
    j++;
    s = Nlm_Uint8ToString(j, buffer, sizeof(buffer));
    assert(s != 0);
    printf("UINT8_MAX+1 = %s\n", s);

    strcpy(buffer, "1234567890abcdef0123546");
    i = Nlm_StringToInt8(buffer, &p);
    assert(p != 0);
    s = Nlm_Int8ToString(i, buffer + strlen(buffer) + 1,
                         sizeof(buffer) - strlen(buffer) - 1);
    assert(s != 0);
    printf("Out of %s only %.*s was accepted as input for Int8 %s\n",
           buffer, (int)(p - buffer), buffer, s);

    strcpy(buffer, "-987654321234567890abcdef0123546");
    i = Nlm_StringToInt8(buffer, &p);
    assert(p != 0);
    s = Nlm_Int8ToString(i, buffer + strlen(buffer) + 1,
                         sizeof(buffer) - strlen(buffer) - 1);
    assert(s != 0);
    printf("Out of %s only %.*s was accepted as input for Int8 %s\n",
           buffer, (int)(p - buffer), buffer, s);

    strcpy(buffer, "987654321234567890abcdef0123546");
    j = Nlm_StringToUint8(buffer, &p);
    assert(p != 0);
    s = Nlm_Uint8ToString(j, buffer + strlen(buffer) + 1,
                          sizeof(buffer) - strlen(buffer) - 1);
    assert(s != 0);
    printf("Out of %s only %.*s was accepted as input for Uint8 %s\n",
           buffer, (int)(p - buffer), buffer, s);

    strcpy(buffer, "-987654321234567890abcdef0123546");
    j = Nlm_StringToUint8(buffer, &p);
    assert(p == 0);
    printf("Conversion of %s (negative) to Uint8 caused error\n", buffer);

    strcpy(buffer, "9223372036854775808");
    i = Nlm_StringToInt8(buffer, &p);
    assert(p == 0);
    printf("Conversion of %s (INT8_MAX + 1) to Int8 caused error\n", buffer);

    strcpy(buffer, "-9223372036854775809");
    i = Nlm_StringToInt8(buffer, &p);
    assert(p == 0);
    printf("Conversion of %s (INT8_MIN - 1) to Int8 caused error\n", buffer);

    strcpy(buffer, "18446744073709551616");
    j = Nlm_StringToUint8(buffer, &p);
    assert(p == 0);
    printf("Conversion of %s (UINT8_MAX + 1) to Uint8 caused error\n", buffer);

    printf("All tests succeeded\n");

    return 0;
}
#endif /* TEST_INT8_CONVERSION */