File: grcollect.c

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

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

#include "io/iof.h"
#include "io/scanarg.h"
#include "io/tokenize.h"
#include "cache.h"
#include "statistics.h"
#include "str.h"

#include "longhelp.h"
#include "fitsh.h"

#ifdef  HAVE_NO_CC_EXTENSION 
#define __extension__ 
#endif 

/*****************************************************************************/

#define		STAT_NONE		0
#define		STAT_COUNT		1
#define		STAT_MEAN		2
#define		STAT_MEANDEV		3
#define		STAT_MIN		4
#define		STAT_MAX		5
#define		STAT_SUM		6
#define		STAT_SUM2		7

#define		STAT_PURE_CUMULATIVE	7

#define		STAT_MEDIAN		8
#define		STAT_MEDIANDEV		9
#define		STAT_MEANMEDDEV		10
#define		STAT_MEDIANMEDDEV	11
#define		STAT_MODE		12
#define		STAT_MODEDEV		13
#define		STAT_MODEMEDDEV		14

#define		STAT_RCOUNT		21
#define		STAT_RMEAN		22
#define		STAT_RMEANDEV		23
#define		STAT_RMIN		24
#define		STAT_RMAX		25
#define		STAT_RSUM		26
#define		STAT_RSUM2		27
#define		STAT_RMEDIAN		28
#define		STAT_RMEDIANDEV		29
#define		STAT_RMEANMEDDEV	30
#define		STAT_RMEDIANMEDDEV	31
#define		STAT_RMODE		32
#define		STAT_RMODEDEV		33
#define		STAT_RMODEMEDDEV	34

typedef struct
 {	char    *name;
	int     code;
 } dataname;

static dataname datanamelist[]=
 {	{ "count",		STAT_COUNT		},
	{ "mean",		STAT_MEAN		},
	{ "average",		STAT_MEAN		},
	{ "avg",		STAT_MEAN		},
	{ "stddev",		STAT_MEANDEV		},
	{ "sigma",		STAT_MEANDEV		},
	{ "meandev",		STAT_MEANDEV		},
	{ "meanstddev",		STAT_MEANDEV		},
	{ "min",		STAT_MIN		},
	{ "max",		STAT_MAX		},
	{ "sum",		STAT_SUM		},
	{ "sum2",		STAT_SUM2		},

	{ "median",		STAT_MEDIAN		},
	{ "mediandev",		STAT_MEDIANDEV		},
	{ "medianstddev",	STAT_MEDIANDEV		},
	{ "meanmeddev",		STAT_MEANMEDDEV		},
	{ "medianmeddev",	STAT_MEDIANMEDDEV	},
	{ "mode",		STAT_MODE		},
	{ "modedev",		STAT_MODEDEV		},
	{ "modestddev",		STAT_MODEDEV		},
	{ "modemeddev",		STAT_MODEDEV		},

	{ "rcount",		STAT_RCOUNT		},
	{ "rmean",		STAT_RMEAN		},
	{ "raverage",		STAT_RMEAN		},
	{ "ravg",		STAT_RMEAN		},
	{ "rstddev",		STAT_RMEANDEV		},
	{ "rsigma",		STAT_RMEANDEV		},
	{ "rmeandev",		STAT_RMEANDEV		},
	{ "rmeanstddev",	STAT_RMEANDEV		},
	{ "rmin",		STAT_RMIN		},
	{ "rmax",		STAT_RMAX		},
	{ "rsum",		STAT_RSUM		},
	{ "rsum2",		STAT_RSUM2		},
	{ "rmedian",		STAT_RMEDIAN		},
	{ "rmediandev",		STAT_RMEDIANDEV		},
	{ "rmedianstddev",	STAT_RMEDIANDEV		},
	{ "rmeanmeddev",	STAT_RMEANMEDDEV	},
	{ "rmedianmeddev",	STAT_RMEDIANMEDDEV	},
	{ "rmode",		STAT_RMODE		},
	{ "rmodedev",		STAT_RMODEDEV		},
	{ "rmodestddev",	STAT_RMODEDEV		},
	{ "rmodemeddev",	STAT_RMODEDEV		},
	{ NULL,			-1			}
 };

static int	statlist_default[] = { STAT_COUNT,STAT_MEAN,STAT_MEANDEV,-1 };

/*****************************************************************************/

typedef struct
 {	char	*key;
	int	id;
 } key;

typedef struct lookupkey lookupkey;

struct lookupkey
 {	lookupkey	*lookups;
	key		value;
 };

/*****************************************************************************/

typedef struct
 {	size_t	offset;		/* offset in collectbuffer->buffer	*/
	int	key;		/* position of the base column		*/
	int	file;		/* infiles[] array index		*/
	char	*keyptr;	/* pointer to base column		*/
 } line;

typedef struct
 {	lookupkey	lk;
	char		*buffer;
	size_t		size,asize;
	line		*lines;
	int		nline;
	int		is_comment;
	char		**comments;
	int		argc;
	char		**argv;
 } collectbuffer;

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#define			REJECTION_CENTER	0x03
#define			REJECTION_C_NONE	0
#define			REJECTION_C_MEAN	1
#define			REJECTION_C_MEDIAN	2
#define			REJECTION_C_MODE	3
#define			REJECTION_MAGNITUDE	0x0C
#define			REJECTION_M_STDDEV	0
#define			REJECTION_M_MEDDEV	4
#define			REJECTION_M_ABSOLUTE	8

typedef struct
 {	int		center;
	double		magnitude;
	int		iterations;
 } rejection;

typedef struct
 {	int		index;
	rejection	r;
 } column;

typedef struct
 {	int	id;
	int	flag;
 } tmpvaluecommon;

typedef struct
 {	char	*key;
	int	id;
	int	count;
 } statfieldcommon;

#define		N_CENTER		3	/* mean, median, mode	     */
#define		C_MEAN			0
#define		C_MEDIAN		1
#define		C_MODE			2
#define		N_DEVIATION		3	/* std, med, abs	     */
#define		D_STD			0
#define		D_MED			1
#define		D_ABS			2

typedef struct
 {	double	center[N_CENTER];
	double	deviation[N_CENTER][N_DEVIATION];
 } cendev;
typedef struct
 {	int	count;
	double	sum,sum2,min,max;
 } bcumul;

typedef struct
  {	double	sum,sum2,min,max;		/* cumulative		     */
	double	median,mediandev;		/* normal non-cumulative 1)  */
	double	meanmeddev,medianmeddev;	/* normal non-cumulative 2)  */
	double	mode,modedev,modemeddev;	/* normal non-cumulative 3)  */
	int	rcount;				/* rej'd  non-cumulative 1)  */
	double	rsum,rsum2,rmin,rmax;		/* rej'd  non-cumulative 2)  */
	double	rmedian,rmediandev;		/* rej'd  non-cumulative 3)  */
	double	rmeanmeddev,rmedianmeddev;	/* rej'd  non-cumulative 4)  */
	double	rmode,rmodedev,rmodemeddev;	/* rej'd  non-cumulative 5)  */
 } statfielddata;

typedef struct
 {	bcumul	nb;
	cendev	nc;
	bcumul	rb;
	cendev	rc;
 } statfielddata2;

typedef struct
 {	lookupkey	lk;		/* hash tree for cumulative stat's   */
	void		*fields;	/* keys				     */
	int		nfield,afield;	/* number of keys (+ alloc'ed)	     */
	char		*tmptemplate;	/* template name of temporary file   */
	int		fh;		/* file handle of the temporary file */
	int		nstat;		/* number of columns for making stat */
	column		*colstats;	/* column spec info (for rejection)  */
	void		*tmps;		/* list of temporary values, cached  */
	size_t		ntmp;		/* number of temporary values.       */
	size_t		atmp;		/* number of allocated entries (tmp) */
	off_t		wtmp;		/* num of written temp entries	     */
	size_t		mxtmp;		/* max number of temporary values    */
	size_t		maxmem;		/* max memory in bytes		     */
 } collectstat;

/*****************************************************************************/

int	is_verbose,is_comment;
char	*progbasename;

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

int fprint_error(char *expr,...)
{
 va_list	ap;
 fprintf(stderr,"%s: error: ",progbasename);
 va_start(ap,expr);
 vfprintf(stderr,expr,ap);
 va_end(ap);
 fprintf(stderr,"\n");
 return(0);
}

int fprint_warning(char *expr,...)
{
 va_list	ap;
 fprintf(stderr,"%s: warning: ",progbasename);
 va_start(ap,expr);
 vfprintf(stderr,expr,ap);
 va_end(ap);
 fprintf(stderr,"\n");
 return(0);
}



/*****************************************************************************/

int	*get_stat_list(char *statstr)
{
 char	*wstr,*cmd[16];
 int	i,n,*ret,j;

 wstr=strdup(statstr);
 n=tokenize_char(statstr,cmd,',',15);

 if ( n <= 0 )
  {	free(wstr);
	return(NULL);
  }
 ret=(int *)malloc(sizeof(int)*(n+1));

 for ( i=0 ; i<n ; i++ )
  {	for ( j=0 ; datanamelist[j].name != NULL ; j++ )
	 {	if ( strcmp(cmd[i],datanamelist[j].name)==0 )	break;	}
	if ( datanamelist[j].name==NULL || datanamelist[j].code<0 )
	 {	free(ret);
		free(wstr);
	 	return(NULL);
	 }
	else	ret[i]=datanamelist[j].code;
  }
 ret[n]=-1;

 free(wstr);

 return(ret);
}

/*****************************************************************************/

#define		HASH_BITS		2

int lookup_get_hash_bit(char *kstr,int offset)
{
 int	k;
#if HASH_BITS == 8
 k=(unsigned char)kstr[offset];
#elif HASH_BITS == 4
 int	w;
 w=(unsigned char)kstr[offset/2];
 if ( offset%2==0 )	k=(w>>4) & 0x0f;
 else			k=(w>>0) & 0x0f;
#elif HASH_BITS == 2 
 int	w;
 w=(unsigned char)kstr[offset/4];
 k=(w>>(2*(3-(offset%4)))) & 0x03;
#elif HASH_BITS == 1 
 int	w;
 w=(unsigned char)kstr[offset/8];
 k=(w>>(7-(offset%8))) & 0x01;
#else
#error "Invalid hash bit value"
#endif
 return(k);
}

int lookup_get_end(char *kstr,int offset)
{
 int	k;
#if HASH_BITS == 8
 k=(unsigned char)kstr[offset];
#elif HASH_BITS == 4
 k=(unsigned char)kstr[offset/2];
#elif HASH_BITS == 2 
 k=(unsigned char)kstr[offset/4];
#elif HASH_BITS == 1 
 k=(unsigned char)kstr[offset/8];
#else
#error "Invalid hash bit value"
#endif
 return(k);
}

key * lookup_search_or_add_key(lookupkey *lk,char *kstr,int offset)
{
 int		k,w,o;
 key		*ret,tmp;
 char		*wkey;
 lookupkey	*wl;

 k=lookup_get_hash_bit(kstr,offset);

 if ( lk->lookups==NULL )		/* empty set */
  {	lk->lookups=(lookupkey *)malloc(sizeof(lookupkey)*(1<<HASH_BITS));
	memset(lk->lookups,0,sizeof(lookupkey)*(1<<HASH_BITS));
	lk->lookups[k].lookups=NULL;
	lk->lookups[k].value.key=strdup(kstr);
	ret=&lk->lookups[k].value;
  }
 else if ( lk->lookups[k].lookups != NULL )
  {	ret=lookup_search_or_add_key(&lk->lookups[k],kstr,offset+1);	}
 else if ( lk->lookups[k].value.key==NULL )
  {	lk->lookups[k].value.key=strdup(kstr);
	ret=&lk->lookups[k].value;
  }
 else if ( strcmp(lk->lookups[k].value.key,kstr)==0 )
  {	ret=&lk->lookups[k].value;		}
 else
  {	wkey=lk->lookups[k].value.key;
	memcpy(&tmp,&lk->lookups[k].value,sizeof(key));
	memset(&lk->lookups[k].value,0,sizeof(key));
	wl=&lk->lookups[k];
	for ( o=offset+1,ret=NULL ; lookup_get_end(wkey,o) || lookup_get_end(kstr,o) ; o++ )
	 {	wl->lookups=(lookupkey *)malloc(sizeof(lookupkey)*(1<<HASH_BITS));
		memset(wl->lookups,0,sizeof(lookupkey)*(1<<HASH_BITS));
		k=lookup_get_hash_bit(kstr,o);
		w=lookup_get_hash_bit(wkey,o);
		if ( k==w )
			wl=&wl->lookups[k];
		else
		 {	memcpy(&wl->lookups[w].value,&tmp,sizeof(key));
			wl->lookups[k].value.key=strdup(kstr);
			ret=&wl->lookups[k].value;
			break;
		 }
	 }
  }
 return(ret);
}

int lookup_free_node(lookupkey *lk)
{
 int		i;
 lookupkey	*wl;
 if ( lk==NULL || lk->lookups==NULL )
	return(0);
 for ( i=0 ; i<(1<<HASH_BITS) ; i++ )
  {	wl=&lk->lookups[i];
	if ( wl->lookups != NULL )
		lookup_free_node(wl);
	else if ( wl->value.key != 0 )
		free(wl->value.key);
  }
 free(lk->lookups);
 return(0);
}

/******************************************************************************
int lookup_dump(FILE *fw,lookupkey *lk,int depth)
{
 int	i,j;

 if ( lk==NULL || lk->lookups==NULL )
	return(0);
 for ( i=0 ; i<256 ; i++ )
  {	if ( lk->lookups[i].value.key != NULL )
	 {	for ( j=0 ; j<depth ; j++ )
		 {	fprintf(fw,"+ ");		}
		fprintf(fw,"%s\n",lk->lookups[i].value.key);
	 }
	else if ( lk->lookups[i].lookups != NULL )
		lookup_dump(fw,&lk->lookups[i],depth+1);
  }
 return(0);
}

int lookup_test(void)
{
 lookupkey	lk;

 memset(&lk,0,sizeof(lookupkey));

 lookup_search_or_add_key(&lk,"B1",0);
 lookup_search_or_add_key(&lk,"B2",0);
 lookup_search_or_add_key(&lk,"A2",0);
 lookup_search_or_add_key(&lk,"B2c",0);

 lookup_dump(stderr,&lk,0);

 return(0);
}
******************************************************************************/

/*****************************************************************************/

int fprint_grcollect_usage(FILE *fw)
{
 fprintf(fw,
"Usage:\tgrcollect [-h|--help|--long-help|--wiki-help] [--version[-short]]\n"
"\t[-V|--verbose]\n"
"Options for data collection and transposition:\n"
"\t<input> [<input> ...] -c|--col-base <> [-t|--tmpdir <tmp-dir>]\n"
"\t{-b|--basename <base-%%b-name>|-x|--extension <xtn> -p|--prefix <pre>}\n"
"\t[--rejection column=<col>,{mean|median|mode},\n"
"\t             {stddev|meddev|absolute}=<magnitude>,[comment|exclude]]\n"
"\t[-a|--pre-allocate <size>[,<nblock>]\n"
"\t[-C|--comment] [-S|--additional-comment <...> [-S ...]]\n");
 fprintf(fw,
"Options for cumulative statistics:\n"
"\t<input> [...] -c|--col-base <> -d|--col-stat <>[,...] -o|--output <out>\n"
"\t[--stat [r]count,[r]{mean|median|mode}[[med|std]dev],\n"
"\t        [r]sum,[r]sum2,[r]min,[r]max]\n"
"\t[--rejection column=<col>,iterations=<n>,{mean|median|mode},\n"
"\t             {stddev|meddev|absolute}=<magnitude>] [--rejection ...]\n");
 fprintf(fw,
"Other options:\n"
"\t[-t|--tmpdir <directory-for-temporary-file>]\n"
"\t[-l|--line-size <maximum-line-size>] [-m|--max-memory <max-memory>]\n");
 fprintf(fw,
"Notes:\n"
" - the default directory for tempoary files is always the current one (which\n"
"   is equivalent to define `--tmpdir ./`);\n"
" - the suffixes 'k', 'm' or 'g' can be added after the amount of max. memory,\n"
"   however, this amount is only a hint, the actual usage depends on the data\n"
"   (the default value of max. memory is %d megabytes)\n",DEFAULT_MAX_MEMORY);

 return(0);
}

longhelp_entry grcollect_long_help[] = 
{
 LONGHELP_OPTIONS,

 { "General options:", NULL },
 { "-h, --help",
	"Give general summary about the command line options." },
 { "--long-help, --help-long",
        "Gives a detailed list of command line options." },
 { "--wiki-help, --help-wiki, --mediawiki-help, --help-mediawiki",
        "Gives a detailed list of command line options in Mediawiki format." },
 { "--version, --version-short, --short-version",
	"Give some version information about the program." },

 { "<input> [,<input>, ...]",
	"Name of the input file. At least, one file should be specified. "
	"Reading from standard input can be forced using a single dash \"-\" "
	"as input file name. More dashes are silently ignored." },
 { "-c, --col-base <key column index>",
	"Column index for the key." },

 { "Data transposition specific options:", NULL },
 { "-b, --basename <base-%b-name>",
	"Base name of the output files. The base name string should conatain "
	"at least one \"%b\" tag, which is replaced by the respective key "
	"string on the creation of the file." },
 { "-x, --extension <extension>, -p, --prefix <prefix>",
	__extension__
	"Equivalent to \"-b|--basename <prefix>%b.<extension>\". Note that "
	"in practice, <prefix> might be some sort of directory name and extension is "
	"a regular file extension, but the above substitution is done literally. "
	"Therefore, the \"dot\" between the key and the <extension> is always "
	"inserted in the final name of the output files but a trailing "
	"slash is required at the end of <prefix> if the files are to be "
	"created in that particular directory. Note also that this case, the target "
	"directory must exist before the invocation of `grcollect`, otherwise "
	"the output files cannot be created. " },
 { "-C, --comment",
	"Insert a commented line (starting with \"#\") containing information "
	"about the version and command line invocation syntax of `grcollect` "
	"to the beginning of the transposed files." },
 { "-S, --additional-comment <...>",
	"Insert an additional commented lines (starting with \"#\") "
	"to the beginning of the transposed files." },

 { "Options for cumulative statistics:", NULL },
 { "-d, --col-stat <>[,...]",
	"Comma-separated list of column indices on which the statistics are "
	"to be calculated. Columns with non-numerical contents are ignored." 
	"Note that this option imply the cumulative statistics mode of "
	"`grcollect`." },
 { "-o, --output <filename>",
	"The name of the output file to which the output statistics are "
	"written. The total number of columns in this file will be "
	"1+C*N, where C is the number of columns (see -d|--col-stat) "
	"on which the statistics are calculated and N is the number of "
	"statistic quantities (see --stat). The first column in the output "	
	"file is the key, which is followed by the per-column list of statistics, "
	"in the same order as the user defined after -d|--col-stat and "
	"--stat." },
 { "-s, --stat <list of statistics>",
	"Comma-separated list of statistics to be estimated on the input data. "
	"These can be one or more of the following:" },
 { "count",
	"Total number of records, for the given key." },
 { "rcount",
	"The number of records after rejecting outliers (i.e. it is always "
	"the same as the \"count\" value if no \"--rejection\" was used). " },
 { "mean, median, mode",
	"Mean, median or mode statistics of the data." },
 { "rmean, rmedian, rmode",
	"Mean, median or mode, after rejecting outliers." },
 { "{mean|median|mode}stddev, {mean|median|mode}meddev, stddev",
	"Scatter of the data around the mean, median or mode. The scatter can "
	"either be standard deviation (stddev) or median deviance (meddev). "
	"The literal \"stddev\" is the classic standard deviation, "
	"equivalent to \"meanstddev\". " },
 { "r{mean|median|mode}stddev, r{mean|median|mode}meddev, rstddev",
	"The same scatters as above but after rejecting outliers." },
 { "sum, rsum",
	"Sum of the data, esp. total sum and sum after rejecting outliers." },
 { "sum2, rsum2",
	"Sum of the squares, total and after rejecting outliers." },
 { "min, max",
	"Minimal and maximal data values." },
 { "rmin, rmax",
	"Minimal and maximal data values after the rejection of outliers." },

 { "-r, --rejection column=<index>,<rejection parameters>",
	"Comma-separated directives for outlier rejection for the "
	"specified column. The rejection parameters are:" },
 { "iterations=<n>",
	"Maximum number of iterations to reject outliers." },
 { "mean, median, mode",
	"Use the mean, median or mode for the center of the rejection." },
 { "stddev, meddev, absolute=<limit>",
	"Use the standard deviation or median deviance  "
	"for rejection limit units or define an absolute limit for "
	"rejection level." },

 { "Note that each column can have different kind of rejection method, thus "
   "more than one \"--rejection ...\" command line option can be used at "
   "the invocation of `grcollect`.", NULL }, {"", NULL },
 
 { "Other options:", NULL },
 { "-m, --max-memory <memory>[kmg]",
	__extension__
	"Maximum amount of memory available for `grcollect`. The prefixes "
	"\"k\", \"m\" or \"g\" can be used for kilobytes, megabytes and "
	"gigabytes, respectively. On 32bit systems, the maximum memory is "
	"limited to 3gigabytes. Note that `grcollect` does not use any "
	"kind of operating system specific methods to determine the maximum "
	"amount of memory, it always should be set by the user. The default "
	"value of 8 megabytes is somewhat small, so upon massive data "
	"transposition (tens or hundreds of gigabytes), this limit is "
	"worth to be set accordingly to the physical memory available. " },
 { "-t, --tmpdir <directory>",
	"Directory for temporary file storage. Note that the default "
	"temporary directory is always the current one (which is "
	"is equivalent to define \"--tmpdir ./\"), since in a usual "
	"configuration the /tmp directory is small, moreover, it can be "
	"some sort of \"tmpfs\", temporary file system mount on the "
	"physical memory itself. " },

 { NULL, NULL }
};

int fprint_grcollect_long_help(FILE *fw,int is_wiki)
{ 
 char	*synopsis=
	"grcollect [options] <input> [...] [-o <output>|-b <basename>]";
 char	*description=
	__extension__
	"The main purpose of the program `grcollect` is twofold. First, it is intended "
	"to do data transposition on the input data, i.e. the input (which is read "
	"from files or standard input) is sorted and splitted to separate files where "
	"the splitting is based on a respective key. These keys are taken from "
	"the input data. In such a case where the input is from more files and each "
	"key is unique in a given file, this process is called data transposition "
	"(since it is similar when a 2 dimensional data matrix is stored in the form "
	"as each row is in a separate file, and one intends to transpose the matrix, "
	"i.e. store each column in a separate file). "
	"The other feature of `grcollect` is to do some sort of statistics on data "
	"associated to different keys. These statistics include average (mean, median, "
	"mode) and scatter (standard deviation or median deviance) estimations with "
	"the optional deselection of outlier points, summation, count statistics and "
	"so on.";

 fprint_generic_long_help(fw,is_wiki,grcollect_long_help,synopsis,description);

 return(0);
}

/*****************************************************************************/

int collect_buffer_reset(collectbuffer *cb)
{

 cb->buffer=NULL;
 cb->size=(size_t)0;
 cb->asize=(size_t)0;
 cb->lines=NULL;
 cb->nline=0;
 return(0);
}
int collect_buffer_free(collectbuffer *cb)
{
 if ( cb->buffer != NULL )	free(cb->buffer);
 if ( cb->lines != NULL )	free(cb->lines);
 collect_buffer_reset(cb);
 return(0);
}

int get_column_position(char *line,int col)
{
 int	pos;

 pos=0;
 while ( isspace((int)*line) )	line++,pos++;
 if ( ! (*line) )		return(-1);
 while ( col>0 )
  {	while ( ! isspace((int)*line) && *line )	line++,pos++;
	while ( isspace((int)*line) )			line++,pos++;
	if ( ! (*line) )				return(-1);
	col--;
  }
 return(pos);
}
int compare_line_by_keyptr(const void *vl1,const void *vl2)
{
 line	*l1=(line *)vl1;
 line	*l2=(line *)vl2;
 return(strcmp(l1->keyptr,l2->keyptr));
}

#define		BUFFSIZE	256

int append_string(char **rbuff,int *rsize,int *rasize,char *str,int len)
{
 if ( str==NULL )	return(0);

 if ( *rsize+len > *rasize )
  {	while ( *rsize+len > *rasize )	(*rasize)+=BUFFSIZE;
	*rbuff=(char *)realloc(*rbuff,*rasize);
  }
 memcpy((*rbuff)+(*rsize),str,len);
 (*rsize)+=len;
 return(len);
}

char *expand_basename(char *basename,char *key)
{
 char	*out;
 int	size,asize,klen,i;

 asize=size=0;
 out=NULL;

 if ( key != NULL )	klen=strlen(key);
 else			klen=0;

 if ( klen>0 )		/* ugly, very ugly, suxx */
  {	for ( i=0 ; i<klen ; i++ )
	 {	if ( isspace((int)key[i]) )
			klen=i;
	 }
  }

 while ( *basename )
  {	if ( *basename=='%' )
	 {	basename++;
		switch ( *basename )
		 {   case 'b':
			append_string(&out,&size,&asize,key,klen);
			break;
		     default:
			append_string(&out,&size,&asize,basename,1);
		 }
		basename++;
	 }
	else
	 {	append_string(&out,&size,&asize,basename,1);
		basename++;
	 }
  }
 append_string(&out,&size,&asize,"",1);
 return(out);
}

/*
int collect_flush(collectbuffer *cb,char *basename,off_t preallocate)
{
 int	i;
 line	*wl;
 char	*filename,*prevfile;
 FILE	*fw;
 key	*wk;

 for ( i=0 ; i<cb->nline ; i++ )
  {	wl=&cb->lines[i];
	wl->keyptr=cb->buffer+wl->offset+(size_t)wl->key;
  }
 qsort(cb->lines,cb->nline,sizeof(line),compare_line_by_keyptr);

 prevfile=NULL;
 fw=NULL;
 for ( i=0 ; i<cb->nline ; i++ )
  {	wl=&cb->lines[i];
	filename=expand_basename(basename,wl->keyptr);
	if ( ( prevfile != NULL && strcmp(prevfile,filename) ) || prevfile==NULL || fw==NULL )
	 {	if ( fw != NULL )	fclose(fw);
		wk=lookup_search_or_add_key(&cb->lk,filename,0);
		if ( wk->id <= 0 )
		 {	fw=fopen(filename,"wb");
			wk->id=1;
		 }
		else
			fw=fopen(filename,"ab");
	 }
	if ( fw != NULL )	fprintf(fw,"%s\n",cb->buffer+wl->offset);

	if ( prevfile != NULL )		free(prevfile);
	prevfile=filename;
  }

 if ( prevfile != NULL )	free(prevfile);
 if ( fw != NULL )		fclose(fw);

 collect_buffer_free(cb);

 return(0);
}
*/

/*****************************************************************************/

#define	HPRINT_BUFFER_SIZE		256

int hprintf(int handle,char *msg,...)
{
 char		buff[HPRINT_BUFFER_SIZE],*tbuff;
 va_list	ap;
 int		n;

 va_start(ap,msg);
 n=vsnprintf(buff,HPRINT_BUFFER_SIZE,msg,ap);
 va_end(ap);
 if ( n<HPRINT_BUFFER_SIZE )
  {	(void)write(handle,buff,n);
	return(n);
  }
 else
  {	tbuff=NULL;
	va_start(ap,msg);
	vstrappendf(&tbuff,msg,ap);
	va_end(ap);
	if ( tbuff != NULL )
	 {	n=strlen(tbuff);
		(void)write(handle,tbuff,n);
		free(tbuff);
	 }
	else
		n=0;

	return(n);
  }

}

/*****************************************************************************/

int collect_flush(collectbuffer *cb,char *basename,off_t preallocate)
{
 int	i,j,*pincr;
 line	*wl;
 char	*filename,*prevfile,*cline;
 int	fd;
 key	*wk;

 for ( i=0 ; i<cb->nline ; i++ )
  {	wl=&cb->lines[i];
	wl->keyptr=cb->buffer+wl->offset+(size_t)wl->key;
  }
 qsort(cb->lines,cb->nline,sizeof(line),compare_line_by_keyptr);

 prevfile=NULL;
 fd=-1;
 pincr=NULL;

 for ( i=0 ; i<cb->nline ; i++ )
  {	
	wl=&cb->lines[i];
	filename=expand_basename(basename,wl->keyptr);

	if ( ( prevfile != NULL && strcmp(prevfile,filename) ) || prevfile==NULL || fd<0 )
	 {	if ( fd >= 0 )
		 {	close(fd);
			fd=-1;
		 }

		wk=lookup_search_or_add_key(&cb->lk,filename,0);

		if ( wk->id <= 0 )
		 {	fd=open(filename,O_CREAT|O_TRUNC|O_RDWR,0666);
			if ( cb->is_comment>=1 )
			 {	hprintf(fd,"# Created by grcollect %s (fi: %s)\n",FITSH_GRCOLLECT_VERSION,FITSH_VERSION);	}
			if ( cb->is_comment>=2 )
			 {	hprintf(fd,"# Invoked command:");
				for ( j=0 ; j<cb->argc ; j++ )
				 {	if ( is_any_nasty_char(cb->argv[j]) )
						hprintf(fd," \"%s\"",cb->argv[j]);
					else
						hprintf(fd," %s",cb->argv[j]);
				 }
				hprintf(fd,"\n");
			 }
			for ( j=0 ; cb->comments != NULL && cb->comments[j] != NULL ; j++ )
			 {	cline=cb->comments[j];
				hprintf(fd,"# %s\n",cline);
			 }			
			wk->id=0;
			if ( preallocate>0 )
			 {	char	*buff;
				int	i,pagesize;
				off_t	size;
#ifdef	HOST_WIN32
				pagesize=4096;
#else
				pagesize=getpagesize();
#endif
				buff=(char *)malloc((size_t)pagesize);
				for ( i=0 ; i<pagesize ; i++ )
				 {	buff[i]=i%256;			}
				size=preallocate;
				while ( size>0 )
				 {	if ( size>(off_t)pagesize )
						i=pagesize;
					else
						i=(int)size;
					(void)write(fd,buff,i);
					size-=(off_t)i;
				 }
				free(buff);
				lseek(fd,(off_t)0,SEEK_SET);
			 }
		 }

		else
		 {	fd=open(filename,O_RDWR);
			lseek(fd,(off_t)wk->id,SEEK_SET);
		 }

		pincr=&wk->id;
	 }

	if ( fd >= 0 )
	 {	int	len;
		char	*wrbuff;
		wrbuff=cb->buffer+wl->offset;
		len=strlen(wrbuff);
		(void)write(fd,wrbuff,(size_t)len);
		(void)write(fd,"\n",(size_t)1);
		if ( pincr != NULL )
			(*pincr)+=len+1;
	 }

	if ( prevfile != NULL )		free(prevfile);

	prevfile=filename;
  }

 if ( prevfile != NULL )	free(prevfile);

 if ( fd>=0 )
	close(fd);

 collect_buffer_free(cb);

 return(0);
}

#define		FRAGSIZE	16384

int collect_read_file(collectbuffer *cb,int fid,FILE *fr,int colbase,
	char *basename,size_t maxmem,off_t preallocate)
{
 char	*buff;
 int	key,len;
 size_t	n;
 line	*wl;

 while ( ! feof(fr) )
  {	buff=freadline(fr);
	if ( buff==NULL )	break;
	remove_newlines_and_comments(buff);
	key=get_column_position(buff,colbase);
	if ( key<0 )
	 {	free(buff);
		continue;
	 }
	cb->lines=(line *)realloc(cb->lines,sizeof(line)*(cb->nline+1));
	wl=&cb->lines[cb->nline];
	cb->nline++;

	len=strlen(buff)+1;	
	if ( cb->size+(size_t)len > cb->asize )
	 {	n=(cb->size+(size_t)(len+FRAGSIZE-1))/(size_t)FRAGSIZE;
		cb->asize=(size_t)n*(size_t)FRAGSIZE;
		cb->buffer=(char *)realloc(cb->buffer,cb->asize);
	 }
	memcpy(cb->buffer+(size_t)cb->size,buff,(size_t)len);

	free(buff);

	wl->offset=cb->size;
	wl->key=key;
	wl->file=fid;
	cb->size+=(size_t)len;

	if ( cb->size > maxmem )
	 {	collect_flush(cb,basename,preallocate);		}

  };

 return(0); 
}

int collect_transposition_truncate(collectbuffer *cb,lookupkey *lk,off_t preallocate)
{
 int			i;
 lookupkey		*wl;

 if ( lk==NULL || lk->lookups==NULL )	return(0);

 for ( i=0 ; i<(1<<HASH_BITS) ; i++ )
  {	wl=&lk->lookups[i];
	if ( wl->lookups != NULL )
		collect_transposition_truncate(cb,wl,preallocate);	
#ifndef	HOST_WIN32
	else if ( wl->value.key != NULL )
	 {	key	*wk;
		wk=&wl->value;
		if ( (off_t)wk->id < preallocate )
			(void)truncate(wk->key,(off_t)wk->id);
	 }
#endif
  }

 return(0);
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

int do_transposition_normal(char **infiles,int ninfile,int colbase,
	char *basename,size_t maxmem,off_t preallocate,
	char **additionalcomments,int argc,char **argv)
{
 collectbuffer	cb; 
 FILE		*fr;
 int		i;
 
 collect_buffer_reset(&cb);
 cb.lk.lookups=NULL;
 cb.lk.value.key=NULL;
 cb.lk.value.id=0;

 cb.is_comment=is_comment;
 cb.comments=additionalcomments;
 cb.argc=argc;
 cb.argv=argv;

 for ( i=0 ; i<ninfile ; i++ )
  {	fr=fopenread(infiles[i]);
	if ( fr==NULL )
	 {	fprint_warning("unable to open file '%s', skipped",infiles[i]);
		continue;
	 }
	collect_read_file(&cb,i,fr,colbase,basename,maxmem,preallocate);
	fcloseread(fr);
  }

 collect_flush(&cb,basename,preallocate);

 if ( preallocate>0 )
	collect_transposition_truncate(&cb,&cb.lk,preallocate);

 lookup_free_node(&cb.lk);

 return(0);
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

int compare_line_by_keyoffset(const void *vl1,const void *vl2)
{
 char	*l1=(char *)vl1;
 char	*l2=(char *)vl2;
 int	k1=(*(int *)l1)+sizeof(int);
 int	k2=(*(int *)l2)+sizeof(int);
 return(strcmp(l1+k1,l2+k2));
}

int do_transposition_cached(char **infiles,int ninfile,int colbase,
	char *basename,size_t maxmem,char *tmpdir,int linesize)
{
 FILE		*fr,*fw;
 int		i,k,l,ln,key;
 char		*tmptemplate;
 int		fh;
 char		*buff,*memcache,*p;
 int		mcline,ncline,ttline,ccline;
 char		*filename,*prevfile;

 tmptemplate=NULL; 
 strappendf(&tmptemplate,"%s/grcollect.XXXXXX",tmpdir);

/* fprintf(stderr,"do_transposition_cached(): template=%s\n",tmptemplate); */

 fh=-1;

 memcache=NULL;
 mcline=(int)(maxmem/linesize);
 ncline=0;
 ttline=0;
 
 for ( i=0 ; i<ninfile ; i++ )
  {	fr=fopenread(infiles[i]);
	if ( fr==NULL )
	 {	fprint_warning("unable to open file '%s', skipped",infiles[i]);
		continue;
	 }
	ln=0;
	while ( ! feof(fr) )
	 {	ln++;
		buff=freadline(fr);
		if ( buff==NULL )	break;
		remove_newlines_and_comments(buff);
		l=strlen(buff);
		if ( l+1>linesize-sizeof(int) )
		 {	fprint_warning("line %d in file '%s' is too long (%d rather than %d), line is truncated",ln,infiles[i],l,(int)(linesize-sizeof(int)));
			l=linesize-sizeof(int)-1;
			buff[l]=0;
		 }
		key=get_column_position(buff,colbase);
		if ( key<0 )
		 {	free(buff);
			continue;
		 }
		memcache=(char *)realloc(memcache,(size_t)(ncline+1)*(size_t)linesize);
		p=memcache+(size_t)ncline*(size_t)linesize;
		*(int *)p=key;
		memcpy(p+sizeof(int),buff,linesize-sizeof(int));
		free(buff);
		ncline++;
		ttline++;
		if ( ncline >= mcline )
		 {	if ( fh<0 )
			 {	
#ifndef	HOST_WIN32
				fh=mkstemp(tmptemplate);
#else
				mktemp(tmptemplate);
				fh=open(tmptemplate,O_CREAT|O_TRUNC|O_RDWR);
#endif
				if ( fh<0 )
				 {	fprint_error("unable to create temporary file using '%s'",tmptemplate);
					exit(1);
				 }
			 }
			qsort(memcache,ncline,linesize,compare_line_by_keyoffset);
			for ( k=0 ; k<ncline ; k++ )
			 {	(void)write(fh,memcache+(size_t)k*(size_t)linesize,(size_t)linesize);
			 }
			free(memcache);
			ncline=0;
			memcache=NULL;
		 }
	 }
 	fcloseread(fr);
  }

 if ( fh>=0 && ncline>0 )
  {	qsort(memcache,ncline,linesize,compare_line_by_keyoffset);
	for ( k=0 ; k<ncline ; k++ )
	 {	(void)write(fh,memcache+(size_t)k*(size_t)linesize,(size_t)linesize);
 	 }
	free(memcache);
	memcache=NULL;
	ncline=0;
  }

 /* all data is in memory: */
 if ( ttline>0 )
  {	if ( fh<0 )
	 	qsort(memcache,ttline,linesize,compare_line_by_keyoffset);
	else 
	 {	cache	ch;
		size_t	blocksize,membcount;
		int	multip;
	
		blocksize=cache_blocksize(linesize);
		membcount=maxmem/blocksize;
		if ( membcount<4 )	membcount=4;
		multip=1;
		while ( membcount>16384 )
		 {	multip *= 2;
			membcount /= 2;
		 }

		cache_init(&ch,linesize,(off_t)ttline,multip,(int)membcount,fh,CACHE_READ_AND_WRITE);
		cache_sort(&ch,compare_line_by_keyoffset);
		cache_finalize(&ch);
	 }
  }

 prevfile=NULL;
 fw=NULL;
 ncline=0;
 ccline=0;
 for ( i=0 ; i<ttline ; i++ )
  {	if ( fh<0 )
	 {	p=memcache+(size_t)i*(size_t)linesize;		}
	else
	 {	if ( ncline<=0 )
		 {	ncline=(mcline<ttline-i?mcline:ttline-i);
			memcache=realloc(memcache,(size_t)ncline*(size_t)linesize);
			for ( k=0 ; k<ncline ; k++ )
			 {	(void)read(fh,memcache+(size_t)k*(size_t)linesize,(size_t)linesize);
			 }
			ccline=0;
		 }
		p=memcache+(size_t)ccline*(size_t)linesize;
		ccline++;
	 }

	key=*(int *)p;
	filename=expand_basename(basename,p+sizeof(int)+key);

	if ( ( prevfile != NULL && strcmp(prevfile,filename) ) || prevfile==NULL || fw==NULL )
	 {	if ( fw != NULL )	fclose(fw);
		fw=fopen(filename,"wb");
	 }
	if ( fw != NULL )	fprintf(fw,"%s\n",p+sizeof(int));

	if ( prevfile != NULL )		free(prevfile);
	prevfile=filename;

	if ( fh>=0 && ccline>=ncline )
		ncline=0;

  }

 if ( prevfile != NULL )	free(prevfile);
 if ( fw != NULL )		fclose(fw);

 if ( memcache != NULL )
  {	free(memcache);
	memcache=NULL;
	ncline=0;
  }

 if ( fh>=0 )
  {	close(fh);
	unlink(tmptemplate);
	free(tmptemplate);
  }

 return(0);
}


/*****************************************************************************/

int collect_stat_reset(collectstat *cs)
{
 memset(&cs->lk,0,sizeof(lookupkey));
 cs->nfield=0;
 cs->afield=0;
 cs->fields=NULL;
 return(0);
}
int collect_stat_flush_tempfile(collectstat *cs)
{
 size_t	cw,cp,cc;

 cw=cs->ntmp*(size_t)(sizeof(tmpvaluecommon)+sizeof(double)*cs->nstat);
 for ( cp=0 ; cw>0 ; )
  {	cc=cw;
	if ( cc>16*1024*1024 )	cc=16*1024*1024;
	(void)write(cs->fh,(void *)((char *)cs->tmps+cp),cc);
	cp+=cc;
	cw-=cc;
  }

 cs->wtmp += (off_t)cs->ntmp;
 free(cs->tmps);

 cs->atmp=(size_t)0;
 cs->ntmp=(size_t)0;
 cs->tmps=NULL;

 return(0);
}

int collect_stat_read_file(collectstat *cs,FILE *fr,int colbase,column *colstats)
{
 int			mxc,i,n;
 char			*rbuff,**cmd,*kstr;
 double			*values;
 key			*wk;
 statfieldcommon	*wsc;
 statfielddata		*wsd;
 tmpvaluecommon		*wtc;
 double			*wtd;

 mxc=colbase;
 for ( i=0 ; i<cs->nstat ; i++ )
  {	if ( colstats[i].index>mxc )
		mxc=colstats[i].index;
  }
 mxc++;

 values=(double *)malloc(sizeof(double)*cs->nstat);

 while ( ! feof(fr) )
  {	rbuff=freadline(fr);
	if ( rbuff==NULL )	break;
	remove_newlines_and_comments(rbuff);
	cmd=tokenize_spaces_dyn(rbuff);
	if ( cmd==NULL || cmd[0]==NULL )
	 {	if ( cmd != NULL )	free(cmd);
		free(rbuff);
		continue;
	 }
	for ( n=0 ; cmd[n] != NULL ; )	n++;
	if ( n<mxc )
	 {	free(cmd);
		free(rbuff);
		continue;
	 }
	for ( i=0 ; i<cs->nstat ; i++ )
	 {	if ( sscanf(cmd[colstats[i].index],"%lg",&values[i])<1 )
			break;
	 }
	if ( i<cs->nstat )
	 {	free(cmd);
		free(rbuff);
		continue;
	 }

	kstr=cmd[colbase];
	wk=lookup_search_or_add_key(&cs->lk,kstr,0);
	if ( wk->id<=0 )
	 {	cs->nfield++;
		wk->id=cs->nfield;
		if ( cs->nfield>cs->afield )
		 {	cs->afield+=64;
			cs->fields=realloc(cs->fields,(sizeof(statfieldcommon)+sizeof(statfielddata)*cs->nstat)*cs->afield);
		 }
		wsc=(statfieldcommon *)((char *)cs->fields+(cs->nfield-1)*(sizeof(statfieldcommon)+sizeof(statfielddata)*cs->nstat));
		wsd=(statfielddata *)((char *)wsc+sizeof(statfieldcommon));
		wsc->id=wk->id;
		wsc->key=wk->key;
		wsc->count=1;
		for ( i=0 ; i<cs->nstat ; i++ )
		 {	wsd[i].min=wsd[i].max=values[i];
			wsd[i].sum=values[i];
			wsd[i].sum2=values[i]*values[i];
		 }
	 }
	else
	 {	wsc=(statfieldcommon *)((char *)cs->fields+(wk->id-1)*(sizeof(statfieldcommon)+sizeof(statfielddata)*cs->nstat));
		wsd=(statfielddata *)((char *)wsc+sizeof(statfieldcommon));
		for ( i=0 ; i<cs->nstat ; i++ )
		 {	if ( values[i]<wsd[i].min )	wsd[i].min=values[i];
			if ( values[i]>wsd[i].max )	wsd[i].max=values[i];
			wsd[i].sum+=values[i];
			wsd[i].sum2+=values[i]*values[i];
		 }
		wsc->count++;
	 }

	if ( cs->tmptemplate != NULL )
	 {	if ( cs->ntmp>=cs->atmp )
		 {	cs->atmp+=(size_t)64;
			cs->tmps=realloc(cs->tmps,(size_t)(sizeof(tmpvaluecommon)+sizeof(double)*cs->nstat)*cs->atmp);
		 }

		wtc=(tmpvaluecommon *)((char *)cs->tmps+(size_t)(sizeof(tmpvaluecommon)+sizeof(double)*cs->nstat)*cs->ntmp);
		wtd=(double *)((char *)wtc+sizeof(tmpvaluecommon));
		cs->ntmp++;
		wtc->id=wk->id;
		wtc->flag=0;
		for ( i=0 ; i<cs->nstat ; i++ )
		 {	wtd[i]=values[i];		}
		if ( cs->ntmp>=cs->mxtmp )
		 {	if ( cs->fh<0 )
			 {	
#ifndef	HOST_WIN32
				cs->fh=mkstemp(cs->tmptemplate);
#else
				mktemp(cs->tmptemplate);
				cs->fh=open(cs->tmptemplate,O_CREAT|O_TRUNC|O_RDWR);
#endif
				if ( cs->fh<0 )
				 {	fprint_error("unable to create temporary file using '%s'",cs->tmptemplate);
					exit(1);
				 }
			 }
			collect_stat_flush_tempfile(cs);
		 }
	 }

	free(cmd);
	free(rbuff);
  };

 return(0);
}

int collect_stat_temp_compare(const void *vt1,const void *vt2)
{
 tmpvaluecommon	*t1=(tmpvaluecommon *)vt1,
		*t2=(tmpvaluecommon *)vt2;
 if ( t1->id < t2->id )					return(-1);
 else if ( t1->id > t2->id )				return(+1);
 else if ( *(double *)(&t1[1]) < *(double *)(&t2[1]) )	return(-1);
 else if ( *(double *)(&t1[1]) > *(double *)(&t2[1]) )	return(+1);
 else							return(0);
}

int collect_stat_order_mem(collectstat *cs)
{
 int	recordsize;
 recordsize=sizeof(tmpvaluecommon)+sizeof(double)*cs->nstat;
 qsort(cs->tmps,cs->ntmp,recordsize,collect_stat_temp_compare);
 return(0);
}

int collect_stat_order_tmp(collectstat *cs)
{
 cache	ch;
 int	recordsize,multip;
 size_t	blocksize,membcount;

 recordsize=sizeof(tmpvaluecommon)+sizeof(double)*cs->nstat;

 blocksize=cache_blocksize(recordsize);
 membcount=cs->maxmem/blocksize;
 if ( membcount<4 )	membcount=4;
 multip=1;
 while ( membcount>16384 )
  {	multip *= 2;
	membcount /= 2;
  }

 cache_init(&ch,recordsize,cs->wtmp,multip,(int)membcount,cs->fh,CACHE_READ_AND_WRITE);
 cache_sort(&ch,collect_stat_temp_compare);
 cache_finalize(&ch);

 return(0);
}

int collect_stat_order(collectstat *cs)
{
 if ( cs->wtmp<=0 )	/* all data in memory, nothing written to tmpfile */
  {	collect_stat_order_mem(cs);	}
 else			/* sort tmpfile instead				  */
  {	collect_stat_order_tmp(cs);	}
 return(0);
}

double get_std_deviation(double *arr,int n,double m)
{
 int	i;
 double	s2,dev;

 if ( n<=0 || arr==NULL )	return(-1.0);
 
 s2=0.0;
 for ( i=0 ; i<n ; i++ )
  {	s2 += (arr[i]-m)*(arr[i]-m);		}
 s2/=(double)n;
 if ( s2>0.0 )	dev=sqrt(s2);
 else		dev=0.0;
 return(dev); 
}

double get_abs_deviation(double *arr,int n,double m)
{
 int	i;
 double	dev;

 if ( n<=0 || arr==NULL )	return(-1.0);
 
 dev=0.0;
 for ( i=0 ; i<n ; i++ )
  {	dev += fabs(arr[i]-m);			}
 dev/=(double)n;
 return(dev); 
}

int get_value_index(double *arr,int n,double m)
{
 int    f,k;
 f=0;
 while ( n )
  {	k=f+n/2;
	if ( arr[k]<m )	f+=n/2+1,n-=n/2+1;
	else            n=n/2;
  };
 return(f);
}

double get_med_deviation(double *arr,int n,double m)
{
 int	i;
 double	meddev,*wrr;

 wrr=(double *)malloc(sizeof(double)*n);
 for ( i=0 ; i<n ; i++ )
  {	wrr[i]=fabs(arr[i]-m);		}
 meddev=median(wrr,n);
 free(wrr);

 return(meddev);
}

int get_noncumulative_statistics(double *arr,int n,statfielddata *wsd,rejection *r)
{
 int	i,lo,nn,ilo,inn,ii;
 double	mean,mlo,mhi,mct,mdv,rmean;

 wsd->median=0.5*(arr[(n-1)/2]+arr[n/2]);

 mean=wsd->sum/(double)n;

 wsd->mediandev=get_std_deviation(arr,n,wsd->median);
 wsd->medianmeddev=get_med_deviation(arr,n,wsd->median);
 wsd->meanmeddev=get_med_deviation(arr,n,mean);
 wsd->mode=2.5*wsd->median-1.5*mean;
 wsd->modedev=get_std_deviation(arr,n,wsd->mode);
 wsd->modemeddev=get_med_deviation(arr,n,wsd->mode);

 wsd->rcount=n;
 wsd->rsum=wsd->sum;
 wsd->rsum2=wsd->sum2;
 wsd->rmin=wsd->min;
 wsd->rmax=wsd->max;
 wsd->rmedian=wsd->median;
 wsd->rmediandev=wsd->mediandev;
 wsd->rmeanmeddev=wsd->meanmeddev;
 wsd->rmedianmeddev=wsd->medianmeddev;
 wsd->rmode=wsd->mode;
 wsd->rmodedev=wsd->modedev;
 wsd->rmodemeddev=wsd->modemeddev;

 lo=0;
 nn=n;

 for ( ii=0 ; r != NULL && (r->center & REJECTION_CENTER) && 
 (ii<r->iterations || r->iterations<0) ; ii++ )
  {	rmean=wsd->rsum/(double)wsd->rcount;
	switch ( r->center & REJECTION_CENTER )
	 {   case REJECTION_C_MEAN:
		mct=rmean;
		switch ( r->center & REJECTION_MAGNITUDE )
		 {   case REJECTION_M_STDDEV:
			mdv=wsd->rsum2/(double)n-rmean*rmean;
			if ( mdv>0 )	mdv=sqrt(mdv);
			else		mdv=0.0;
			break;
		     case REJECTION_M_MEDDEV:
			mdv=wsd->rmeanmeddev;
			break;
		     case REJECTION_M_ABSOLUTE:
			mdv=1.0;
			break;
		     default:
			mdv=0.0;
			break;
		 }
		break;
	     case REJECTION_C_MEDIAN:
		mct=wsd->rmedian;
		switch ( r->center & REJECTION_MAGNITUDE )
		 {   case REJECTION_M_STDDEV:
			mdv=wsd->rmediandev;
			break;
		     case REJECTION_M_MEDDEV:
			mdv=wsd->rmedianmeddev;
			break;
		     case REJECTION_M_ABSOLUTE:
			mdv=1.0;
			break;
		     default:
			mdv=0.0;
			break;
		 }
		break;
	     case REJECTION_C_MODE:
		mct=wsd->rmode;
		switch ( r->center & REJECTION_MAGNITUDE )
		 {   case REJECTION_M_STDDEV:
			mdv=wsd->rmodedev;
			break;
		     case REJECTION_M_MEDDEV:
			mdv=wsd->rmodemeddev;
			break;
		     case REJECTION_M_ABSOLUTE:
			mdv=1.0;
			break;
		     default:
			mdv=0.0;
			break;
		 }
		break;
	     default:
		mct=0.0;
		mdv=0.0;
		break;
	 }
	if ( mdv>0.0 )
	 {	mlo=mct-mdv*r->magnitude;
		mhi=mct+mdv*r->magnitude;
		ilo=get_value_index(arr,n,mlo);
		inn=get_value_index(arr,n,mhi)-ilo;
	 }
	else
	 {	ilo=lo;
		inn=nn;
	 }
	/*
	fprintf(stderr,"mct=%12g mdv=%12g ilo=%3d inn=%3d\n",mct,mdv,ilo,inn);
	*/
	if ( inn <= 0 )
	 {	wsd->rcount=0;
		wsd->rmin=wsd->rmax=0.0;
		wsd->rsum=wsd->rsum2=0.0;
		wsd->rmedian=0.0;
		wsd->rmediandev=0.0;
		wsd->rmedianmeddev=0.0;
		wsd->rmeanmeddev=0.0;
		wsd->rmode=0.0;
		wsd->rmodedev=0.0;
		wsd->rmodemeddev=0.0;
		break;
	 }
	else if ( ilo>lo || inn<nn )
	 {	lo=ilo;
		nn=inn;

		wsd->rcount=nn;
		wsd->rmin=arr[lo];
		wsd->rmax=arr[lo+nn-1];
		wsd->rsum=wsd->rsum2=0.0;
		for ( i=0 ; i<nn ; i++ )
		 {	wsd->rsum+=arr[lo+i];
			wsd->rsum2+=arr[lo+i]*arr[lo+i];
		 }
		rmean=wsd->rsum/(double)wsd->rcount;
		wsd->rmedian=0.5*(arr[lo+(nn-1)/2]+arr[lo+nn/2]);

		wsd->rmediandev=get_std_deviation(arr+lo,nn,wsd->rmedian);
		wsd->rmedianmeddev=get_med_deviation(arr+lo,nn,wsd->rmedian);
		wsd->rmeanmeddev=get_med_deviation(arr+lo,nn,rmean);
		wsd->rmode=2.5*wsd->rmedian-1.5*rmean;
		wsd->rmodedev=get_std_deviation(arr+lo,nn,wsd->rmode);
		wsd->rmodemeddev=get_med_deviation(arr+lo,nn,wsd->rmode);
	 }
	else
		break;
  }

 return(0);
}

int collect_stat_non_cumulative(collectstat *cs)
{
 int			i,j,k,aa,n;
 size_t			offset;
 statfieldcommon	*wsc;
 statfielddata		*wsd;
 tmpvaluecommon		*wtc;
 double			*wtd;
 double			*arr;
 cache			ch;
 int			recordsize;

 aa=0;
 arr=NULL;

 offset=(size_t)0;

 recordsize=sizeof(tmpvaluecommon)+sizeof(double)*cs->nstat;
 if ( cs->fh>=0 )
  {	lseek(cs->fh,(off_t)0,SEEK_SET);
	cache_init(&ch,recordsize,cs->wtmp,1,4,cs->fh,CACHE_READONLY);
  }

 for ( k=0 ; k<cs->nfield ; k++ )
  {	wsc=(statfieldcommon *)((char *)cs->fields+(size_t)k*(size_t)(sizeof(statfieldcommon)+sizeof(statfielddata)*cs->nstat));
	wsd=(statfielddata *)((char *)wsc+sizeof(statfieldcommon));

	n=wsc->count;
	if ( n>aa )
	 {	aa=n;
		arr=(double *)realloc(arr,sizeof(double)*aa);
	 }

	for ( i=0 ; i<cs->nstat ; i++ )
	 {	if ( cs->wtmp<=0 )
		 {	for ( j=0 ; j<n ; j++ )
			 {	wtc=(tmpvaluecommon *)((char *)cs->tmps+(offset+(size_t)j)*(size_t)recordsize);
				wtd=(double *)((char *)wtc+sizeof(tmpvaluecommon));
				arr[j]=wtd[i];
			 }
		 }
		else
		 {	for ( j=0 ; j<n ; j++ )
			 {	wtc=cache_read_record(&ch,(off_t)(offset+(size_t)j));
				wtd=(double *)((char *)wtc+sizeof(tmpvaluecommon));
				arr[j]=wtd[i];
			 }
		 }
		if ( i>0 )	median(arr,n);	/* only the first column has been ordered */

		get_noncumulative_statistics(arr,n,&wsd[i],&cs->colstats[i].r);

	 }
	offset+=(size_t)wsc->count;
  }

 if ( arr != NULL )	free(arr);

 if ( cs->fh>=0 )
	cache_finalize(&ch);

 return(0);
}

int collect_stat_write_stat_one(FILE *fw,statfieldcommon *wsc,statfielddata *wsd,int *statlist)
{
 double	mean,m2,sigma,rmean,rsigma;
 int	j,s;

 mean=wsd->sum /(double)wsc->count;
 m2  =wsd->sum2/(double)wsc->count;
 sigma=m2-mean*mean;
 if ( sigma>0.0 )	sigma=sqrt(sigma);
 else			sigma=0.0;

 if ( wsd->rcount>0 )
  {	rmean=wsd->rsum/(double)wsd->rcount;
 	m2=wsd->rsum2/(double)wsd->rcount;
	rsigma=m2-rmean*rmean;
	if ( rsigma>0.0 )	rsigma=sqrt(rsigma);
	else			rsigma=0.0;
  }
 else
  {	rmean=0.0;
	rsigma=0.0;
  }
	
 for ( j=0 ; statlist[j]>0 ; j++ )
  {	s=statlist[j];
	switch ( s )
	 {   case STAT_COUNT:
		fprintf(fw,"%6d ",wsc->count);
		break;
	     case STAT_MEAN:
		fprintf(fw,"%12g ",mean);
		break;
	     case STAT_MEANDEV:
		fprintf(fw,"%12g ",sigma);
		break;
	     case STAT_MIN:
		fprintf(fw,"%12g ",wsd->min);
		break;
	     case STAT_MAX:
		fprintf(fw,"%12g ",wsd->max);
		break;
	     case STAT_SUM:
		fprintf(fw,"%12g ",wsd->sum);
		break;
	     case STAT_SUM2:
		fprintf(fw,"%12g ",wsd->sum2);
		break;

	     case STAT_MEDIAN:
		fprintf(fw,"%12g ",wsd->median);
		break;
	     case STAT_MEDIANDEV:
		fprintf(fw,"%12g ",wsd->mediandev);
		break;
	     case STAT_MEDIANMEDDEV:
		fprintf(fw,"%12g ",wsd->medianmeddev);
		break;
	     case STAT_MEANMEDDEV:
		fprintf(fw,"%12g ",wsd->meanmeddev);
		break;
	     case STAT_MODE:
		fprintf(fw,"%12g ",wsd->mode);
		break;
	     case STAT_MODEDEV:
		fprintf(fw,"%12g ",wsd->modedev);
		break;
	     case STAT_MODEMEDDEV:
		fprintf(fw,"%12g ",wsd->modemeddev);
		break;

	     case STAT_RCOUNT:
		fprintf(fw,"%6d ",wsd->rcount);
		break;
	     case STAT_RMEAN:
		fprintf(fw,"%12g ",rmean);
		break;
	     case STAT_RMEANDEV:
		fprintf(fw,"%12g ",rsigma);
		break;
	     case STAT_RMIN:
		fprintf(fw,"%12g ",wsd->rmin);
		break;
	     case STAT_RMAX:
		fprintf(fw,"%12g ",wsd->rmax);
		break;
	     case STAT_RSUM:
		fprintf(fw,"%12g ",wsd->rsum);
		break;
	     case STAT_RSUM2:
		fprintf(fw,"%12g ",wsd->rsum2);
		break;
	     case STAT_RMEDIAN:
		fprintf(fw,"%12g ",wsd->rmedian);
		break;
	     case STAT_RMEDIANDEV:
		fprintf(fw,"%12g ",wsd->rmediandev);
		break;
	     case STAT_RMEDIANMEDDEV:
		fprintf(fw,"%12g ",wsd->rmedianmeddev);
		break;
	     case STAT_RMEANMEDDEV:
		fprintf(fw,"%12g ",wsd->rmeanmeddev);
		break;
	     case STAT_RMODE:
		fprintf(fw,"%12g ",wsd->rmode);
		break;
	     case STAT_RMODEDEV:
		fprintf(fw,"%12g ",wsd->rmodedev);
		break;
	     case STAT_RMODEMEDDEV:
		fprintf(fw,"%12g ",wsd->rmodemeddev);
		break;

	 }
  }
 return(0);
}

int collect_stat_write_stat_line(FILE *fw,
	statfieldcommon *wsc,statfielddata *wsd,int nstat,int *statlist)
{
 int	i;
 fprintf(fw,"%s\t",wsc->key);
 for ( i=0 ; i<nstat ; i++ )
  {	collect_stat_write_stat_one(fw,wsc,&wsd[i],statlist);		}
 fprintf(fw,"\n");
 return(0);
}

int collect_stat_write_node(FILE *fw,collectstat *cs,lookupkey *lk,int *statlist)
{
 int			i;
 key			*wk;
 lookupkey		*wl;
 statfieldcommon	*wsc;
 statfielddata		*wsd;

 if ( lk==NULL || lk->lookups==NULL )	return(0);

 for ( i=0 ; i<(1<<HASH_BITS) ; i++ )
  {	wl=&lk->lookups[i];
	if ( wl->lookups != NULL )
		collect_stat_write_node(fw,cs,wl,statlist);	
	else if ( wl->value.key != NULL )
	 {	wk=&wl->value;
		wsc=(statfieldcommon *)((char *)cs->fields+(wk->id-1)*(sizeof(statfieldcommon)+sizeof(statfielddata)*cs->nstat));
		wsd=(statfielddata *)((char *)wsc+sizeof(statfieldcommon));
		collect_stat_write_stat_line(fw,wsc,wsd,cs->nstat,statlist);
	 }
  }

 return(0);
}

int collect_stat_write(FILE *fw,collectstat *cs,int *statlist)
{
 collect_stat_write_node(fw,cs,&cs->lk,statlist);
 return(0);
}

int collect_stat_free(collectstat *cs)
{
 lookup_free_node(&cs->lk);
 return(0);
}


int do_collective_statistics(char **infiles,int ninfile,FILE *fw,
	int colbase,column *colstats,int ncolstat,
	int *statlist,size_t maxmem,char *tmpdir)
{
 int		i;
 int		is_non_cumulative;
 FILE		*fr;
 collectstat	cs;
 size_t		mx;

 if ( statlist==NULL )
	return(1);

 is_non_cumulative=0;
 for ( i=0 ; statlist[i]>0 && ! is_non_cumulative ; i++ )
  {	if ( statlist[i]>STAT_PURE_CUMULATIVE )
		is_non_cumulative=1;
  }

 collect_stat_reset(&cs);

 if ( is_non_cumulative )
  {	if ( tmpdir==NULL || strlen(tmpdir) <= 0 )
		cs.tmptemplate=strdup("./grcollect.XXXXXX");
	else
	 {	i=strlen(tmpdir);
		cs.tmptemplate=(char *)malloc(i+32);
		strcpy(cs.tmptemplate,tmpdir);
		if ( tmpdir[i-1] !='/' )	strcat(cs.tmptemplate,"/");
		strcat(cs.tmptemplate,"grcollect.XXXXXX");
	 }
  }
 else
	cs.tmptemplate=NULL;

 cs.tmps=NULL;
 cs.ntmp=(size_t)0;
 cs.atmp=(size_t)0;
 cs.wtmp=(off_t)0;
 mx=(maxmem/(size_t)(sizeof(tmpvaluecommon)+ncolstat*sizeof(double))+(size_t)63)/(size_t)64;
 cs.mxtmp=(size_t)64*mx;
 cs.fh=-1;
 cs.maxmem=maxmem;

 cs.nstat=ncolstat;
 cs.colstats=colstats;
 
 for ( i=0 ; i<ninfile ; i++ )
  {	fr=fopenread(infiles[i]);
	if ( fr==NULL )
	 {	fprint_warning("unable to open file '%s', skipped",infiles[i]);
		continue;
	 }
	collect_stat_read_file(&cs,fr,colbase,colstats);
	fcloseread(fr);
  }

 if ( is_non_cumulative )
  {	if ( cs.wtmp>(size_t)0 && cs.fh>=0 )
	 {	collect_stat_flush_tempfile(&cs);		}
	collect_stat_order(&cs);
	collect_stat_non_cumulative(&cs);
	if ( cs.fh>=0 )
	 {	close(cs.fh);
		unlink(cs.tmptemplate);
	 }
  }

 collect_stat_write(fw,&cs,statlist);
 collect_stat_free(&cs);
 
 return(0);
}

/*****************************************************************************/

int main(int argc,char *argv[])
{
 int		i,is_help;
 int		colbase;
 char		**infiles,*basename,*extension,*tmpdir,
		*prefix,*maxmemstr,*outfile,*statstr,*colstatstr,*preallocarg,
		**rejectionlist,**additionalcomments;
 int		ninfile,*statlist;
 column		*colstats;
 int		ncolstat;
 int		linesize;
 off_t		preallocate;

 size_t		maxmem;

 progbasename=strrchr(argv[0],'/');
 if ( progbasename != NULL )	progbasename++;
 else				progbasename=argv[0];

 is_comment=0;is_verbose=is_help=0;
 additionalcomments=NULL;
 rejectionlist=NULL;

 infiles=NULL;
 outfile=basename=extension=prefix=NULL;
 statstr=maxmemstr=NULL;
 tmpdir=NULL;

 colbase=1;
 colstatstr="2";

 linesize=240;
 preallocarg=NULL;

 i=scanarg(argc,argv,SCANARG_ALLOW_FLAGS,
	"--version:%NS-1f%q",&is_help,
        "--version-short|--short-version:%NS-2f%q",&is_help,
	"-C|--comment:%i",&is_comment,
	"-S|--additional-comment:%Dt",&additionalcomments,
	"-h|--help|--short-help|--help-short:%f%q",&is_help,
	"--long-help|--help-long:%SN2f%q",&is_help,
	"--mediawiki-help|--help-mediawiki|--wiki-help|--help-wiki:%SN3f%q",&is_help,
	"-b|--basename:%s",&basename,
	"-o|--output:%s",&outfile,
	"-x|--extension:%s",&extension,
	"-p|--prefix:%s",&prefix,
	"-a|--pre-allocate:%s",&preallocarg,
	"-m|--max-mem|--max-memory:%s",&maxmemstr,
	"-s|--stat:%s",&statstr,
	"-t|--tmpdir|--tempdir|--temporary-directory:%s",&tmpdir,
	"-r|--rejection:%Dt",&rejectionlist,
	"-l|--linesize|--line-size:%d",&linesize,
	"-c|--col-base:%d",&colbase,
	"-d|--col-stat:%s",&colstatstr,
	"--comment:%f",&is_comment,"(C):%f",&is_comment,
	"--verbose:%i",&is_verbose,"(V):%i",&is_verbose,
	"-:%Dl",&infiles,
	"-*|+*:%e",
	"*:%Dl",&infiles,
	NULL);

 if ( i )		
  {	fprint_error("invalid command line argument near '%s'",argv[i]);
	return(1);
  }
 else if ( is_help<0 )
  {	fprint_generic_version(stdout,argv[0],"grcollect",FITSH_GRCOLLECT_VERSION,is_help);
	return(0);
  }
 else if ( 1<is_help )
  {	fprint_grcollect_long_help(stdout,2<is_help);
	return(0);
  }
 else if ( is_help )
  {	fprint_grcollect_usage(stdout);
	return(0);
  }

 if ( maxmemstr != NULL )
  {     maxmem=parse_max_memory_string(maxmemstr);
        if ( maxmem<=1 )
         {      fprint_error("invalid maximum memory specification '%s'",maxmemstr);
                return(1);
         }
  }
 else
	maxmem=0;

 if ( maxmem <= 0 )
	maxmem=(size_t)(DEFAULT_MAX_MEMORY*1024*1024);

 if ( statstr != NULL )
  {	statlist=get_stat_list(statstr);
	if ( statlist==NULL )
	 {	fprint_error("invalid list of statistics");
		return(1);
	 }
  }
 else
	statlist=statlist_default;

 /* fprintf(stderr,"maxmem=%zd\n",maxmem); */

 colbase--;
 if ( colbase<0 )	
  {	fprint_error("invalid column index specification");
	return(1);
  }

 if ( colstatstr != NULL )
  {	char	**cmd;
	int	c;
	cmd=tokenize_char_dyn_wwt(colstatstr,',',0);
	colstats=NULL;
	for ( ncolstat=0 ; cmd[ncolstat] != NULL && cmd != NULL ; )
	 {	colstats=(column *)realloc(colstats,sizeof(column)*(ncolstat+1));
		if ( sscanf(cmd[ncolstat],"%d",&c)<1 || c<=0 )
		 {	fprint_error("invalid column index specification");
			return(1);
		 }
		colstats[ncolstat].index=c-1;
		colstats[ncolstat].r.center=0;
		colstats[ncolstat].r.magnitude=0.0;
		ncolstat++;
	 }
	if ( cmd != NULL )	free(cmd);
  }
 else
  {	ncolstat=0;
	colstats=NULL;
  }

 if ( rejectionlist != NULL )
  {	int		index,magtype,j,k;
	rejection	r;
	
	for ( i=0 ; rejectionlist[i] != NULL ; i++ )
	 {	index=magtype=0;
		r.center=0;
		r.magnitude=0.0;
		r.iterations=1;
		k=scanpar(rejectionlist[i],SCANPAR_DEFAULT,
			"column:%d",	&index,
			"mean:"		SNf(REJECTION_C_MEAN),    &r.center,
			"median:"	SNf(REJECTION_C_MEDIAN),  &r.center,
			"mode:"		SNf(REJECTION_C_MEAN),	  &r.center,
			"stddev:%g"	SNf(REJECTION_M_STDDEV),  &r.magnitude,&magtype,
			"meddev:%g"	SNf(REJECTION_M_MEDDEV),  &r.magnitude,&magtype,
			"absolute:%g"	SNf(REJECTION_M_ABSOLUTE),&r.magnitude,&magtype,
			"iterations:%d",&r.iterations,
			NULL);
		for ( j=0 ; j<ncolstat ; j++ )
		 {	if ( colstats[j].index==index-1 )
				break;
		 }
		if ( r.magnitude <= 0.0 )
		 {	r.center=magtype=0;
			r.magnitude=0;
		 }
		if ( k || ( j>=ncolstat ) )
		 {	fprint_error("invalid rejection content (index=%d)",index);
			return(1);
		 }
		colstats[j].r.center=r.center|magtype;
		colstats[j].r.magnitude=r.magnitude;
		colstats[j].r.iterations=r.iterations;
	 }
  }
			

 if ( basename != NULL && (extension != NULL || prefix != NULL) )
  {	fprint_error("invalid combination of command line arguments");
	return(1);
  }
 else if ( extension != NULL || prefix != NULL )
  {	int	len;
	len=3;
	if ( extension != NULL )	len+=strlen(extension)+1;
	if ( prefix != NULL )		len+=strlen(prefix)+1;
	basename=malloc(len);
	if ( extension != NULL && prefix != NULL )
		sprintf(basename,"%s%%b.%s",prefix,extension);
	else if ( extension==NULL && prefix != NULL )
		sprintf(basename,"%s%%b",prefix);
	else if ( extension != NULL && prefix==NULL )
		sprintf(basename,"%%b.%s",extension);
  }

 if ( basename==NULL && outfile==NULL )
  {	fprint_error("neither basename nor output file name has been specified");
	return(1);
  }
 else if ( basename != NULL && outfile != NULL )
  {	fprint_error("both basename and output file name have been specified");
	return(1);
  }

 if ( infiles==NULL )	return(0);	/* no input files */
 for ( ninfile=0 ; infiles[ninfile] != NULL ; )	ninfile++;
 if ( ninfile<=0 )	return(0);	/* no input files */

 if ( linesize<0 )	linesize=240;
 linesize=(linesize+8+16)&(~0xf);
/* fprintf(stderr,"linesize=%d\n",linesize); */

 if ( basename != NULL )		/* do transposition */
  {	/* fprintf(stderr,"tmpdir=%s\n",tmpdir); */

	if ( preallocarg==NULL )
		preallocate=0;

	else
	 {	int	s1,s2;
		off_t	pagesize;

		i=sscanf(preallocarg,"%d,%d",&s1,&s2);
		if ( i<1 )
		 {	fprint_error("unexpected pre-allocation size definition '%s'",preallocarg);
			return(1);
		 }
		else if ( i<2 )
			preallocate=(off_t)s1;
		else
		 {	s1=(s1+15)&(~15);
			s2=(s2+15)&(~15);
			preallocate=((off_t)s1)*((off_t)s2);
		 }
#ifdef	HOST_WIN32
		pagesize=(off_t)4096;
#else
		pagesize=(off_t)getpagesize();
#endif
		preallocate=(preallocate+pagesize-1)&(~(pagesize-1));
	 }

	/*
	if ( tmpdir == NULL )
	*/

	do_transposition_normal(infiles,ninfile,
		colbase,basename,maxmem,preallocate,
		additionalcomments,argc,argv);

	/*
	else
		do_transposition_cached(infiles,ninfile,colbase,basename,maxmem,tmpdir,linesize);
	*/

	return(0);
  }

 if ( outfile != NULL )
  {	FILE	*fw;
	fw=fopenwrite(outfile);
	if ( fw==NULL )
	 {	fprint_error("unable to create output file '%s'",outfile);
		return(1);
	 }
	do_collective_statistics(infiles,ninfile,fw,colbase,
		colstats,ncolstat,statlist,maxmem,tmpdir);
	fclosewrite(fw);
	return(0);
  }

 return(0);
}

/*****************************************************************************/